text_a
stringlengths 5
12.3k
⌀ | text_b
stringlengths 36
15.7k
| Score
int64 1
3
|
---|---|---|
the real way know would profile measure your code could anything dosomething might timesleep case forking processes would make whole program run approximately seconds ignoring forking overhead resulting slowdowns use httpdocspythonorglibraryprofilehtml check see bottle necks see optimise fully optimised program using better coding if already fast enough stop then depending whether cpu io bound hardware might want try multiprocessing threading you also try distributing multiple machines mapreduce kind thing problem broken | i project written python work big size data i would like speed execution time in simple words let say i sample fully optimized code def foox dosomething main range fooi is way speed for example using multiprocessing stuff and important worth thanks replies i think i try route multiprocessing someone suggest guide example helping | 3 |
you could use pypy interpreter jit compiler built might actually improve performance loops like here link explains speed ups pypy interpreter offers regular cpython or could write code using cython allows native c extensions inside python huge chunks numpy written way get good speed ups or could forget using python write asm sure harder see program runs faster everyone elses you happy went extra mile | i project written python work big size data i would like speed execution time in simple words let say i sample fully optimized code def foox dosomething main range fooi is way speed for example using multiprocessing stuff and important worth thanks replies i think i try route multiprocessing someone suggest guide example helping | 2 |
besides already said could check cython but profile also pypy might worth checking there work needed make work | i project written python work big size data i would like speed execution time in simple words let say i sample fully optimized code def foox dosomething main range fooi is way speed for example using multiprocessing stuff and important worth thanks replies i think i try route multiprocessing someone suggest guide example helping | 1 |
to answer last question first problem performance worth that criterion really as if algorithm slow computationally expensive consider rewriting c extension use cython let write fast extensions pythonesque language also pypy getting faster faster may able run code without modification if code computationally expensive loops huge amount may possible break multiprocessing gets done parallel lastly kind basic data splatting task consider using fast data store all major relational databases optimised wazoo may find task sped simply getting database you may even able shape fit redis store aggregate big data sets brilliantly | i project written python work big size data i would like speed execution time in simple words let say i sample fully optimized code def foox dosomething main range fooi is way speed for example using multiprocessing stuff and important worth thanks replies i think i try route multiprocessing someone suggest guide example helping | 3 |
selecting elements numpy array based one conditions straightforward using numpy beautifully dense syntax import numpy np generate matrix demo code a nprandomrandint reshape a array many elements column greater ndx a ndx arrayfalse true false false true true true true dtypebool npsumndx many elements last column a absolute value larger a nprandomrandint reshape a array ndx npabsa npsumndx many elements first two rows a greater equal ndx a npsumndxravel ravel flattens ndx originally d x numpy indexing syntax pretty close r given fluency r key differences r numpy context numpy indices zerobased r indexing begins numpy like python allows index right left using negative indiceseg get last column a a get penultimate column a a big deal r equivalent expresson a dima numpy uses colon notation denote unsliced eg r get first three rows a would use a in numpy would use a numpy necessary fact preferable use a | i using numpy store data matrices coming r background extremely simple way apply function rowcolumns matrix is something similar pythonnumpy combination it problem write little implementation seems versions i come significantly less efficientmore memory intensive existing implementation i would like avoid copying numpy matrix local variable etc possible the functions i trying implement mainly simple comparisons eg many elements certain column smaller number x many absolute value larger | 3 |
there documented way switch file modes r w open file instead tempfile consider using mmap share data programs | in python i open temporary file write using tempfilemkstemp order sure file destroyed released even application crashes now i need pass file another application application going able open file long file opened write can i change access mode reopen file without changing file handle order prevent deleted soon update opening file read mode solve problem file must opened shared mode | 1 |
may program helps backgroundpy import subprocess def backgroundexecutecommand launching command p subprocesspopencommandshelltruestdouttrue pwait print wait child exits here add code send mail usage backgroundexecutepython sleeppy sleeppy import time print i sleep script sleep sec timesleep print exit child | i fairly complex report generating work needs generated spaning multiple tables final report created excel sheetthe process takes anything minutes we provided django web app client only issue client requests report generating url takes time issue far ui go i would like task running behind mail client link report what right strategy libraries used | 1 |
true r randomstuff meetsconditionr break condition true condition r randomstuff condition meetsconditionr | i often randomly generate stuff certain constraints in many cases quicker ignore constraints generation check met afterwards redo process otherwise lacking keyword i usually write r randomstuff meetsconditionr r randomstuff that bit ugly i line code twice what i really like construct like r randomstuff meetsconditionr similar ternary operator introduced b condition else c just condition evaluated lefthand side statement executed does anybody suggestion design pattern work python remedies constructs intrinsic unpythonic ugliness | 3 |
i understand first line work stdin stdout stderr redirections need blocking the second one supposed block process expects data via stdin sends data stdout pipe hold wothout read but subprocess terminates correctly i cannot see reason blocking well are sure really terminates | i problem using subprocesspopen subprocesscall i use execute command lines generates lot output python scripts hangs weird waiting script hanging state i find job commanded cmd line done script hung subprocesscallcmd shell true or subprocesspopencmd stdout subprocesspipe stdin subprocesspipe shell true hangs here print show something subprocess note last print never executed actually cmd executed note also cmd related serial port i plug serial cable everything become fine last print statetement get executed but i use terminal everything fine even serial plugged occurs python script thanks lot | 1 |
your idea bad new keyword rather like expression condition extending idea generator expressions as exist help but use iter function sentinel dummysentinel object r iterrandomstuff dummysentinel meetsconditionr break if sure randomstuff returning certain kind values numbers strings etc take value sentinel especially none never occur take order neverending generator r iterrandomstuff none meetsconditionr break then randomstuff gets called meets condition even better might r nextr r iterrandomstuff none meetsconditionr gives first matching one | i often randomly generate stuff certain constraints in many cases quicker ignore constraints generation check met afterwards redo process otherwise lacking keyword i usually write r randomstuff meetsconditionr r randomstuff that bit ugly i line code twice what i really like construct like r randomstuff meetsconditionr similar ternary operator introduced b condition else c just condition evaluated lefthand side statement executed does anybody suggestion design pattern work python remedies constructs intrinsic unpythonic ugliness | 1 |
python special syntax passing sequence arguments todaydatedaysplit but parameters also ints use todaydatemapintdaysplit | this works datetime import date todaydate but i day todaydatedaysplit note daysplit i seen linkbut need integers date list | 1 |
this work datemapint daysplit mapint daysplit datemapint daysplit datetimedate | this works datetime import date todaydate but i day todaydatedaysplit note daysplit i seen linkbut need integers date list | 1 |
use datetimedatetimestrptime designed specifically parsing dates in datetimedatetimestrptime ymd date out datetimedate | this works datetime import date todaydate but i day todaydatedaysplit note daysplit i seen linkbut need integers date list | 3 |
you loop list get daysplit convert entry int today dateintx x daysplit | this works datetime import date todaydate but i day todaydatedaysplit note daysplit i seen linkbut need integers date list | 1 |
dictzipkeys values please call dict dict builtin name | i read link but i initialize dictionary well say two list keys b c values dict i want initialize dict keys amp values | 3 |
i know would help using gcc os x compile c program embedded python i link python library for instance command line i compiled gcc pythontestc lpython pythontest l flag python python library folder | i using eclipse cygwin gcc compiler trying use pythonh c program encounter errors compiling any ideas in file included cpythonincludepythonh srcembeddedpythonc cpythonincludeintobjecth error parse error pyintasunsignedlonglongmask cpythonincludeintobjecth warning type defaults int declaration pyintasunsignedlonglongmask cpythonincludeintobjecth warning data definition type storage class in file included cpythonincludepythonh srcembeddedpythonc cpythonincludelongobjecth warning parameter names without types function declaration cpythonincludelongobjecth error parse error pylongaslonglong cpythonincludelongobjecth warning type defaults int declaration pylongaslonglong cpythonincludelongobjecth warning data definition type storage class cpythonincludelongobjecth error parse error pylongasunsignedlonglong cpythonincludelongobjecth warning type defaults int declaration pylongasunsignedlonglong cpythonincludelongobjecth warning data definition type storage class cpythonincludelongobjecth error parse error pylongasunsignedlonglongmask cpythonincludelongobjecth warning type defaults int declaration pylongasunsignedlonglongmask cpythonincludelongobjecth warning data definition type storage class cpythonincludelongobjecth error parse error pylongaslonglongandoverflow cpythonincludelongobjecth warning type defaults int declaration pylongaslonglongandoverflow cpythonincludelongobjecth warning data definition type storage class make srcembeddedpythono error | 1 |
i found djangotemplateaddons library counter tag works template level independent nested loops | i trying make custom template tag increment variable that would used like fruit basket fruitisapple count apples endif endfor pthere apples apples basketp i came projectapptemplatetagscounterpy class counternodetemplatenode def initself varname selfvarname varname def renderself context selfvarname context contextselfvarname else contextselfvarname return registertag def counterparser token try tagname args tokencontentssplitnone except valueerror raise templatetemplatesyntaxerror counter node requires variable name return counternodeargs this works fine try use counter tag within loop the count variable increments inside loop gets reset variable called outside loop this render method templatedefaulttagsfornode class calls contextpop end i able grasp done dealt within custom template tag so question could i get counter tag increment even loops | 1 |
i think may need save carpool object adding legs otherwise leg count might zero wont another database hit carpool object that would explain loop skipping am i right thinking leg count zero loop print try saveing carpool object adding legs just hunch | djangopython rookie have function finishing called no error stops goes back python command prompt it first loop stops gets next print command takes back prompt everything executed correct i sure something basic i missed function def createcarpoolfamily startdate enddate name carpool carpool carpoolname name carpoolsave currentdate startdate currentdate enddate print processing currentdatestrftime mdy going enddatestrftime mdy currentdateday startleg leg startlegdrivedate currentdate startlegstarttime starttimeam startlegendpoint endpointam startlegsave endleg leg endlegdrivedate currentdate endlegstarttime starttimepm endlegendpoint endpointpm endlegsave carpoollegsaddstartleg carpoollegsaddendleg currentdate datetimetimedeltadays print adding driving preferences carpool legs numlegs carpoollegsallcount legidx leg carpoollegsall legidx print processing leg strlegidx strnumlegs rider riderobjectsall choicenumberlist legridersaddrider driver carpooldriversall drivepreference drivingpreference drivepreferenceleg leg drivepreferencedriver familydrivers drivepreferencepreference choice drivepreferencesave return carpool | 1 |
i quite understand want use executormap i tried function return anything f function actually worked fine run map actually print values version f function print values import concurrentfutures fred def fx return x x concurrentfuturesprocesspoolexecutor executor num executormapf fred printnum | iâm trying understand use concurrentfutures module python playing examples documentation when i try apply understanding examples fail i hope somebody help get track i want able set number processes running concurrently asynchronously my processes return anything to simulate i written trivial example import concurrentfutures fred def fx printx x def main concurrentfuturesprocesspoolexecutor executor num fred executorsubmitf num name main main this code runs core windows xp box returns hangs clearly iâm something wrong so correct way python run processes process pool i donât want use executormap approach i donât return process orâ¦do i fake process return true false something thanks | 1 |
the builtin function zip almost want zip the difference get tuples instead lists you convert lists using maplist zip | suppose i list tuples i want convert multiple lists for example list tuples is builtin function python convert this simple program but i curious existence builtin function python | 3 |
someone asked question like turned bucket global public read set using bucket policy double check acls etc allow access also looks like listing access want can call get bucket get listing files you able don know help use stringlike policy httpwwwtechtrickycomamazonshowtorestrictuseraccesstospecificfolderorbucket httpsforumsawsamazoncomsearchjspaobjidfampqstringlikeampxampy | i writing app i set users user number files associated directory within s bucket users authenticating using amazon sts getting temporary security credentials allow access resources allowing access resources think home directories assuming user already exists system authenticated file bucket created without specified policy acl using naming scheme app bucket user identifier during request user accessing file grant temporary security credentials follows using boto getfederationtoken user identifier durationpolicyuserpolicy userpolicy userpolicy r statement effectallow action sputobject sgetobject sgetobjectversion sdeleteobject sdeleteobjectversion resourcearnawsss user identifier i thought i understood policies apparently i missing something using scheme i able getput resources user directory also directoriesresources belonging users for life i get access properly segregated i played bucket policies well bear fruit any direction would appreciated note i stuck using sts likely many users createuse iam users | 2 |
from python docs zip conjunction operator used unzip list specific example zip zip or really want lists maplist zip | suppose i list tuples i want convert multiple lists for example list tuples is builtin function python convert this simple program but i curious existence builtin function python | 3 |
use b zipa | suppose i list tuples i want convert multiple lists for example list tuples is builtin function python convert this simple program but i curious existence builtin function python | 2 |
i know enough python give specific code looks like need write execpy handle array commands provide control logic then json file would need write value cmd key first cmd second cmd last cmd i following question i really like idea | i various shell build scripts project want create one centralized build system options allow shell script run for example user presses cmd b user given option shellscriptsh shellscriptsh shellscriptsh the user presses sublime text runs sh shellscriptsh i reading httpsublimetextinfodocsenreferencebuildsystemshtml unsure integrate option json code sublime text build system how accomplish build system sublime text thanks | 1 |
i feel pain as developer coming desktop world web development i used setting appearance application time i select arrange user interface widgets you accept browser based software work way you must separately learn css hopefully learn like method specifying appearance application whether really alternative approach browser | i hope knocked general i recently occasion learn webpy final year university project in subject teams four weeks design web app ultimately found webpy quite versatile easy get site running fast lot options janrain etc end style result relied almost entirely us amongst teams used frameworks team different one whole sites came slick polished look without spend much photoshopcss design time effort i got impression frameworks friendly came box design elements buttons navigation options widgets base css etc others i python cjava background intend learn php point what frameworks exist provided base site design beyond bare bones and emphasise i browsed python page listing frameworks interested design aspect even see assumption correct | 1 |
in python python also make dictionary comprehension keyvalue key value zipkeys values although little verbose i found clear clearly see relationship | i read link but i initialize dictionary well say two list keys b c values dict i want initialize dict keys amp values | 3 |
items python usually things retrieved modified using getitem setitem functions lists dictionaries items sets contrast implement getitem setitem documentation uses one usual terms refer members set element one | let take random container python list dict say container items refer members documentation seems suggest sets members | 1 |
i say contents container inside refer element refer specific one i would restraint use items anything different keyvalue pairs dictionary returned dictitems avoid possible confusions but take look list constructor read listiterable new list initialized iterable items i guess item ok refer iterable yields taking look httpdocspythonorglibrarystdtypeshtml find references element item like particular tuples lists compared lexicographically comparing corresponding elements this means compare equal every element must compare equal what happened one element list containing empty list three elements pointers single empty list the pop method supported list array types the optional argument defaults default last item removed returned cmp specifies custom comparison function two arguments list items overall count element appearances item | let take random container python list dict say container items refer members documentation seems suggest sets members | 1 |
no windows python suport cygwin paths cygwin python if add existing cygwin install might want consider userspecific cygwin install directory allowed write there way obtain limited cygwin path support windows programs although i suspect option either install cygwin c cygwin path equivalent cpath this relies fact windows api albeit windows programs accepts backslashes slashes path separators considers absolute paths without drive letter referring system drive ie c obviously work cygwin paths point drives via cygwin mount table it also work programs use rather introduce options includes builtin windows commandline tools but usually work crossplatform tools python yet another option use msys instead cygwin fork old cygwin version whereby distinctive feature automatically translates posix paths windows paths invoking windows programs note however approach pitfalls always clear whether argument path hence sometimes fail translate path wrongly change argument path | i access machine minimal cygwin installation windows version python i need run python scripts however python requires windows paths i use cygpath w arguments i provide however unixcygwin paths included numerous scripts subsequently invoked is way tell windows python accept unixcygwin paths | 1 |
if attacker access password database way still hide password hashing include salt prevent attacker relying generic hash tables import hashlib salt uphieiv hash aaaccfbdbdccbebcbddcff hashlibmdhexdigestsalt rawinputhexdigest hash print correct password note still help poorly chosen passwords for make sure attacker access password database if want potential attackers able run program access piece data program manipulates move piece data remote secured server program performs authentication | i looking way use password statement obviously therawinput thecorrectpassword extremely nonsecure any ideas i seen questions topic suggest base also nonsecure i cracked compiled script password without using password | 3 |
basically boolean array want find start stop contiguous regions it far better avoid looping item numpy array there different ways i usually something similar i probably originally got import numpy np def contiguousregionscondition finds contiguous true regions boolean array condition returns d array first column start index region second column end index find indicies changes condition idx npdiffconditionnonzero prepend append start end indicies idx block true start end condition idx npr idx condition idx npridx lencondition return idxreshape as quick example import numpy np def main generate data nplinspace nppi x npsint condition x regions contiguousregionscondition lengths regions regions reg length zipregions lengths print condition true seconds formatlength print from time formatreg def contiguousregionscondition idx npdiffconditionnonzero condition idx npr idx condition idx npridx lencondition return idxreshape main this yields condition true seconds from time condition true seconds from time condition true seconds from time | statussignal measured heatpump numpymaarray together timestamps what want lengths periods length periods not daily running time something would easy what exemplary fact minutevalues months time value and want output runningtimewas time value minutes offtimewas time value minutes exact timestamps matter much i already asked people know know python idea neither tried search internet know search so maybe someone could least give hint words could type google ps wow stackoverflow fantastic i already amazed usability passive user asking interface even better | 1 |
you use methoddecorator dispatch method class djangoviewsgeneric import view djangoutilsdecorators import methoddecorator djangocontribauthdecorators import userpassestest class myviewview methoddecoratoruserpassestestlambda u uissuperuser def dispatchself args kwargs return supermyview selfdispatchargs kwargs | how i implement userpassestestlambda u uissuperuser decorator class based views i used function based views i work around feels unnaturally shouldn covered dispatch method | 3 |
you also try package numpyscipymatplotlib installation using virtualenv a step step recipe using homebrew described it worked fine hope helps | what could i done instead order get items working together should i move everything windows i prefer reliable way okay happened i wanted install numpyscipy onto mac runs unfortunately numpy ver supports python i go install python but python work appicon bounces automatically quits this strange retrospect i heard python numpy ships mac i tried using sample code numpy website failed now real bind i eventually found httpstronginferencecomscipysuperpack which somehow installs numpy scipy matplotlib ipython pandas well pymc alpha it seemed like worked numpy work example code provided python but i working practice problems i found matplotlib working anymore the python launcher i think python launcher appicon says python name bounces app tray eventually freezes i worried could i matplotlib installed i followed instructions clean uninstall matplotlib followed installation scipysuperpack still fails way now i done clean install matplotlib hopes works and i import pylab throws ton error messages any advice would greatly appreciated | 2 |
compile see c code cython produces nicely annotated cyexamplepyx cdef pyssizet n leninput n cur inputi pyxt pyxvn pyxvi pyxvi pyxt pyxvi cyexamplepyx n cur inputi return cur n pyxt pyxvi pyxt pyxt pyxt pyxbshapeinput unlikelypyxt pyxt else unlikelypyxt pyxbshapeinput pyxt unlikelypyxt pyxraisebufferindexerrorpyxt pyxfilename pyxf pyxlineno pyxclineno line goto pyxlerror pyxvcur pyxvcur pyxbufptrstrideddpyxtnumpydoublet pyxbstructinputbuf pyxt pyxbstrideinput and loop successfully turned c note days cython handle range naturally older n style necessary the point introducing nonpython forfrom syntax signify loops cified | i learning cython came across snippit code import numpy np cimport numpy np def meannpndarraynpdoublet input cdef npdoublet cur pyssizet numpy index type cdef pyssizet cdef pyssizet n leninput n cur inputi return cur n anparray dtypenpdouble obviously returns mean my question is loop python loop cython c | 2 |
forfrom seems pyrex cython loop httpdocscythonorgsrcuserguidelanguagebasicshtmlintegerforloops | i learning cython came across snippit code import numpy np cimport numpy np def meannpndarraynpdoublet input cdef npdoublet cur pyssizet numpy index type cdef pyssizet cdef pyssizet n leninput n cur inputi return cur n anparray dtypenpdouble obviously returns mean my question is loop python loop cython c | 3 |
you could check eventkeysym return class appobject def initself master kwargs selfmastermaster masterbind keyrelease selfrelease def releaseselfevent eventkeysym return print return release roottktk appapproot rootmainloop note autokey repeat keyrelease events even physically release key to turn autorepeat xwindows import xlibdisplay display import xlibx x import tkinter tk import atexit atexitregister def autorepeat ddisplaydisplay dchangekeyboardcontrolautorepeatmodexautorepeatmodeon xdgetkeyboardcontrol class appobject def initself master kwargs selfmastermaster masterbind keyrelease selfrelease def releaseselfevent eventkeysym return print return release ddisplaydisplay dchangekeyboardcontrolautorepeatmodexautorepeatmodeoff xdgetkeyboardcontrol roottktk appapproot rootmainloop | is way make return event call key release instead press if use keyrelease eventchar blank special key return | 2 |
here variation cã©dric julien answer fail rare cases anytrue devdevices name devname here admittedly unusual possible case illustrates anytrue ⦠gives correct result anyd ⦠class specialdictdict def nonzeroself return false all specialdict objects false dev devices specialdictnamedevname xrange anyd devdevices name devname incorrect false anytrue devdevices name devname correct true in fact specialdict objects evaluate false make sense test truth value using true works though ps timing tests indicate anytrue ⦠⦠⦠⦠approach faster nice any⦠⦠⦠solution doublep python timeit dev devices name badname xrange anyd name devname dev devices loops best usec per loop python timeit dev devices name badname xrange anytrue dev devices name devname loops best usec per loop the reason second generator returns one value true this seen disassembling python code two generators in def fmylist return anyx x mylist in ffunccodecoconsts out code object genexpr xfb file ipythoninputce line in disdis loadfast foriter storefast x loadfast x loadconst compareop yieldvalue poptop jumpabsolute loadconst none returnvalue this code contains yieldvalue poptop take additional time compared version answer in def gmylist return anytrue x mylist x in gfunccodecoconsts out code object genexpr xf file ipythoninputcd line in disdisgfunccodecoconsts loadfast foriter storefast x loadfast x loadconst compareop popjumpiffalse loadglobal true yieldvalue poptop jumpabsolute loadconst none returnvalue | i got lines code iterating dict within list i looking shorten it works perfectly seems like much code i trying get feel keep code efficient python general really dev devices name devname devfound true break the structure dev bit confusing data i care dev dict devices list n dict value name key within inner numbered dict varies depending search value elsewhere needs checked user input devname any input much appreciated | 1 |
the basic operations described wikipedia transformation matrix page i going try ascii matrix art output p rp p output point r x transformation matrix containing sine cosine rotation angle p input point if want rotate something origin shift origin prior rotation p t rpt t translation coordinate the basic matrix operations interpolation using numpybased image processing library want reverse transform integervalued output coordinate find floating point coordinate point would rotated interpolate value input point surrounding pixels | i set greyscale images d numpy arrays i need rotate images one point inside different float angles the rotation need place i allow course i explained well far interpolation i like remain numpy i need perform numerical operations result i also impossible allow step inout example i tried using pil namely imagerotatetheta understand apply arrays get array back thank input | 1 |
i quite sure i understand correctly goal i think i understand seem necessary crazy stuff descriptors let alone typesmethodtype a simple property fine like lambda use ordinary function decorated property class user name modelscharfieldmaxlength property def companyself return userprofileobjectsgetorcreateuserselfgetcompany edit if touch user class create derived class adding desired property class myuseruser property def companyself return userprofileobjectsgetorcreateuserselfgetcompany | i want nice convenient attribute following djangocontribauthmodels import user user userobjectsgetid usercompany company big company llc i currently solving using lambda in searching answer looks like perhaps right way solve would use typesmethodtype i seem get head around yes i read raymond excellent guide i clearly missing something here current solution interested defined elsewhere class user name modelscharfieldmaxlength class companymodelsmodel users modelsmanytomanyfielduser relatednamecompanies blanktrue nulltrue here meat class userprofilemodelsmodel this defines users user modelsonetoonefielduser def getcompanyself try companies selfusercompaniesall except attributeerror indexerror return none usercompany propertylambda u userprofileobjectsgetorcreateuserugetcompany right works but better way i crazy lambdas | 1 |
f open filetxt r print fread fclose from httpdocspythonorgtutorialinputoutputhtml to read fileâs contents call freadsize reads quantity data returns string size optional numeric argument when size omitted negative entire contents file read returned itâs problem file twice large machineâs memory otherwise size bytes read returned if end file reached fread return empty string | i searched i find questions way around writing stdin file is quick easy way dump contents file stdout | 3 |
sure assuming string file name called fname following trick openfname r fin print finread | i searched i find questions way around writing stdin file is quick easy way dump contents file stdout | 3 |
mul know x represent scalars matrix multiplication depends order arguments example k k necessarily equal if know program x always scalars type value multiplication commutative associative may way factor constants term compare constants compare sorted list terms | in project i use evaluatefalse time creating add mul objects in case i facing problem i apply equality checks objects the issue ordering arguments please consider example kmulxyevaluatefalse kmulxyevaluatefalse print kk the result false kargs xy kargs xy so comparison checks tuple equality returns false is way i get wanted result also i put operation tuples like reversing order checking fails cases k k formed different mul objects like kargs xy kargs yx edit cannot use sorting case addxyzevaluatefalse addxzyevaluatefalse two different expression also use evalautetrue case addxyx addxy dont want | 1 |
if large file want consume ton memory might happen ben solution extra code import shutil import sys opentesttxt r f shutilcopyfileobjf sysstdout also works | i searched i find questions way around writing stdin file is quick easy way dump contents file stdout | 3 |
rather attempting expand variable inside single quoted string typical solution concatenate single double quoted strings in words today date poor | first take look question bash googlecl new line string parameter i want add variable date summary google youtube post videoscatfallsdownstairsavi comedy tags currency internet summary today date poor whiskers takes tumblenshe fine though worry variable wont expand inside single quote bash is possible note googlecl commandline program written python i ubuntu python | 3 |
i pleased say listing imports actually quite simple i need minimal implementation importer protocol defined pep findmodule returns none fallback next one this simple script actually show imports done program passed import sys class importinspectorobject def findmoduleself module path printimporting module module name main progname sysargv shift one position sysargv sysargv sysmetapathappendimportinspector code compileopenprogname rb read progname exec execcode given kind trick implemented top for example keep track imports set store program quits i think might even get hiearchy imports produce graph similar gprofdot based analysis imports | in general i would like understand exactly code code projects actually using big framework first i want know imports possibly static analysis possible imports actually used for first problem i could use regexp course i would like find cleaner way i see astinspectparser and second problem i able find automatically imports actually unused i edit second issue maybe best way simple import hook records everything imported call default importing mechanisms so i tried something like class myloaderobject loader object def initself selfloaded set def findmoduleself modulename packagenone printrequesting modulename selfloadedaddmodulename return self def loadmoduleself fullname fp pathname stuff impfindmodulefullname imploadmodulefullname fp pathname stuff but trying import random i get future import division importerror no module named future which i think means i missing something i found simple example using imp import introspection hints | 1 |
you list deployed versions admin console admin logs short screenscraping page way access data programmatically you submit enhancement request issue tracker | i like get list deployed versions appengine either remote api via appcfgpy i seem find way certainly documented way does anyone know way even undocumented | 1 |
a callback takes code calling gui toolkit passes if want pass convince said caller pass something extra luck but luckily loophole you pass arbitrary callables construct partial functions functions wrapping another function remembering additional arguments pass along whenever called import functools def callbackx return x g functoolspartialcallback g there issues strange argument orders eg easily call partial positional arguments first argument supplied via keyword argument use case add arguments end argument list work fine you need use keyword arguments | i creating couple swing jbuttons buttons loop jython on press button call function one different parameter i trouble passing parameters outside self event this works x range name jbuttonstrx nameactionperformed selffoo def fooself event print i work somehow event magically passed method this x range name jbuttonstrx nameactionperformed selffoox def fooself event number print i work print strnumber the issue i see i i add argument i longer pass event i end error telling foo takes exactly arguments given i get i extract event button | 2 |
sets ordered collections python language matter sets usually implemented using hash keys hash codes so order probably related hash functions used instead natural order elements if need order please consider using list | with code print setab range b range i get answer set why sorted | 3 |
sets nature unordered containers from documentation a set object unordered collection distinct hashable objects they implemented using hash table facilitating o membership tests if need ordered set try ordereddictfromkeys collections import ordereddict ordereddictfromkeysab range b range | with code print setab range b range i get answer set why sorted | 1 |
variables expanded within single quotes either like william suggests rewrite line double quotes expand variable want today date poor whiskers takes tumblenshe fine though worry bonus doing way escape single quotes now i read link say n expand a workaround would something like summary echo e today it bit crude use subshell save backslashing quotes | first take look question bash googlecl new line string parameter i want add variable date summary google youtube post videoscatfallsdownstairsavi comedy tags currency internet summary today date poor whiskers takes tumblenshe fine though worry variable wont expand inside single quote bash is possible note googlecl commandline program written python i ubuntu python | 1 |
it pretty much returning what see simply list url strings encoded unicode strings u front if simply want print urls nicely python module pretty printing used follows pprint import pprint pprintmylistofurls however print line line to need use url mylistofurls print url edit i tried pretty print module list unicode strings i think actually anything different u front strings i leaving wonders representing long data structures | my script import beautifulsoup bs beautifulsoup import beautifulsoup urllist sysargv urls tag href tag beautifulsoupopenurllistfindall returns u httpwwwyoutubecomwatchvggzipheg u httpwwwyoutubecomwatchvppvjgmmhfo u httpwwwyoutubecomwatchvytaudfye u httpwwwyoutubecomwatchvvhvqffge u httpwwwyoutubecomwatchvezgwqqu u httpwwwyoutubecomwatchvkhlsbvn u httpwwwyoutubecomwatchvxtndqbyva u httpwwwyoutubecomwatchvxttmqgwrrc u httpwwwyoutubecomwatchvjzyqngwsuw u httpwwwyoutubecomwatchvrzwvgunru u httpwwwyoutubecomwatchvvzqoywwm u httpwwwyoutubecomwatchvyarvqxyw u httpwwwyoutubecomwatchvlrreyhgci i would like return httpwwwyoutubecomwatchvggzipheg httpwwwyoutubecomwatchvppvjgmmhfo httpwwwyoutubecomwatchvytaudfye httpwwwyoutubecomwatchvvhvqffge httpwwwyoutubecomwatchvezgwqqu httpwwwyoutubecomwatchvkhlsbvn httpwwwyoutubecomwatchvxtndqbyva httpwwwyoutubecomwatchvxttmqgwrrc httpwwwyoutubecomwatchvjzyqngwsuw httpwwwyoutubecomwatchvrzwvgunru httpwwwyoutubecomwatchvvzqoywwm httpwwwyoutubecomwatchvyarvqxyw httpwwwyoutubecomwatchvlrreyhgci i really hard time wrapping head around beautifulsoup anything would help thank time | 1 |
but completely basic python you getting list want output one url per line url urls print url | my script import beautifulsoup bs beautifulsoup import beautifulsoup urllist sysargv urls tag href tag beautifulsoupopenurllistfindall returns u httpwwwyoutubecomwatchvggzipheg u httpwwwyoutubecomwatchvppvjgmmhfo u httpwwwyoutubecomwatchvytaudfye u httpwwwyoutubecomwatchvvhvqffge u httpwwwyoutubecomwatchvezgwqqu u httpwwwyoutubecomwatchvkhlsbvn u httpwwwyoutubecomwatchvxtndqbyva u httpwwwyoutubecomwatchvxttmqgwrrc u httpwwwyoutubecomwatchvjzyqngwsuw u httpwwwyoutubecomwatchvrzwvgunru u httpwwwyoutubecomwatchvvzqoywwm u httpwwwyoutubecomwatchvyarvqxyw u httpwwwyoutubecomwatchvlrreyhgci i would like return httpwwwyoutubecomwatchvggzipheg httpwwwyoutubecomwatchvppvjgmmhfo httpwwwyoutubecomwatchvytaudfye httpwwwyoutubecomwatchvvhvqffge httpwwwyoutubecomwatchvezgwqqu httpwwwyoutubecomwatchvkhlsbvn httpwwwyoutubecomwatchvxtndqbyva httpwwwyoutubecomwatchvxttmqgwrrc httpwwwyoutubecomwatchvjzyqngwsuw httpwwwyoutubecomwatchvrzwvgunru httpwwwyoutubecomwatchvvzqoywwm httpwwwyoutubecomwatchvyarvqxyw httpwwwyoutubecomwatchvlrreyhgci i really hard time wrapping head around beautifulsoup anything would help thank time | 2 |
when tried inserting br tag literally show output br if django automatically escaping error message see httpsdocsdjangoprojectcomendevtopicstemplatesautomatichtmlescaping details | i overriding clean method variables want specify custom error message error myerrormsg this error message myerrormsg nthis error message i would like next line selferrorsmytag myerrormsg however seems ignore line breaks i tried html br n nothing works everything gets put one line i loose capitalization | 1 |
constructor texttestrunner class failfast parameter shown constructor documentation update i raised bug fixed verify httpdocspythonorglibraryunittesthtmlunittesttexttestrunner | all i found documentation unittest module description texttestrunner constructor following sample code using run method unittesttexttestrunnerverbosityrunsuite i would like know i use texttestrunner failfast mode | 3 |
selferrorsmytag selferrorsgetmytag selferrorclass selferrorsmytagappendthis error message selferrorsmytagappendthis error message i would like next line like two errors escaping saying try selferrorsmytagappendmarksafetextbrtext selferrorsmytag selferrorclassmarksafetextbrtext | i overriding clean method variables want specify custom error message error myerrormsg this error message myerrormsg nthis error message i would like next line selferrorsmytag myerrormsg however seems ignore line breaks i tried html br n nothing works everything gets put one line i loose capitalization | 1 |
you use valueslist mywords mygroupobjectsgetname blaallkeywordvalueslist name flattrue | how i convert queryset returned array string mywords mygroupobjectsgetname blaallkeyword mywords meltemi bla class mygroupmodelsmodel name modelscharfieldmaxlength uniquetrue allkeyword modelsmanytomanyfield keywordtag def unicodeself return selfname class keywordtagmodelsmodel name modelscharfieldmaxlength uniquetrue def unicodeself return selfname | 3 |
you provide string beautifulsoup parse bookmarkshtml opensysargv bookmarkfile soup beautifulsoupbookmarkfileread extract youtube video urls videourlregex recompile httpwwwyoutubecomwatch urls link href link soup hrefvideourlregex separate fast url parsing much longer downloading stats extract video ids urls ids could use set idsadd avoid duplicates videourl urls url urlparseurlparsevideourl videoid urlparseparseqsurlqueryget v videoid continue videoid url idsappendvideoid you need authenticate readonly requests get statistics videos ytservice youtubeservice ytservicessl true note works readonly requests ytservicedebug true show requests save statistics csv file provided commandline don stop video causes error writer csvwriteropensysargv wb save cvs file videoid ids try entry ytservicegetyoutubevideoentryvideoidvideoid except exception e print sysstderr failed retrieve entry videoids videoid e else title entrymediatitletext print title title viewcount entrystatisticsviewcount print view count viewcount writerwriterowvideoid title viewcount write here full script press playback watch written output python downloadvideostatspy neudorferhtml outcsv send u get httpsgdatayoutubecomfeedsapivideosggzipheg httprnacc eptencoding identityrnhost gdatayoutubecomrncontenttype applicationato mxmlrnuseragent none gdatapythonrnrn reply http okrn header xgdatausercountry ru header contenttype applicationatomxml charsetutf header expires thu nov gmt header date thu nov gmt header cachecontrol private maxage notransform header vary header gdataversion header lastmodified wed nov gmt header transferencoding chunked header xcontenttypeoptions nosniff header xframeoptions sameorigin header xxssprotection modeblock header server gse title paramore let the flames begin walmart soundcheck view count outcsv ggziphegparamore let the flames begin walmart soundcheck ppvjgmmhfoparamore walmart soundcheck ytaudfyeparamorewalmart soundcheck crushcrushcrushhq vhvqffgeparamorewalmart soundcheck that what you gethq ezgwqquparamorewalmart soundcheck interviewhq khlsbvnparamorewalmart soundcheck emergencyhq xtndqbyvaparamorewalmart soundcheck for pessimisthq xttmqgwrrcparamorewalmart soundcheck pressurehq jzyqngwsuwparamore walmart soundcheck interview rzwvgunruparamore interview walmart soundcheck vzqoywwmparamore that what you get walmart soundcheck yarvqxywparamore pressure walmart soundcheck lrreyhgciparamore walmart promo | bookmarkshtml looks like dta hrefhttpwwwyoutubecomwatchvggzipheg adddate lastmodified iconurihttpsytimgcomytfaviconvflzlzsbuico icondataimagepngbaseivborwkggoaaaansuheugaaabaaaaaqcayaaaafhaaabeeleqvqjawspudqbcfwgodzpqteqqjjlsujlgbnsdrdrqarsumyprjogkijiwitoyhrsepjrhptxkdrhrnmnbzxfsdpsprwrazbjhxdruakegvbfnepfzbqdjfroucsfhqdyjwcudzqpjtoylzknhzmidzgdeqgcmlfwpxnwadfvambuistxrwxbjalhgmizoldkicvbreezwtkgkbkqagqdogzljqayyxpmpgixhpwaesdunzzlwmbnnwekbqfgjnpabdggbvwbnoamnzewpfxynwuuqbkqtyyfrrkvqdptjzjpsbekaaaaasuvorkcyiihttpwwwyoutubecomwatchvggziphega dta hrefhttpwwwyoutubecomwatchvppvjgmmhfo adddate lastmodified iconurihttpsytimgcomytfaviconvflzlzsbuico icondataimagepngbaseivborwkggoaaaansuheugaaabaaaaaqcayaaaafhaaabeeleqvqjawspudqbcfwgodzpqteqqjjlsujlgbnsdrdrqarsumyprjogkijiwitoyhrsepjrhptxkdrhrnmnbzxfsdpsprwrazbjhxdruakegvbfnepfzbqdjfroucsfhqdyjwcudzqpjtoylzknhzmidzgdeqgcmlfwpxnwadfvambuistxrwxbjalhgmizoldkicvbreezwtkgkbkqagqdogzljqayyxpmpgixhpwaesdunzzlwmbnnwekbqfgjnpabdggbvwbnoamnzewpfxynwuuqbkqtyyfrrkvqdptjzjpsbekaaaaasuvorkcyiihttpwwwyoutubecomwatchvppvjgmmhfoa dta hrefhttpwwwyoutubecomwatchvytaudfye adddate lastmodified iconurihttpsytimgcomytfaviconvflzlzsbuico icondataimagepngbaseivborwkggoaaaansuheugaaabaaaaaqcayaaaafhaaabeeleqvqjawspudqbcfwgodzpqteqqjjlsujlgbnsdrdrqarsumyprjogkijiwitoyhrsepjrhptxkdrhrnmnbzxfsdpsprwrazbjhxdruakegvbfnepfzbqdjfroucsfhqdyjwcudzqpjtoylzknhzmidzgdeqgcmlfwpxnwadfvambuistxrwxbjalhgmizoldkicvbreezwtkgkbkqagqdogzljqayyxpmpgixhpwaesdunzzlwmbnnwekbqfgjnpabdggbvwbnoamnzewpfxynwuuqbkqtyyfrrkvqdptjzjpsbekaaaaasuvorkcyiihttpwwwyoutubecomwatchvytaudfyea dta hrefhttpwwwyoutubecomwatchvvhvqffge adddate lastmodified iconurihttpsytimgcomytfaviconvflzlzsbuico icondataimagepngbaseivborwkggoaaaansuheugaaabaaaaaqcayaaaafhaaabeeleqvqjawspudqbcfwgodzpqteqqjjlsujlgbnsdrdrqarsumyprjogkijiwitoyhrsepjrhptxkdrhrnmnbzxfsdpsprwrazbjhxdruakegvbfnepfzbqdjfroucsfhqdyjwcudzqpjtoylzknhzmidzgdeqgcmlfwpxnwadfvambuistxrwxbjalhgmizoldkicvbreezwtkgkbkqagqdogzljqayyxpmpgixhpwaesdunzzlwmbnnwekbqfgjnpabdggbvwbnoamnzewpfxynwuuqbkqtyyfrrkvqdptjzjpsbekaaaaasuvorkcyiihttpwwwyoutubecomwatchvvhvqffgea dta hrefhttpwwwyoutubecomwatchvezgwqqu adddate lastmodified iconurihttpsytimgcomytfaviconvflzlzsbuico icondataimagepngbaseivborwkggoaaaansuheugaaabaaaaaqcayaaaafhaaabeeleqvqjawspudqbcfwgodzpqteqqjjlsujlgbnsdrdrqarsumyprjogkijiwitoyhrsepjrhptxkdrhrnmnbzxfsdpsprwrazbjhxdruakegvbfnepfzbqdjfroucsfhqdyjwcudzqpjtoylzknhzmidzgdeqgcmlfwpxnwadfvambuistxrwxbjalhgmizoldkicvbreezwtkgkbkqagqdogzljqayyxpmpgixhpwaesdunzzlwmbnnwekbqfgjnpabdggbvwbnoamnzewpfxynwuuqbkqtyyfrrkvqdptjzjpsbekaaaaasuvorkcyiihttpwwwyoutubecomwatchvezgwqqua dta hrefhttpwwwyoutubecomwatchvkhlsbvn adddate lastmodified iconurihttpsytimgcomytfaviconvflzlzsbuico icondataimagepngbaseivborwkggoaaaansuheugaaabaaaaaqcayaaaafhaaabeeleqvqjawspudqbcfwgodzpqteqqjjlsujlgbnsdrdrqarsumyprjogkijiwitoyhrsepjrhptxkdrhrnmnbzxfsdpsprwrazbjhxdruakegvbfnepfzbqdjfroucsfhqdyjwcudzqpjtoylzknhzmidzgdeqgcmlfwpxnwadfvambuistxrwxbjalhgmizoldkicvbreezwtkgkbkqagqdogzljqayyxpmpgixhpwaesdunzzlwmbnnwekbqfgjnpabdggbvwbnoamnzewpfxynwuuqbkqtyyfrrkvqdptjzjpsbekaaaaasuvorkcyiihttpwwwyoutubecomwatchvkhlsbvna dta hrefhttpwwwyoutubecomwatchvxtndqbyva adddate lastmodifiedparamore walmart soundcheck for pessimisthqa dta hrefhttpwwwyoutubecomwatchvxttmqgwrrc adddate lastmodifiedparamore walmart soundcheck pressurehqa dta hrefhttpwwwyoutubecomwatchvjzyqngwsuw adddate lastmodifiedparamore walmart soundcheck interviewa dta hrefhttpwwwyoutubecomwatchvrzwvgunru adddate lastmodifiedparamore interview walmart soundcheck a dta hrefhttpwwwyoutubecomwatchvvzqoywwm adddate lastmodifiedparamore thatamps what you get walmart soundcheck a dta hrefhttpwwwyoutubecomwatchvyarvqxyw adddate lastmodifiedparamore pressure walmart soundcheck a dta hrefhttpwwwyoutubecomwatchvlrreyhgci adddate lastmodifiedparamore walmart promoa it standard bookmarks export file firefox i feed bookmarkspy looks like usrbinenv python import sys import beautifulsoup bs beautifulsoup import beautifulsoup urllist sysargv urls tag href tag beautifulsoupopenurllistfindall print urls this returns much clean list urls u httpwwwyoutubecomwatchvggzipheg u httpwwwyoutubecomwatchvppvjgmmhfo u httpwwwyoutubecomwatchvytaudfye u httpwwwyoutubecomwatchvvhvqffge u httpwwwyoutubecomwatchvezgwqqu u httpwwwyoutubecomwatchvkhlsbvn u httpwwwyoutubecomwatchvxtndqbyva u httpwwwyoutubecomwatchvxttmqgwrrc u httpwwwyoutubecomwatchvjzyqngwsuw u httpwwwyoutubecomwatchvrzwvgunru u httpwwwyoutubecomwatchvvzqoywwm u httpwwwyoutubecomwatchvyarvqxyw u httpwwwyoutubecomwatchvlrreyhgci next step get youtube urls videoinfopy usrbinpython import urlparse import sys import gdatayoutube import gdatayoutubeservice import import urlparse import urllib youtubeurl sysargv urldata urlparseurlparseyoutubeurl query urlparseparseqsurldataquery youtubeid queryv print youtubeid ytservice gdatayoutubeserviceyoutubeservice ytservicedeveloperkey aisiyomigehstxhnkivdftqjckqoysbbylkerpqxwjilwnujacdxpocglbbcapdyemlisbkvcoagykvkvg entry ytservicegetyoutubevideoentryvideoidyoutubeid print video title entrymediatitletext print video view count entrystatisticsviewcount url httpwwwyoutubecomwatchvaxrgwcrsw output looks like axrgwcrsw video title onerepublic good life live walmart soundcheck video view count how i feed list urls bookmarkspy videoinfopy extra points output csv format extra extra points checking duplicates bookmarkshtml passing data videoinfopy thanks help guys because stackoverflow i gotten far david so combined i usrbinenv python import urlparse import gdatayoutube import gdatayoutubeservice import import urlparse import urllib import sys import beautifulsoup bs beautifulsoup import beautifulsoup ytservice gdatayoutubeserviceyoutubeservice ytservicedeveloperkey aisiyomigehstxhnkivdftqjckqoysbbylkerpqxwjilwnujacdxpocglbbcapdyemlisbkvcoagykvkvg urllist sysargv urls tag href tag beautifulsoupopenurllistfindall print urls youtubeurl urls urldata urlparseurlparseyoutubeurl query urlparseparseqsurldataquery youtubeid queryv listsetmylist entry ytservicegetyoutubevideoentryvideoidyoutubeid myyoutubes myyoutubesappend joinyoutubeid entrymediatitletextentrystatisticsviewcount print njoinmyyoutubes how i pass list urls youtubeurl variable need cleaned passed one time i believe i got usrbinenv python import urlparse import gdatayoutube import gdatayoutubeservice import import urlparse import urllib import sys import beautifulsoup bs beautifulsoup import beautifulsoup ytservice gdatayoutubeserviceyoutubeservice ytservicedeveloperkey aisiyomigehstxhnkivdftqjckqoysbbylkerpqxwjilwnujacdxpocglbbcapdyemlisbkvcoagykvkvg urllist sysargv urls tag href tag beautifulsoupopenurllistfindall url urls youtubeurl url urldata urlparseurlparseyoutubeurl query urlparseparseqsurldataquery youtubeid queryv listsetmylist entry ytservicegetyoutubevideoentryvideoidyoutubeid myyoutubes myyoutubesappend joinyoutubeid entrymediatitletextentrystatisticsviewcount print njoinmyyoutubes i pass bookmarkshtml combinedpy returns first line how i loop line youtubeurl | 1 |
i think need graphvv weight no need recreate whole dictionary add new item | please take look var name dictvar var i need name how i use dict dictelement way append element dictgraph also dictionary graphv dictgraphv vweight please help modify append method | 2 |
var name var name | please take look var name dictvar var i need name how i use dict dictelement way append element dictgraph also dictionary graphv dictgraphv vweight please help modify append method | 1 |
you question moot when got whole interpreter boxed number types heap allocations said types etc code machine cache efficency least worries since python builtin sequence types use dynamic overallocating c arrays hood rules apply two major caveats there lot hidden memory access every python operations eg type checking variable member lookup creating bound method objects calling methods number coercion may reduce benefit in many cases ie unless noted otherwise containers store references boxed objects iterate list int objects cpu cache help fetching pointers faster handling objects behind i surprised could measure difference if want optimize many things thousand times effective far obvious use builtins numpy write bit c use cython simply optimize python code | pretty inexperienced python i realize awfully basic well python cache blocks compared c for example c gridwidth gridheight igridheight j jgridwidth j massivenum arrigridwidth j way faster massivenum arri jgridwidth data cached efficiently first if i going speed python i something simple rangegridheight j rangegridwidth massivenum arrigridwidth j special thing i | 1 |
you could simple way var name dict dvar graphv or var name graphv var or could use dictitems trick var name graphv dictvar dictditems trick or could silly var graphv dictd i think works | please take look var name dictvar var i need name how i use dict dictelement way append element dictgraph also dictionary graphv dictgraphv vweight please help modify append method | 1 |
so far i seen yii framework php generate initial nice styled web application backbone ready work adding functionality dbs user roles etc course freedom define look feel defining html views css js etc i start learning using php framework next project i never yet used framework i several years using phpmysql for weeks i researched php frameworks cakephp codeigniter zend yii kohana etc i leaning yii even though codeigniter seems followers i stubborn checking yii high praise getting specially quality built performance i know good php frameworks default visual style area | i hope knocked general i recently occasion learn webpy final year university project in subject teams four weeks design web app ultimately found webpy quite versatile easy get site running fast lot options janrain etc end style result relied almost entirely us amongst teams used frameworks team different one whole sites came slick polished look without spend much photoshopcss design time effort i got impression frameworks friendly came box design elements buttons navigation options widgets base css etc others i python cjava background intend learn php point what frameworks exist provided base site design beyond bare bones and emphasise i browsed python page listing frameworks interested design aspect even see assumption correct | 1 |
there course templating systems like jinja probably overkill asking you also format page using rst use generate latex probably overkill heck autogenerating page probably overkill number fields got define since overkill stop us i done something similar python string formatting take latex document tokenize file placing placeholdernames tokens document for example want class name go use coursenames textbflarge homeworktitles vspacecm textbflarge coursenames then python load template format template file templatetex r read page template coursename computer science homeworktitle npcomplete file resulttex w writepage if want find tokens automatically following pretty well import sys import import subprocess template file templatetex r read pattern recompile bcdeeffggnosxx tokens patternfindalltemplate tokenvalues dict token tokens sysstdoutwrite enter value token tokenvaluestoken sysstdinreadlinestrip page template tokenvalues file resulttex w writepage subprocesscall pdflatex resulttex the code iterate across tokens print prompt console asking input token in example get two prompts example answers enter value homeworktitle npcomplete enter value coursename computer science the final line calls pdflatex resulting file generates pdf if want go could also ask user output file name take command line option | i college guy college present kind homework standard coverpage college logo course name professor name name bla bla bla so i tex document generate standard coverpages pdfs it goes something like begindocument college logo vspacecm begincenter textbfhuge school program name vspacecm textbflarge homework title vspacecm textbflarge course name endcenter vspacecm beginflushright large my name endflushright so i wondering way make python script asks title homework course name rest strings use generate coverpage after compile tex generate pdf information given any opinions advice snippet library accepted | 3 |
it widget needs attrs form field mylist formsmodelmultiplechoicefield label list requiredfalse queryset widgetselectmultipleattrs class foobar | how exactly i add css formsmodelmultiplechoicefield i tried pass attrs class foo but failing saying init got unexpected keyword argument attrs mylist formsmodelmultiplechoicefieldlabel list requiredfalse queryset | 3 |
you start defining template tex file string content r documentclassarticle begindocument textbfhuge schools vspacecm textbflarge titles enddocument next use argparse accept values course title name school parser argparseargumentparser parseraddargument c course parseraddargument title parseraddargument n name parseraddargument school default my u a bit string formatting takes stick args content args parserparseargs contentargsdict after writing content file covertex open covertex w f fwritecontentargsdict could use subprocess call pdflatex covertex proc subprocesspopen pdflatex covertex proccommunicate you could add lpr command add printing workflow remove unneeded files osunlink covertex osunlink coverlog the script could called like makecoverpy c hardest class ever theoretical theory n me putting together import argparse import os import subprocess content r documentclassarticle begindocument p amp b textbfhuge schools vspacecm textbflarge titles enddocument parser argparseargumentparser parseraddargument c course parseraddargument title parseraddargument n name parseraddargument school default my u args parserparseargs open covertex w f fwritecontentargsdict cmd pdflatex interaction nonstopmode covertex proc subprocesspopencmd proccommunicate retcode procreturncode retcode osunlink coverpdf raise valueerror error executing command formatretcode joincmd osunlink covertex osunlink coverlog | i college guy college present kind homework standard coverpage college logo course name professor name name bla bla bla so i tex document generate standard coverpages pdfs it goes something like begindocument college logo vspacecm begincenter textbfhuge school program name vspacecm textbflarge homework title vspacecm textbflarge course name endcenter vspacecm beginflushright large my name endflushright so i wondering way make python script asks title homework course name rest strings use generate coverpage after compile tex generate pdf information given any opinions advice snippet library accepted | 3 |
your problem stems fact endofline anchor the way nongreedy matching works engine first searches first unconstrained pattern line case it looks first character constrained anchor end line so nongreedy different greedy situation since cannot remove re looking final tag line need take different tacksee mark answer work | i confused python greedynotgreedy characters given multiline html return final tag line i would think would correct refindall html remultiline i irked i expected list single tags like html ul td my o reilly pocket reference says wil match times times possible so i getting greedier matches ie one tag matches | 1 |
you try using sphinxapidoc sphinxapidoc help usage sphinxapidoc options outputpath modulepath excludepaths look recursively modulepath python modules packages create one rest file automodule directives per package outputpath you mix sphinxapidoc sphinxquickstart order create whole doc project like sphinxapidoc f docs project this call generate full project sphinxquickstart look recursively project python modules hope helps | i trying autogenerate basic documentation codebase using sphinx however i difficulty instructing sphinx recursively scan files i python codebase folder structure like workspace src mypackage initpy subpackagea initpy submodulea submodulea subpackageb initpy submoduleb submoduleb i ran sphinxquickstart workspace structure looks like workspace src mypackage initpy subpackagea initpy submodulea submodulea subpackageb initpy submoduleb submoduleb indexrst build static templates i read quickstart tutorial httpsphinxpocooorgtutorialhtml although i still trying understand docs way worded makes concerned sphinx assumes i going manually create documentation files every single moduleclassfunction codebase however i notice automodule statement i enabled autodoc quickstart i hoping documentation automatically generated i modified confpy add src folder syspath modified indexrst use automodule so indexrst looks like contents toctree maxdepth indices tables refgenindex refmodindex refsearch automodule alphabuyer members i dozens classes functions defined subpackages yet i run sphinxbuild b html build reports updating environment added changed removed and appears failed import anything inside package viewing generated indexhtml shows nothing next contents the index page shows mypackage module clicking shows also contents how direct sphinx recursively parse package automatically generate documentation every classmethodfunction encounters without manually list every class | 3 |
firstly try except functions statements to convert string type converted integer python simply call int builtin function int raise valueerror fails catch specifically in python x value l b xfe not convertable try print int strvalue intvalue except valueerror ex print cannot converted int value ex int int int int int int not convertable cannot converted int invalid literal int base not convertable in python x syntax changed slightly value b xfe not convertable try print int strvalue intvalue except valueerror ex print cannot converted int value ex int int int int int int not convertable cannot converted int invalid literal int base not convertable | so i pretty stumped convert string int using tryexcept function does anyone know simple function i feel like i still little hazy string ints i pretty confident ints related numbers stringsnot much | 2 |
i produced simple example could test the result could look like usrbinpython reportlabgraphicschartslineplots import lineplot reportlabgraphicsshapes import drawing reportlablib import colors random import randint datetime import date timedelta generate testdata data xrandint x range xrandint x range xrandint x range create drawing lineplot drawing drawing lp lineplot lpx lpy lpheight lpwidth lpinfill lpdata data rangelendata lplinesistrokecolor colorstocolor hsls specify labels lpxvalueaxisvaluesteps create formatter takes value format however like def formatterval return val return xs val return date timedeltavalstrftime ymd use formatter lpxvalueaxislabeltextformat formatter drawingaddlp reportlabgraphics import renderpdf renderpdfdrawtofiledrawing examplepdf lineplot dates in formatter alternative return statements could play get better grip of course data xaxis dates begin need formatter case could specify labels satisfied default positioning the example borrows ideas page reportlab documentation good luck | i using reportlab generate lineplot chart i seem get non numeric labels x axis does anyone ideas this lineplot chart class note im donig calculations setup outside class get gist import reportlab advisorchartingfont import font reportlablibcolors import color hexcolor reportlablibpagesizes import cm inch reportlabgraphicschartslegends import legend reportlabgraphicschartstextlabels import label reportlabgraphicschartslinecharts import horizontallinechart reportlabgraphicschartslineplots import lineplot reportlabgraphicsshapes import drawing string drawingeditormixin reportlabgraphicswidgetsmarkers import makemarker class tacticalauglinegraphdrawingeditormixin drawing def initself width height legendfalse args kw applydrawinginit self width height args kw chartfont font gothambold selfaddself lineplot name chart validatenone descnone selfchartinfill selfchartx selfcharty selfchartwidth selfchartheight selfchartlinelabelformat selfchartyvalueaxisvaluemin selfchartyvalueaxisvaluemax selfchartyvalueaxisvaluestep def applycolorsself colors selfchartlinesstrokecolor colors selfchartlinesstrokecolor colors selfchartlinesstrokecolor colors selfchartlinesstrokecolor colors | 3 |
strings immutable modify directly create new string existing one try lens return else return | i using python trying find solution problem get string certain function need switch first last character example string hello return oellh slicing work cant replace characters like normally dont know string going long would i thought replacing character position character position cant find something enable does anyone suggestions | 2 |
use following xpath expression nsentrynscontentname type directory | i filesyste represented xml document following format xml xmlnsnamespace xmlnsnsnamespace entry idid nscontent nametypedirectorynscontent nscontent namenumerrorsnscontent entry entry idid nscontent nametypefilenscontent nscontent namedocstatesuccessnscontent entry xml what i need using python lxml retrieve entry objects represent directories all entries contain nscontent namedocstate object i need know retrieve list entry objects object text equal directory i several inconvenient steps i would rather one query here way i would steps xmlparsepy ns ns namespace ns namespace node treexpathnsentrynamespacesns nodefindnscontentname type textdirectory stuff node pass can anyone explain within statement instead using thanks | 3 |
lens else this swap everything except edge cases single char the snippet code slices string three chunks the end chunks swap first last letters middle chunk grabs middle string below i show chunk interpreter hello ell h you slice string length index errors fact reason swap character string that else protects if understand else works read snippet this returns expr expr true otherwise returns expr expr expr else expr the expression short hand expr expr else expr i hope made sense | i using python trying find solution problem get string certain function need switch first last character example string hello return oellh slicing work cant replace characters like normally dont know string going long would i thought replacing character position character position cant find something enable does anyone suggestions | 3 |
what want search something called sqlstate set standard error codes cover common rdbms error states they necessarily provide enough detail purposes though i know sqlite supports httpwwwpostgresqlorgdocsstaticerrcodesappendixhtml httpdevmysqlcomdocrefmanenerrorhandlinghtml | in project i started mysql database instead checking first i insert i get integrityerror exception code i know duplicate entry warn user looks basically like try add duplicate nothing bad happens yet sqla session dbsessionadduseremail alreadyusedemailaddressthathastobeuniquecom commit integrityerror raised sqla inserts dbsessioncommit except integrityerror e dbsessionrollback mysql check exception code replace something db independent code msg eorig code send warning pass now one makes already impossible test eg inmemory sqlite not nice i could live second however i might towant scope question issues switch postgres of course i could change code also check postgres error codes i hoping way sqlalchemy tell duplicate happened independent database a database dialect abstraction | 2 |
i add yet another option list define variable newline use inside doublequotes nl n summary today date poor whiskers takes tumblenlshe fine though worry | first take look question bash googlecl new line string parameter i want add variable date summary google youtube post videoscatfallsdownstairsavi comedy tags currency internet summary today date poor whiskers takes tumblenshe fine though worry variable wont expand inside single quote bash is possible note googlecl commandline program written python i ubuntu python | 2 |
the web page reopened single ie instance using one pamie instance if really want multiple ie windows open use multiple pamie instances here one simple crude example note import line may slightly different mine pamie import pam ie pampamiehttpwwwgooglecom ie pampamiehttpnewsgooglecom so use ienavigate ienavigate etc fill forms websites for example use first ie instance iesettextboxqmy text goes ieclickbuttonbtnk and done instance kill leave web page open done anything else kills python object ie none | i using pamie auto log websites i couple i got scripts i get pamie open new ie window i run script opens one logs next one open closes first opens second so i get pamie open new windows this i websitehttpswebsite ienavigatewebsite iesettextboxusernamemyusername iesettextboxpasswordmypassword ieclickbuttonbtnsubmit then i want need new window websitehttpswebsite ienavigatewebsite iesettextboxusernamemyusername iesettextboxpasswordmypassword ieclickbuttonbtnsubmit i tried ienew navigatewebsite someone could please tell command open new window i would appreciate i also trie iechangewindow get work thanks | 1 |
this exactly model managers class myactivemanagermodelsmanager def activeself return selffilterisactivetrue def onlineself return selffilterisonlinetrue class mymodel objects myactivemanager activeobjects mymodelobjectsactive onlineobjects mymodelobjectsonline | in django application several views may contain similar db queries for instance query entities isactive true isonline true during refactoring duplicate calls need moved function question filterquery function better placed into definition classentity but object know filter methods this seems typical solution may good design since selection feels feature external object on hand methods inside object create sideeffects seem pretty safe into modulenamespace dealing filtering like filterusers filterentities or somewhere else whats best practice | 2 |
as schildmeijer quoted tornado website i recommend using nginx serve static files having setup early convenient easy this also allows potential benefits future using nginx load balancing using nginx handle ssl | i directory structure setup like root js css libs indexhtml from tornado i want serve js css libs static directories i find serve one can done | 1 |
here i would first define string search remove extraneous characters tosearch this text string i typed hlelo i meant type hello import string exclude setstringpunctuation tosearch joinch ch tosearch ch exclude tosearch this text string i typed hlelo i meant type hello words settosearchsplit next use difflib library find close matches given word import difflib difflibgetclosematches hello words hello hlelo | i list keywords i trying find text string the exact matches works fine anyone aware library could help approximate matches instance list words i provide hello bye i like watch text string hlelo certain degree closeness any recommendations | 2 |
you could invoke windows shell command dir q parse output find owners subprocesscalldir q shelltrue | i writing script needs determine username owner files windows while i found solution using pywin i hesitant use i want add module dependency the script written python run bit plattforms i wondering different method maybe ctypes determine information | 2 |
v v cexecute update archive set date where id vv for cursorexecute pass sequence values sequence sequence values for cursorexecutemany contrast would want pass sequence sequences | how take two values sqlite v v vvv vvv conn sqliteconnect datedb c conncursor cexecute update archive set date where id vvvv vvvv work conncommit i know probably simple find anything net tnx | 1 |
beautifulsoup unicodedammit able detect encoding document even specified what happens run page question beautifulsoup import unicodedammit unicodedammithtmlstringunicode what specific line code throwing error sample problematic html | i plugging away hours i seem get bottom i website detail although others seem similar problem solutions given work i python script reads html website uses beautiful soup find things like head body h etc store utf mysql table seems straight forward i keep running unicodedecodeerror ascii codec decode byte xxxxxx when i encode i tried everything i find stop happening avail here one version code soup beautifulsoupstrindexpage strindexpagebody strsoupbody strindexpagebody strindexpagebodyencode ascii ignore i know ignore best practice i really interested anything outside ascii character set strindexpagebody strindexpagebody replace ampquot strindexpagebody strindexpagebody replace amprsquo an earlier version i tried convert utf works better i end character present html breaks mysql insertupdate obviously i tried searching character replacing python tells i non ascii character code i read tons articles say i looking encoding html first decode encode suit encoding always come back bs andor declared within html i sure simple way around i find thanks help | 1 |
there technique strip accents characters characters need directly replaced check article httpeffbotorgzoneunicodeconverthtm | know wether trivial i need convert unicode string ascii string i like escape chars around i mean possible approximate conversion quite similar ascii character for example gavin oâconnor gets converted gavin oxconnor i really like converted gavin o connor is possible did anyone write util i manually replace chars thank much marco | 1 |
import unicodedata unicodestring ugavin oâconnor print unicodedatanormalize nfkd unicodestringencode ascii ignore output gavin o connor here document describes normalization forms httpunicodeorgreportstr | know wether trivial i need convert unicode string ascii string i like escape chars around i mean possible approximate conversion quite similar ascii character for example gavin oâconnor gets converted gavin oxconnor i really like converted gavin o connor is possible did anyone write util i manually replace chars thank much marco | 1 |
use unidecode package transliterate string import unidecode unidecodeunidecodeu gavin oâconnor gavin o connor | know wether trivial i need convert unicode string ascii string i like escape chars around i mean possible approximate conversion quite similar ascii character for example gavin oâconnor gets converted gavin oxconnor i really like converted gavin o connor is possible did anyone write util i manually replace chars thank much marco | 3 |
b straencode utf decode ascii ignore work fine | know wether trivial i need convert unicode string ascii string i like escape chars around i mean possible approximate conversion quite similar ascii character for example gavin oâconnor gets converted gavin oxconnor i really like converted gavin o connor is possible did anyone write util i manually replace chars thank much marco | 3 |
python float builtin set stone you change you could use float numpy | is anyway i ask python explicitly treat floats bits even bit machine i want change codes | 2 |
filter returns iterator python iterator consumed first run inner forloop after measuring speed contructor repeat often make consume least bit time so seems constructor set fastest one dealing empty iterator | iâm running filter interable want store result sequence i need sequence i use randomchoice i noticed creating set filter object lot faster creating list tuple why i first though filter type subtype set would explain filter function actually identical generator expression cannot really set internally i ran following test check speed import time def test n seq method set list tuple timetime range n method seq print methodname timetime somefilter filter lambda x x range test somefilter and results speaking clearly using set set list tuple so creating set filter much faster shouldnât usually take long creating set sequence every element hashed or somehow getting boost internal filter representation for comparison running test range expression set takes twice long list tuple nearly identical speed edit svenâs answer totally right completeness updated test run actual filter import time def testfilter n test rangesize method set list tuple timetime range n method filter test range rangesize print methodname timetime testfilter lambda x x the result actually shows makes sense list tuple fastest although set isnât really slower wonât make difference use set list tuple | 3 |
why use youtube data api the video feed contains gdrating average max min numraters rel httpschemasgooglecomgoverall within entry | lots results php likedislike results youtube nothing python i want scrape number likes dislikes using beautifulsoup youtubeapi include i know likes dislikes contained within spanclass span classwatchlikesdislikes span classlikesspan likes span classdislikesspan dislikes span thank | 2 |
when timings suggest results illogical often timing suite fault try using timeit module help steer clear common timing mistakes in particular want run fresh setup test time loop body rather body plus test code in case would least made timings comparable would used fresh iterator returned python version filter would shown unbelievably fast timings methoditerator code would timed loop fwiw pypy even harder time overly simple loops get optimized away completely answer question edited you new timings comparable good improvement results still show combination setup time loop time making difficult see differences might significant your expectation lists tuples beat sets sets work hashing inputs rather simply storing | iâm running filter interable want store result sequence i need sequence i use randomchoice i noticed creating set filter object lot faster creating list tuple why i first though filter type subtype set would explain filter function actually identical generator expression cannot really set internally i ran following test check speed import time def test n seq method set list tuple timetime range n method seq print methodname timetime somefilter filter lambda x x range test somefilter and results speaking clearly using set set list tuple so creating set filter much faster shouldnât usually take long creating set sequence every element hashed or somehow getting boost internal filter representation for comparison running test range expression set takes twice long list tuple nearly identical speed edit svenâs answer totally right completeness updated test run actual filter import time def testfilter n test rangesize method set list tuple timetime range n method filter test range rangesize print methodname timetime testfilter lambda x x the result actually shows makes sense list tuple fastest although set isnât really slower wonât make difference use set list tuple | 2 |
it known issue ipython it fixed hopefully christmas | ipython i set automatic launch pdb exceptions in ipython works fine in zerodivisionerror traceback recent call last homezoncaipython console module zerodivisionerror float division zero ipython consolemodule ipdb instead ipython exception not visible in ipythoninputebfbdamodule ipdb i see i exit debugger in ipythoninputebfbdamodule ipdb zerodivisionerror traceback recent call last homezoncaipythoninputebfbda module zerodivisionerror float division zero in anybody else issue i ubuntu python ipython installed pip | 1 |
you could find files created modified last halfhour looking mtime file import os import datetime dt dtdatetimenow ago nowdttimedeltaminutes root dirsfiles oswalk fname files path ospathjoinroot fname st osstatpath mtime dtdatetimefromtimestampststmtime mtime ago print modified path mtime to generate list deleted files also list files minutes ago a robust alternative use revision control system like git making commit files directory like making snapshot then command git status would list files changed since last commit this list files deleted | i know list subdirectories files directory tree but i looking way list newly created files modified possible deleted files directories directory tree starting root directory | 3 |
looks like need qpixmapfill pyqt import qtgui class windowqtguiqcombobox def initself qtguiqcomboboxinitself selfresize pixmap qtguiqpixmap color red orange yellow green blue grey violet split pixmapfillqtguiqcolorcolor selfadditemqtguiqiconpixmap colortitle name main import sys app qtguiqapplicationsysargv win window winshow sysexitappexec | i know possible i cannot life get proper code work what i want simple monochromatic rectangle size say x constructed presumably qpainter from i wish use painted rectangle qicon use qcombobox any ideas thanks advance | 2 |
this size float baked compilation time you pass compile option treat c double float fresh python executable file | is anyway i ask python explicitly treat floats bits even bit machine i want change codes | 1 |
for worth simple numpy numpyarangereshape array block block numpyrotblock copy array | x matrix list lists python the matrix divided square blocks size x i want way take transpose block i using traditional method going element copying another array back i want see better way transposing matrix python done one line using zip method eg representation matrix blocks block block block block rotate right result block block block block i want find method takes block number rotates block left right is easy way | 2 |
note getting decode error call encode this ugliest part python lets try encode string already encoded first decoding ascii what equivalent sdecode ascii strict encode ascii ignore i think expect soup beautifulsoupstrindexpage strindexpagebody unicodesoupbody strindexpagebody strindexpagebodyencode ascii ignore note calling unicode get unicode string validly try encode | i plugging away hours i seem get bottom i website detail although others seem similar problem solutions given work i python script reads html website uses beautiful soup find things like head body h etc store utf mysql table seems straight forward i keep running unicodedecodeerror ascii codec decode byte xxxxxx when i encode i tried everything i find stop happening avail here one version code soup beautifulsoupstrindexpage strindexpagebody strsoupbody strindexpagebody strindexpagebodyencode ascii ignore i know ignore best practice i really interested anything outside ascii character set strindexpagebody strindexpagebody replace ampquot strindexpagebody strindexpagebody replace amprsquo an earlier version i tried convert utf works better i end character present html breaks mysql insertupdate obviously i tried searching character replacing python tells i non ascii character code i read tons articles say i looking encoding html first decode encode suit encoding always come back bs andor declared within html i sure simple way around i find thanks help | 2 |
httpdocspythonorgtutorialfloatingpointhtml almost machines today july use ieee floating point arithmetic almost platforms map python floats ieee âdouble precisionâ doubles contain bits precision input computer strives convert closest fraction form jn j integer containing exactly bits it looks like sized floats bit machine neither bits if must bit floats either use virtual machine run version python use bit floats though i idea thing exists compile idea you able use bit python version bit machine though change way floats work i think main difference bit bit python ram use bit use ram also ram hungry | is anyway i ask python explicitly treat floats bits even bit machine i want change codes | 1 |
use csvreader parse file dictionary cluster results the strrpartition method splitoff seconds use sum len compute average data splitlines import csv timestamp value csvreaderdata minute colon second timestamprpartition minute dminute floatvalue else dminuteappendfloatvalue minute values sortedditems avgvalue sumvalues lenvalues print minute stravgvalue | i big csv file datetime value recorded every seconds the csv file looks like datetime data i want write script would calculate minute average write new csv file giving following output datetime data any idea done suggestions modules i look examples | 1 |
it seems easiest way treat time string rather time use itertoolsgroupby csv import reader itertools import groupby lines datetime data lines iterlinessplitlines testing really open filename rb lines indent rest nextlines minute group groupbyreaderlines lambda row row group listgroup print minute sumfloatrow row group lengroup | i big csv file datetime value recorded every seconds the csv file looks like datetime data i want write script would calculate minute average write new csv file giving following output datetime data any idea done suggestions modules i look examples | 1 |
edit i recommend using greenlet but interested pure python approach read this addressed pep somewhat tough understand first i try explain simply works first let sum i think problem really trying solve problem you callstack generator functions calling generator functions what really want able yield generator top yield propagate way stack the problem python language level support real coroutines generators but implemented real coroutines allow halt entire stack function calls switch different stack generators allow halt single function if generator f wants yield yield statement f another function f calls the solution i think using something like simon stelling answer ie f call g yielding g results this verbose ugly looking syntax sugar wrap pattern note essentially unwinds stack every time yield winds back afterwards solution there better way solve problem you basically implement coroutines running generators top trampoline system to make work need follow couple patterns when want call another coroutine yield instead returning value yield def f result g ⦠return returnvalue becomes def f result yield g ⦠yield returnvalue say f the trampoline system called f when yield generator say g trampoline system calls g behalf then g finished yielding values trampoline system restarts f this means actually using python stack trampoline system manages callstack instead when yield something generator trampoline system treats return value it passes value back caller generator yield statement using send method generators comments this kind system extremely important useful asynchronous applications like using tornado twisted you halt entire callstack blocked go something else come back continue execution first callstack left the drawback solution requires write essentially functions generators it may better use implementation true coroutines python see alternatives there several implementations coroutines python see httpenwikipediaorgwikicoroutineimplementationsforpython greenlet excellent choice it python module modifies cpython interpreter allow true coroutines swapping callstack python provide syntax delegating subgenerator see pep | i studying coroutines generators various programming languages i wondering cleaner way combine together two coroutines implemented via generators yielding back caller whatever callee yields let say using following convention yields apart last one return null last one returns result coroutine so example could coroutine invokes another def a yield certain condition met yield result def b something may may yield x binda return result case i wish bind may may implementable question coroutine b yields whenever a yields a returns final result assigned x allowing b continue i suspect actual code explicitly iterate a def b something may may yield x a return result tad ugly error prone ps game users language designers write scripts script coroutine each character associated script many subscripts invoked main script consider example runship invokes many times reachclosestenemy fightwithclosestenemy fleetoallies all subscripts need invoked way describe developer problem designer less code write better | 3 |
here excerpt one batch files rem configure environment bit builds rem use vcvarsbat bit build cprogram files xmicrosoft visual studio vcbinvcvarsbat rem convince setuppy use sdk tools set mssdk set distutilsusesdk the sdk uses effectively vs python compiled vs if use sdk i think also known net sdk access vs compiler it risky mix different compilers runtimes libraries | i trying compile simple cython extension example page windows bit machine python bit version installed i installed cython windows bit version gohlke page basically answer options i really need python bit version address larger memory also i trying compile using microsoft sdk net i cannot use approach latter solution i tried steps observed green window compilation throws cannot find vcvarsallbat error following sequence commands i tried ccd program filesmicrosoft sdkswindowsv cprogram filesmicrosoft sdkswindowsvset distutilsusesdk cprogram filesmicrosoft sdkswindowsvsetenv x release setting sdk environment relative cprogram filesmicrosoft sdkswindowsv targeting windows x release cprogram filesmicrosoft sdkswindowsve ecd cython ecythonpython setuppy buildext inplace running buildext skipping fibc cython extension uptodate building fib extension error unable find vcvarsallbat any suggestions i solve | 3 |