text_a
stringlengths 9
150
| text_b
stringlengths 18
20.9k
| labels
int64 0
2
|
---|---|---|
how do i mount a filesystem using python | pbadly mounting and unmounting belongs to the things that are highly system dependent and since they arep
ul
lirarely used andli
lican affect system stabilityli
ul
pthere is no solution that is portable available since that i agree with ferdinand beyer that it is unlikely a general python solution is existingp
| 0 |
whenever handlers executed need to push message to zeromq stays hanging | blockquote
pis this real way to push to zeromq whenever the handler is executedp
blockquote
pno your code calls zmqcontext every time the request handler is invoked this is bad it should be called exactly once usually at the very beginning of your process perhaps in some kind of init handler you can safely share the context instance among any number of threadsp
psame thing with socket creation and binding this should be done once at startup you must be more careful with the socket if all your handlers application request etc are executing in the same thread each time the handler is called then you can use the same socketp
panother problem is the way your a sending to a push socket as described in a hrefhttpapizeromqorg323azmqsocket relnofollowhttpapizeromqorg32zmqsocketa a send to a push socket may very well block in certain situations and you probably want to avoid that use the zmqpoller with the pollout flag and a 0 timeout to determine if the send would block if not then send right away if so you have to decide if you want to just drop the message or store it in your application to try again laterp
| 0 |
how should i append to small filelike objects in mongodb | pyou could just store the data as binary or text in a mongodb collection but youd have two problemsp
ol
lipyoud have to implement as much of the python file protocol as your other code expects to have implementedpli
lipwhen you append to the file the document would grow in mongodb and possibly need to be moved on disk to a location with enough space to hold the larger document moving documents is expensivepli
ol
pgo with gridfs the documentation discourages you from using for emstaticem files but for your case its perfect because pymongo has done the work for you of implementing pythons file protocol for mongodb data to append to a gridfs file you must read it save a new version with the additional data and delete the previous version but this isnt much more expensive than moving a grown document anywayp
| 0 |
finding the last occurrence of an item in a list python | precodedef positionlastx l
try return maxi for ie in enumeratel if ex
except return none
codepre
| 0 |
python error ioerror errno2 bad interpretation of file or directory | pyou can try replace codecode to codecodep
| 0 |
how to open readwrite file and recreate the file | pif you want quick and structured files use pythons csv libraryp
precodeimport csv
mainheaders state chinese
compounddata
with openlanguages1csv r as csvfile
csvreader csvdictreadercsvfile
for row in csvreader
compounddataappendrow
printcompounddata
with openlanguages2csv r as csvfile
csvreader csvdictreadercsvfile
for row in csvreader
compounddataappendrow
printcompounddata
codepre
poutputp
precodestate ca chinese 10 state vt chinese 20
state ca chinese 10 state vt chinese 20 state ca vietnamese 01 state vt vietnamese 15
codepre
ponce you have your data you can rewrite to csv file or whatever file you want and apply formattingp
| 0 |
triangular numbers using loops python | pcould be something like this p
precodedef alltrianglenumbersn
for i in range1 n 1
printn 0 triangle 1formati i 2 i2
alltrianglenumbers10
codepre
| 0 |
distinguishing 2 lines in a file read | puse a hrefhttpsdocspythonorg3libraryjsonhtml relnofollowthe codejsoncode modulea to parse jsonp
pstrongpython 3 codestrongp
precodeimport json
import subprocess
with subprocesspopencat tmpfoojson stdoutsubprocesspipe as f
j fstdoutread
o jsonloadsjdecodeutf8
printo
printodef1val1
printodef29val1
codepre
pstrongoutputstrongp
precodedef1 val1 316 val2 10 def2 9 val1 201 val2 22
316
201
codepre
pstrongeditstrongp
pfor python 2 use this insteadp
precodeimport json
import subprocess
f subprocesspopencat tmpfoojson stdoutsubprocesspipe
j fstdoutread
o jsonloadsjdecodeutf8
print o
print odef1val1
print odef29val1
codepre
| 0 |
python number guessing game | pyou just have to define your main function like thisp
precodedef main
global randomnumber
print
randomnumber randomrandrange1 1000
number inputi have a number between 1 and 1000 can you guess my number please type your first guess
guessnumber
codepre
pand everything will be perfect hope this helpsp
| 0 |
why is my python programme running correctly in my virtual environment despite not having the packages installed in that environment | pyou have installed prettytables globally when you create a virtual environment it will include the globally installed packages hence the reason why your program is running p
| 0 |
python programming socket stream to functions | pa hrefhttpstackoverflowcomquestions2483041whatisthedifferencebetweenforkandthreadthisa should give you a brief idea of threads vs forkp
pcreation of threads require lot less overhead i would go with the thread architecture each of the three thread functions will be supplied with the respective queue on which it needs to do the realtime computation use of synchronization and mutual exclusion mechanisms will prevent unexpected behaviors you can also use valgrind with drd for debugging your multithreaded programp
| 0 |
enabledhcp returns 81 unable to configure dhcp service | pit looks like you are using windows 7 make sure to run the script as administratorp
| 0 |
adding up number in a list with every 3 number | pthis will skip the remaining numbers that cant fit into a group of threep
precodegtgtgt def sumthreeiterable
iterable iteriterable
while true
yield nextiterable nextiterable nextiterable
gtgtgt mylist 0 1 0 2 0 4 99 1
gtgtgt listsumthreemylist
gtgtgt 1 6
codepre
| 0 |
in python how do you create a 2d list from a file and assign a type to each item in each sublist | pthe main problem you have is that codefreadlinescode reads everything as a string you can then map each item in your sublist through a type checker like thisp
precodedef typechecks
try
return ints
except valueerror
try
return floats
except
return s
codepre
pwill try to explicitly cast your parameter as an int then a float then just leave it as is it is this order because all things that can be cast as a int can also be cast as a float but not the other way around so you want to check for the codeintcode first ie code1231code will raise an error for codeint1231code but not codefloat1231codep
pyou can then append the mapped list like thisp
precodefor line in lines
mylistappendlistmaptypechecklinestripsplit
codepre
pand your values that can be converted to floats and int will be convertedp
pexamplep
precodegtgtgt def typechecks
try
return ints
except valueerror
try
return floats
except
return s
gtgtgt l afghanistan 6475000 25500100 albania 287480 2821977 algeria 23817400 38700000 american samoa 1990 55519 andorra 4680 76246
gtgtgt for i in l printlistmaptypechecki
afghanistan 6475000 25500100
albania 287480 2821977
algeria 23817400 38700000
'american samoa', 199.0, 55519]
['andorra', 468.0, 76246]
</code></pre>
| 0 |
removing a variable from a list of comma seperated email ids | psplit it out by comma then join back them back on comma minus the excluded onep
precodemsgto joinemail for email in msgtosplit if email username1companycom
codepre
pyou could also generalise it to have a list of do not mails egp
precodedonotmail username1companynamecom username2anothercompanycom
def emailbody subject tonone
msg mimetexts body
msgcontenttype texthtml
msgfrom serviceaccountcompanycom
msgto joinemail for email in settodifferencedonotmail
codepre
| 0 |
table equating old and new python string formatting | pid say yes there is from the a hrefhttpsdocspythonorg2librarystringhtmlformatexamples relnofollowpython documentationap
blockquote
pemthis section contains examples of the new format syntax and comparison with the old formattingemp
blockquote
pheres a summary of whats in therep
precode old new arg result
s s foo foo
r r foo foo
c c x x
f f 314 3140000
f f 314 3140000
f f 314 3140000
d d 42 42
x x 42 2a
o `{:o}` | `42` | `52` |
| `â
` | `{:b}` | `42` | `101010` |
</code></pre>
<p>i guess the upper case equivalent work the same. </p>
<p>to prepend the digital base:</p>
<pre><code>| old | new | arg | result |
| ----- | ------- | ------- | -------- |
| `%#d` | `{:#d}` | `42` | `42` |
| `%#x` | `{:#x}` | `42` | `0x2a` |
| `%#o` | `{:#o}` | `42` | `052` |
| `â
` | `{:#b}` | `42` | `0b101010` |
</code></pre>
<p>and to convert the number to scientific notation:</p>
<pre><code>| old | new | arg | result |
| ----- | ------- | ------- | -------- |
| `%e` | `{:e}` | `0.00314` | 3.140000e-03 |
</code></pre>
<p>for the alignment, there is:</p>
<pre><code>| old | new | arg | result |
| ----- | ------- | ------- | -------- |
| `%-12s` | `{:<12}` | `meaw` | ` meaw` |
| `%+12s` | `{:>12}` | `meaw` | `meaw ` |
</code></pre>
<p>for filling:</p>
<pre><code>| old | new | arg | result |
| ----- | ------- | ------- | -------- |
| `%012d` | `{:>012}` | `42` | `000000000042` |
</code></pre>
<p>as you can see, most of the base symbols are the same between old format and new format. the main difference, is that the new format is a well defined language matching the following grammar:</p>
<pre><code>format_spec ::= [[fill]align][sign][#][0][width][.precision][type]
</code></pre>
<p>whereas the old format was a bit more voodoo.</p>
| 0 |
quicksort first element as pivot quick code check | pmodified your code as belowp
precodedef quicksortalist l r
if l lt r
swap l1
pivot alistl
for run in range l1r
if pivot gt alistrun
alistswapalistrun alistrunalistswap
swap1
alistlalistswap1 alistswap1alistl
quicksortalist l swap1
quicksortalist swap r
return alist
test 46372
t quicksorttest0lentest
print t
codepre
| 0 |
trouble comparing elements of sets python | pyou can use a combination of intersection and set to solve this problemp
precodegtgtgt s1 set123
gtgtgt s2 set345
gtgtgt s3 set678
gtgtgt lens1intersections2
1
gtgtgt lens1intersections3
0
codepre
pso basically write an if statement to check the length of the intersection of the two sets if length is greater than 0 make newlist equal to your second setp
| 0 |
python keyerror with formgetfirst | ptry codeltdtmlvar requestjobidgtcodep
| 0 |
django 14 with apache2 | pperhaps you should change your test like this use a variable already instantiated for testing in the if statement your testing for a variable codefalsecode and codenonecode is evaluating as codefalsecode in that testp
precodemodelfound false
try
applabel modelname settingsauthprofilemodulesplit
profile modelsgetmodelapplabel modelname
modelfound true
except importerror improperlyconfigured
raise siteprofilenotavailable
if not modelfound
raise siteprofilenotavailable
codepre
| 0 |
error unknown file type hpp in distutils extension module | pare you sure header files are supposed to go in the sources argument and not in another like headersp
| 0 |
scraping product names using beautifulsoup | pyour code is correct but the problem is that the div which includes the product name is dynamically generated via javascript
in order to be able to successfully parse this element you should mind using a hrefhttpseleniumhqorg relnofollowseleniuma or a similar tool that will allow you to parse the webpage after all the dom has been fully loadedp
| 0 |
list of tuples from a all b to b all a | pa sorting version for funp
precodeimport itertools
import operator
function to get first element of a tuple
fst operatoritemgetter0
def invertitems
b a pairs sorted by b
pairs sortedb a for a bs in items for b in bs
b b a groups
groups itertoolsgroupbypairs keyfst
b a groups
return b a for a in items for b items in groups
printinvert
a1 b1 b2 b3
a2 b2
a3 b1 b2
codepre
| 0 |
script to move messages from one imap server to another | pim not sure what volume of messages youre dealing with but you could extract the codemessageidcode from each one and use that to find out if its a duplicate either generate a list of ids already on the target server each time you prepare to move messages or add them to a simple database as they are archivedp
pyou could narrow things down by an additional message property like codedatecode if the lookups are too expensive then drop the older lists when you no longer need themp
| 0 |
access a node of string label with an int part of the string | pnetworkx keeps the nodes and edges of the graph in a dictionary structure where the node is the key and its data is an associated dictionary structure apparently when you read the pajek file format given your example file the dictionnary is this onep
precodegtgtgt g nxreadpajektestpj
gtgtgt pprintgnode
uauthor1 id u123
uauthor2 id u456
uauthor3 id u789
uauthor4 id u111
uauthor5 id u222
uauthor6 id u333
codepre
pwhich means node codeuauthor1code is associated with data codeid u123codep
pnow i dont know in the pajek file format which field is supposed to be the actual node maybe its not implemented correctly in networkx but if you reverse names and ids in your file you get what you wantp
precodenetwork
vertices 6
author1 123
author2 456
author3 789
author4 111
author5 222
author6 333
edges
123 333
333 789
789 222
codepre
pandp
precodegtgtgt g nxreadpajektestpj
gtgtgt pprintgnode
u111 id uauthor4
u123 id uauthor1
u222 id uauthor5
u333 id uauthor6
u456 id uauthor2
u789 id uauthor3
>>> g.node['111']
{'id': u'author4'}
</code></pre>
<p>moreover, the node id is a string, not an integer. if you need an integer, you may need to relabel the nodes.</p>
| 0 |
management of photos for django applications | pwhat about using the django filebrowser and reference your photos from the folders you upload to
a hrefhttpcodegooglecompdjangofilebrowser relnofollowdjangofilebrowserap
| 0 |
python code to play an audio file | pthis will work if the alarm noise file is in the same directory as the python file itself i do warn you though this is very clunky and the sound file is opened separately but nevertheless it does what you requiredp
precodeimport os time
while true
osstartfilefilename of sound replace with the appropriate file name make sure the alarm sound is in the same directory as the python file else this will not work
timesleepdelay in seconds this is how long the delay is between each time it opens the sound
codepre
| 0 |
cant find a string within a string only one char | pthis is weird i figured out that the error was not in source code but in text file
although it has txt suffix and it looks like a standard text file in pspad its not running the script from dos i discovered that there are spaces between each letter in the file so i examined it with an hex editor and i found that its an unicode file
i dont know why it happened i obtained the file by saving an excel xls file in txt formatp
| 0 |
automatically changing name of downloaded files using python | pif i understand the problem correctly you could loop through the files in your download directory each time you download a new file and look for the file with a dash in it then make the character replacement on that file this should do itp
precodeusrbinpython
import subprocess os
def renamefile
for f in oslistdirosgetcwd
if in f and fendswithcsv
osrenameffreplace
file openlinks20151111txtr
for url in file
print downloadin urlstrip
subprocesscallwget contentdisposition urlstrip
renamefile
codepre
pdepending on how the file names are structured you may need to tighten the criteria for your file search you could compile a regular expression to match the text format more strictly p
| 0 |
django logging from batchcron scripts | pdefine logging in settingspy in following wayp
precodelogging
version 1
disableexistingloggers false
handlers
file
level debug
class loggingfilehandler
filename pathtododailymagiclog
loggers
myappmyscriptlogger
handlers file
level debug
propagate true
codepre
pthan you can use logger codemyappmyscriptloggercode to write info to the file directly from djangop
precodeimport logging
logger logginggetloggermyappmyscriptlogger
class commandbasecommand
def handleself args options
do some stuff
loggerinfosome info for logs
codepre
phowever i suggest you to keep logging from crontab as well because it can handle any error that happens before invocation of django for example it will also handle missing python interpreter or wrong environmentp
pps if you just want to write all logs from django to stdout use following config for loggerp
precodelogging
version 1
disableexistingloggers false
handlers
console
class loggingstreamhandler
loggers
myappmyscriptlogger
handlers console
level debug
propagate true
codepre
| 0 |
append numpy ndarray to pandas dataframe | pcreate iteratively the array to make it 10x100 then pass it to codedataframecodep
pyou can use codenpinsertcode or codenpvstackcode to create the 10x100 arrayp
| 0 |
how to update a field based on the update of another field | pi was able to resolve the issue i changed the code to thisp
precodecustomerobjchangechangedictfieldupdatenewaccountfieldrefnewaccount6
codepre
pthis grabbed the 6 digits as necessary and i was able to eliminate a line of code p
| 0 |
django 17 how to purge single users all sessions to allow access to app only from one tab | pyou do not understand exactly how sessions work what you want to do cannot be enforced in a secure mannerp
pimagine that sessions amp cookies work much in the same way that your safety deposit box amp security key work anyone with an extra copy of the keycookie will be able to access the session from anywhere they please there is no way with your simple implementation of doing something funny with sessions in django to overcome this limitation so just forget about itp
plarger websites such as facebook get around this problem by using more advanced mechanisms of security ssl heuristics etcp
| 0 |
mezzanine customizing profiles | pthis question is a bit old but i think you can safely ignore the warningp
pyou should be able to accomplish the extra configuration by connecting to the pre or post save signal for the profile modelp
| 0 |
python extract values from text using keys | passuming your file is in something called sampletxttxt this would work it creates a dictionary mapping from key list of valuesp
precodeimport re
with opensampletxttxt r as f
txt fread
keys firstname lastname color
d
for key in keys
dkey refindallkeyrssn txt
codepre
| 0 |
separate year from other number in python | passuming a year is four digits long and is an integerp
precodedef intlenn
length 0
while n gt 0
length 1
n 10
return length
ll 700 13844 5 1862 398 30 2050 30 981 180 10 6 640 29 4653 45 114 10 231 2002 2002 17647 10
print i for i in ll if typei int and intleni 4
out 1862 2002 2002
codepre
| 0 |
linking two programs together in python | pif you are using a hrefhttpswikipythonorgmoinpyqt relnofollowpyqta you can use a hrefhttppyqtsourceforgenetdocspyqt4newstylesignalsslotshtml relnofollowsignals and slotsa to define a callback function when a certain button is clickedp
pyou can hide the ui of the current program and display the ui of the other program when the button is clickedp
| 0 |
search patterns with variable gaps in python | precodeimport re
def grepl pattern
r recompilepattern
return for in l if rsearchpattern
nameselected grepnames tw2t
codepre
pnote the use of codewcode instead of codealphacodep
| 0 |
django orderby in cbv | pyou can try something like to order my queryset by nevp
pfor ascendingp
precodedef getquerysetself
qs selfmodelobjectsorderbynev
codepre
pfor descendingp
precodedef getquerysetself
qs selfmodelobjectsorderbynev
codepre
| 0 |
python break a function nested inside a loop | pyou can use a hrefhttpsdocspythonorg2libraryexceptionshtmlexceptionsstopiteration relnofollowcodestopiterationcodea to exit from all loops until its caughtp
precodetry
for i in range10
if i 5
raise stopiteration
else
print i
except stopiteration
print caught
codepre
pgivesp
p0
1
2
3
4
caughtp
pthe codestopiterationcode codeexceptioncode is exactly that an exception not an errorp
blockquote
praised by an iterators next method to signal that there are no
further values this is derived from exception rather than
standarderror since this is not considered an error in its normal
applicationp
blockquote
pyou can put it as deeply as you want in your nested loops but you have to catch it at the level you want to break out of ie the level at which you want to emstop iterationem top
plooking at your question and trying to make sense of what youve written it looks like you want to do something like this maybep
precodefor url in listofurls
if urlqueryurl
htmlminingurl
def urlqueryurl
page parseurllibrequesturlopenurl
return text in pageread
here is where i want a statement to stop and go to the next
item in the loop like continue in a for loop
codepre
pthis will then only run codehtmlminingurlcode when codetextcode is in the page youre parsing if its not it will skip that entry and move onto the next onep
| 0 |
how to fetch the value from form errors attribute in django | pnot very elegant but can try thisp
precode for field in form
if fielderrors
fieldlabel fielderrors
endif
endfor
codepre
| 0 |
how do you check an object is an instance of file | ptypically you dont need to check an object type you could use ducktyping instead ie just call codefreadcode directly and allow the possible exceptions to propagate it is either a bug in your code or a bug in the caller code eg codejsonloadcode raises codeattributeerrorcode if you give it an object that has no codereadcode attributep
pif you need to distinguish between several acceptable input types you could use codehasattrgetattrcodep
precodedef readfileorfilename
readfile getattrfileorfilename read none
if readfile is not none got file
return readfile
with openfileorfilename as file got filename
return fileread
codepre
pif you want to support a case when codefileoffilenamecode may have codereadcode attribute that is set to codenonecode then you could use codetryexceptcode over codefileorfilenamereadcode note no parens the call is not made eg a hrefhttphgpythonorgcpythonfile34libxmletreeelementtreepyl787 relnofollowcodeelementtreegetwritercodeap
pif you want to check certain guarantees eg that only one single system call is made codeiorawiobasereadncode for n 0 or there are no short writes codeiobufferediobasewritecode or whether readwrite methods accept text data codeiotextiobasecode then you could use codeisinstancecode function with a hrefhttpsdocspythonorg3libraryiohtmlclasshierarchy relnofollowabcs defined in codeiocode modulea eg a hrefhttphgpythonorg/cpython/file/3.4/lib/xml/sax/saxutils.py#l72" rel="nofollow">look at how <code>saxutils._gettextwriter()</code> is implemented</a>.</p>
| 0 |
switch translations in python and gettext | precodex cardrank
print xj xa xq xk
codepre
pemtotally worksemp
pyes the string literals must be somewhere in ur codep
pthe string literals emneed not be in the same moduleem which displays the text putting the string literals in the same module is not pretty on the eyes not oopp
psuccessfully tested using py v27 gtk v22410 gettext 0181p
precodepython
import gtk
gtkgtkversion
2 24 10
gettext version
gettext gnu gettextruntime 0181
codepre
pstrongdisclaimerstrong
dont attempt this before getting gettext working for your python application including being able to change locales languages on the fly these are no small feats this will remove 99 of the confusion then itll either work or it wont im saying itll workp
| 0 |
log in to django site through facebook | phave a look at the widely used a hrefhttppypipythonorgpypidjangofacebook relnofollowdjangofacebooka appp
| 0 |
pandas sliding average based on unevenly index values | pwhat you needed to do from the a hrefhttpstackoverflowcomquestions14300768pandasrollingcomputationwithwindowbasedonvaluesinsteadofcountslq1answera you linked to was to turn the index into a series so you can then call apply on it the other key thing here is that you also have to index the constructed series the same as your df index as the default is to just create an index from scratch like 0123p
precodein 26
def fx c
ser dflocdfindex gt x amp dfindex lt x cb
return sermean
dfc pdseriesdata dfindex index dfindexapplylambda x fxc04
df
out26
a b c
a
00 00 10 11000000
01 01 11 12666667
02 02 12 13500000
05 05 15 15000000
10 10 20 25000000
14 14 30 40000000
15 15 50 50000000
codepre
| 0 |
how to download a xls into a python object via ftp with python ftplib | palthough i was looking for a way to directly purse the ftped excel file into python object if i allows saving the excel file in my directory and reread it again the following worksp
precodeftp ftpwebftpvancouverca
ftplogin
ftpcwdopendataxls
filename newfoodvendorlocationsxls
ftpretrbinaryretr s filename openmylovelynewfilexls wwrite
ftpquit
workbook xlrdopenworkbookmylovelynewfilexls
worksheet workbooksheetbynamequeryvendorfood
numrows worksheetnrows 1
currrow 1
while currrow lt numrows
currrow 1
row worksheetrowcurrrow
print row
codepre
pi thank jacoppens for his advice p
| 0 |
odoo 80 creating slave records in code | precodeclass agreementmodelsmodel
name attagreement
lineid fieldsone2manyattagreementlineagreementid lines copytrue
name fieldscharstringname requiredtrue
apimodel
def createself values
return superagreement selfcreate values
apionchangename
def onchangenameself
if selfname
for x in range151
selfenvattagreementlinecreateagreementid self id name strx qty x 100
class agreementlinemodelsmodel
name attagreementline
agreementid fieldsmany2oneattagreement ondeletecascade selecttrue requiredtrue readonly true
name fieldscharstringname requiredtrue
qty fieldsintegerstring qty
apimodel
def createself values
return superagreementline selfcreate values
codepre
| 0 |
how can i model a scalable set of definitionterm pairs | pa hrefhttpblogcameronlegercom20110531pythonexamplepicklingthingsintomysqldatabases relnofollowpickling objects into a databasea means itll take some effort to create an interface to modify the weekly lessons from the front end but is well worth the timep
| 0 |
beautifulsoup text method returns text without separators n r etc | pyou can do thisp
precodesoup beautifulsouphtml
ols soupfindallol for the two languages
for ol in ols
ps olfindallp
for p in ps
for item in pcontents
if stritemltbr gt
print stritem
codepre
| 0 |
linking sublime text 2 to my anaconda packages | pthe best doc youre going to find is the a hrefhttpssublimetextunofficialdocumentationreadthedocsorgenlatestextensibilitypluginshtml relnofollowsublime text unofficial documentationap
pthis question asks about adding modules to sublime as well
a hrefhttpstackoverflowcomq151805371695680how to include third party python packages in sublime text 2 pluginsap
pgist of the answer is to modify the embedded pythons path to look for your modulesp
| 0 |
how to print what i think is an object | pit might be handy to look at the pprint module a hrefhttpdocspythonorglibrarypprinthtml relnofollowhttpdocspythonorglibrarypprinthtmla if youre running python 27 or morep
precodefrom pprint import pprint
pprintx
codepre
| 0 |
how to disable nose tests coverage report | pi am not familiar with django managepy script but i guess that you can look into the test task and see hot it calls nose i guess that you would like to only run the tests without the coverage
nose documentation is here a hrefhttpsomethingaboutorangecommrlprojectsnose0113usagehtml relnofollowhttpsomethingaboutorangecommrlprojectsnose0113usagehtmlap
| 0 |
how to dbchange mongo flask | pjust use dbalias aliasname in your document classp
pjust to make sure you register the alias name
registerconnectaliasnamedbhostport
you can register as many alias as you want
here is the doc for registerconnect
a hrefhttpsmongoengineodmreadthedocsorgenlatestapireferencehtmlmongoengineregisterconnection relnofollowhttpsmongoengineodmreadthedocsorgenlatestapireferencehtmlmongoengineregisterconnectionap
| 0 |
tensorflow 09 skflow model save and restore doesnt work | pi belive save and restore have been deprecated in favor of the codemodeldircode param when building the estimatorregressor p
precoderegressor skflowtensorflowlinearregressormodeldirhomemodel
regressorfitx bostontarget
estimator skflowtensorflowlinearregressormodeldirhomemodel
estimatorpredict
codepre
| 0 |
python code fragment list | pat least two elements means that you can say the following for your list codelcode without worrying about an codeindexerrorcode being raisedp
ul
licodel0 first element is guaranteed to existcodeli
licodel1 second element is guaranteed to existcodeli
licodel1 last element is guaranteed to exitcodeli
licodel2 nexttolast element is guaranteed to existcodeli
ul
pi emthinkem second and last refer to codel1code and codel1code unless its a poorly worded ellipsis and they mean secondtolast and lastmdashcodel2code and codel1codep
| 0 |
python reading text file and splitting into different lists | pif you are looking to have a list for each line you can use a dictionary where the key is the line number and the value of the dictionary entry is the list of names for that line something like thisp
precodewith openmyfiletxt r as fin
students kline1split for kline in enumeratefin
print students
codepre
pthe line1 is to get rid off the carriage return at the end of each linep
| 0 |
how can i get input and rawimput functions to work in python | pnote that the meaning and purpose of both codeinputcode and coderawinputcode have strongchangedstrong between python 2 and python 3p
h2python 2h2
ul
licodeinputcode reads keyboard input emandem parses it as a python expression possibly returning a string number or something elseli
licoderawinputcode reads keyboard input and returns a string without parsingli
ul
h2python 3h2
ul
licodeinputcode reads keyboard input and returns a stringli
licoderawinputcode does not existli
ul
pto get similar behaviour in python 3 as python 2s codeinputcode use codeevalinputcodep
| 0 |
how can i write a python function to accept arguments and a keyword argument | pwell all args really is a variable list of arguments and all kwargs really is a dictionary keywordonly argumentsp
punless i am misunderstanding why not just do thisp
precodedef xargs afalse
print args a
x12true lt just passes in a list instead of special list and dict
output
12 true
x12
output
12 false
codepre
pit is not as pythonic without the variable argument list and detection of the kwargs keywordonly arguments dict but probably works for your needsp
| 0 |
python regex replace to create smiley faces | pheres your oneliner sorry no regexp
precodefor word in sentencesplit print 8 lenword 2 d
codepre
| 0 |
select rows for a given value from file in python | pyoure close i think im really not even sure what that last if statement is going to be doing but it looks like a list comprehension mixed with an if also mixed with the fact that youre reassigning x if that statement actually worked try something like thisp
precodefor line in a
columns linestripsplit
if columns0 gt 20
print line
codepre
| 0 |
win32api pyhook how to get the users typing language | pcheck a hrefhttpstackoverflowcoma12383335660175this answera to a similar question seems you need to use getguithreadinfo to determine the current active thread on the desktop and then pass that to getkeyboardlayoutp
| 0 |
inserting tuples elements to database | pnote that the codeexecutemanycode is for inserting multiple rows egp
precodeimport sqlite3
the table structure is
create table tab
a char1
b char2
c char3
conn sqlite3connectctestdb
stmt insert into tab a b c values
cur conncursor
many rows
vals 123 234 345
curexecutemanystmt vals
curclose
codepre
pthis will result in three rows in the database if it is because you have multiple values in one query you need to format itp
pstrongeditstrong added formatting with dictionariesp
pby using the following approach you do not need to consider the order of the values in the codeformatcode call because the key in the dictionary is mapping the value into the codekeywordcode placeholderp
precodevalues a valuea
b valueb
stmt insert into tab cola colb values a bformatvalues
codepre
| 0 |
looking for input in model design for django schools | pheyi agreeit looks pretty good someone advised me to use autoincrement on all tables just to be sure there really is a unique id on every record its your choice if youd like to go that routep
| 0 |
how can i extrat a specific src url format using regex | ptry this p
precodesrc
codepre
pand get group 1p
pa hrefhttpsregex101comrei3bf22 relnofollowdemoap
| 0 |
pygeolibgeocodererror error zeroresults | ptry apis from other sources your addresses are not recognizable by geocoderp
| 0 |
in python how to remove a range of lines from a file without using fileinput module | pstrongwith second filestrongp
precodewith openfileinput as fin with openfileoutput as fout
for il in fin
if start lt i lt start upto
foutwritesnl
codepre
pstronginmemorystrongp
pif you are adamant about not using a second file how about loading the entire file into memory eg p
precodeimport sys
filename start upto sysargv14
start upto intstart intupto
fread openfilename
original listfread
freadclose
fileinput openfilename w
for line in original
if start lt fileinputlineno lt start upto
pass
else
fileinputwritesn line
fileinputclose
codepre
pyou might want to consider using context managers for file io also replacing with the list of lines allows you to simply slice into that listp
precodeimport sys
filename start upto sysargv14
start upto intstart intupto
with openfilename as fread
original listfread
with openfilename w as fileinput
for line in originalstartstartupto
fileinputwritesn line
codepre
| 0 |
python json encoder to support datetime | precodejsondumpsr defaultlambda o oisoformat if hasattro isoformat else o
codepre
| 0 |
how can twisted interact with command line programs can nodejs | pif you want your twisted application to interact with commandline programs by calling them and capturing their output you can do that with a hrefhttptwistedmatrixcomdocumentscurrentapitwistedinternetinterfacesireactorprocesshtml relnofollowspawnprocessa as described at tritium21s link it runs asynchronously so your twisted app will carry on processing and can run other programs in the meantimep
pif you want to run a commandline program which will have some effect on the twisted app you can have twisted a hrefhttpstwistedmatrixcomdocumentscurrentcorehowtoservershtml relnofollowlisten on a socketa and have the programs connect to it to send commands again twisted can talk to many programs at once provided you write the processing code asynchronously one really good way to talk to the server is with amp the a hrefhttptwistedmatrixcomdocumentscurrentapitwistedprotocolsamphtml relnofollowasynchronous messaging protocolap
pand of course the same app can do both of those things at once and more besidesp
| 0 |
django registration page with country state field after submission | pthese kind of filtered forms can be easily done using dajax if i understand correctly you want to do something along the lines of a hrefhttpwwwdajaxprojectcomforms relnofollowhttpwwwdajaxprojectcomformsa p
pi have tried this before and it helps make great filtered forms if not dajax your other option is to write javascript to send your form data to your view and then fetch your state depending on your country and append the new choices to your state selection fieldp
| 0 |
how i could write it better without counter etc libraries | pi dont like loops and try to avoid them whenever possible i didnt implement the parsing of the string into a list of integer tho so just for fun i whipped up a solution that relies only on map filter and zipp
precodegtgtgt groupedbynumber maplambda n filterlambda m m n 111112222333445 range110
1 1 1 1 1 2 2 2 2 3 3 3 4 4 5
gtgtgt countwithnumber ziprange110 maplambda n lenn groupedbynumber
gtgtgt countwithnumber
1 5 2 4 3 3 4 2 5 1 6 0 7 0 8 0 9 0
codepre
pnothing but the standard library was used also no mutability or juggling with indexes anywhere hopefully the fact that theyre tuples and not lists is okay p
| 0 |
http request object does not respond | pwhy not you are using coderendertoresponsecode p
pthe answer of your question is you are not returning the codehttpresponsecode object p
pif your login is successful then only you will be redirect to success p
ptry this p
precode return rendertoresponseyourtemplatename
contextinstancerequestcontextrequest
codepre
pdont forget to import contextinstance like p
precodefrom djangotemplate import requestcontext
codepre
| 0 |
django variables with a list of values | pi would suggest a foreign key instead of a many to many relationshipp
precodeclass personmodelsmodel
class hungrymodelsmodel
person modelsforeignkeyfieldperson
start models datetimefield
end models datetimefield
hungry models booleanfield
codepre
pi guess you could replace the codepersoncode field on codehungrycode with a codecharfieldcode so as to squeeze this into one table but thats poor db design it should really be two separate tablesp
| 0 |
pip search aap shows availability but pip install aap will not succeed | plong ago in a galaxy not too far away pippypisetuptools used to scrape any linked site for what looked like download links it no longer does this so while aap my have pipinstalled in the past it will not until the package maintainer puts a distribution on pypip
| 0 |
python console progress | pi do it as followsp
pre classlangpy prettyprintoverridecodeprint currentline 100 totallines end r
codepre
pdont forget that too many outputs to console will slow down your loopsp
| 0 |
python import error specific case | pi want to share my solution with you since anybody reading the question seems to have similar problems p
pthe problem occured because the package werent included in pythonpath syspath i am calling the plugins in a new thread with a script called executepy this is called via cmd from the mainpy because i cant multiprocess my classes and since the plugins are located in plugins python only includes this path not the importmodule path somehow it seems that it has been included on windows i dont really know what has happened there tbh p
pwhat i did was i included the codesyspathappendcode stuff on my executepy which executes the plugins as follows codefrom pluginhelper import scrapehostnames hostnamestoips getsourcecode my ide marks the import statement red now but it is working since i am appending the packagep
| 0 |
systematic modifying of lists elements | precodegtgtgt segmentsinit 1 2 3 4 5 6 7 8 9
gtgtgt listzipsegmentsinit03 listmaplambda xx segmentsinit23 0lensegmentsinit3
1 3 0 4 6 0 7 9 0
codepre
peven though its better to club a single 3d coordinate together for better readability but if you want to flatten the list you can use this p
precodegtgtgt i for l in listzipsegmentsinit03 listmaplambda xx segmentsinit23 0lensegmentsinit3 for i in l
1 3 0 4 6 0 7 9 0
codepre
| 0 |
cannot run appengineadmin on devserver | pit wired that i have been using gae with python26probably 261 and every thing worked finep
pbut now i get the same multiprocess import errorpython262p
| 0 |
python how do i use only 1 column when using multiple text files | pusing ipython panda i was able to easily and quickly analyze all text filesp
pa hrefhttpnbviewerjupyterorggithubjvnspandascookbookblobv01cookbookchapter2022020selecting20data20amp20finding20the20most20common20complaint20typeipynb relnofollowjupyter notebookap
pcode i usedp
precodeimport pandas as pd
dft pdreadcsvsampletxt
dftcolumnvaluecounts
codepre
| 0 |
looping a program with while statement | ptry the followingp
precodenumber 10
guess 9
while guess number
guess intinputtype in an integer
if guess number
print good job
elif guess lt number
print the number is higher
elif guess gt number
print the number is lower
else
print try again
print done
codepre
| 0 |
python send recv binary data | blockquote
pcodeintremotestruct0codep
blockquote
pthis looks a lot like some c code python doesnt have type casts like cp
pcodeintcode refers to an object the way you use it is by calling it like its a functionp
pinstead write something like codeintremotestruct0code what you wrote works because the extra parenthesis are totally redundant and dont change the meaning this isnt just a syntactic difference though its a basic difference in the type systems of the two languagesp
pthis has nothing to do with your question thoughp
precodeipbytes intremotestruct0tobytes1 byteorderlittle intremotestruct1tobytes1 byteorderlittle intremotestruct2tobytes1 byteorderlittle intremotestruct3tobytes1 byteorderlittle
codepre
pthis is an emincrediblyem verbose way to pack an ipv4 address into four bytes try this insteadp
precodeimport socket
print socketinetptonsocketafinet 1234
codepre
pthough this is also not directly related to your questionp
pthe source of your codeindexerrorcode problem im guessing thats the exception you encounter you said access out of bounds error which isnt something that actually exists in pythons builtin types dont paraphrase errors quote them verbatim is very likely somewhere in the vicinity ofp
precodevar serversockrecvfrom12
codepre
pnotice the return value of a hrefhttpdocspythonorg3librarysockethtmlsocketsocketrecvfrom relnofollowrecvfroma emthe return value is a pair bytes address)</em>.</p>
<p>if you try to index into this object at <code>6</code> then you'll definitely get an <code>indexerror</code> raised, yes.</p>
<p>using <code>str</code> to get a unicode string representation of this pair won't really help though - although it might prevent the indexing operation from failing because the resulting unicode string will probably be long enough. :) you'll be getting garbage, though.</p>
<p>instead, try indexing into the bytes that you read instead:</p>
<pre><code>data, addr = serversock.recvfrom(12)
if len(data) > 6:
seqnum = ord(data[6])
</code></pre>
<p>notice you really do need to be careful about length checking here. just because you passed <code>12</code> to <code>recvfrom</code> doesn't mean it returns 12 bytes. it means it returns <em>up to</em> 12 bytes. you don't want your program to explode with an unhandled exception the first time someone sends you a short datagram.</p>
| 0 |
prevent change of field if related objects exist | pset codesurveycode and coderesponsecode field in coderesponsecode model unique by
a hrefhttpsdocsdjangoprojectcomen18refmodelsoptionsuniquetogether relnofollowunique togethera like thisp
precodeclass responsemodelsmodel
survey modelsforeignkeysurvey
response modelstextfield
class meta
uniquetogether survey response
codepre
| 0 |
installing easyinstall with setup tools | pit means that you should have the path to the directory containing the file when you do p
precodeecho path windows
echo path linuxcygwin
codepre
pin the command line if it does not appear you should add itp
pto do so check out the following linksp
ul
lia hrefhttpstackoverflowcomquestions7488329gitsettingpathvariablegit setting path variablea linuxli
lia hrefhttpstackoverflowcomquestions9290243howtosetanthome92904319290431how to set anthomea windowsli
ul
| 0 |
save python queue to a file | pa simple option i can offer would be to wrap a database table in a class and use that as your queue a autoincrement column would work wonders for this the next item to remove is the one with the lowest idp
precodeclass dbqueue
init
pick some random id for this run or set it to some thing you know
put
insert entry into table
get
the update select combo removes the need for a database that has transactions
if no entries bear your id
update the next entry that is not already marked with your id
select the entry that matches your id and return it
taskdone
delete the entry with your id
codepre
pthis wont have the best performance depending on how often the queue gets updated even the inmemory sqlite database wont be as fast as a linked list structure the flip side is that you can view the database using any tool that can access the database so you can see which one is in progressp
| 0 |
how change table contents and style using pythondocx | pprobably ive found a solution
it depends of documentxpath a way to take a map of it is decompress the docx and read the worddocumentxml filep
precodepathcell the path you individuate in documentxml
docbody documentxpathwdocumentwbodypathcell
namespacesnsprefixes0
print replacing
docbody replacedocbodywelcomehello
codepre
pive found this way to run the game any else p
| 0 |
rapidly redrawing tkinter window what is a faster way | pa few things could probably be done to improve the fps of your codep
ol
liget rid of the wupdate and use the normal event loop via mainloopli
liget rid of the wdeleteall and reuse the blocks just move them around instead of delete and recreate them allli
liuse the help of the canvas find method to do collision detection instead of your check only in python codeli
lirewrite in tcl so you can use tcls threading instead of the crippled cpython threads only useful if you have more than one cpucore li
ol
| 0 |
how can we test the address of the server | pif the connection fails then there must be an error on the server side that means the url is good but something breaks and you should see an error in the error log or the terminal where you started the serverp
| 0 |
printing data from list | precodegtgtgt new2 id fk 1 1 2 1 5 3 6 2
gtgtgt for cols in new2
print 55formatcols
codepre
pprintsp
precodeid fk
1 1
2 1
5 3
6 2
codepre
| 0 |
how to write dictionary values to a csv file using python | ptry to use a hrefhttppandaspydataorg relnofollowcodepandascodea here is pandass feature about your problem p
ptools for reading and writing data between inmemory data structures and different formats csv and text files microsoft excel sql databases and the fast hdf5 formatp
pits very convenient and powerfulp
| 0 |
how to get a random line from within a gzip compressed file in python without reading it into memory | pforgive the very late answer but you can use the codeseekcode method to position in the file if you know the size of the file from codegunzip lcodebr
then throw away the next read as it will probably be a partial line and use the subsequent read as your random datap
pprint 10 random lines from a gzipped text filep
precodeimport random
import gzip os
f gzipopensometxtgzr
uncsize ospopengunzip lq sometxtgzread
uncsize uncsizestripsplit 1
uncsize uncsize1stripsplit 1
for x in range111
fseekrandomrandint0intuncsize0
dump nextf
print random line from byte pos ftell nextf
fclose
codepre
| 0 |
how to make statements in python script behave just like them executed in interactive shell | ptry sticking a pause codetimesleep1code for instance after each codecomportwritecode this will give the device time to respond to each command before you look for the responsep
pas a hrefhttpstackoverflowcomquestions7101284howtomakestatementsinpythonscriptbehavejustlikethemexecutedininterac71017127101712hyry points outa setting codetimeoutcode to code0code will return immediately so it does not do what you think it does beyond that though when you execute the statements one at a time theres a delay as you type in each line when you execute them in a script they run without much of a gap in between p
| 0 |
python 27 select words in list prior to number | ptry this which will split on the number and get you the name partsp
precodeimport re
exp recompilerdd
with openmainfiletxt as f opennamestxtw as out
for line in f
line linestrip
if lenline
try
outwritenformatresplitexp line0strip
except
printcould not parse formatline
codepre
pthe regular expression codeddcode meansp
ul
licodedcode one or more digitsli
licodecode an optional codecode note in regular expressions codecode has special meaning so we escape it when we mean the emliteralem codecodeli
licodedcode followed by one or more digitsli
ul
pthe codecode around it makes it to a capture group which results in the followingp
precodegtgtgt x rdd
gtgtgt l benzoyl peroxide 50 mgml topical lotion
gtgtgt resplitx l
benzoyl peroxide 50 mgml topical lotion
codepre
| 0 |
copy past objet in python opencv2 | puse grabcut algorithm to extract the forground image here is some code that u will also like p
precodeimg cv2imreadimagejpg
mask npzerosimgshape2npuint8
bgdmodel npzeros165npfloat64
fgdmodel npzeros165npfloat64
rect 5050450290
cv2grabcutimgmaskrectbgdmodelfgdmodel5cv2gcinitwithrect
mask2 npwheremask2mask001astypeuint8
img imgmask2npnewaxis
pltimshowimgpltcolorbarpltshow
codepre
pthis might be little hazzy or not soo sharp what u can do is apply a edge detection first to refine ur input and apply the above p
| 0 |
how can i convert a list of hex colors or rgb srgb stored in a text file into an image | pyouve tagged this with the a hrefquestionstaggedprocessing classposttag titleshow questions tagged 39processing39 reltagprocessinga tag so here is the processing solutionp
pstrongstep 1strong load the file you can use the codeloadstringscode functions for this this gives you an array of codestringcode values which in your case will hold your hex values more info can be found in a hrefhttpsprocessingorgreferenceloadstringshtml relnofollowthe referenceap
pstrongstep 2strong loop through those hex values use a regular codeforcode loop or an enhanced codeforcode loopp
pstrongstep 3strong convert each hex codestringcode into an codeintcode color using the codeunhexcode function this gives you an codeintcode that can be passed into any color function such as codefillcode more info can be found in a hrefhttpsprocessingorgreferenceunhexhtml relnofollowthe referenceap
pstrongstep 4strong use those colors to draw your image you havent said how the lines in the file map to a coordinate onscreen so youll have to do that mapping then just change the fill color and draw a rectangle at that coordinatep
pits hard to answer general how do i do this type questions other than to point you to a hrefhttpsprocessingorgreference relnofollowthe referencea and tell you to break your problem down into smaller steps and just try something then if you get stuck on one of those specific steps you can ask a more specific i tried x expected y but got z instead type question which is more what stack overflow was designed for good luckp
| 0 |
python and zmq rep socket not receiving all requests | panswering my own question it seems like it was an issue with the large number of sockets i was using and also possibly the memory limitations of the gce instances used see comment thread above for more detailsp
| 0 |
pyqt open another window from a button | pat the end of the openwindow function you havep
precodesysexitappexec
codepre
pwhich is ending the code and i dont think you should be making a new app per windowp
| 0 |
flask 404 on dreamhost | pi found the answer here a hrefhttpblogtuxcodercom201198dreamhostpythonwsgi relnofollowhttpblogtuxcodercom201198dreamhostpythonwsgiap
blockquote
pif you plan to do any active development on the dreamhost side this step will simplify your efforts werkzeug comes with a really nice debugging engine but it does not work with the dreamhost configuration by default
or example if you have a simple python coding error in your app it will result in the followingp
pimg srchttpistackimgurcomylb7hpng altdefault error page of werkzeugp
pin this mode youre out of luck the only option is to startup a local server where you can go back and test the app in some cases it might be a big effort just to replicate the bugp
pwith the werkzeug debugger enabled and patched youll get a much nicer outputp
pimg srchttpistackimgurcomisalhpng altwerkzeug debuggerp
blockquote
phere is what it says on the dreamhost wiki a hrefhttpwikidreamhostcomflask relnofollowhttpwikidreamhostcomflaska in codepassengerwsgipycodep
blockquote
precode uncomment next two lines to enable debugging
from werkzeugdebug import debuggedapplication
application debuggedapplicationapplication evalextrue
codepre
blockquote
| 0 |
need help in python variable updation pygame module | pyou are confusing the emeventem keyup with the up emkeyem the event keyup occurs when a key any key is released the event keydown occurs when any key is pressed downp
pin you code this means that when the up key is pressed down the speed is set to 01 and when the up key is release the speed is set to 00p
pif you want the speed to emkeepem increasing and decreasing when a key is released you should use a timer like sop
precodeimport pygame
speed 0
screen pygamedisplaysetmode400400032
pygamedisplayupdate
clock pygametimeclock
pygametimesettimerpygameuserevent1 20
while true
for event in pygameeventget
if eventtype pygamequit
break
if eventtype pygameuserevent1
if pygamekeygetpressedpygamekup
if speed lt 8
speed01
else
if speed gt 01
speed 01
else
speed 00
pygamedisplayupdate
printspeed
clocktick60
pygamequit
quit
codepre
padjust the delay in the settimer to suit your taste also note the addition to reset the speed to zero float operations are not completely exact so repeated adding and substracting can lead to a zero that is negativep
| 0 |
how to properly create a list subclass that returns a list generated from file in python | pif you want to avoid inheritance and userdefined methods id leverage pythons a hrefhttpwwwrafekettlercommagicmethodshtml relnofollowmagica methods to do so p
| 0 |
building a python counter with rollover | pi have an example just more shorterp
precodeclass messagecounter
def initself
selfvalue 0
def incrementself resetfalse
selfvalue selfvalue 1 if selfvalue lt 4294967295 and not reset else 1
codepre
| 0 |
python subprocess output on nohup | pim not 100 sure of the underlying issue here but when you invoke nohup in the shell its disconnected some of the stdinstdout from the terminal process which i suspect it causing some of this interactions youre seeingp
pgiven that youre doing this from a remote machine id actually recommend you look at using something like a hrefhttpdocsfabfileorgen18 relnofollowfabrica as a library to do what youre after its pretty straightforward and does most of the handling of terminal sessions as well as closing things down nicely for you when youre completep
psomething likep
precodefrom fabric import api
from fabricapi import env
import fabric
envhoststring ss username remotehost
envdisableknownhosts true
envpassword password
fabricstateoutputstdout false
fabricstateoutputstderr false
results apirundf h
codepre
| 0 |
Subsets and Splits