text_a
stringlengths
5
12.3k
text_b
stringlengths
36
15.7k
Score
int64
1
3
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

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
0
Add dataset card