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 takes two seconds itrnext returns immediately itrnext setup call takes two seconds itrnext returns immediately note generator automatically processing get next value caller call next twice value for use case would call next setup time user clicks button would display next value generated call next prefetch
i generator takes long time iteration run is standard way yield value generate next value waiting called the generator would called time button pressed gui user would expected consider result button press edit workaround might def initialize res nextgen def btncallback displayres res nextgen res return
1
strings foo bar applesplit
i new python essentially trying figure syntax replicates functionality strings foo bar apple something similar strings foo bar apple i put quotes around entries thanks
3
strings rfoo bar applesplit
i new python essentially trying figure syntax replicates functionality strings foo bar apple something similar strings foo bar apple i put quotes around entries thanks
1
you use subprocesspipe also split command use shlexsplit prevent strange behaviours cases subprocess import popen pipe shlex import split p popensplittar c mydir stdoutpipe p popensplitmdsum stdinpstdout but make archive generate checksum use python builtin modules tarfile hashlib instead calling shell commands
i run normally command line linux tar c mydir mdsum but i try call python i get error subprocesspopen tar c mydir mdsum shelltrue subprocesspopen object xc tar you must specify one acdtrux testlabel options try tar help tar usage information
3
ok i sure seems work subprocesscalltar c mydir mdsumshelltrue anyone know original code work
i run normally command line linux tar c mydir mdsum but i try call python i get error subprocesspopen tar c mydir mdsum shelltrue subprocesspopen object xc tar you must specify one acdtrux testlabel options try tar help tar usage information
1
you could place strings text file one string line then strings listopendatafile r
i new python essentially trying figure syntax replicates functionality strings foo bar apple something similar strings foo bar apple i put quotes around entries thanks
1
subprocess import popenpipe import hashlib proc popen tar c etchosts stdoutpipe stdout stderr proccommunicate hashlibmdstdouthexdigest acecf
i run normally command line linux tar c mydir mdsum but i try call python i get error subprocesspopen tar c mydir mdsum shelltrue subprocesspopen object xc tar you must specify one acdtrux testlabel options try tar help tar usage information
1
i would say easier way create list strings already as answers pointed ways put strings one big string file split opinion difficult type quotes particularly decent ide automatically closes string quotes also syntax already using anyone else reads code expect using something else adds unnecessary confusion almost zero gain
i new python essentially trying figure syntax replicates functionality strings foo bar apple something similar strings foo bar apple i put quotes around entries thanks
1
there two major differences posted the quotes indicate string like would list integers if remove quotes essentially creating list python objects a python object basically foundation python classes eg integers strings python objects basic level you something like foo foo bar bar apple apple strings foobarapple
i new python essentially trying figure syntax replicates functionality strings foo bar apple something similar strings foo bar apple i put quotes around entries thanks
1
runserver developmenttesting it handle high load security etc pythonorg docs set proper webserver serve python code httpdocspythonorghowtowebservershtml
as experienced php programmer i tend avoid things like python however must play cards dealt i work satchmo website i little python django satchmo i need help i ok setting development server i cannot get website work production server i seen use python managepy runserver solution even stack overflow however i see solution usually someone saying i hope using production i assume incorrect way to frustration people seem know command line insecure also desire share rest us excatly one initiate satchmo production server many thanks
1
the code kevin jacobs former question employs biopython uses sequences type seq ⫠essentially strings letters like agtacactggt seems natural since common way sequences seen biological file formats ⻠⫠there two important differences seq objects standard python strings first different methods secondly seq object important attribute alphabet object describing individual characters making sequence string “mean” interpreted for example agtacactggt dna sequence protein sequence happens rich alanines glycines cysteines threonines the alphabet object perhaps important thing makes seq object string the currently available alphabets biopython defined bioalphabet module ⻠httpbiopythonorgdistdocstutorialtutorialhtml the reason problem simply seqioparse create seq objects file containing characters alphabet attribute able manage so must use another method not try plate inadapted method different problem here way itertools import groupby operator import itemgetter import regx recompile remultiline open pastierb f records regxfindallfread recordssortkeyitemgetter print lenrecords sn lenrecords n seqequal groupbyrecords itemgetter ids tuplex x equal lenids print ns joinids seq else n print nnumber unique occurences n result lenrecords number unique occurences edit i understood my problem i let fasta instead phylip code phylip valid value attribute alphabet works fine records listseqioparsefile pastierb phylip def seqgetters return strsseq recordssortkeyseqgetter ecr seqequal groupbyrecords seqgetter ids tuplesid equal lenids ecrappend sns joinidsseq print n joinecr produces there incredible amount characters interesting data i wonder but code useless see time import clock itertools import groupby operator import itemgetter import bio import seqio def seqgetters return strsseq clock open pastierb f records listseqioparsef phylip recordssortkeyseqgetter print clockt seconds clock regx recompile remultiline open pastierb f records regxfindallfread recordssortkeyitemgetter print clockt seconds result seconds seconds ratio
i trying something similar previous question my purpose join sequences equal but time instead letters i numbers alignment file found phylip file problem i try records listseqioparsefilefilename phylip i get error valueerror sequence length expected length i understand second file i creating first one worked perfectly below code used build alignment file flwrite flwritestr flwrite flwritestrsize flwrite n infoplex ref hrv flwritestri num leni flwrite num x flwritestrx flwrite n so interpret number since string any ideas thank
1
satchmo seems like django derivative setting django production quite easy deployment environment linux apache use modwsgi well documented windows use pyisapie module follow documentation hope helps
as experienced php programmer i tend avoid things like python however must play cards dealt i work satchmo website i little python django satchmo i need help i ok setting development server i cannot get website work production server i seen use python managepy runserver solution even stack overflow however i see solution usually someone saying i hope using production i assume incorrect way to frustration people seem know command line insecure also desire share rest us excatly one initiate satchmo production server many thanks
1
to deploy django website production server serve either apachemodwsgi nginxgunicorn nginxuwsgi server supporting wsgi the django documentation page deploying django apache modwsgi solutions plenty useful documentation around web
as experienced php programmer i tend avoid things like python however must play cards dealt i work satchmo website i little python django satchmo i need help i ok setting development server i cannot get website work production server i seen use python managepy runserver solution even stack overflow however i see solution usually someone saying i hope using production i assume incorrect way to frustration people seem know command line insecure also desire share rest us excatly one initiate satchmo production server many thanks
1
django automatically creates default permissions every model add delete change you getting integrity error trying create permissions name just remove delete meta description everything ok
i trying purge database mydb repopulate see effects changes django model then happened i rolled back earlier model setup i still get errors i mysql pro i can’t quite figure problem i tried creating new database another name didn’t happen i assume problem created django project here info cuserspython managepy syncdb creating tables creating table authpermission creating table authgrouppermissions creating table authgroup creating table authuseruserpermissions creating table authusergroups creating table authuser creating table authmessage creating table djangocontenttype creating table djangosession creating table djangosite creating table djangoadminlog creating table forumcategory creating table forumthread creating table forumpost you installed django auth system means superusers defined would like create one yesno yes username leave blank use admin email address exampleexamplecom password password superuser created successfully traceback recent call last file managepy line executemanagersettings file cpythonlibsitepackagesdjangocoremanagementinitpy line executemanager utilityexecute file cpythonlibsitepackagesdjangocoremanagementinitpy line execute selffetchcommandsubcommandrunfromargvselfargv file cpythonlibsitepackagesdjangocoremanagementbasepy line runfromargv selfexecuteargs optionsdict file cpythonlibsitepackagesdjangocoremanagementbasepy line execute output selfhandleargs options file cpythonlibsitepackagesdjangocoremanagementbasepy line handle return selfhandlenoargsoptions file cpythonlibsitepackagesdjangocoremanagementcommandssyncdbpy line handlenoargs emitpostsyncsignalcreatedmodels verbosity interactive db file cpythonlibsitepackagesdjangocoremanagementsqlpy line emitpostsyncsignal interactiveinteractive dbdb file cpythonlibsitepackagesdjangodispatchdispatcherpy line send response receiversignalself sendersender named file cpythonlibsitepackagesdjangocontribauthmanagementinitp line createpermissions contenttypectype file cpythonlibsitepackagesdjangodbmodelsmanagerpy line create return selfgetquerysetcreatekwargs file cpythonlibsitepackagesdjangodbmodelsquerypy line create objsaveforceinserttrue usingselfdb file cpythonlibsitepackagesdjangodbmodelsbasepy line save selfsavebaseusingusing forceinsertforceinsert forceupdateforceup date file cpythonlibsitepackagesdjangodbmodelsbasepy line savebase result managerinsertvalues returnidupdatepk usingusing file cpythonlibsitepackagesdjangodbmodelsmanagerpy line insert return insertqueryselfmodel values kwargs file cpythonlibsitepackagesdjangodbmodelsquerypy line insertquery return querygetcompilerusingusingexecutesqlreturnid file cpythonlibsitepackagesdjangodbmodelssqlcompilerpy line executesql cursor supersqlinsertcompiler selfexecutesqlnone file cpythonlibsitepackagesdjangodbmodelssqlcompilerpy line executesql cursorexecutesql params file cpythonlibsitepackagesdjangodbbackendsutilpy line execute return selfcursorexecutesql params file cpythonlibsitepackagesdjangodbbackendsmysqlbasepy line execute return selfcursorexecutequery args file cusersmeappdataroamingpythonpythonsitepackagesmysqldbcursorspy line execute selferrorhandlerself exc value file cusersmeappdataroamingpythonpythonsitepackagesmysqldbconnectionspy line defaulterrorhandler raise errorclass errorvalue djangodbutilsintegrityerror duplicate entry deletecategory key contenttypeid modelspy djangodb import models djangocontribauthmodels import user class categorymodelsmodel title modelscharfieldmaxlength class meta verbosenameplural categories permissions createcategory can create new categories editcategory can edit titles categories deletecategory can delete category mergecategory can merge multiple categories together class threadmodelsmodel creationdate modelsdatetimefield author modelsforeignkeyuser title modelscharfieldmaxlength category modelsforeignkeycategory class meta ordering creationdate permissions createthread create new threads editthread edit thread titles deletethread delete threads mergethread merge multiple threads together lockthread lock threads unlockthread open locked threads banuserinthread ban user post thread timeoutuserinthread ban user posting thread temporarily appointthreadmin give user modlike permissions thread class bookmarkmodelsmodel user modelsforeignkeyuser thread modelsforeignkeythread class subscriptionmodelsmodel user modelsforeignkeyuser thread modelsforeignkeythread class postmodelsmodel creationdate modelsdatetimefield author modelsforeignkeyuser thread modelsforeignkeythread content modelstextfield class meta ordering creationdate permissions createpost can create new post editpost can edit users posts deletepost can delete posts tablesinmydb authgroup authgrouppermissions authmessage authpermission authuser authusergroups authuseruserpermissions djangoadminlog djangocontenttype djangosession djangosite forumbookmark forumcategory forumpost forumsubscription forumthread mysql select djangocontenttype id name applabel model permission auth permission group auth group user auth user message auth message content type contenttypes contenttype session sessions session site sites site log entry admin logentry category forum category thread forum thread bookmark forum bookmark subscription forum subscription post forum post
3
i used pyc innosetup create installers you also download run wix command line without using develop visual studio the key make sure include dll need ngen install shorter start times better performance
i using sharpdevelop visual studio ironpython app development i reasons using app development what console based options compiling ironpython exe file packaging manually is possible create executable app ironpython pack using installer
1
do mean maximum filter if look scipyndimagemaximumfilterd as quick example import numpy np import scipyndimage ndimage input npsinnplinspace nppi input input astypenpint makes easier read output ndimagemaximumfilterdinput print in input print out output this yields in out
do happen d nonmaximum suppression algorithm written python i need making canny edge detector python using scipy takes input d intensity vector i looked around web lot information describing behavior canny edge detector examples written java describe edge detection d however scipy support algorithms needed canny edge detection namely gaussian filtering differentiation d thanks advance
1
you basically rand bend int result rand rangeend rangestart rangestart to explain rand generates random number across subset integer values you use modulo lo limit range numbers use start value provide offset also sure seed random number generator note rand apparently pretty lousy random number generator i idea see comments
just switch python c i begin rewrite python tools c better understanding solve one this function generate range random numbers example randomrange may return range numbers like python def randomrangen rangestart n rangeend n return randintrangestart rangeend number randomrange c int n int randomrangen int rangestart int rangeend int result rangestart rangeend return result int number randomrange i find equivalent question marks
1
first look how split list evenly sized chunks python using one answers import itertools networktable cluster one primary system node one xxxx node ip node two xxxx node ip cluster two primary system node one xxxx node ip node two xxxx node ip l networktableii range lennetworktable l cluster one primary system node one xxxx node ip node two xxxx node ip cluster two primary system node one xxxx node ip node two xxxx node ip now easy do want l joini n l cluster one primary system node one xxxx node ip node two xxxx node ipn cluster two primary system node one xxxx node ip node two xxxx node ipn
i building python script network inventory internal system each system five clusters i looking way adjust list put one line per cluster here way stored system cluster one primary system node one xxxx node ip node two xxxx node ip cluster two primary system node one xxxx node ip node two xxxx node ip i need adjusted look like cluster oneprimary systemnode onexxxx node ipnode twoxxxx node ip cluster twoprimary systemnode onexxxx node ipnode twoxxxx node ip here really sloppy code i using right i wondering efficient way networktablecount lennetworktable count count networktablecount count temp networktablenetworktablenetworktablenetworktablenetworktablenetworktablen elif count temp networktablenetworktablenetworktablenetworktablenetworktablenetworktablen elif count temp networktablenetworktablenetworktablenetworktablenetworktablenetworktablen elif count temp networktablenetworktablenetworktablenetworktablenetworktablenetworktablen elif count temp networktablenetworktablenetworktablenetworktablenetworktablenetworktablen networktopologywritetemp count count i self taught python may simple adjustment thanks advance
1
you trouble getting good randomness high values n include mathh pow include stdlibh drand long randomrangeint n method needs start size range rather start end long rangestart pown long rangesize pownrangestart expect rand functions offer randomness morewellknown rand function drand gives doubleprecision float scale rangesize start range return rangestart longdrand rangesize here another approach on bit platforms digits int make function return double generate string ascii digits convert include mathh pow include stdlibh atof arbitrary limit const int maxdigits double randomrangeint n char bignumstring maxdigits n maxdigits return first digit bignumstring rand int n subsequent digits zero bignumstringi rand terminate string bignumstringi convert float return atofbignumstring
just switch python c i begin rewrite python tools c better understanding solve one this function generate range random numbers example randomrange may return range numbers like python def randomrangen rangestart n rangeend n return randintrangestart rangeend number randomrange c int n int randomrangen int rangestart int rangeend int result rangestart rangeend return result int number randomrange i find equivalent question marks
2
you look facilities boost httpwwwboostorgdoclibsdochtmlboostrandomtutorialhtmlboostrandomtutorialgeneratingintegersinarange
just switch python c i begin rewrite python tools c better understanding solve one this function generate range random numbers example randomrange may return range numbers like python def randomrangen rangestart n rangeend n return randintrangestart rangeend number randomrange c int n int randomrangen int rangestart int rangeend int result rangestart rangeend return result int number randomrange i find equivalent question marks
2
you work around throwing exception catching middleware httpdjangosnippetsorgsnippets
i absolute novice djangocms i gone tutorial configured exactly mentioned documentation now i build application uses form upload products i dont clue move ahead i want start simple forms say username password textbox kind how i use django forms djangocms page i snippet plugin enabled i need guidance any suggestions plsss thanks
1
i think covered options you either subclass monkeypatch typically monkeypatching actually changing rd party class runtime frowned upon depending change need make may way work around bug make sure every time class used new method since tests use method tests monkeypatching unnecessary quite reasonable subclass testcase typically use monkeypatching needed augment method existing class for example wanted calls testcaseassertequal existing test cases augmented logic compare option objects could monkeypatch testcaseassertequal include custom logic plus normal logic something like originalassertequal testcaseassertequal def newassertequalself first second result originalassertequalfirst second isinstancefirst option isinstancesecond option custom comparison return result testcaseassertequal newassertequal however seems least example subclasses monkeypatches unnecessary assuming issue calling selfassertequalfirstoptions secondoptions fails even though option instances equal need write new assertoptionsequal method you probably need option objects define eq properly so assuming got class knowngoodinputstestcase def testgoodoptionsself first second systemundertestgetoptions selfassertoptionsequalfirst second what classes first second for python builtin types assertequal work for custom option class something like class optionobject def init self usefoo false usebar true def eqself selfusefoo otherusefoo selfusebar otherusebar return true return false then assuming first second instances option write test class knowngoodinputstestcase def testgoodoptionsself first second systemundertestgetoptions selfassertequalfirst second
i special cases i need test django i trying extend existing django tests writing test cases here i currently djangotests import testcase define method function def assertoptionsequalself first second logic pass attach method testcase class this feels inelegant testcaseassertoptionsequal assertoptionsequal tests go class knowngoodinputstestcase def testgoodoptionsself selfassertoptionsequal while works defining method function self first parameter attaching testcase feels inelegant is better way augmenting testcase class methods i class mytestcasetestcase def assertoptionsequalself first second use mytestcase tests wondering better alternative thanks
1
if i wanted something like workaround i write class like class prefetchedgeneratorobject def initself generator selfdata generatornext selfgenerator generator selfready true def nextself selfready selfprefetch selfready false return selfdata def prefetchself selfready selfdata selfgeneratornext selfready true it complicated version i made handles calling prefetch calling prefetch many times the basic idea call next want next item you call prefetch time kill your option thread class backgroundgeneratorthreadingthread def initself generator threadingthreadinitself selfqueue queuequeue selfgenerator generator selfdaemon true selfstart def runself item selfgenerator selfqueueputitem selfqueueputnone def nextself nextitem selfqueueget nextitem none raise stopiteration return nextitem this run separately main application your gui remain responsive matter long takes fetch iteration
i generator takes long time iteration run is standard way yield value generate next value waiting called the generator would called time button pressed gui user would expected consider result button press edit workaround might def initialize res nextgen def btncallback displayres res nextgen res return
1
ok i seems solution answer persay way moving multipoint differential i tested result looks similar moving regression i used d sobel filter ramp convolved data def kdpphidp dx fitlen kdpnpzerosphidpshape dtypefloat myshapekdpshape swn rangemyshape print sweep swn rayn rangemyshape print ray rayn kdpswn rayn sobelphidpswn rayn windowlenfitlendx return kdp def sobelxwindowlen sobel differential filter calculating kdp output differential signal unscaled gate spacing example snprxwindowlenxxwindowlen printlens wnparangewindowlenwindowlen print w wwabswsum ynpconvolvewsmode valid return ywindowlenlenxwindowlenwindowlen runs quick
i d array data wish extract spatial variation the standard way i wish pythonize perform moving linear regression data save gradient def nsslkdpphidp distance fitlen kdpzerosphidpshape dtypefloat myshapekdpshape swn rangemyshape print sweep swn rayn rangemyshape print ray rayn smallpolyfitdistanceaafitlen phidpswn rayn aafitlen xrangemyshapefitlen kdpswn rayn arraylistitertoolschainfitlensmall small fitlensmall return kdp this works well slow i need times i imagine overhead iterator arange line is implimentation moving fit numpyscipy
1
here reasons i think would wrong extra code complexity without big need adding one line settings every time bad especially step become explicit apps project using when another developer work project might know app installed step step code versioning system test whole system commit changes deploy i think something wrong point view developdeploy process looking optimization i think much easier better use installedapps if building something public use want make easy possible add modules would nice in case i would recommend package project apps python eggs make use entry points then could deploy app project like pip install myappname without even step step done pip step done setup hooks defined project paste script good example entrypoints utilization install paste script pip install pastescript install django templates pastescript pip install fezdjangoskel paste script knows fezdjangoskel entrypoints start new django project fez templates paste create djangobuildout here portion setuppy fezdjangoskel package entrypoints pastepastercreatetemplate djangobuildoutfezdjangoskelpastertemplatesdjangobuildouttemplate djangoappfezdjangoskelpastertemplatesdjangoapptemplate zcbuildout another great tool might make deployments much easier python eggs plays nice buildout
i written django app i want make easy deploy multiple servers the basic installation copy app folder django project folder add installedapps settingspy run managepy collectstatic this particular app need use db i use south run managepy migrate another story the part i trouble i want manually edit file every time what easiestmost robust way update i thinking i could use inspect module find variable somehow append i luck inspectgetsourcelines find variables
1
why use module directly pointed models singletons if create module like mymodulepy mydb import connection connection connection host port use import mechanism connection instance everywhere mymodule import connection of course define much complex initialization connection possibly via writing class point python initialize module provide objects every subsequent call i believe singleton borg patterns specific applications python part rely direct imports proven otherwise
i wondering implementing singleton class following httpcodeactivestatecomrecipesthesingletonpatternimplementedwithpython wondering blocking issues my code suppose cache sql statements execute cached statements using cursorexecutemanysql listofparams certain number cached elements reached specific executecall done user implementing singleton suppose make possible cache statements applicationwide i afraid i run blocking issues any thoughts
1
python enforced private anything convention letting others know methodfunctionclasswhathaveyou private prefix single leading underscore thirdparty programs use autodocumenting systems help idle ignore names your code would translate like class circleobject python need object member none needed since three initialized member none init others member none would def initself member selfmembermember selfrest def restself lots computing selfmemberresult selfmemberresult given comments code though would well make rest part init class circleobject python need object def initself member selfmembermember lots computing selfmemberresult selfmemberresult
i need following structure python public class circle int member int member int member public circlemember thismember member initializerest private intializerest lot computation get result amp result thismember result thismember result
1
i missing point question there takesnapshot function bit actually takes snapshot commented modify code look like following def takesnapshotselfwidget filename strtimetime jpg pixbuf gtkgdkpixbufgetfromdrawableselfmoviewindowwindow selfmoviewindowwindowgetcolormap pixbufsavefilename jpeg quality take snapshot save image current time
i code monitoring webcam python pygtk the question i take snapshot code usrbinenv python import sys os import pygtk gtk gobject import pygst pygstrequire import gst import time class webcam def initself window gtkwindowgtkwindowtoplevel windowsettitlewebcamviewer windowsetdefaultsize windowconnectdestroy gtkmainquit wm destroy vbox gtkvbox windowaddvbox selfmoviewindow gtkdrawingarea vboxaddselfmoviewindow hbox gtkhbox vboxpackstarthbox false hboxsetborderwidth hboxpackstartgtklabel selfbutton gtkbuttonstart selfbuttonconnectclicked selfstartstop hboxpackstartselfbutton false selfbutton gtkbuttonsnapshot selfbuttonconnectclicked selftakesnapshot hboxpackstartselfbutton false selfbutton gtkbuttonquit selfbuttonconnectclicked selfexit hboxpackstartselfbutton false hboxaddgtklabel set gstreamer pipeline selfplayer gstparselaunch vlsrc autovideosink bus selfplayergetbus busaddsignalwatch busenablesyncmessageemission busconnectmessage selfonmessage busconnectsyncmessageelement selfonsyncmessage windowsetborderwidth windowsetpositiongtkwinposcenteralways windowshowall def takesnapshotselfwidget filename strtimetime jpg selfmoviewindowwindowgetimage print snapshot def startstopself w selfbuttongetlabel start selfbuttonsetlabelstop selfplayersetstategststateplaying else selfplayersetstategststatenull selfbuttonsetlabelstart def exitself widget datanone gtkmainquit def onmessageself bus message messagetype gstmessageeos selfplayersetstategststatenull selfbuttonsetlabelstart elif gstmessageerror err debug messageparseerror print error err debug selfplayersetstategststatenull selfbuttonsetlabelstart def onsyncmessageself bus message messagestructure none return messagename messagestructuregetname messagename preparexwindowid assign viewport imagesink messagesrc imagesinksetpropertyforceaspectratio true imagesinksetxwindowidselfmoviewindowwindowxid name main try webcam gtkgdkthreadsinit gtkmain except keyboardinterrupt pass thanks
1
tar file headers include field modified time file act changing file even change later changed back mean tar file headers different leading different hashes
i trying write python script get mdsum files directory linux which i believe i done code i want able run make sure files within directory changed files added deleted the problem i make change file directory change back i get different result running function even though i changed modified file back can anyone explain and let know think workaround def getdirmddirpath build tar file directory return md sum temptarpath teststar tarfiletarfiletemptarpathmode w tadddirpath tclose hashlibmd mupdateopentemptarpath rb read retstr mhexdigest delete tar file osremovetemptarpath return retstr edit as fine folks answered looks like tar includes header information like date modified would using zip work differently another format any ideas work arounds
3
tar files contain metadata beyond actual file contents file access times modification times etc even file contents change tar file fact different
i trying write python script get mdsum files directory linux which i believe i done code i want able run make sure files within directory changed files added deleted the problem i make change file directory change back i get different result running function even though i changed modified file back can anyone explain and let know think workaround def getdirmddirpath build tar file directory return md sum temptarpath teststar tarfiletarfiletemptarpathmode w tadddirpath tclose hashlibmd mupdateopentemptarpath rb read retstr mhexdigest delete tar file osremovetemptarpath return retstr edit as fine folks answered looks like tar includes header information like date modified would using zip work differently another format any ideas work arounds
1
you need make tar file propose here workaround algorithm walk directory tree take md signature file sort signatures take md signature text string signatures individual files the single resulting signature looking heck even need python you find pathtodir type f name py exec mdsum awk print sort mdsum
i trying write python script get mdsum files directory linux which i believe i done code i want able run make sure files within directory changed files added deleted the problem i make change file directory change back i get different result running function even though i changed modified file back can anyone explain and let know think workaround def getdirmddirpath build tar file directory return md sum temptarpath teststar tarfiletarfiletemptarpathmode w tadddirpath tclose hashlibmd mupdateopentemptarpath rb read retstr mhexdigest delete tar file osremovetemptarpath return retstr edit as fine folks answered looks like tar includes header information like date modified would using zip work differently another format any ideas work arounds
2
as answers mentioned two tar files different even contents either due tar metadata changes file order changes you run checksum file data directly sorting directory lists ensure always order if want include metadata checksum include manually untested example using oswalk import os import ospath def getdirmddirroot build tar file directory return md sum hash hashlibmd dirpath dirnames filenames oswalkdirroot topdowntrue dirnamessortkeyospathnormcase filenamessortkeyospathnormcase filename filenames filepath ospathjoindirpath filename if metadata required add checksum filename good idea hashupdateospathnormcaseospathrelpathfilepath dirroot mtime possibly bad idea st osstatfilepath hashupdatestructpack ststmtime size good idea perhaps hashupdatebytesststsize f openfilepath rb chunk iterlambda fread b hashupdatechunk return hashhexdigest
i trying write python script get mdsum files directory linux which i believe i done code i want able run make sure files within directory changed files added deleted the problem i make change file directory change back i get different result running function even though i changed modified file back can anyone explain and let know think workaround def getdirmddirpath build tar file directory return md sum temptarpath teststar tarfiletarfiletemptarpathmode w tadddirpath tclose hashlibmd mupdateopentemptarpath rb read retstr mhexdigest delete tar file osremovetemptarpath return retstr edit as fine folks answered looks like tar includes header information like date modified would using zip work differently another format any ideas work arounds
3
it possible get email user connected app using graph however connecting signing using facebook users must explicitly give permission use email address since none friends gave permission email addresses limits what means encourage user friends join well make sure sign include request email address
i using djangosocialregistration facebook python sdk this code get friends friends requestfacebookgraphgetconnections friends i get name id i get email address facebookcom email this another attempt also get email friend friends data requestfacebookgraphgetobjectfriend id how i get facebook friends email
1
if want lock either use globals use threadlocal storage webapp fairly sure request cross thread boundary if global state avoided avoided this makes multithreading way easier implement debug i also disagree passing objects around makes application harder maintain — usually way around — global state hides dependencies addition requiring careful synchronisation well also lockfree approaches like stm whatnot probably overkill web application
after reading lot subject discussing irc response seems stay away threads sorry repeating question intention go deeper subject accepting threading evil answer hope find common solution edit just say no combined evils locking deadlocks lock granularity livelocks nondeterminism race conditions guido van rossum i developing python web application i like create global object user accessible current user example requested uri the suggested way pass object around imo makes application harder maintain beautiful code i need value different places might rd party plugins i see many popular frameworks django cherrypy flask use python threading locks solve issue if frameworks go pythonic way feel need create globally accessible object means community needs sort thing and is best way pass objects around is alternative solution use evil threading locks would pythonic store information database memcached thanks advance
3
i would proces lines based name begin seems cluster specifies new set data file open myfile clusters line filereadline linestripstartswithcluster cluster clusterappendlinestrip line filereadline clusterappendlinestrip line filereadline linestripstartswithnode node nodeappendlinestrip line filereadline nodeappendlinestrip clusterappendnode line filereadline clustersappendcluster list clusters nodes list printclusters printclusters
i building python script network inventory internal system each system five clusters i looking way adjust list put one line per cluster here way stored system cluster one primary system node one xxxx node ip node two xxxx node ip cluster two primary system node one xxxx node ip node two xxxx node ip i need adjusted look like cluster oneprimary systemnode onexxxx node ipnode twoxxxx node ip cluster twoprimary systemnode onexxxx node ipnode twoxxxx node ip here really sloppy code i using right i wondering efficient way networktablecount lennetworktable count count networktablecount count temp networktablenetworktablenetworktablenetworktablenetworktablenetworktablen elif count temp networktablenetworktablenetworktablenetworktablenetworktablenetworktablen elif count temp networktablenetworktablenetworktablenetworktablenetworktablenetworktablen elif count temp networktablenetworktablenetworktablenetworktablenetworktablenetworktablen elif count temp networktablenetworktablenetworktablenetworktablenetworktablenetworktablen networktopologywritetemp count count i self taught python may simple adjustment thanks advance
1
read httpwwwsqlalchemyorgdocscoreschemahtmldefiningsequences key generation part database you simply want database assign unique keys
i created simple db using sqlalchemy python column unique user id user entered i want running counter supplies next id whenever new user added what would best way implement a column value last id number would entirely separate table seems wasteful is way check last userid add one here user base class class userbase tablename users id columninteger primarykey true emailaddress columnstring nullable false username columnstring nullable false password columnstring nullable false firstname columnstring fullname columnstring joindate columndatetime defaultfuncnow enters time upon initialization def initself emailaddress username password selfemailaddress emailaddress selfusername username selfpassword password def reprself return user selfemailaddress selfusername selfpassword selfjoindate
3
some additional details implement keyboardinteractive authentication i thought i working first time server sends two interactive requests the first requests contains prompt password false the second contains empty prompt the code works every server i tested far redhat ubuntu opensuse twistedconchssh import keys userauth class clientuserauthuserauthsshuserauthclient def getpasswordself prompt none normal password authentication print password auth return defersucceed your password def getgenericanswersself name instruction prompts interactive password authentication print interactive auth response lenprompts p enumerateprompts try password plower responsei your password except pass the response always sequence length always identical length prompts return defersucceedresponse enabling logging twisted helpful debugging conch hood well twistedpython import log logmsg started logging a conch program logstartloggingsysstdout
i trying override default authentication scheme twisted conch module something i thought i understood the script answer question i subclassing sshuserauthclient following way class clientuserauthsshuserauthclient def getpasswordself prompt none return defersucceed i obviously replacing sshuserauthclient call call class script for reasons i understand script executing getpassword method class superclass getpassword method does anyone know i wrong the change script i made i added following module import twistedinternet import defer thanks edit strangely subclass method getpublickey called correctly it getpassword method acting weird
2
you also use spynner allows programmatic web browsing
i’m writing little private app automatically log internet banking every day download latest transactions i’m writing django app i’m working python my internet banking doesn’t seem work without javascript — i think uses javascript assign session id sort fetching signin page via httplib gives page telling javascript’s required so i’m looking libraries fetch web pages execute javascript pretty much headless browsers i’m fiddling selenium moment i think it’ll job although designed testing web apps i wondering anything similar capabilities designed general purposes testing any python alternatives selenium sort thing
2
one thing might help use lists list comprehension statements loops eg qcount intrawinput how many questions per quiz quizitems strsamplerx x rangeqcount usersel mydictbookx x quizitems answers rangeqcount nextanswer intrawinput nwhich number sampleri answersappendbooksnextanswer
in code shows neophyteness python i took books kjv bible put logical order via list dictionary i used random method display random books user along position book random list user match something better learn books bible my difficulty figuring go saving results tallying number correctwrong i also would like give user option choose number questions like can someone give direction thanks import random import os name main books genesis exodus leviticus numbers deuteronomy joshua judges ruth i samuel ii samuel i kings ii kings i chronicles ii chronicles ezra nehemiah esther job psalms proverbs ecclesiastes song solomon isaiah jeremiah lamentations ezekiel daniel hosea joel amos obadiah jonah micah nahum habakkuk zephaniah haggai zechariah malachi matthew mark luke john acts romans i corinthians ii corinthians galatians ephesians philippians colossians i thessalonians ii thessalonians i timothy ii timothy titus philemon hebrews james i peter ii peter i john ii john iii john jude revelation title formatwelcome bible book quiznn selection rawinput the bible number strlenbooks booksn select next see belown formatnext exitn selection this section displays books bible indexes count indexmap bname enumeratebooks print nd formatcount bname indexmapcount count elif selection print title print n let start quiznnn else print you must select mydictbook genesis exodus leviticus numbers deuteronomy joshua judges ruth i samuel ii samuel i kings ii kings i chronicles ii chronicles ezra nehemiah esther job psalms proverbs ecclesiastes song solomon isaiah jeremiah lamentations ezekiel daniel hosea joel amos obadiah jonah micah nahum habakkuk zephaniah haggai zechariah malachi matthew mark luke john acts romans i corinthians ii corinthians galatians ephesians philippians colossians i thessalonians ii thessalonians i timothy ii timothy titus philemon hebrews james i peter ii peter i john ii john iii john jude revelation newdict dictfromkeysbooks counter print newdict try this section starts random book selection index match usersel print nnn here first books quiz n sampler randomsamplebooks first strsampler second strsampler third strsampler fourth strsampler fifth strsampler usersel mydictbookfirst mydictbooksecond mydictbookthird mydictbookfourth mydictbookfifth numsampler randomsampleusersel print sampler print nmatch correct numeric position print n numsampler samp intrawinput nwhich number sampler samp intrawinput which number sampler samp intrawinput which number sampler samp intrawinput which number sampler samp intrawinput which number sampler taking users answer finding resultant book need put statement condition answerbookssamp answerbookssamp answerbookssamp answerbookssamp answerbookssamp taking book finding numeric value associated right mydictbookanswer right mydictbookanswer right mydictbookanswer right mydictbookanswer right mydictbookanswer display answers yield print nyour answers yieldn print stranswer print stranswer print stranswer print stranswer print stranswer takes random books converts strings first strsampler second strsampler third strsampler fourth strsampler fifth strsampler print numeric value string value correct answers print nthe correct answers print sampler mydictbookfirst tstmnt print sampler mydictbooksecond tstmnt print sampler mydictbookthird tstmnt print sampler mydictbookfourth tstmnt print sampler mydictbookfifth tstmnt continue except valueerror break
1
my difficulty figuring go saving results tallying number correctwrong i also would like give user option choose number questions like can someone give direction i guess something like right wrong numsamp rawinputenter amount samples xrangenumsamp answer intrawinput nwhich number sampleri bookanswer sampleri rightright else wrongwrong
in code shows neophyteness python i took books kjv bible put logical order via list dictionary i used random method display random books user along position book random list user match something better learn books bible my difficulty figuring go saving results tallying number correctwrong i also would like give user option choose number questions like can someone give direction thanks import random import os name main books genesis exodus leviticus numbers deuteronomy joshua judges ruth i samuel ii samuel i kings ii kings i chronicles ii chronicles ezra nehemiah esther job psalms proverbs ecclesiastes song solomon isaiah jeremiah lamentations ezekiel daniel hosea joel amos obadiah jonah micah nahum habakkuk zephaniah haggai zechariah malachi matthew mark luke john acts romans i corinthians ii corinthians galatians ephesians philippians colossians i thessalonians ii thessalonians i timothy ii timothy titus philemon hebrews james i peter ii peter i john ii john iii john jude revelation title formatwelcome bible book quiznn selection rawinput the bible number strlenbooks booksn select next see belown formatnext exitn selection this section displays books bible indexes count indexmap bname enumeratebooks print nd formatcount bname indexmapcount count elif selection print title print n let start quiznnn else print you must select mydictbook genesis exodus leviticus numbers deuteronomy joshua judges ruth i samuel ii samuel i kings ii kings i chronicles ii chronicles ezra nehemiah esther job psalms proverbs ecclesiastes song solomon isaiah jeremiah lamentations ezekiel daniel hosea joel amos obadiah jonah micah nahum habakkuk zephaniah haggai zechariah malachi matthew mark luke john acts romans i corinthians ii corinthians galatians ephesians philippians colossians i thessalonians ii thessalonians i timothy ii timothy titus philemon hebrews james i peter ii peter i john ii john iii john jude revelation newdict dictfromkeysbooks counter print newdict try this section starts random book selection index match usersel print nnn here first books quiz n sampler randomsamplebooks first strsampler second strsampler third strsampler fourth strsampler fifth strsampler usersel mydictbookfirst mydictbooksecond mydictbookthird mydictbookfourth mydictbookfifth numsampler randomsampleusersel print sampler print nmatch correct numeric position print n numsampler samp intrawinput nwhich number sampler samp intrawinput which number sampler samp intrawinput which number sampler samp intrawinput which number sampler samp intrawinput which number sampler taking users answer finding resultant book need put statement condition answerbookssamp answerbookssamp answerbookssamp answerbookssamp answerbookssamp taking book finding numeric value associated right mydictbookanswer right mydictbookanswer right mydictbookanswer right mydictbookanswer right mydictbookanswer display answers yield print nyour answers yieldn print stranswer print stranswer print stranswer print stranswer print stranswer takes random books converts strings first strsampler second strsampler third strsampler fourth strsampler fifth strsampler print numeric value string value correct answers print nthe correct answers print sampler mydictbookfirst tstmnt print sampler mydictbooksecond tstmnt print sampler mydictbookthird tstmnt print sampler mydictbookfourth tstmnt print sampler mydictbookfifth tstmnt continue except valueerror break
1
depending want handle edge cases seems work def pointsbetweenp p xs rangep p p ys rangep p p return xy x xs ys print pointsbetween print pointsbetween
this fairly easy i getting headache trying figure i want list coordinates two points like in or in it need work diagonals
1
you appear beginning programmer a general technique i find useful job paper look translate program if see break simpler steps
this fairly easy i getting headache trying figure i want list coordinates two points like in or in it need work diagonals
2
maybe django httpwwwgoogleplsearchqdjangotreemenu js httpwwwgoogleplsearchqjavascripttreemenu better jquery httpwwwgoogleplsearchqjquerytreemenu anyway simple cases hard make impl
i web app three frames banner menu content the menu frame needs dynamic rollup menu example teachers create edit delete schools create edit delete view staff classrooms create edit delete if click schools hideunhide items the menu needs dynamically drawn user login based user group role some users may authorized see classrooms edit users see everything is anything built plugin anyone used would provide framework i need
1
simple implementation using jquery div idmenu ateachersabr div styledisplay none hrefeditabr hrefdeleteabr div aschoolsabr div styledisplay none hrefeditabr hrefdeleteabr div div script typetextjavascript srchttpajaxgoogleapiscomajaxlibsjqueryjqueryminjsscript script typetextjavascript menu clickfunction thisnextnextslidetoggle return false script
i web app three frames banner menu content the menu frame needs dynamic rollup menu example teachers create edit delete schools create edit delete view staff classrooms create edit delete if click schools hideunhide items the menu needs dynamically drawn user login based user group role some users may authorized see classrooms edit users see everything is anything built plugin anyone used would provide framework i need
3
if absolutely know final size array increment size array like myarr numpyzeros range myarrnumpyconcatenate myarr numpyones printmyarr notice first line numpyappend another option it calls numpyconcatenate
i figure use array matrix way i would normally use list i want create empty array matrix add one column row time at moment way i find like mat none col columns mat none mat col else mat hstackmat col whereas list i something like list item data listappenditem is way use kind notation numpy arrays matrices
1
looks like smth windowsspecific did try provide full path python executable command line like ccodepythonbinpythonexe managepy celerydmulti start settingssettings l info also use full paths python file usefull ccodepythonbinpythonexe cpathtoyourprojectmanagepy celerydmulti start settingssettings l info
so far i working python managepy celeryd starting like python managepy celeryd l info settingssettings the code view binaryexectaskdelayrequestpostbinarypath and code settingspy import djcelery djcelerysetuploader brokerbackend djkombutransportdatabasetransport celery brokerhost localhost brokerport brokeruser guest brokerpassword guest brokervhost execute binaries background the thing binaries take pretty short time run others may take half hour working celeryd tasks blocked current one finishes execution i saw examples starting celerydmulti running python managepy celerydmulti start settingssettings l info gives error celerydmulti v starting nodes celeryx traceback recent call last file managepy line module executemanagersettings file ccodepythonlibsitepackagesdjangopyeggdjangocoremanagement line executemanager utilityexecute file ccodepythonlibsitepackagesdjangopyeggdjangocoremanagement line execute selffetchcommandsubcommandrunfromargvselfargv file ccodepythonlibsitepackagesdjangocelerypyeggdjcelerymanage scelerydmultipy line runfromargv argv argv argv file ccodepythonlibsitepackagescelerypyeggcelerybincelerydmul executefromcommandline selfcommandsargvargv cmd file ccodepythonlibsitepackagescelerypyeggcelerybincelerydmul start retcode selfwaitexecargv file ccodepythonlibsitepackagescelerypyeggcelerybincelerydmul waitexec pipe popenargstr envselfenv file ccodepythonlibsubprocesspy line init errread errwrite file ccodepythonlibsubprocesspy line executechild startupinfo windowserror error the system cannot find file specified the celerydmulti start c throws error what i i could succesfully start celery instance allow run tasks parallel also would i need something different view edit debugging led sitepackagescelerypyeggcelerybincelerydmultipywaitexec def waitexecself argv pathsysexecutable args joinpath listargv argstr shlexsplitargsencodeutf pipe popenargstr envselfenv pdb p argstr ccodepythonpythonexe managepy celeryddetach l info pidfilecelerydpid n celeryx logfilecelerydlog pdb p popenargstr envselfenv windowserror windowserror the system cannot find file specified pdb so see path python gets destroyed what i next edit i opened issue
1
two ideas come mind test another robust webserver nginx it run concurrently need see problem persists while paste handle web apps meant handle huge file transfers far i know are using chunked transfer encoding upload
so i rather vexing issue file uploads pylons i hoping someone might able assist originally i posted issue thinking issue pylons i since come conclude issue due server ie paste i tracked exactly issue occurs unsure resolve the behavior follows i pylons web application i serving via paster one piece application allows users upload files systems sometimes rather big mb during uploads server sporadically resets connection ie chrome error reads error neterrconnectionreset the connection reset this always occur time larger files on cases server never hands post application level no exception thrown least i find i narrowed issue cascadepy particular wsgiapplication method invoked httpserverpy from latter result selfserverwsgiapplicationselfwsgienviron selfwsgistartresponse in call function cascadepy file appears written temporary file the relevant loop begins copylen it writes chunks one one open file none writes individually throws exception however server often simply go away writes seemingly random time seem correlated either so i print copylen size decremented i watch decrease point server sudden sends connection reset least client thinks method seems exited copylen ceases printed loop exited though i completely stumped happens sporadically i seem track actual errorexception sort dies if matters i running paste python fedora os does anyone insight might happening i might able resolve thank much help
1
it like says fileopened openfno w that line code problem typeerror coercing unicode need string buffer file found that problem w string clearly fno causes problem the problem string buffer needed actually file you need string buffer filename parameter open the purpose open open files given file name already file so use file
why error appear error exception tkinter callback traceback recent call last file cpythonliblibtktkinterpy line call return selffuncargs file editorpy line onopen fileopened openfno w typeerror coercing unicode need string buffer file found code httpscodegooglecompchildreneditorsourcebrowsetrunkeditornewpy
1
you need set size request textview container scroll example window textview try following import gtk name main window gtkwindowgtkwindowtoplevel scroll gtkscrolledwindow scrollsetpolicygtkpolicynever gtkpolicyalways view gtktextview viewsetwrapmodegtkwrapchar scrollsetsizerequest scrolladdview windowaddscroll windowshowall gtkmain
i textview inside scrolledwindow refuses wrap wordscharswordschars matter i set wrap mode it simply extends size containers pleases here example import gtk window gtkwindowgtkwindowtoplevel windowsetdefaultsize scroll gtkscrolledwindow scrollsetpolicygtkpolicynever gtkpolicyalways view gtktextview viewsetwrapmodegtkwrapchar scrolladdview windowaddscroll windowshowall gtkmain how i make wrap if matters i need parent window resizeable user text
1
you use one following css rule graphicsviewsetstylesheetborderwidth px borderstyle solid graphicsviewsetstylesheetborder px your border disappear import sys pyqtqtgui import class uiqwidget def initself parentnone qwidgetinitself parent graphicsview qgraphicsview graphicsviewsetstylesheetborder px grid qgridlayout gridaddwidgetgraphicsview selfsetlayoutgrid app qapplicationsysargv ui ui uishow sysexitappexec here widget default style httpistackimgurcomgpwawpng and widget style applied httpistackimgurcomakupng
i tried calling selfsetstylesheetbackground transparent border transparent qgraphicsview still leaves pixel border top edge i also tried replacing border transparent borderstyle none work either here screenshot problem what command fully remove border qgraphicsview
2
after posting i discovered nifty little library ftputil httpftputilsschwarzernet presents different ftp interface cribs much os ospath modules possible using final code went roughly like import ftputil host ftputilftphostconstantsftphost constantsftplogin constantsftppass hostmakedirspath hostclose
i ftp ing pile files python directory trees may exist is ftp version makedirs available somewhere i build scratch
1
you actually creating entity key you change counter counterdbkeyfrompath counter defaultcounter counter counterkeydbkeyfrompath counter defaultcounter and since immediately setting amount could initializing entity well counter counterkeydbkeyfrompath counter defaultcounter amount please also note good way create counter app engine you want use technique like sharded counters something using memcached
i first small project pythongae difficulty operating gae database using queries but comes editing single entity i face problem all i need simple counter would increment every site visit so i create entity done create entity code removed project countername defaultcounter def counterkeycounternnone return dbkeyfrompath counter countername class counterdbmodel amount dbintegerproperty class counterclasswebapprequesthandler def getself counter countercounterkeycountername counteramount counterput it ok but i try increment using counter dbgetdbkeyfrompath counter defaultcounter counteramount counterput i get error error webapppy nonetype object attribute amount traceback recent call last file cprogram files xgooglegoogleappenginegoogleappengineextwebappwebapppy line call handlerpostgroups file hgaebincounterpy line post counteramount attributeerror nonetype object attribute amount i checked different variations still cant change entity value what i wrong thanks advance
1
the code use create counter entity likely wrong what creating counter entity whose parent counter keyname equal defaultcounter that seem want evidenced code use update counter you need assign keyname counter entity via one following ways counter counterkeyname defaultcounter counter counterkeydbkeyfrompath counter defaultcounter note general bad idea visit counter like gae entities limti updates per seconds ever scale beyond run problems common technique dealing update limitation use sharding counters described httpcodegooglecomintlplappenginearticlesshardingcountershtml a combination datastore memcache also option mind occasionally losing counter increments
i first small project pythongae difficulty operating gae database using queries but comes editing single entity i face problem all i need simple counter would increment every site visit so i create entity done create entity code removed project countername defaultcounter def counterkeycounternnone return dbkeyfrompath counter countername class counterdbmodel amount dbintegerproperty class counterclasswebapprequesthandler def getself counter countercounterkeycountername counteramount counterput it ok but i try increment using counter dbgetdbkeyfrompath counter defaultcounter counteramount counterput i get error error webapppy nonetype object attribute amount traceback recent call last file cprogram files xgooglegoogleappenginegoogleappengineextwebappwebapppy line call handlerpostgroups file hgaebincounterpy line post counteramount attributeerror nonetype object attribute amount i checked different variations still cant change entity value what i wrong thanks advance
1
import time timesleep this sleep seconds see httpdocspythonorglibrarytimehtmltimesleep
i working integrate api limit number requests per second is way running loop python delay cycle conceptually something like def functionrequest x abcd something wait seconds thank
3
create index tuple first index numpyst xindex
suppose i defined xx numpy array x numpyarangereshape now i get array containing element x subarray x returns array what i tuple mn want retrieve mn element subarray stored tuple for example suppose i i tried x right behaviour returns rows subarray the simplest solution i found xtransposetuplereversedttranspose i sure must better way of course case i could x generalised case i know many dimensions x
3
replace angle angle pi
i created simple polar plot using matplotlib i trying make plot degrees top clock position rather righthand side clock position i see simple way matplotlib documentation i found older question stackoverflow accepted answer seem work year old i thought may better way any ideas
2
perhaps i missing something django objects dict attribute seems want
if came google looking model dict skip question jump first answer my question confuse is good way django entire set model objects single dictionary i mean like class dictmodelmodelsmodel key modelscharfield value modelscharfield dictmodelobjectsalltodict result dictionary keyvalue pairs made records model has anyone else seen useful thanks update i wanted add ultimate goal able simple variable lookup inside template something like dictmodelexamplekey with result dictmodelobjectsgetkeyexactexamplekeyvalue overall though guys really surprised helpful allof responses different ways approach thanks lot update october this question top result google django modeltodict actually pretty awful given solves different problem i asking what i wanted able map instances queryset single dictionary specified model field key modeltodict hand converts single model instance dictionary now needs time pretty darn specific probably extremely rare i even remember project i needed so i would pretty surprised anyone looking information modeltodict going find question actually useful sorry modeltodict seems much common usage case i update dec i changed title hopefully better reflect original intent
2
collections import defaultdict dictb defaultdictlist b listb dictbb id appendb lista things b dictba id things appendb turn algorithm onm omon nlenlista mlenlistb basically avoids looping dict listb dict lista precalculating dicts listb match id
i lists dictionaries list a long list b long i essentially inserting list b dicts list a dicts based key match currently i obvious taking forever seriously like day there must quicker way lista things b listb id b id things appendb
2
here approach may help i leave fill details your code slow on algorithm comparing every a every b if sort lista listb id first onlogn operations iterate easily sorted versions a b linear time this approach common external merges large data sets mihai answer better internal merging simply index everything id memory if memory hold additional structures dictionary lookup constant time approach likely faster mention simpler by way example let say a following ids sorting acfgjp b ids sorting aaaabbbbcccddeeeefffggiikknnnnppppqqqrrr the idea strangely enough keep indexes a b i know sound pythonic at first looking a b so walk b adding things array once exhaust b move one a c but next item b b less c skip b then arrive c b start adding things c continue fashion lists exhausted just one pass
i lists dictionaries list a long list b long i essentially inserting list b dicts list a dicts based key match currently i obvious taking forever seriously like day there must quicker way lista things b listb id b id things appendb
1
there optional saveas parameter sendblob function by default set false setting true cause file treated attachment ie trigger saveopen download dialog user see proper filename example class servehandlerblobstorehandlersblobstoredownloadhandler def getself resource resource strurllibunquoteresource blobinfo blobstoreblobinfogetresource selfsendblobblobinfosaveastrue it also possible overwrite filename passing string selfsendblobblobinfosaveas myfiletxt if want content pdfs open rather save could use contenttype determine behavior blobinfo blobstoreblobinfogetresource type blobinfocontenttype type applicationpdf selfresponseheaders contenttype type selfsendblobblobinfosaveasfalse else selfsendblobblobinfosaveastrue
i using google app engine blobstore store range file types pdf xls etc trying find mechanism original filename uploaded file stored blobinfo used name downloaded file ie user sees somefilepdf save dialogue rather verylongdbkeypdf i see anything docs would allow httpcodegooglecomappenginedocspythonblobstoreoverviewhtml i seen hints posts could use information blobinfo set contentdisposition header is best approach achieving desired end
3
import logging class progressconsolehandlerloggingstreamhandler a handler class allows cursor stay one line selected messages onsameline false def emitself record try msg selfformatrecord stream selfstream sameline hasattrrecord sameline selfonsameline sameline streamwriteselfterminator streamwritemsg sameline streamwrite selfonsameline true else streamwriteselfterminator selfonsameline false selfflush except keyboardinterrupt systemexit raise except selfhandleerrorrecord name main import time progress progressconsolehandler console loggingstreamhandler logger logginggetlogger test loggersetlevelloggingdebug loggeraddhandlerprogress loggerinfo test range loggerinfo remaining seconds extra sameline true timesleep loggerinfo test notice one handler registered extra keyword argument let handler know stay one line there logic emit method handle changes messages stay one line messages need line
how write custom console log function output console window log messages single line append first regular log record progress progressconsolehandler console loggingstreamhandler logger logginggetlogger test loggersetlevelloggingdebug loggeraddhandlerconsole loggeraddhandlerprogress loggerinfo test range loggerprogress remaining seconds timesleep loggerinfo test so console output three lines info test remaining seconds info test any suggestions best way implement
3
you use javascript ajaxstyle post background save whatever information like click then redirect page success
the following html works user clicks word music shows html page ie httpssnuackrmusichtml href onclickparentcontentlocation httpssnuackrmusichtml return falsemusica my question user clicks word web way system server write clicked word music separate file server using python cgi i need store userclicked words separate file perform task server i stuck proceeding part any tips would helpful thanks
1
import random import os name main books genesis exodus leviticus numbers deuteronomy joshua judges ruth i samuel ii samuel i kings ii kings i chronicles ii chronicles ezra nehemiah esther job psalms proverbs ecclesiastes song solomon isaiah jeremiah lamentations ezekiel daniel hosea joel amos obadiah jonah micah nahum habakkuk zephaniah haggai zechariah malachi matthew mark luke john acts romans i corinthians ii corinthians galatians ephesians philippians colossians i thessalonians ii thessalonians i timothy ii timothy titus philemon hebrews james i peter ii peter i john ii john iii john jude revelation mydictbook dictbnamei ibname enumeratebooksstart true selection rawinput the bible number booksn lenbooks select next see belown formatprint all books start quizn selection print n join formati bname ibname mydictbookiteritems break elif selection print nlet start quiznnformatwelcome bible book quiznn break else print you must select try numques intrawinput nenter number questions wanna asked sampler randomsamplebooks numques sampler exit numsampler maplambda bname mydictbookbname sampler print numsampler numsampler print nnnhere first books quiz ns nmatch correct numeric positions ns numques strsampler strrandomsamplenumsamplernumques samp intrawinput nwhich number booksi numsampler zipsampsampler yoursort print nyour answers yieldn n join nbk nbk correct zipnumsamplersampler correctsort print nthe correct answers n join nbk nbk correct continue except valueerror break
in code shows neophyteness python i took books kjv bible put logical order via list dictionary i used random method display random books user along position book random list user match something better learn books bible my difficulty figuring go saving results tallying number correctwrong i also would like give user option choose number questions like can someone give direction thanks import random import os name main books genesis exodus leviticus numbers deuteronomy joshua judges ruth i samuel ii samuel i kings ii kings i chronicles ii chronicles ezra nehemiah esther job psalms proverbs ecclesiastes song solomon isaiah jeremiah lamentations ezekiel daniel hosea joel amos obadiah jonah micah nahum habakkuk zephaniah haggai zechariah malachi matthew mark luke john acts romans i corinthians ii corinthians galatians ephesians philippians colossians i thessalonians ii thessalonians i timothy ii timothy titus philemon hebrews james i peter ii peter i john ii john iii john jude revelation title formatwelcome bible book quiznn selection rawinput the bible number strlenbooks booksn select next see belown formatnext exitn selection this section displays books bible indexes count indexmap bname enumeratebooks print nd formatcount bname indexmapcount count elif selection print title print n let start quiznnn else print you must select mydictbook genesis exodus leviticus numbers deuteronomy joshua judges ruth i samuel ii samuel i kings ii kings i chronicles ii chronicles ezra nehemiah esther job psalms proverbs ecclesiastes song solomon isaiah jeremiah lamentations ezekiel daniel hosea joel amos obadiah jonah micah nahum habakkuk zephaniah haggai zechariah malachi matthew mark luke john acts romans i corinthians ii corinthians galatians ephesians philippians colossians i thessalonians ii thessalonians i timothy ii timothy titus philemon hebrews james i peter ii peter i john ii john iii john jude revelation newdict dictfromkeysbooks counter print newdict try this section starts random book selection index match usersel print nnn here first books quiz n sampler randomsamplebooks first strsampler second strsampler third strsampler fourth strsampler fifth strsampler usersel mydictbookfirst mydictbooksecond mydictbookthird mydictbookfourth mydictbookfifth numsampler randomsampleusersel print sampler print nmatch correct numeric position print n numsampler samp intrawinput nwhich number sampler samp intrawinput which number sampler samp intrawinput which number sampler samp intrawinput which number sampler samp intrawinput which number sampler taking users answer finding resultant book need put statement condition answerbookssamp answerbookssamp answerbookssamp answerbookssamp answerbookssamp taking book finding numeric value associated right mydictbookanswer right mydictbookanswer right mydictbookanswer right mydictbookanswer right mydictbookanswer display answers yield print nyour answers yieldn print stranswer print stranswer print stranswer print stranswer print stranswer takes random books converts strings first strsampler second strsampler third strsampler fourth strsampler fifth strsampler print numeric value string value correct answers print nthe correct answers print sampler mydictbookfirst tstmnt print sampler mydictbooksecond tstmnt print sampler mydictbookthird tstmnt print sampler mydictbookfourth tstmnt print sampler mydictbookfifth tstmnt continue except valueerror break
1
you could add results another table unless compelling reason calculated column adjacent columns probably easiest there something said separating raw data calculations anyways if must increase size table look using hpy it provides direct interface h file keep mind depending data set created h file may possible simply append column data see section dataspace httpwwwhdfgrouporghdfdocugdatamodelhtml discussion regarding general data format hpy supports resize underlying dataset supports you could also use single buffer store input data like z zerosnrows n moredatainfile read data block zn fromfile yourparams set final column znn fzn append data tableshandleappendz
i trying append large dataset gb existing pytables table the table n columns dataset n columns one column calculated i know n columns i using numpyfromfile read chunks dataset memory appending database ideally i like stick data database calculate final column finish using tablemodifycolumn complete operation i considered appending numpyzeroslennewdata n table using tablemodifycolumns fill new data i hopeful someone knows nice way avoid generating huge array empty data chunk i need append
1
this get started i current time passed function datetime argument est work def findnextcurdt import datetime dt dttime dttime dttime dttime curt curdttime curd curdtdate rangelent ti curt rt tjilent j rangelent rd curd lenti curd dttimedeltadaysi return dtdatetimecombinerdjrtj j rangelenrt everything happens tomorrow return dtdatetimecombinecurd dttimedeltadays the result objects order starting soonest one
i need generate four datetime objects python the next instance am est the next instance am est the next instance pm est the next instance pm est then i need find closest current datetime i wish i could say i starting code i idea start one
1
hyry solution correct i always found numpy r c index tricks bit strange looking so equivalent thing using slice object xslicenone that single argument slice stop position ie none meaning way x equivalent xnonenone
suppose i defined xx numpy array x numpyarangereshape now i get array containing element x subarray x returns array what i tuple mn want retrieve mn element subarray stored tuple for example suppose i i tried x right behaviour returns rows subarray the simplest solution i found xtransposetuplereversedttranspose i sure must better way of course case i could x generalised case i know many dimensions x
2
you create yet another orm layer rather waste lot time reinventing wheel learn existing orm adapt one nosql database engine choice start example sqlalchemy orm want sql because python duck typing invent compatible nosql orm repository orm anything else think important do however reinvent wheel scratch read implementations sqlobject django orm sqlalchemy good places start
i wondering ways accomplish abstracting data storage access away main application small example ioc framework seems overkill maybe passing object via constructor parameter facade pseudocode good way things fill missing pieces python mainpy resp repositoryenginenosql easily switch nosql respsavehello respselecthello repositorypy class repository def initself engine selfengine engine def saveself str enginesavestr def selectself str engineselectstr nosqlpy class nosql def saveself str nosqlsavestr def selectself str nosqlselectstr mysqlpy class mysql def saveself str mysqlsavestr def selectself str mysqlselectstr
1
if columns type use numpylibstridetricksasstrided make array read file shape l n look like shape l n for example in numpyarangereshape in out array in astrides out in b numpylibstridetricksasstrideda shape strides in b out array now use array b fill table the last column row first column next row overwrite compute values this work record array ie complex dtype for try numpylibrecfunctionsappendfields as copy data new array save significant amount memory allow writing
i trying append large dataset gb existing pytables table the table n columns dataset n columns one column calculated i know n columns i using numpyfromfile read chunks dataset memory appending database ideally i like stick data database calculate final column finish using tablemodifycolumn complete operation i considered appending numpyzeroslennewdata n table using tablemodifycolumns fill new data i hopeful someone knows nice way avoid generating huge array empty data chunk i need append
1
here one wxpython httpwxgladesourceforgenet
i hoping find tool similar borland delphi visualbasic python basically i want able program windows apps ease without actually code every single widget does software exist thanks
3
based comment i would simply create book class author class author list chapter class assign chapters book list chapter objects book maintain authorlist dict ids pointing actual author objects use data member book object contain id provide method pull author authorlist dict convenience
following xml file bookxml xml version sample xml document bookstore book ide title sample xml book title author name idau first benjamin first last smith last name affiliation a affiliation author chapter number title first chapter title para b count count para chapter chapter number title third chapter title para b count count para chapter book book idc title xml master title author name idau first john first last doe last name affiliation c affiliation author chapter number title second chapter title para k count count para chapter chapter number title third chapter title para k count count para chapter chapter number title seventh chapter title para k count count para chapter chapter number title ninth chapter title para k count count para chapter book bookstore following python code bookdompy xmldom import minidom node import textwrap class samplescanner def initself doc child docchildnodes childnodetype nodeelementnode childtagname bookstore selfhandlebookstorechild def gettextself nodelist retlist node nodelist nodenodetype nodetextnode retlistappendnodewholetext elif nodehaschildnodes retlistappendselfgettextnodechildnodes return resub joinretlist def handlebookstoreself node child nodechildnodes childnodetype nodeelementnode continue childtagname book selfhandlebookchild def handlebookself node child nodechildnodes childnodetype nodeelementnode continue childtagname title print book title selfgettextchildchildnodes childtagname author selfhandleauthorchild childtagname chapter selfhandlechapterchild def handleauthorself node child nodechildnodes childnodetype nodeelementnode continue childtagname name selfhandleauthornamechild elif childtagname affiliation print author affiliation selfgettextchild def handleauthornameself node surname selfgettextnodegetelementsbytagnamelast givenname selfgettextnodegetelementsbytagnamefirst print author name surname givenname def handlechapterself node print start chapter nodegetattribute number selfgettextnodegetelementsbytagname title child nodechildnodes childnodetype nodeelementnode continue childtagname para selfhandleparachild def handleparaself node partext selfgettextnode partext textwrapfillpartext print partext print doc minidomparse bookxml samplescannerdoc output python bookdompy book id e book title sample xml book name id au author name smith benjamin author affiliation a start chapter first chapter b start chapter third chapter b book id c book title xml master name id au author name doe john author affiliation c start chapter second chapter k start chapter third chapter k start chapter seventh chapter k start chapter ninth chapter k my aim store books books table author info authors table preserving book author relationship mysql db book table id title e sample xml book chapter table bookidchapternumbertitle para e first chapter b e third chapter b author table id bookid name affiliation au e smith benjamin a how i go storing data database i thousand books authors chapters i trouble uniquely identifying dataset bookauthor i use ids pass functions preserve relation i sure best way any pointers highly appreciated ps i working sql part script update i test feel free post thoughts code samples thanks
1
here using qt designer qt httpdiotavellinetpyqtwikicreatingguiapplicationswithpyqtandqtdesigner you might also want look traits it pretty easy simple designs
i hoping find tool similar borland delphi visualbasic python basically i want able program windows apps ease without actually code every single widget does software exist thanks
2
datetimeastimezone basic conversion datetime object if trying get datetime object string pip install pythondateutil simple dateutilparser import parse dateutiltz import tzoffset dt parse datetimedatetime tzinfotzoffsetnone dtastimezonetzoffsetnone datetimedatetime tzinfotzoffsetnone
i timestamp timezone information string format i would like convert display correct datetime using local timezone so eg i timestamp i would like convert say timezone offset dsiplay timestamp i tried using pytz couldnt find many examples showing use offset information one link i found stackoverflow depicts exact problem i hoping better way i could handle using pytz thanks suggestions advance update thanks cixate i found solution similar found links helpful link link posting solution everyones benefit datetime import datetime import sys os import pytz dateutilparser import parse datestr dt parsedatestr print dt localtime dtastimezone pytztimezone australiamelbourne print localtimestrftime ymd hms
3
print u hello ä½ å¥½ bye encode unicodeescape hello ufud bye but consider using json via json
for example i file ajs whose content hello ä½ å¥½ bye which contains two chinese characters whose unicode form ufud i want write python program convert chinese characters ajs unicode form output bjs whose content hello ufud bye my code fp openajs content fpread fpclose fp openbjs w result contentdecodeutf fpwriteresult fpclose seems chinese characters still one character ascii string like i want
3
that actually limit underlying select system call from man page an fdset fixed size buffer executing fdclr fdset value fd negative equal larger fdsetsize result undefined behavior and standard fdsetsize usrincludelinuxposixtypeshdefine fdsetsize so python issue the poll epoll system calls much larger limit what really need use use selectepoll object still select module instead select
the workaround issue supervisord compile python supports file descriptors httpsgithubcomsupervisorsupervisorissues can someone please walk changes necessary accomplish i python source extracted ready go running centos matters thanks update ulimit n already set this full error i getting starting supervisord traceback recent call last file usrlocalbinsupervisord line loadentrypoint supervisora consolescripts supervisord file usrlocallibpythonsitepackagessupervisorapyeggsupervisorsupervisordpy line main gooptions file usrlocallibpythonsitepackagessupervisorapyeggsupervisorsupervisordpy line go dmain file usrlocallibpythonsitepackagessupervisorapyeggsupervisorsupervisordpy line main selfrun file usrlocallibpythonsitepackagessupervisorapyeggsupervisorsupervisordpy line run selfrunforever file usrlocallibpythonsitepackagessupervisorapyeggsupervisorsupervisordpy line runforever r w x selfoptionsselectr w x timeout file usrlocallibpythonsitepackagessupervisorapyeggsupervisoroptionspy line select return selectselectr w x timeout valueerror filedescriptor range select
1
you try codecs module codecsopenfilename mode encoding errors buffering codecsopenajs r cpread unicode object codecsopenbjs w utfwritea
for example i file ajs whose content hello ä½ å¥½ bye which contains two chinese characters whose unicode form ufud i want write python program convert chinese characters ajs unicode form output bjs whose content hello ufud bye my code fp openajs content fpread fpclose fp openbjs w result contentdecodeutf fpwriteresult fpclose seems chinese characters still one character ascii string like i want
1
the devappserver production environment concept projects libraries need structure app necessary libraries application root the easiest way usually symlink subdirectories worstcase copy using version control make subrepositories how maps operations ide depends ide general probably easiest get app structured need disk work backwards get ide set like
couple months i started development python c java background i currently working different pythonappengine applications often happens cases application share common code i would like refactor move commongeneric code shared place in either java c i create new library project move code new project add reference library main projects i tried python i unable make work i using eclipse pydev plugin i created new pydev project moved code attempted reference library project main projects using project properties project references add library src folder folder main projects case i error i presume possible leave project boundaries adding existing source folder add external library pretty much google libraries defined using properties external libraries import link import file system enabling create links workspace in cases i able reference library code developing i start debugging appengine development server throws exception find i moved separate library project of course i searched solution lot looks like nobody experienced problem maybe nobody need the closest solution i able find add ant script zip library sources copy target project way debugging pain i unable step library code any suggestion needless say proposed solution must take account library code included upload process appengine thanks
2
this called natsort natural sort a quick google gives httpwwwskynetiecaolanpackagespythonnatsorthtml tried though maybe helps oh necessarily ascii sort number order know like real axis
this might sound like silly question i tried find answer works without much success i got list lists v sortedlist print v i iterated list using sorted function however brings items ascii order sorted floats human readable order ie do i need create index somekind convert floats ints any help much appreciated david
1
you need give sorted comparison function something like following sortedlist cmplambda x cmpx just write function need want plug you probably want something like reverse radix sort
this might sound like silly question i tried find answer works without much success i got list lists v sortedlist print v i iterated list using sorted function however brings items ascii order sorted floats human readable order ie do i need create index somekind convert floats ints any help much appreciated david
1
a design patterns help prototype factory abstract factory use two patterns configuration objects each method take configuration object use needs also consider applying logical grouping config parameters think ways reduce number inputs psuedo code consider run three different kinds simulations sim sim sim configfactory configfactory new configfactorypathtooptionfile simulation sim simulation sim simulation sim simrun configfactoryconfigforsim simrun configfactoryconfigforsim simrun configfactoryconfigforsim inside factory method might create configuration prototype object sane defaults option file becomes things different default this would paired clear documentation defaults person program might want change edit also consider config returned factory subset overall config
lets say i program large number configuration options the user specify config file my program parse config file internally store pass around options in case software used perform scientific simulation there options sane defaults typically user specify dozen the difficulty i face design internal code many objects need constructed depend many configuration options for example object might need several paths data stored options need passed algorithms object call options used directly object this leads objects needing large number arguments constructed additionally codebase active development big pain go call stack pass along new configuration option way needed one way prevent pain global configuration object freely used anywhere code i particularly like approach leads functions classes take one argument obvious reader data functionclass deals it also prevents code reuse code depends giant config object can anyone give advice program like structured here example i mean configuration option passing style class a def initself opta optb optz selfopta opta selfoptb optb selfoptz optz def fooself arg algoarg opta opte here example global config style class a def initself config selfconfig config def fooself arg algoarg config the examples python question stands similar programming langauge
1
pass around either config parsing class write class wraps intelligently pulls requested options python standard library configparser exposes sections options ini style configuration file using mapping protocol retrieve options directly though dictionary myconf configparserconfigparser myconfread myconfini whattodo myconf section option if explicitly want provide options using attribute notation create class overrides getattr class myconf def initself path selfparser configparserconfigparser selfparserread myconfini def getattrself option return selfparser whattodo section optionoption myconf myconf whattodo myconfwhattodo
lets say i program large number configuration options the user specify config file my program parse config file internally store pass around options in case software used perform scientific simulation there options sane defaults typically user specify dozen the difficulty i face design internal code many objects need constructed depend many configuration options for example object might need several paths data stored options need passed algorithms object call options used directly object this leads objects needing large number arguments constructed additionally codebase active development big pain go call stack pass along new configuration option way needed one way prevent pain global configuration object freely used anywhere code i particularly like approach leads functions classes take one argument obvious reader data functionclass deals it also prevents code reuse code depends giant config object can anyone give advice program like structured here example i mean configuration option passing style class a def initself opta optb optz selfopta opta selfoptb optb selfoptz optz def fooself arg algoarg opta opte here example global config style class a def initself config selfconfig config def fooself arg algoarg config the examples python question stands similar programming langauge
1
convert float string first split sorteda keylambda xmapint strfloatxsplit
this might sound like silly question i tried find answer works without much success i got list lists v sortedlist print v i iterated list using sorted function however brings items ascii order sorted floats human readable order ie do i need create index somekind convert floats ints any help much appreciated david
2
this kind hack v sorteda keylambda strtsplit intstrtsplit strt print v result disclaimer assumes places decimal point adjust accordingly
this might sound like silly question i tried find answer works without much success i got list lists v sortedlist print v i iterated list using sorted function however brings items ascii order sorted floats human readable order ie do i need create index somekind convert floats ints any help much appreciated david
1
matplotlib large package many configuration options it use rcparams module manage default parameters rcparams save default parameters dict every functions get options keyword argurments example def fxyoptanone optbnone opta none opta rcparams groupopta
lets say i program large number configuration options the user specify config file my program parse config file internally store pass around options in case software used perform scientific simulation there options sane defaults typically user specify dozen the difficulty i face design internal code many objects need constructed depend many configuration options for example object might need several paths data stored options need passed algorithms object call options used directly object this leads objects needing large number arguments constructed additionally codebase active development big pain go call stack pass along new configuration option way needed one way prevent pain global configuration object freely used anywhere code i particularly like approach leads functions classes take one argument obvious reader data functionclass deals it also prevents code reuse code depends giant config object can anyone give advice program like structured here example i mean configuration option passing style class a def initself opta optb optz selfopta opta selfoptb optb selfoptz optz def fooself arg algoarg opta opte here example global config style class a def initself config selfconfig config def fooself arg algoarg config the examples python question stands similar programming langauge
3
particularly given technique knearest neighbors mentioned q would strongly recommend scikitslearn note answer posted lead developer project informed new homepage project a features believe distinguish library others least python ml libraries used extensive diagnostics amp testing library including plotting modules via matplotlibincludes featureselection algorithms confusion matrix roc precisionrecall etc nice selection batteriesincluded data sets including handwriting digits facial images etc particularly suited ml techniques extensive documentation nice surprise given project two years old including tutorials stepbystep example code use supplied data sets without exception least think moment python ml libraries superb see pymvpa homepag e list dozen popular python ml libraries in past months instance used ffnet mlp neurolab also mlp pybrain qlearning neurolab mlp pymvpa svm available python package index vary significantly wrt maturity scope supplied infrastructure found high quality still best might scikitslearn instance aware python ml libraryother scikitslearnthat includes three features mentioned though solid example code andor tutorials none know integrate library researchgrade data sets diagnostic algorithms second given technique intend use knearest neighbor scikitslearn particularly good choice scikitslearn includes knn algorithms regression returns score classification returns class label well detailed sample code using scikitslearn knearest neighbor module literally easier import numpy relevant scikitslearn module import numpy np sklearn import neighbors knn load one sklearnsuppplied data sets sklearn import datasets iris datasetsloadiris call loadiris loaded data class labels bind variable data irisdata classlabels iristarget construct classifierbuilder instantiating knn module primary class knn knnneighborsclassifier construct train classifier passing data class labels classifierbuilder knnfitdata classlabels neighborsclassifiernneighbors leafsize algorithm auto what unlike nearly ml techniques crux knearest neighbors coding working classifier builder rather difficult step building productiongrade knearest neighbor classifierregressor persistence layerie storage fast retrieval data points nearest neighbors selected for knn data storage layer scikitslearn includes algorithm ball tree know almost nothing apparently superior kdtree traditional data structure knn performance degrade higher dimensional features space additionally knearest neighbors requires appropriate similarity metric euclidean distance usual choice though always best one scikitslearn includes standalong module comprised various distance metrics well testing algorithms selection appropriate one finally libraries mentioned either scope pyml bayesian primarily libraries developers rather applications end users eg orange unusual difficulttoinstall dependencies eg mlpy requires gsl turn must built source least os mac os x note developercommitter scikitslearn
i need classify data i hope nearestneighbour algorithm i googled problem found lot libraries including pyml mlpy orange i unsure start how i go implementing knn using python
3
to make mouse look right direction i try pygametransformrotate make degrees rotation depend directionx directiony variables greater less zero
i learning python pygame working simple game play mouse avoid snakes spawn every seconds roam across screen right i trying get mouse sprite face direction moving the image mouse facing i tried couple ideas get face right direction nothing worked hoping someone could help here code collision detection yet basic code mouse still usrbinpython imports import os sys math import pygame random pygamelocals import sets path game images maindir ospathsplitospathabspathfile datadir ospathjoinmaindir data pygameinit main screen background width height screen pygamedisplaysetmodewidth height pygamedisplaysetcaptiondon get eaten background pygameimageloadospathjoindatadir liquidbmp background pygametransformscalebackground width height screenblitbackground game time setup clock pygametimeclock pygametimesettimeruserevent functions assist image loading def loadimagefile file ospathjoindatadir file surface pygameimageloadfile return surfaceconvertalpha def loadimagesfiles imgs file files imgsappendloadimagefile return imgs class player mouse class mousepygamespritesprite speed def initself image loadimage mousepng image pygametransformscaleimage pygamespritespriteinitselfselfgroups selfimage image selfrect selfimagegetrect surface pygamedisplaygetsurface selfrectcenter width height selfarea surfacegetrect def movexself directionx selfrectmoveipdirectionxselfspeed def moveyself directiony selfrectmoveip directionyselfspeed def updateself pass class snake enemy class snakepygamespritesprite def initself pygamespritespriteinitselfselfgroups image loadimagerandomchoice snakepng snakepng snakepng image pygametransformscaleimage selfimage image selfrect selfimagegetrect surface pygamedisplaygetsurface selfarea surfacegetrect selfmovex randomrandint selfmovey randomrandint def updateself selfrect selfrectmoveselfmovexselfmovey selfrectleft selfarealeft selfrectright selfarearight selfmovex selfmovex newpos selfrectmoveselfmovex selfimage pygametransformflipselfimage selfrect newpos selfrecttop selfareatop selfrectbottom selfareabottom selfmovey selfmovey newpos selfrectmove selfmovey selfrect newpos pregame setup allsprites pygamespritegroup snakesprites pygamespritegroup mousesprites pygamespritegroup snakegroups allsprites snakesprites mousegroups allsprites mousesprites mouse mouse snake snake def main main game loop setup blits seconds clocktick screenblitbackground game events event pygameeventget eventtype pygamequit sysexit elif eventtype userevent snake keystate pygamekeygetpressed directionx keystatekright keystatekleft directiony keystatekup keystatekdown mousemovexdirectionx mousemoveydirectiony allspritesupdate allspritesdrawscreen pygamedisplayupdate pygamedisplayflip clocktick name main main
1
have look itertoolsmodule particulary product method example usage itertoolsproductrange repeat stuff listappendruniii note function call shortened listappendruni example see docspythonorg explanation unpacking argument lists as example output productrange repeat looks like
i working python currently following code list range b range c range listappendrunabc runabc returns integer example could multiply three numbers together is faster way either loop numbers use map function thanks
3
i think use imap itertools import imap result listimaprun range range range imap yields result want iterate results use list
i working python currently following code list range b range c range listappendrunabc runabc returns integer example could multiply three numbers together is faster way either loop numbers use map function thanks
1
itertools import product mylist runa b c b c productxrange xrange xrange or itertools import product mylist runa b c b c productxrange repeat
i working python currently following code list range b range c range listappendrunabc runabc returns integer example could multiply three numbers together is faster way either loop numbers use map function thanks
1
use sympy sympy import abcde symbolsabcde x bcminde csqrtxe values abcde print x print print xsubsvalues print ysubsvalues print nxsubsvalues print nysubsvalues output bc c ea bc
i looking way store series formulasequations text easily diffable later formulas depend results earlier ones i able evaluate formulas similar live worksheets mathcad numeric results also able programmatically produce string representation original formula put another way i like able treat formulas data well evaluate formulas i would like text editor syntax highlighting editing formulas my first approach python file formulas stored strings call eval strings however allow syntax highlighting formulas my language choice python i would open nonproprietary solutions example b c e x b c mind e c sqrtx e the intent automatically generate code using evaluated results formulas commenting generated code original formulas
2
you use subprocess module python if logs big simply use python result subprocesscheckoutputpathtoprocesstolauch arg python process subprocesspopenpathtoprocesstolauch arg stdoutsubprocesspipe stderrsubprocesspipe strout strerrr processcommunicate strout find standard output process strerr find standard output process but outputs really big let talk mo ko may cause memory overflow in case big output use file handles stdout stderr outfile openoutfilename w errfile openoutfilename w process subprocesspopenpathtoprocesstolauch arg stdoutoutfile stderrerrfile returncode processwait outfileclose errfileclose and outfile find output process errfile error output of course want relaunch process die put code loop
java program runs particular port ubuntu while running program need take output program needs save log file i use nohub run currentlywhen fail i know failthen process restart nohub get overwritten i want process restart update log file i check later date currently i know state running failed i heard pretty easy using python scripts anyone please help thanks advance renjith raj
1
using python certainly possible if reading mysql might check mysqlpython reading text file use file open filename r filereadline get line parse however added overhead using python if text file orderly one reacord per row row number columns consistent delimiter comma tab semicolon etc efficient way load directly in mysql something like load data infile folderinputdat into table destinationtable fields terminated by idfieldfieldfield if need minor modifications file changing commas things beginning end line might use command line sed nix osx install windows update load data infile quickest httpdevmysqlcomdocrefmanenloaddatahtml when say start article text text text maino maino different fields if fields header article might format text document look something like this header articleand article nice story programming my article goes many lines and many this second article headerand article it and etc then could use load data infile like load data infile folderfilenametxt into table destinationtable lines terminated by fields terminated by headerarticle
i trying load text file database my text file gb i need write python script load text file headers database any guidelines i go thanks
1
there multiple ways solve install webserver local machine write fullfledged python web application write simple webserver application python using basehttpserver write htmljavascript application use python parses file note due recently tightened restrictions may still require served webserver write python application writes database javascript file while inflexible need run every time want update database also simple encode data json write javascript file element like htmlfile open databasehtml w htmlfilewrite html htmlfilewrite scriptvar db jsonencodedatabase script either way going write html javascript
i created database python results kept text file i would like create simple html search button looks database my database would accessible computer my database looks something like reference name dimension xxx aaa so example i search specific reference i would like obtain name dimension obviously is even possible python i start i mention i basic skills html python
1
try replacing sysexit finishedloading qapplicationinstanceexit
i trying hand scraping javascript reliant site it pretty basic site simple list entires names cities actually i want copy paste excel the list controlled javascript i figur i need use something like qt emulate browser i trying pyside i started basic code i adapted usrbinenv python import sys import signal import argparse pysideqtcore import pysideqtgui import pysideqtwebkit import qwebpage class crawler qwebpage def initself url file qwebpageinit self selfurl url selffile file def crawl self signalsignal signalsigint signalsigdfl selfconnect self signal loadfinishedbool selffinishedloading selfmainframeload qurl selfurl def finishedloading self result file open selffile w filewrite selfmainframetohtml fileclose sysexit def main app qapplication sysargv args getargs crawler crawler argsurl argsfile crawlercrawl sysexit appexec def getargs command argument parser returns structure argsurl argsfile parser argparseargumentparserdescription basic scraper parseraddargument u url dest url help url fetch data default httpwwwgooglecom parseraddargument f file dest file help local file path save data default datatxt args parserparseargs return args name main main problem i know pysideqt really well i get error error calling slot finishedloading i even sure means is something i get around without engaging long arduous process figuring qt pyside is simple fix thanks input
1
as noone else offered solution using generator one sample thisisagoodexample def uppersplitdata buff item data itemisupper buff yield buff buff buff item yield buff listuppersplitsample this is a good example joinuppersplitsamplelower thisisagoodexample
i new python i trying replace uppercaseletters within word underscores example thisisagoodexample become thisisagoodexample any ideastipslinkstutorials achieve
1
did set fixturedirs setting value settingspy see documentation
i trying use postrgesql django apps i get following error right starting project i following files initpy managepy settingspyc urlspyc initpyc settingspy urlspy i added models python managepy syncdb creating tables installing custom sql installing indexes no fixtures found i even trying load fixtures psycopg installed this database section settingspy databases default engine djangodbbackendspostgresqlpsycopg add postgresqlpsycopg postgresql mysql sqlite oracle name myappdevelopment or path database file using sqlite user foo not used sqlite password password not used sqlite host set empty string localhost not used sqlite port set empty string default not used sqlite
1
you simple use case already web server installed probably simplest quickest way use cgi script written python check cgi module httpdocspythonorglibrarycgihtml basically handle get request show html form asking query string post request process query show results
i created database python results kept text file i would like create simple html search button looks database my database would accessible computer my database looks something like reference name dimension xxx aaa so example i search specific reference i would like obtain name dimension obviously is even possible python i start i mention i basic skills html python
1
this passes tests including extra i created it uses recursion here rules i used the first letter abbreviation must match first letter text the rest abbreviation abbrev minus first letter must abbreviation remaining words remaining text starting position first word tests fck fc kopenhavn true fco fc kopenhavn false irl real life true irnl real life false ifk ifk gotebork true ifko ifk gotebork false aik allmanna idrottskluben true aid allmanna idrottskluben true manu manchester united true fz faz zoo true fzz faz zoo true fzzz faz zoo false def isabbrevabbrev text abbrevabbrevlower texttextlower wordstextsplit abbrev return true abbrev text return false abbrevtext return false else return isabbrevabbrev joinwords anyisabbrevabbrevtexti rangelenwords abbrevtextanswer tests resultisabbrevabbrevtext printabbrevtextresultanswer assert resultanswer
i trying develop python algorithm check string could abbrevation another word for example fck match fc kopenhavn matches first characters word fhk would match fco match fc kopenhavn one irl would abbrevate fc kopenhavn fco irl match real life ifk match ifk goteborg aik match allmanna idrottskluben aid match allmanna idrottsklubben this real team name abbrevation i guess hard exclude unless apply domain specific knowledge swedish abbrevations formed manu match manchester united it hard describe exact rules algorithm i hope examples show i update i made mistake showing strings matching letters uppercased in real scenario letters lowercase easy checking letters uppercased
3
this type encoding known mime encodedword email module decode emailheader import decodeheader print decodeheaderutfbieryzwltbhdhnmcmlzdcbmwxyifzlcnbmbgvndwnclahjhdwzzwkdw this outputs list tuples containing decoded string encoding used this format supports different encodings single header to merge single string need convert shared encoding concatenate accomplished using python unicode object emailheader import decodeheader dh decodeheader gewstutfbifdlzzhbgwgzgvyifzvcmzdphvmawdrzwl defaultcharset ascii print join unicodet defaultcharset dh update the problem subject line decoding subject elstamutfbifzlcmbdvgdbmcgdmtidix januar is actually senders fault violates requirement encodedwords header separated whitespace specified rfc section paragraph encodedword appears header field defined text must separated adjacent encodedword text linearwhitespace if need work around preprocessing corrupt headers regex inserts whitespace encodedword part unless end like import headervalue resubr r headervalue
python module helps decode various forms encoded mail headers mainly subject simple say utf strings here example subject headers mail files i subject utfbimknidensbbynm ao subject gewstutfbifdlzzhbgwgzgvyifzvcmzdphvmawdrzwl subject utfbieryzwltbhdhnmcmlzdcbmwxyifzlcnbmbgvndwnclahjhdwzzwkdw utfbzvuigvpbmvzifnlzwhbmz text encoded sting text text encoded string text encoded string encoded string encodig could also something else like iso update i forgot mention i tried emailheaderdecodeheader item messageitems item subject sub emailheaderdecodeheaderitem loggingdebug subject sub this outputs debugrootsubject elstamutfbifzlcmbdvgdbmcgdmtidix januar none really help update thanks ingmar hupp comments first example decodes list two tupels print decodeheader gewstutfbifdlzzhbgwgzgvyifzvcmzdphvmawdrzwl gewst none wegfall der vorlxcxaufigkeit utf always string encodingstring encoding i need loop concat items one string get one string subject elstamutfbifzlcmbdvgdbmcgdmtidix januar decode well print decodeheader elstamutfbifzlcmbdvgdbmcgdmtidix januar elstamutfbifzlcmbdvgdbmcgdmtidix januar none
3
setopenfile amp setopenfile equivalent using intersection pythonic way you might able speed setintx x openfile amp setintx x openfile since storing comparing integers rather strings this works ids numeric course if still fast enough turn slightly imperative style heuristic set smallerfile largerfile checking file size setintx x opensmallerfile note storing strings r r setx x openlargerfile intx if files guaranteed contain duplicates also use list speed things setintx x opensmallerfile r x x openlargerfile intx be sure measure various solutions check whether actually waiting disk network input
i two large files their contents looks like the file contains unsorted list ids some ids may appear one time single file now i want find intersection part two files that ids appear files i read two files sets and get intersection sintersections but consumes lot memory seems slow so better pythonic way if file contains many ids read set limited memory i edit i read file sets using generator def idgenpath line openpath tmp linesplit yield inttmp c idgenpath setc all ids numeric and max id may if use bitarray consume memory
2
i happy say fact possible lines code i know easy toolkits tkinter import import os root tk termf frameroot height width termfpackfillboth expandyes wid termfwinfoid ossystem xterm geometry x sb amp wid rootmainloop the problem use wrong function wid
i want embed terminal main tkinter window i would like sub window terminal bash based terminal would run i would like also able let program interact terminal least i would like read current working directory andor set i know really impossible i able past perltk maybe replicated the code i used something like framemwframeborderwidth relief groove label stuff thought labelbackgroundcadrawwincolorbackgroundcadrawwincolor cvframecanvasheightcvheightwidthcvwidthbackgroundcadrawwincolor bg cadrawwincolor relief sunken packexpand fill frame needed including xterm tkcanvas xtermcontainer cvframecontainer xtid xtermcontainerid converting id hex decimal xterm requires decimal id xtid sprintf hex xtid dcontitem cvcreatewindowxtermwidthxtermheight window xtermcontainer width xtermwidth height xtermheight state normal systemxterm xtid fn fontname geometry geometry sb bg black fg white e xtermjobpl aafname amp mw main tk window of course i completely agree bryan though i never programmed gui library program rather large kind wiki running well surprisingly low amount code devoted gui i tried translating perl code i stumbling id problem the place i found reference way extract id tkinter effbot i use i get attributeerror frame instance attribute windowid must something wrong termf frameroot termfpacksidebottom fillx idtermfwindowid ossystemxterm fn miscfixedmediumrnormalciso geometry x sb bg black fg white e rootbashrc amp id
3