text_a
stringlengths
5
12.3k
text_b
stringlengths
36
15.7k
Score
int64
1
3
you definitely generators create generator next call alternates getting next value returning putting multiple yield statements here example import itertools time def quickgen counter itertoolscountnext def longrunningfunc timesleep return counter true x longrunningfunc yield yield x itr quickgen itrnext setup call take...
i generator takes long time iteration run is standard way yield value generate next value waiting called the generator would called time button pressed gui user would expected consider result button press edit workaround might def initialize res nextgen def btncallback displayres res nextgen res return
1
strings foo bar applesplit
i new python essentially trying figure syntax replicates functionality strings foo bar apple something similar strings foo bar apple i put quotes around entries thanks
3
strings rfoo bar applesplit
i new python essentially trying figure syntax replicates functionality strings foo bar apple something similar strings foo bar apple i put quotes around entries thanks
1
you use subprocesspipe also split command use shlexsplit prevent strange behaviours cases subprocess import popen pipe shlex import split p popensplittar c mydir stdoutpipe p popensplitmdsum stdinpstdout but make archive generate checksum use python builtin modules tarfile hashlib instead calling shell commands
i run normally command line linux tar c mydir mdsum but i try call python i get error subprocesspopen tar c mydir mdsum shelltrue subprocesspopen object xc tar you must specify one acdtrux testlabel options try tar help tar usage information
3
ok i sure seems work subprocesscalltar c mydir mdsumshelltrue anyone know original code work
i run normally command line linux tar c mydir mdsum but i try call python i get error subprocesspopen tar c mydir mdsum shelltrue subprocesspopen object xc tar you must specify one acdtrux testlabel options try tar help tar usage information
1
you could place strings text file one string line then strings listopendatafile r
i new python essentially trying figure syntax replicates functionality strings foo bar apple something similar strings foo bar apple i put quotes around entries thanks
1
subprocess import popenpipe import hashlib proc popen tar c etchosts stdoutpipe stdout stderr proccommunicate hashlibmdstdouthexdigest acecf
i run normally command line linux tar c mydir mdsum but i try call python i get error subprocesspopen tar c mydir mdsum shelltrue subprocesspopen object xc tar you must specify one acdtrux testlabel options try tar help tar usage information
1
i would say easier way create list strings already as answers pointed ways put strings one big string file split opinion difficult type quotes particularly decent ide automatically closes string quotes also syntax already using anyone else reads code expect using something else adds unnecessary confusion almost zero ga...
i new python essentially trying figure syntax replicates functionality strings foo bar apple something similar strings foo bar apple i put quotes around entries thanks
1
there two major differences posted the quotes indicate string like would list integers if remove quotes essentially creating list python objects a python object basically foundation python classes eg integers strings python objects basic level you something like foo foo bar bar apple apple strings foobarapple
i new python essentially trying figure syntax replicates functionality strings foo bar apple something similar strings foo bar apple i put quotes around entries thanks
1
runserver developmenttesting it handle high load security etc pythonorg docs set proper webserver serve python code httpdocspythonorghowtowebservershtml
as experienced php programmer i tend avoid things like python however must play cards dealt i work satchmo website i little python django satchmo i need help i ok setting development server i cannot get website work production server i seen use python managepy runserver solution even stack overflow however i see soluti...
1
the code kevin jacobs former question employs biopython uses sequences type seq â« essentially strings letters like agtacactggt seems natural since common way sequences seen biological file formats â» â« there two important differences seq objects standard python strings first different methods secondly seq object impo...
i trying something similar previous question my purpose join sequences equal but time instead letters i numbers alignment file found phylip file problem i try records listseqioparsefilefilename phylip i get error valueerror sequence length expected length i understand second file i creating first one worked perfectly b...
1
satchmo seems like django derivative setting django production quite easy deployment environment linux apache use modwsgi well documented windows use pyisapie module follow documentation hope helps
as experienced php programmer i tend avoid things like python however must play cards dealt i work satchmo website i little python django satchmo i need help i ok setting development server i cannot get website work production server i seen use python managepy runserver solution even stack overflow however i see soluti...
1
to deploy django website production server serve either apachemodwsgi nginxgunicorn nginxuwsgi server supporting wsgi the django documentation page deploying django apache modwsgi solutions plenty useful documentation around web
as experienced php programmer i tend avoid things like python however must play cards dealt i work satchmo website i little python django satchmo i need help i ok setting development server i cannot get website work production server i seen use python managepy runserver solution even stack overflow however i see soluti...
1
django automatically creates default permissions every model add delete change you getting integrity error trying create permissions name just remove delete meta description everything ok
i trying purge database mydb repopulate see effects changes django model then happened i rolled back earlier model setup i still get errors i mysql pro i can’t quite figure problem i tried creating new database another name didn’t happen i assume problem created django project here info cuserspython managepy syncdb...
3
i used pyc innosetup create installers you also download run wix command line without using develop visual studio the key make sure include dll need ngen install shorter start times better performance
i using sharpdevelop visual studio ironpython app development i reasons using app development what console based options compiling ironpython exe file packaging manually is possible create executable app ironpython pack using installer
1
do mean maximum filter if look scipyndimagemaximumfilterd as quick example import numpy np import scipyndimage ndimage input npsinnplinspace nppi input input astypenpint makes easier read output ndimagemaximumfilterdinput print in input print out output this yields in out
do happen d nonmaximum suppression algorithm written python i need making canny edge detector python using scipy takes input d intensity vector i looked around web lot information describing behavior canny edge detector examples written java describe edge detection d however scipy support algorithms needed canny edge d...
1
you basically rand bend int result rand rangeend rangestart rangestart to explain rand generates random number across subset integer values you use modulo lo limit range numbers use start value provide offset also sure seed random number generator note rand apparently pretty lousy random number generator i idea see com...
just switch python c i begin rewrite python tools c better understanding solve one this function generate range random numbers example randomrange may return range numbers like python def randomrangen rangestart n rangeend n return randintrangestart rangeend number randomrange c int n int randomrangen int rangestart in...
1
first look how split list evenly sized chunks python using one answers import itertools networktable cluster one primary system node one xxxx node ip node two xxxx node ip cluster two primary system node one xxxx node ip node two xxxx node ip l networktableii range lennetworktable l cluster one primary system node one ...
i building python script network inventory internal system each system five clusters i looking way adjust list put one line per cluster here way stored system cluster one primary system node one xxxx node ip node two xxxx node ip cluster two primary system node one xxxx node ip node two xxxx node ip i need adjusted loo...
1
you trouble getting good randomness high values n include mathh pow include stdlibh drand long randomrangeint n method needs start size range rather start end long rangestart pown long rangesize pownrangestart expect rand functions offer randomness morewellknown rand function drand gives doubleprecision float scale ran...
just switch python c i begin rewrite python tools c better understanding solve one this function generate range random numbers example randomrange may return range numbers like python def randomrangen rangestart n rangeend n return randintrangestart rangeend number randomrange c int n int randomrangen int rangestart in...
2
you look facilities boost httpwwwboostorgdoclibsdochtmlboostrandomtutorialhtmlboostrandomtutorialgeneratingintegersinarange
just switch python c i begin rewrite python tools c better understanding solve one this function generate range random numbers example randomrange may return range numbers like python def randomrangen rangestart n rangeend n return randintrangestart rangeend number randomrange c int n int randomrangen int rangestart in...
2
you work around throwing exception catching middleware httpdjangosnippetsorgsnippets
i absolute novice djangocms i gone tutorial configured exactly mentioned documentation now i build application uses form upload products i dont clue move ahead i want start simple forms say username password textbox kind how i use django forms djangocms page i snippet plugin enabled i need guidance any suggestions plss...
1
i think covered options you either subclass monkeypatch typically monkeypatching actually changing rd party class runtime frowned upon depending change need make may way work around bug make sure every time class used new method since tests use method tests monkeypatching unnecessary quite reasonable subclass testcase ...
i special cases i need test django i trying extend existing django tests writing test cases here i currently djangotests import testcase define method function def assertoptionsequalself first second logic pass attach method testcase class this feels inelegant testcaseassertoptionsequal assertoptionsequal tests go clas...
1
if i wanted something like workaround i write class like class prefetchedgeneratorobject def initself generator selfdata generatornext selfgenerator generator selfready true def nextself selfready selfprefetch selfready false return selfdata def prefetchself selfready selfdata selfgeneratornext selfready true it compli...
i generator takes long time iteration run is standard way yield value generate next value waiting called the generator would called time button pressed gui user would expected consider result button press edit workaround might def initialize res nextgen def btncallback displayres res nextgen res return
1
ok i seems solution answer persay way moving multipoint differential i tested result looks similar moving regression i used d sobel filter ramp convolved data def kdpphidp dx fitlen kdpnpzerosphidpshape dtypefloat myshapekdpshape swn rangemyshape print sweep swn rayn rangemyshape print ray rayn kdpswn rayn sobelphidpsw...
i d array data wish extract spatial variation the standard way i wish pythonize perform moving linear regression data save gradient def nsslkdpphidp distance fitlen kdpzerosphidpshape dtypefloat myshapekdpshape swn rangemyshape print sweep swn rayn rangemyshape print ray rayn smallpolyfitdistanceaafitlen phidpswn rayn ...
1
here reasons i think would wrong extra code complexity without big need adding one line settings every time bad especially step become explicit apps project using when another developer work project might know app installed step step code versioning system test whole system commit changes deploy i think something wrong...
i written django app i want make easy deploy multiple servers the basic installation copy app folder django project folder add installedapps settingspy run managepy collectstatic this particular app need use db i use south run managepy migrate another story the part i trouble i want manually edit file every time what e...
1
why use module directly pointed models singletons if create module like mymodulepy mydb import connection connection connection host port use import mechanism connection instance everywhere mymodule import connection of course define much complex initialization connection possibly via writing class point python initial...
i wondering implementing singleton class following httpcodeactivestatecomrecipesthesingletonpatternimplementedwithpython wondering blocking issues my code suppose cache sql statements execute cached statements using cursorexecutemanysql listofparams certain number cached elements reached specific executecall done user ...
1
python enforced private anything convention letting others know methodfunctionclasswhathaveyou private prefix single leading underscore thirdparty programs use autodocumenting systems help idle ignore names your code would translate like class circleobject python need object member none needed since three initialized m...
i need following structure python public class circle int member int member int member public circlemember thismember member initializerest private intializerest lot computation get result amp result thismember result thismember result
1
i missing point question there takesnapshot function bit actually takes snapshot commented modify code look like following def takesnapshotselfwidget filename strtimetime jpg pixbuf gtkgdkpixbufgetfromdrawableselfmoviewindowwindow selfmoviewindowwindowgetcolormap pixbufsavefilename jpeg quality take snapshot save image...
i code monitoring webcam python pygtk the question i take snapshot code usrbinenv python import sys os import pygtk gtk gobject import pygst pygstrequire import gst import time class webcam def initself window gtkwindowgtkwindowtoplevel windowsettitlewebcamviewer windowsetdefaultsize windowconnectdestroy gtkmainquit wm...
1
tar file headers include field modified time file act changing file even change later changed back mean tar file headers different leading different hashes
i trying write python script get mdsum files directory linux which i believe i done code i want able run make sure files within directory changed files added deleted the problem i make change file directory change back i get different result running function even though i changed modified file back can anyone explain a...
3
tar files contain metadata beyond actual file contents file access times modification times etc even file contents change tar file fact different
i trying write python script get mdsum files directory linux which i believe i done code i want able run make sure files within directory changed files added deleted the problem i make change file directory change back i get different result running function even though i changed modified file back can anyone explain a...
1
you need make tar file propose here workaround algorithm walk directory tree take md signature file sort signatures take md signature text string signatures individual files the single resulting signature looking heck even need python you find pathtodir type f name py exec mdsum awk print sort mdsum
i trying write python script get mdsum files directory linux which i believe i done code i want able run make sure files within directory changed files added deleted the problem i make change file directory change back i get different result running function even though i changed modified file back can anyone explain a...
2
as answers mentioned two tar files different even contents either due tar metadata changes file order changes you run checksum file data directly sorting directory lists ensure always order if want include metadata checksum include manually untested example using oswalk import os import ospath def getdirmddirroot build...
i trying write python script get mdsum files directory linux which i believe i done code i want able run make sure files within directory changed files added deleted the problem i make change file directory change back i get different result running function even though i changed modified file back can anyone explain a...
3
it possible get email user connected app using graph however connecting signing using facebook users must explicitly give permission use email address since none friends gave permission email addresses limits what means encourage user friends join well make sure sign include request email address
i using djangosocialregistration facebook python sdk this code get friends friends requestfacebookgraphgetconnections friends i get name id i get email address facebookcom email this another attempt also get email friend friends data requestfacebookgraphgetobjectfriend id how i get facebook friends email
1
if want lock either use globals use threadlocal storage webapp fairly sure request cross thread boundary if global state avoided avoided this makes multithreading way easier implement debug i also disagree passing objects around makes application harder maintain — usually way around — global state hides dependencie...
after reading lot subject discussing irc response seems stay away threads sorry repeating question intention go deeper subject accepting threading evil answer hope find common solution edit just say no combined evils locking deadlocks lock granularity livelocks nondeterminism race conditions guido van rossum i developi...
3
i would proces lines based name begin seems cluster specifies new set data file open myfile clusters line filereadline linestripstartswithcluster cluster clusterappendlinestrip line filereadline clusterappendlinestrip line filereadline linestripstartswithnode node nodeappendlinestrip line filereadline nodeappendlinestr...
i building python script network inventory internal system each system five clusters i looking way adjust list put one line per cluster here way stored system cluster one primary system node one xxxx node ip node two xxxx node ip cluster two primary system node one xxxx node ip node two xxxx node ip i need adjusted loo...
1
read httpwwwsqlalchemyorgdocscoreschemahtmldefiningsequences key generation part database you simply want database assign unique keys
i created simple db using sqlalchemy python column unique user id user entered i want running counter supplies next id whenever new user added what would best way implement a column value last id number would entirely separate table seems wasteful is way check last userid add one here user base class class userbase tab...
3
some additional details implement keyboardinteractive authentication i thought i working first time server sends two interactive requests the first requests contains prompt password false the second contains empty prompt the code works every server i tested far redhat ubuntu opensuse twistedconchssh import keys useraut...
i trying override default authentication scheme twisted conch module something i thought i understood the script answer question i subclassing sshuserauthclient following way class clientuserauthsshuserauthclient def getpasswordself prompt none return defersucceed i obviously replacing sshuserauthclient call call class...
2
you also use spynner allows programmatic web browsing
i’m writing little private app automatically log internet banking every day download latest transactions i’m writing django app i’m working python my internet banking doesn’t seem work without javascript — i think uses javascript assign session id sort fetching signin page via httplib gives page telling javas...
2
one thing might help use lists list comprehension statements loops eg qcount intrawinput how many questions per quiz quizitems strsamplerx x rangeqcount usersel mydictbookx x quizitems answers rangeqcount nextanswer intrawinput nwhich number sampleri answersappendbooksnextanswer
in code shows neophyteness python i took books kjv bible put logical order via list dictionary i used random method display random books user along position book random list user match something better learn books bible my difficulty figuring go saving results tallying number correctwrong i also would like give user op...
1
my difficulty figuring go saving results tallying number correctwrong i also would like give user option choose number questions like can someone give direction i guess something like right wrong numsamp rawinputenter amount samples xrangenumsamp answer intrawinput nwhich number sampleri bookanswer sampleri rightright ...
in code shows neophyteness python i took books kjv bible put logical order via list dictionary i used random method display random books user along position book random list user match something better learn books bible my difficulty figuring go saving results tallying number correctwrong i also would like give user op...
1
depending want handle edge cases seems work def pointsbetweenp p xs rangep p p ys rangep p p return xy x xs ys print pointsbetween print pointsbetween
this fairly easy i getting headache trying figure i want list coordinates two points like in or in it need work diagonals
1
you appear beginning programmer a general technique i find useful job paper look translate program if see break simpler steps
this fairly easy i getting headache trying figure i want list coordinates two points like in or in it need work diagonals
2
maybe django httpwwwgoogleplsearchqdjangotreemenu js httpwwwgoogleplsearchqjavascripttreemenu better jquery httpwwwgoogleplsearchqjquerytreemenu anyway simple cases hard make impl
i web app three frames banner menu content the menu frame needs dynamic rollup menu example teachers create edit delete schools create edit delete view staff classrooms create edit delete if click schools hideunhide items the menu needs dynamically drawn user login based user group role some users may authorized see cl...
1
simple implementation using jquery div idmenu ateachersabr div styledisplay none hrefeditabr hrefdeleteabr div aschoolsabr div styledisplay none hrefeditabr hrefdeleteabr div div script typetextjavascript srchttpajaxgoogleapiscomajaxlibsjqueryjqueryminjsscript script typetextjavascript menu clickfunction thisnextnextsl...
i web app three frames banner menu content the menu frame needs dynamic rollup menu example teachers create edit delete schools create edit delete view staff classrooms create edit delete if click schools hideunhide items the menu needs dynamically drawn user login based user group role some users may authorized see cl...
3
if absolutely know final size array increment size array like myarr numpyzeros range myarrnumpyconcatenate myarr numpyones printmyarr notice first line numpyappend another option it calls numpyconcatenate
i figure use array matrix way i would normally use list i want create empty array matrix add one column row time at moment way i find like mat none col columns mat none mat col else mat hstackmat col whereas list i something like list item data listappenditem is way use kind notation numpy arrays matrices
1
looks like smth windowsspecific did try provide full path python executable command line like ccodepythonbinpythonexe managepy celerydmulti start settingssettings l info also use full paths python file usefull ccodepythonbinpythonexe cpathtoyourprojectmanagepy celerydmulti start settingssettings l info
so far i working python managepy celeryd starting like python managepy celeryd l info settingssettings the code view binaryexectaskdelayrequestpostbinarypath and code settingspy import djcelery djcelerysetuploader brokerbackend djkombutransportdatabasetransport celery brokerhost localhost brokerport brokeruser guest br...
1
two ideas come mind test another robust webserver nginx it run concurrently need see problem persists while paste handle web apps meant handle huge file transfers far i know are using chunked transfer encoding upload
so i rather vexing issue file uploads pylons i hoping someone might able assist originally i posted issue thinking issue pylons i since come conclude issue due server ie paste i tracked exactly issue occurs unsure resolve the behavior follows i pylons web application i serving via paster one piece application allows us...
1
it like says fileopened openfno w that line code problem typeerror coercing unicode need string buffer file found that problem w string clearly fno causes problem the problem string buffer needed actually file you need string buffer filename parameter open the purpose open open files given file name already file so use...
why error appear error exception tkinter callback traceback recent call last file cpythonliblibtktkinterpy line call return selffuncargs file editorpy line onopen fileopened openfno w typeerror coercing unicode need string buffer file found code httpscodegooglecompchildreneditorsourcebrowsetrunkeditornewpy
1
you need set size request textview container scroll example window textview try following import gtk name main window gtkwindowgtkwindowtoplevel scroll gtkscrolledwindow scrollsetpolicygtkpolicynever gtkpolicyalways view gtktextview viewsetwrapmodegtkwrapchar scrollsetsizerequest scrolladdview windowaddscroll windowsho...
i textview inside scrolledwindow refuses wrap wordscharswordschars matter i set wrap mode it simply extends size containers pleases here example import gtk window gtkwindowgtkwindowtoplevel windowsetdefaultsize scroll gtkscrolledwindow scrollsetpolicygtkpolicynever gtkpolicyalways view gtktextview viewsetwrapmodegtkwra...
1
you use one following css rule graphicsviewsetstylesheetborderwidth px borderstyle solid graphicsviewsetstylesheetborder px your border disappear import sys pyqtqtgui import class uiqwidget def initself parentnone qwidgetinitself parent graphicsview qgraphicsview graphicsviewsetstylesheetborder px grid qgridlayout grid...
i tried calling selfsetstylesheetbackground transparent border transparent qgraphicsview still leaves pixel border top edge i also tried replacing border transparent borderstyle none work either here screenshot problem what command fully remove border qgraphicsview
2
after posting i discovered nifty little library ftputil httpftputilsschwarzernet presents different ftp interface cribs much os ospath modules possible using final code went roughly like import ftputil host ftputilftphostconstantsftphost constantsftplogin constantsftppass hostmakedirspath hostclose
i ftp ing pile files python directory trees may exist is ftp version makedirs available somewhere i build scratch
1
you actually creating entity key you change counter counterdbkeyfrompath counter defaultcounter counter counterkeydbkeyfrompath counter defaultcounter and since immediately setting amount could initializing entity well counter counterkeydbkeyfrompath counter defaultcounter amount please also note good way create counte...
i first small project pythongae difficulty operating gae database using queries but comes editing single entity i face problem all i need simple counter would increment every site visit so i create entity done create entity code removed project countername defaultcounter def counterkeycounternnone return dbkeyfrompath ...
1
the code use create counter entity likely wrong what creating counter entity whose parent counter keyname equal defaultcounter that seem want evidenced code use update counter you need assign keyname counter entity via one following ways counter counterkeyname defaultcounter counter counterkeydbkeyfrompath counter defa...
i first small project pythongae difficulty operating gae database using queries but comes editing single entity i face problem all i need simple counter would increment every site visit so i create entity done create entity code removed project countername defaultcounter def counterkeycounternnone return dbkeyfrompath ...
1
import time timesleep this sleep seconds see httpdocspythonorglibrarytimehtmltimesleep
i working integrate api limit number requests per second is way running loop python delay cycle conceptually something like def functionrequest x abcd something wait seconds thank
3
create index tuple first index numpyst xindex
suppose i defined xx numpy array x numpyarangereshape now i get array containing element x subarray x returns array what i tuple mn want retrieve mn element subarray stored tuple for example suppose i i tried x right behaviour returns rows subarray the simplest solution i found xtransposetuplereversedttranspose i sure ...
3
replace angle angle pi
i created simple polar plot using matplotlib i trying make plot degrees top clock position rather righthand side clock position i see simple way matplotlib documentation i found older question stackoverflow accepted answer seem work year old i thought may better way any ideas
2
perhaps i missing something django objects dict attribute seems want
if came google looking model dict skip question jump first answer my question confuse is good way django entire set model objects single dictionary i mean like class dictmodelmodelsmodel key modelscharfield value modelscharfield dictmodelobjectsalltodict result dictionary keyvalue pairs made records model has anyone el...
2
collections import defaultdict dictb defaultdictlist b listb dictbb id appendb lista things b dictba id things appendb turn algorithm onm omon nlenlista mlenlistb basically avoids looping dict listb dict lista precalculating dicts listb match id
i lists dictionaries list a long list b long i essentially inserting list b dicts list a dicts based key match currently i obvious taking forever seriously like day there must quicker way lista things b listb id b id things appendb
2
here approach may help i leave fill details your code slow on algorithm comparing every a every b if sort lista listb id first onlogn operations iterate easily sorted versions a b linear time this approach common external merges large data sets mihai answer better internal merging simply index everything id memory if m...
i lists dictionaries list a long list b long i essentially inserting list b dicts list a dicts based key match currently i obvious taking forever seriously like day there must quicker way lista things b listb id b id things appendb
1
there optional saveas parameter sendblob function by default set false setting true cause file treated attachment ie trigger saveopen download dialog user see proper filename example class servehandlerblobstorehandlersblobstoredownloadhandler def getself resource resource strurllibunquoteresource blobinfo blobstoreblob...
i using google app engine blobstore store range file types pdf xls etc trying find mechanism original filename uploaded file stored blobinfo used name downloaded file ie user sees somefilepdf save dialogue rather verylongdbkeypdf i see anything docs would allow httpcodegooglecomappenginedocspythonblobstoreoverviewhtml ...
3
import logging class progressconsolehandlerloggingstreamhandler a handler class allows cursor stay one line selected messages onsameline false def emitself record try msg selfformatrecord stream selfstream sameline hasattrrecord sameline selfonsameline sameline streamwriteselfterminator streamwritemsg sameline streamwr...
how write custom console log function output console window log messages single line append first regular log record progress progressconsolehandler console loggingstreamhandler logger logginggetlogger test loggersetlevelloggingdebug loggeraddhandlerconsole loggeraddhandlerprogress loggerinfo test range loggerprogress ...
3
you use javascript ajaxstyle post background save whatever information like click then redirect page success
the following html works user clicks word music shows html page ie httpssnuackrmusichtml href onclickparentcontentlocation httpssnuackrmusichtml return falsemusica my question user clicks word web way system server write clicked word music separate file server using python cgi i need store userclicked words separate fi...
1
import random import os name main books genesis exodus leviticus numbers deuteronomy joshua judges ruth i samuel ii samuel i kings ii kings i chronicles ii chronicles ezra nehemiah esther job psalms proverbs ecclesiastes song solomon isaiah jeremiah lamentations ezekiel daniel hosea joel amos obadiah jonah micah nahum ...
in code shows neophyteness python i took books kjv bible put logical order via list dictionary i used random method display random books user along position book random list user match something better learn books bible my difficulty figuring go saving results tallying number correctwrong i also would like give user op...
1
you could add results another table unless compelling reason calculated column adjacent columns probably easiest there something said separating raw data calculations anyways if must increase size table look using hpy it provides direct interface h file keep mind depending data set created h file may possible simply ap...
i trying append large dataset gb existing pytables table the table n columns dataset n columns one column calculated i know n columns i using numpyfromfile read chunks dataset memory appending database ideally i like stick data database calculate final column finish using tablemodifycolumn complete operation i consider...
1
this get started i current time passed function datetime argument est work def findnextcurdt import datetime dt dttime dttime dttime dttime curt curdttime curd curdtdate rangelent ti curt rt tjilent j rangelent rd curd lenti curd dttimedeltadaysi return dtdatetimecombinerdjrtj j rangelenrt everything happens tomorrow r...
i need generate four datetime objects python the next instance am est the next instance am est the next instance pm est the next instance pm est then i need find closest current datetime i wish i could say i starting code i idea start one
1
hyry solution correct i always found numpy r c index tricks bit strange looking so equivalent thing using slice object xslicenone that single argument slice stop position ie none meaning way x equivalent xnonenone
suppose i defined xx numpy array x numpyarangereshape now i get array containing element x subarray x returns array what i tuple mn want retrieve mn element subarray stored tuple for example suppose i i tried x right behaviour returns rows subarray the simplest solution i found xtransposetuplereversedttranspose i sure ...
2
you create yet another orm layer rather waste lot time reinventing wheel learn existing orm adapt one nosql database engine choice start example sqlalchemy orm want sql because python duck typing invent compatible nosql orm repository orm anything else think important do however reinvent wheel scratch read implementati...
i wondering ways accomplish abstracting data storage access away main application small example ioc framework seems overkill maybe passing object via constructor parameter facade pseudocode good way things fill missing pieces python mainpy resp repositoryenginenosql easily switch nosql respsavehello respselecthello rep...
1
if columns type use numpylibstridetricksasstrided make array read file shape l n look like shape l n for example in numpyarangereshape in out array in astrides out in b numpylibstridetricksasstrideda shape strides in b out array now use array b fill table the last column row first column next row overwrite compute valu...
i trying append large dataset gb existing pytables table the table n columns dataset n columns one column calculated i know n columns i using numpyfromfile read chunks dataset memory appending database ideally i like stick data database calculate final column finish using tablemodifycolumn complete operation i consider...
1
here one wxpython httpwxgladesourceforgenet
i hoping find tool similar borland delphi visualbasic python basically i want able program windows apps ease without actually code every single widget does software exist thanks
3
based comment i would simply create book class author class author list chapter class assign chapters book list chapter objects book maintain authorlist dict ids pointing actual author objects use data member book object contain id provide method pull author authorlist dict convenience
following xml file bookxml xml version sample xml document bookstore book ide title sample xml book title author name idau first benjamin first last smith last name affiliation a affiliation author chapter number title first chapter title para b count count para chapter chapter number title third chapter title para b c...
1
here using qt designer qt httpdiotavellinetpyqtwikicreatingguiapplicationswithpyqtandqtdesigner you might also want look traits it pretty easy simple designs
i hoping find tool similar borland delphi visualbasic python basically i want able program windows apps ease without actually code every single widget does software exist thanks
2
datetimeastimezone basic conversion datetime object if trying get datetime object string pip install pythondateutil simple dateutilparser import parse dateutiltz import tzoffset dt parse datetimedatetime tzinfotzoffsetnone dtastimezonetzoffsetnone datetimedatetime tzinfotzoffsetnone
i timestamp timezone information string format i would like convert display correct datetime using local timezone so eg i timestamp i would like convert say timezone offset dsiplay timestamp i tried using pytz couldnt find many examples showing use offset information one link i found stackoverflow depicts exact problem...
3
print u hello ä½ å¥½ bye encode unicodeescape hello ufud bye but consider using json via json
for example i file ajs whose content hello ä½ å¥½ bye which contains two chinese characters whose unicode form ufud i want write python program convert chinese characters ajs unicode form output bjs whose content hello ufud bye my code fp openajs content fpread fpclose fp openbjs w result contentdecodeutf fpwriteresult...
3
that actually limit underlying select system call from man page an fdset fixed size buffer executing fdclr fdset value fd negative equal larger fdsetsize result undefined behavior and standard fdsetsize usrincludelinuxposixtypeshdefine fdsetsize so python issue the poll epoll system calls much larger limit what really ...
the workaround issue supervisord compile python supports file descriptors httpsgithubcomsupervisorsupervisorissues can someone please walk changes necessary accomplish i python source extracted ready go running centos matters thanks update ulimit n already set this full error i getting starting supervisord traceback re...
1
you try codecs module codecsopenfilename mode encoding errors buffering codecsopenajs r cpread unicode object codecsopenbjs w utfwritea
for example i file ajs whose content hello ä½ å¥½ bye which contains two chinese characters whose unicode form ufud i want write python program convert chinese characters ajs unicode form output bjs whose content hello ufud bye my code fp openajs content fpread fpclose fp openbjs w result contentdecodeutf fpwriteresult...
1
the devappserver production environment concept projects libraries need structure app necessary libraries application root the easiest way usually symlink subdirectories worstcase copy using version control make subrepositories how maps operations ide depends ide general probably easiest get app structured need disk wo...
couple months i started development python c java background i currently working different pythonappengine applications often happens cases application share common code i would like refactor move commongeneric code shared place in either java c i create new library project move code new project add reference library m...
2
this called natsort natural sort a quick google gives httpwwwskynetiecaolanpackagespythonnatsorthtml tried though maybe helps oh necessarily ascii sort number order know like real axis
this might sound like silly question i tried find answer works without much success i got list lists v sortedlist print v i iterated list using sorted function however brings items ascii order sorted floats human readable order ie do i need create index somekind convert floats ints any help much appreciated david
1
you need give sorted comparison function something like following sortedlist cmplambda x cmpx just write function need want plug you probably want something like reverse radix sort
this might sound like silly question i tried find answer works without much success i got list lists v sortedlist print v i iterated list using sorted function however brings items ascii order sorted floats human readable order ie do i need create index somekind convert floats ints any help much appreciated david
1
a design patterns help prototype factory abstract factory use two patterns configuration objects each method take configuration object use needs also consider applying logical grouping config parameters think ways reduce number inputs psuedo code consider run three different kinds simulations sim sim sim configfactory ...
lets say i program large number configuration options the user specify config file my program parse config file internally store pass around options in case software used perform scientific simulation there options sane defaults typically user specify dozen the difficulty i face design internal code many objects need c...
1
pass around either config parsing class write class wraps intelligently pulls requested options python standard library configparser exposes sections options ini style configuration file using mapping protocol retrieve options directly though dictionary myconf configparserconfigparser myconfread myconfini whattodo myco...
lets say i program large number configuration options the user specify config file my program parse config file internally store pass around options in case software used perform scientific simulation there options sane defaults typically user specify dozen the difficulty i face design internal code many objects need c...
1
convert float string first split sorteda keylambda xmapint strfloatxsplit
this might sound like silly question i tried find answer works without much success i got list lists v sortedlist print v i iterated list using sorted function however brings items ascii order sorted floats human readable order ie do i need create index somekind convert floats ints any help much appreciated david
2
this kind hack v sorteda keylambda strtsplit intstrtsplit strt print v result disclaimer assumes places decimal point adjust accordingly
this might sound like silly question i tried find answer works without much success i got list lists v sortedlist print v i iterated list using sorted function however brings items ascii order sorted floats human readable order ie do i need create index somekind convert floats ints any help much appreciated david
1
matplotlib large package many configuration options it use rcparams module manage default parameters rcparams save default parameters dict every functions get options keyword argurments example def fxyoptanone optbnone opta none opta rcparams groupopta
lets say i program large number configuration options the user specify config file my program parse config file internally store pass around options in case software used perform scientific simulation there options sane defaults typically user specify dozen the difficulty i face design internal code many objects need c...
3
particularly given technique knearest neighbors mentioned q would strongly recommend scikitslearn note answer posted lead developer project informed new homepage project a features believe distinguish library others least python ml libraries used extensive diagnostics amp testing library including plotting modules via ...
i need classify data i hope nearestneighbour algorithm i googled problem found lot libraries including pyml mlpy orange i unsure start how i go implementing knn using python
3
to make mouse look right direction i try pygametransformrotate make degrees rotation depend directionx directiony variables greater less zero
i learning python pygame working simple game play mouse avoid snakes spawn every seconds roam across screen right i trying get mouse sprite face direction moving the image mouse facing i tried couple ideas get face right direction nothing worked hoping someone could help here code collision detection yet basic code mou...
1
have look itertoolsmodule particulary product method example usage itertoolsproductrange repeat stuff listappendruniii note function call shortened listappendruni example see docspythonorg explanation unpacking argument lists as example output productrange repeat looks like
i working python currently following code list range b range c range listappendrunabc runabc returns integer example could multiply three numbers together is faster way either loop numbers use map function thanks
3
i think use imap itertools import imap result listimaprun range range range imap yields result want iterate results use list
i working python currently following code list range b range c range listappendrunabc runabc returns integer example could multiply three numbers together is faster way either loop numbers use map function thanks
1
itertools import product mylist runa b c b c productxrange xrange xrange or itertools import product mylist runa b c b c productxrange repeat
i working python currently following code list range b range c range listappendrunabc runabc returns integer example could multiply three numbers together is faster way either loop numbers use map function thanks
1
use sympy sympy import abcde symbolsabcde x bcminde csqrtxe values abcde print x print print xsubsvalues print ysubsvalues print nxsubsvalues print nysubsvalues output bc c ea bc
i looking way store series formulasequations text easily diffable later formulas depend results earlier ones i able evaluate formulas similar live worksheets mathcad numeric results also able programmatically produce string representation original formula put another way i like able treat formulas data well evaluate fo...
2
you use subprocess module python if logs big simply use python result subprocesscheckoutputpathtoprocesstolauch arg python process subprocesspopenpathtoprocesstolauch arg stdoutsubprocesspipe stderrsubprocesspipe strout strerrr processcommunicate strout find standard output process strerr find standard output process b...
java program runs particular port ubuntu while running program need take output program needs save log file i use nohub run currentlywhen fail i know failthen process restart nohub get overwritten i want process restart update log file i check later date currently i know state running failed i heard pretty easy using p...
1
using python certainly possible if reading mysql might check mysqlpython reading text file use file open filename r filereadline get line parse however added overhead using python if text file orderly one reacord per row row number columns consistent delimiter comma tab semicolon etc efficient way load directly in mysq...
i trying load text file database my text file gb i need write python script load text file headers database any guidelines i go thanks
1
there multiple ways solve install webserver local machine write fullfledged python web application write simple webserver application python using basehttpserver write htmljavascript application use python parses file note due recently tightened restrictions may still require served webserver write python application w...
i created database python results kept text file i would like create simple html search button looks database my database would accessible computer my database looks something like reference name dimension xxx aaa so example i search specific reference i would like obtain name dimension obviously is even possible pytho...
1
try replacing sysexit finishedloading qapplicationinstanceexit
i trying hand scraping javascript reliant site it pretty basic site simple list entires names cities actually i want copy paste excel the list controlled javascript i figur i need use something like qt emulate browser i trying pyside i started basic code i adapted usrbinenv python import sys import signal import argpar...
1
as noone else offered solution using generator one sample thisisagoodexample def uppersplitdata buff item data itemisupper buff yield buff buff buff item yield buff listuppersplitsample this is a good example joinuppersplitsamplelower thisisagoodexample
i new python i trying replace uppercaseletters within word underscores example thisisagoodexample become thisisagoodexample any ideastipslinkstutorials achieve
1
did set fixturedirs setting value settingspy see documentation
i trying use postrgesql django apps i get following error right starting project i following files initpy managepy settingspyc urlspyc initpyc settingspy urlspy i added models python managepy syncdb creating tables installing custom sql installing indexes no fixtures found i even trying load fixtures psycopg installed ...
1
you simple use case already web server installed probably simplest quickest way use cgi script written python check cgi module httpdocspythonorglibrarycgihtml basically handle get request show html form asking query string post request process query show results
i created database python results kept text file i would like create simple html search button looks database my database would accessible computer my database looks something like reference name dimension xxx aaa so example i search specific reference i would like obtain name dimension obviously is even possible pytho...
1
this passes tests including extra i created it uses recursion here rules i used the first letter abbreviation must match first letter text the rest abbreviation abbrev minus first letter must abbreviation remaining words remaining text starting position first word tests fck fc kopenhavn true fco fc kopenhavn false irl ...
i trying develop python algorithm check string could abbrevation another word for example fck match fc kopenhavn matches first characters word fhk would match fco match fc kopenhavn one irl would abbrevate fc kopenhavn fco irl match real life ifk match ifk goteborg aik match allmanna idrottskluben aid match allmanna id...
3
this type encoding known mime encodedword email module decode emailheader import decodeheader print decodeheaderutfbieryzwltbhdhnmcmlzdcbmwxyifzlcnbmbgvndwnclahjhdwzzwkdw this outputs list tuples containing decoded string encoding used this format supports different encodings single header to merge single string need c...
python module helps decode various forms encoded mail headers mainly subject simple say utf strings here example subject headers mail files i subject utfbimknidensbbynm ao subject gewstutfbifdlzzhbgwgzgvyifzvcmzdphvmawdrzwl subject utfbieryzwltbhdhnmcmlzdcbmwxyifzlcnbmbgvndwnclahjhdwzzwkdw utfbzvuigvpbmvzifnlzwhbmz tex...
3
setopenfile amp setopenfile equivalent using intersection pythonic way you might able speed setintx x openfile amp setintx x openfile since storing comparing integers rather strings this works ids numeric course if still fast enough turn slightly imperative style heuristic set smallerfile largerfile checking file size ...
i two large files their contents looks like the file contains unsorted list ids some ids may appear one time single file now i want find intersection part two files that ids appear files i read two files sets and get intersection sintersections but consumes lot memory seems slow so better pythonic way if file contains ...
2
i happy say fact possible lines code i know easy toolkits tkinter import import os root tk termf frameroot height width termfpackfillboth expandyes wid termfwinfoid ossystem xterm geometry x sb amp wid rootmainloop the problem use wrong function wid
i want embed terminal main tkinter window i would like sub window terminal bash based terminal would run i would like also able let program interact terminal least i would like read current working directory andor set i know really impossible i able past perltk maybe replicated the code i used something like framemwfra...
3