text_a
stringlengths
5
12.3k
text_b
stringlengths
36
15.7k
Score
int64
1
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 to...
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 to...
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 persis...
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 we...
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 ...
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 foobarmodelsm...
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 floa...
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 digit...
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 m...
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 sessionaddsu...
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 ...
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 cryptenc...
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 argum...
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 th...
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 ...
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 cryptenc...
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 defau...
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...
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...
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 ...
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 whet...
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 p...
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 ro...
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 funct...
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 ro...
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 ...
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 httpwikinginxorg...
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...
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 ...
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 mat...
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 e...
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 ...
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 handl...
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 n...
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 syst...
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...
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 whet...
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 httpwwwlinuxjournalcoma...
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 un...
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...
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 o...
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 defi...
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 dat...
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 vari...
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 ftpluginpluginp...
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 ...
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 cond...
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 cond...
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 functi...
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 me...
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 rela...
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 floatsta...
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 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 whet...
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 o...
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 a...
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 gette...
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...
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 ...
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 ...
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 w...
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 mil...
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 ...
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 cwi...
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 excelapplicatio...
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 homedepl...
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 ens...
model modelform django project defined like class consumptionmodelsmodel datemodelsdatetimefielddefaultdatetimenow productnamemodelsforeignkeystocktofield productname quantitymodelsintegerfield customermodelscharfieldmaxlengthnulltrueblanktrue def unicodeself return selfproductname class consumptionformmodelform class ...
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 l...
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 ...
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 s...
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 end...
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...
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 ...
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 whet...
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 djangocontrib...
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...
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 v...
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 mi...
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 schema...
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 depen...
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 an...
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 y...
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 lo...
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 w...
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 lo...
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 s...
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 s...
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 ...
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 he...
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 he...
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 selfr...
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 fram...
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...
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 schema...
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 syst...
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 s...
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 ...
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 httpmapsgooglecommap...
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 ...
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 subex...
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 tryin...
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 n...
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 createwidgetssel...
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 wa...
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 orderbna...
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 recta...
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 ...
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 lo...
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 s...
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 lo...
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 ...
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 ...
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 sin...
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 ...
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 ...
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 ...
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