text_a
stringlengths 9
150
| text_b
stringlengths 18
20.9k
| labels
int64 0
2
|
---|---|---|
kivy syntax error conditions inside widgetadd | pyou are correct you cannot have conditionals inside a functions arguments move your codeifelifcode conditional outside just after the codeobject whatcode line calculate the value of codeposhintcode then call codeselfaddwidgetlabelargscodep
| 0 |
finding minimum of interpolated function | pfrom the help of a hrefhttpdocsscipyorgdocscipy0161referencegeneratedscipyinterpolateinterp2dcallhtmlscipyinterpolateinterp2dcall29 relnofollowcodescipyinterpolateinterp2dcodeap
precode callself x y dx0 dy0 assumesortedfalse
interpolate the function
parameters
x 1d array
xcoordinates of the mesh on which to interpolate
y 1d array
ycoordinates of the mesh on which to interpolate
codepre
pfrom the help of a hrefhttpdocsscipyorgdocscipy0161referencegeneratedscipyoptimizeminimizehtml relnofollowcodescipyoptimizeminimizecodeap
precodeminimizefun x0 args methodnone jacnone hessnone hesspnone boundsnone constraints tolnone callbacknone optionsnone
minimization of scalar function of one or more variables
parameters
fun callable
objective function
x0 ndarray
initial guess
codepre
pso it seems that codeinterp2dcode constructs a function with 2 separate input parameters but codeminimizecode tries to stuff in both variables as two components of the same input codendarraycode you can use a codelambdacode to mediate between the two syntaxesp
precodef timefunction
return minimizelambda v fv0v1 nparray10 04
code></pre>
<p>on a side note, i've found <code>interp2d</code> to <a href="http://stackoverflow.com/a/34656728/5067311">give weird results</a> sometimes. you might want to consider using <a href="http://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.interpolate.griddata.html" rel="nofollow"><code>scipy.interpolate.griddata</code></a>, which doesn't construct an interpolating function for you, but rather computes substituted values for given input points (but you can access the interpolating functions themselves, such as <a href="http://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.interpolate.linearndinterpolator.html#scipy.interpolate.linearndinterpolator" rel="nofollow"><code>linearndinterpolator</code></a>). while i'd expect <code>griddata</code> to do a better job at interpolating, it would possibly (probably) be slower than substituting into a single interpolating function constructed with <code>interp2d</code> (but i'd check regardless).</p>
| 0 |
running methods on different cores on python | pin general running different threads is the best portable way to run on multiple cores of course in python the global interpreter lock makes this a moot point only one thread will make progress at a timep
| 0 |
django grouping and ordering across foreign keys with conditions | pagf has already showed you how to group by songartist what i would do to get the actual song object is store it in memcached or if the method you are calling is rather simplistic make it a static method or a class method you might could also initialize a song object with the data from the query and not actually save it to get access to this method might help to know the details of the methods you want to call from the song objectp
| 0 |
python recipie book writing and reading to files | puse thisp
precodetextfile openrname w
for item in ing
textfilewritelinesstritem
codepre
| 0 |
calculate bleu score in python | pthe bleu score consists of two parts modified precision and brevity penalty
details can be seen in the a hrefhttpwwwaclweborganthologyp021040pdf relnofollowpapera
you can use the a hrefhttpwwwnltkorgmodulesnltkalignbleuscorehtml relnofollowcodenltkalignbleuscorecodea module inside the nltk
one code example can be seen as belowp
precodeimport nltk
hypothesis it is a cat at room
reference it is a cat inside the room
there may be several references
bleuscore nltktranslatebleuscoresentencebleureference hypothesis
print bleuscore
codepre
pnote that the default bleu score uses n4 which includes unigrams to 4 grams if your sentence is smaller than 4 you need to reset the n value otherwise codezerodivisionerror fraction0 0code error will be returned
so you should reset the weight like thisp
precodeimport nltk
hypothesis open the file
reference open file
the maximum is bigram so assign the weight into 2 half
bleuscore nltktranslatebleuscoresentencebleureference hypothesis weights 05 05
print bleuscore
codepre
| 0 |
how to add model in django | pread django documentation
a hrefhttpsdocsdjangoprojectcomen14 relnofollowhttpsdocsdjangoprojectcomen14ap
pand do the tutorial
a hrefhttpsdocsdjangoprojectcomen14intro relnofollowhttpsdocsdjangoprojectcomen14introap
pthis will help you to get in touch with djangop
| 0 |
how to remove a pandas dataframe from another dataframe | pa set logic approach turn the rows of codedf1code and codedf2code into sets then use codesetcode subtraction to define new codedataframecodep
precodeidx1 setdf1setindexa bindex
idx2 setdf2setindexa bindex
pddataframelistidx1 idx2 columnsdf1columns
a b
0 3 4
codepre
| 0 |
django admin view limiting the selection of items from foreign key according to user | pto read only branch of hod in mclassadmin first make a relation between hod and branch for this make changes in modelpy asp
precodefrom djangocontribauthmodels import user
codepre
padd hod field as p
precode hod modelsforeignkeyuser
codepre
pto store hod and branch relationp
pnow modelpy willbep
precodeclass mbranchmodelsmodel
hod modelsforeignkeyuser
branchid modelscharfieldmaxlength20
branchname modelscharfieldmaxlength50
def strself
return selfbranchname
class macademicyearmodelsmodel
academicyear modelscharfieldmaxlength20
def strself
return selfacademicyear
class mclassmodelsmodel
branchid modelsforeignkeymbranch
academicyear modelsforeignkeymacademicyear
classid modelscharfieldmaxlength20
classname modelscharfieldmaxlength20
def strself
return selfclassname
codepre
pthen in adminpy override getqueryset and formfieldforforeignkeyp
precodeclass mclassadminadminmodeladmin
def getquerysetself request
printquery set
qs supermclassadmin selfgetquerysetrequest
if requestuserissuperuser
return qs
user userobjectsgetusernamerequestuserusername
branch mbranchobjectsgethod user
printbranchididbranch
return qsfilterbranchididbranch
def formfieldforforeignkeyself dbfield request kwargs
printi am in func
if dbfieldname branchid
printdbfieldnamedb_field.name)
user = user.objects.get(username=request.user.username)
if not user.is_superuser:
print('user=',user)
branch = m_branch.objects.get(hod = user)
print('branch = ',branch)
'''if user=='e0711001':
kwargs["queryset"] = m_branch.objects.filter(branch_id='b101')
#elif user=='e0711002':
else:
kwargs["queryset"] = m_branch.objects.filter(branch_id='b102')'''
#kwargs["queryset"] = m_branch.objects.filter(branch_id=user.branch.id)
kwargs["queryset"] = m_branch.objects.filter(branch_name=branch)
return super(m_classadmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
fields = ['branch_id','academic_year','class_name']
list_filter = ['academic_year','class_name']
search_fields = ['branch_id','academic_year','class_name']
list_display = ('class_name','branch_id','academic_year')
admin.site.register(m_class,m_classadmin)
</code></pre>
| 0 |
python xlrd test if string is in row | pdoh i neededp
precodeif flag in srowvaluesr
codepre
phope this helps someone elsep
| 0 |
loglog plot point not showing | pif you have some data with either x0 or y0 you wont be able to print those points on a loglogplot as a hrefhttpsenwikipediaorgwikilogarithm relnofollowlog0 is undefineda however usingp
precodeaxsetyscalesymlog
axsetxscalesymlog
codepre
pwill allow you to see points a x0 or y0 theres a good explanation of the abilities of codesymlogcode a hrefhttpstackoverflowcomquestions3305865whatisthedifferencebetweenlogandsymloghereap
| 0 |
facebook api registerusers error 100 invalid email hash | pis the hash being stored as the right typep
palso it may be good to store the hash as a separate variable in case theres some strange race condition popping upp
| 0 |
true false boolean in python | pcodeelifcode in python is equivilent to codeelse ifcode if one of the codeelifcode blocks execute none of the others can and will jump to the bottom of the codeifcodep
pafter codenext taunt bear and not bearmovedcode is executed and evaluates to true and the block executes control of the program continues back at the front of the loop and will ask for input againp
| 0 |
finding the indices which has generate 5 larges sums | precodelargest aindex bindex 0 3
for i n1 in enumeratea
for j n2 in enumerateb
if n1 n2 gt largest
largest n1 n2
aindex i
bindex j
codepre
| 0 |
use type information to cast values stored as strings | pyou might want to look at the xlrd module if you can load your data into excel and it knows what type is associated with each column xlrd will give you the type when you read the excel file of course if the data is given to you as a csv then someone would have to go into the excel file and change the column types by handp
pnot sure this gets you all the way to where you want to go but it might helpp
| 0 |
using python how do i get a binary serialization of my google protobuf message | pyou can use pythons strings for getting proto buffers serialized data doesnt matter how they ware crated in python java c or any other languagep
pthese is line from pythons version of proto buffers tutorial
codeaddressbookparsefromstringfreadcodep
| 0 |
iterating over a file omitting lines based on condition efficiently | pif the file is small you may read it whole with codereadlinescode at once possibly reducing io traffic and iterate the sequence of lines
if the sample rate is small enough you may consider sampling from geometric distribution which may be more efficientp
pi do not know cython but i would consider alsop
ul
lisimplifying codetakesamplecode by removal of unnecessary variables and returning boolean result of the test instead of integerli
lichange signature of codetakesamplecode to codetakesampleintcode to avoid inttofloat conversion every testli
ul
peditp
paccording to comment of hpaulj it may be better if you use codereadsplitncode instead of codereadlinescode suggested by mep
| 0 |
using float values in imagedraw | pif you want subpixel positioning one possibleifinefficient solution would be to scale everything up by a factor of say 10 rounding originalfloatingpointcoordinates 10 to integers then resize the whole image back down at the end doesnt help with angles i supposep
| 0 |
edges with direction in pyqtgraph graphitem | pfor direction you might add a codepgarrowitemcode at the end of each line although this could have poor performance for large networks and for self connections codeqtguiqgraphicsellipseitemcode combined with an arrow p
| 0 |
how to successfully verify that 2 names are identical | pyou can try for any existing fuzzy string matching algorithm in pythonp
peg simstringp
pa hrefhttpwwwchokkanorgsoftwaresimstring relnofollowhttpwwwchokkanorgsoftwaresimstringap
phope it will helpp
| 0 |
id like someone to help me understand a few lines of code | psort words by lengthp
precodew abcd za wyya dssffgdg
print sortbylengthw
codepre
pa hrefhttpideonecomjrzatv relnofollowhttpideonecomjrzatvap
| 0 |
python search for an element inside a dictionary inside a list | pegp
precodeset id 50 id 80
def findsetid
return elem for elem in set if elemid id
codepre
pthis will return all items with the specified id if you only want the first one add 0 after checking if it exists egp
precodedef findsetid
elems elem for elem in set if elemid id
return elems0 if elems else none
codepre
| 0 |
subprocess with variables command from different class | pmanage to get this corrected heres the correct way of doing this for future viewers a hrefhttppastebincomum0z8q2v relnofollowhttppastebincomum0z8q2vap
| 0 |
how can i check if a frame exists and if so destroy it | pmframe is only defined within the function it gets destroyed automatically after every pass of the function to verify this you could add global mframe to make it a global variable that lives until the next call of the functionp
pthere are better solutions like storing the variable in a class as suggested in the other answerp
pwhat about updating the label context also you might try to use only a single multiline labelp
| 0 |
parse all whitespace and grammar | pinstead of splitting you can use strongrefindallstrong for thisp
precodeimport re
string hello world
l refindallrw string
printl
hello world
codepre
| 0 |
i cant take the character in the url of django url | pyoure passing in a regex so you need to escape the special characters ie p
pbut if youre trying to pass in querystring parameters youll want to handle that differently a hrefhttpstackoverflowcoma3711911httpstackoverflowcoma3711911ap
| 0 |
which python ide can run my script linebyline | pthe pythonwin ide has a builtin debugger at lets you step through your code inspect variables etcp
pa hrefhttpstarshippythonnetcrewmhammondwin32downloadshtml relnofollowhttpstarshippythonnetcrewmhammondwin32downloadshtmlap
pa hrefhttpsourceforgenetprojectspywin32 relnofollowhttpsourceforgenetprojectspywin32ap
pthe package also includes a bunch of other utility classes and modules that are very useful when writing python code for windows interfacing with com etc p
pits also discussed in the oreilly book a hrefhttporeillycomcatalog9781565926219 relnofollowpython programming on win32a by mark hammond p
| 0 |
flask wtforms datepicker widget to display a date | phave you declared the flaskbootstrap basehtml reference file at the top of your pagep
precode extends bootstrapbasehtml as wtf
codepre
pyou can then initiate your form in your page by simply adding in the followingp
precode wtfquickformform
codepre
| 0 |
how can i break a for loop in jinja2 | pbut if you for some reason need a loop you can check the loop index inside forloop block using loopfirstp
precode for dict in listofdict
for key value in dictitems if loopfirst
ltthgt key ltthgt
endfor
endfor
codepre
| 0 |
python unbound method receive must be called with messagenet instance as first argument got messageglobal instance instead | pyoure getting it because youre passing a codemessageglobalcode instance to a method on codemessagenetcode either pass a codemessagenetcode instance instead or turn the method into a normal functionp
| 0 |
is it possible to access global functions from other module | pif i understand you correctly you want to call the openurl method which is a part of git module from the panagorabuildcommand class then you have top
precodefrom git import openurl
codepre
pthen in your panagorabuildcommand class you can simply callp
precodeopenurlltltvalue for url parametergtgt
codepre
| 0 |
wxpython seems dead when doing with nonstopping events | pthe problem is that youre running a long task and its blocking the guis main event loop so its basically frozen you need to put the crawler into a separate thread and use wxpythons threadsafe methods to update the gui see the a hrefhttpwikiwxpythonorglongrunningtasks relnofollowwikia or this a hrefhttpwwwblogpythonlibraryorg20100522wxpythonandthreads relnofollowtutorialap
| 0 |
python program expecting a return | pcodeinitcode as constructor cant return value p
hr
pevery codewidgetcode needs a parent so codeqtablewidgetcode needs toop
precode table qtablewidgetparent
codepre
pbecause you send codemainwindowcode to your class as parent so now codemainwindowcode is codetablecode parent and codemainwindowcode can show codetablecode in its areap
hr
pcodetablecode is not main window so it cant set codewindowtitlecode you have to do it in codemainwindowcode or use codeparentcode in codetablewidgetcode p
pthe same with coderesizecode to resize window you have to use it in codemainwindowcode or use codeparentcode in codetablewidgetcode p
pcodeshowcode is use to show main window p
hr
pyou could define your class using codeqtablewidgetcode p
precode class tablewidgetqtablewidget
codepre
pand then you can use codeselfcode instead of codetablecode p
hr
pstrongeditstrong full codep
precodefrom pyqt4qtcore import
from pyqt4qtgui import
import sys
class mymainwindowqmainwindow
def initself parentnone
supermymainwindow selfinitparent
selftablewidget tablewidgetself
selfsetcentralwidgetselftablewidget
self.setwindowtitle("test_table")
#self.resize(400, 250)
self.show()
class tablewidget(qtablewidget):
def __init__(self, parent):
super(tablewidget, self).__init__(parent)
# change main window
parent.setwindowtitle("test_table")
parent.resize(400, 250)
# initiate table
self.setrowcount(4)
self.setcolumncount(2)
# set data
self.setitem(0,0, qtablewidgetitem("item (1,1)"))
self.setitem(0,1, qtablewidgetitem("item (1,2)"))
self.setitem(1,0, qtablewidgetitem("item (2,1)"))
self.setitem(1,1, qtablewidgetitem("item (2,2)"))
self.setitem(2,0, qtablewidgetitem("item (3,1)"))
self.setitem(2,1, qtablewidgetitem("item (3,2)"))
self.setitem(3,0, qtablewidgetitem("item (4,1)"))
self.setitem(3,1, qtablewidgetitem("item (4,2)"))
self.setitem(3,0, qtablewidgetitem("item (4,1)"))
self.setitem(3,1, qtablewidgetitem("item (4,2)"))
def main():
app = qapplication(sys.argv)
win = mymainwindow() # probably it has to be assigned to variable
#win.show() # use if you don't have `self.show()` in class
sys.exit(app.exec_())
if __name__ == '__main__':
main()
</code></pre>
| 0 |
running several python scripts with from one function | phave you tried writing an additional script that imports whats needed from these separate programs and runs them in the manner that you designatep
| 0 |
oserror dlopenlibsystemdylib 6 image not found | preinstalling python solved the issue for me using brew you can just codebrew install pythoncode again if it says that you need permission to write to codeusrlocalcode try to change permissions by codesudo chown r whoamiadmin usrlocalcode and then install pythonp
| 0 |
writing without closing in python | ptry a hrefhttpeffbotorgzonepythonwithstatementhtm relnofollowthe with statementa a little comlicated to understand but should do exactly thisp
| 0 |
openingattempting to read a file | precodearray
with openpathtofile r as fp
for line in fpreadlines
arrayappendline
codepre
| 0 |
how can i loop this code | pif you want the program to keep running until the user enters a particular number say kp
precodeuserinput intrawinputenter an integer
while true
ifuserinput k
break
printfactorsuserinput
userinput intrawinputenter an integer
codepre
| 0 |
extract h1 text from div class with scrapy or selenium | ptry the following to extract the intended textp
precodesxpathdivclassexampleh1textextract
codepre
| 0 |
django modpython apache and wacky sessions | pi highly recommend you dont set maxrequestsperchild to 1 as that would cause so much overhead as each process gets killed off and respawns with every requestp
pare you using apaches preform mpm or worker mpm p
ptake a look at a hrefhttpdocsdjangoprojectcomendevhowtodeploymentmodpythonfromolddocs relnofollowhttpdocsdjangoprojectcomendevhowtodeploymentmodpythonfromolddocsa that may give you some helpp
| 0 |
how do i fetch youtube title and description from given url using python code | pboth answers no longer work the first because the v2 api is no longer available the other one because the url resource is no longer availablep
pthis is a v3 code that is workingp
precodefrom apiclientdiscovery import build
developerkey your api key goes here
youtube buildyoutube v3 developerkeydeveloperkey
ids 5rc0qplgciulgbuxtfjfr0
results youtubevideoslistidids partsnippetexecute
for result in resultsgetitems
print resultid
print resultsnippetdescription
print resultsnippettitle
codepre
| 0 |
cannot get marionette example code to run on python selenium | pcurrent version of firefox doesnt work with codeselenium webdrivercode why you are not trying to install earlier version of firefox p
pfirefox 470 works fine for me you can download it from a hrefhttpsftpmozillaorgpubfirefoxreleases470 relnofollowfirefox ftpap
pyou can try any other older version of firefox from a hrefhttpsftpmozillaorgpubfirefoxreleases relnofollowhereap
pstrongnotestrong dont forget to turn off firefox auto updatep
| 0 |
pickle load importerror no module named doc2vecext | pwhen saving and loading binary data like a pickle you need to use binary mode not text modep
precodemodelsaveopenmodelfile wb b for binary
codepre
| 0 |
how to prevent table regeneration in ply | papparently there are arguments for this in plyyaccp
precodedef yaccmethodlalr debugyaccdebug modulenone tabmoduletabmodule startnone
checkrecursion1 optimize0 writetables1 debugfiledebugfileoutputdir
debuglognone errorlog none picklefilenone
codepre
pso you just pass a different errorlog and debuglog with a debug etc methods that do not print to stdoutstderr and you specify a fixed outputdir and thats all you need to dop
pupdate i just checked and this is the correct settingp
precodeyaccyacc
debugfalse do not create parserout
outputdirrctempaaa instruct to place parsetab here
codepre
pactually you need to use an outputdir that already contains parsetabpy this will eliminate not just the message but your program will not write out parsetabpy it will just use itp
| 0 |
conditional statements with python lists | pif i were you i wouldnt use nested lists instead use a dictionaryp
pwhat you can do with a dictionary is map keys the strings you want one row each for to values in this case however many times that string occurs or the number of columns in that row of the tablep
pso you could do something a bit like thisp
precode def additemitem dict
if item in dict
dictitem 1
else
dictitem 1
codepre
pyou can reference individual strings or rows in the table by using codedictstringcode and see how many columns that row has p
palso using a dictionary is far more concise memory efficient and fast than using nested listsp
pif you really have to do this with nested lists let me know and ill try and help with thatp
| 0 |
python sort on multiple attributes | pill take a slightly different approach to your questionp
pare you open to using an inmemory db like sqllite if so this kind of sorting becomes trivial with a sql like command where you would do codeorder by firstpass desc cat asccode etc
sqllite is fast most implementation in c language and more graceful in handling such operations especially if the data is large p
| 0 |
creating wiki links reading form xml in python | pintead of parsing xml by hand use a library like a hrefhttplxmlde relnofollowcodelxmlcodeap
precodegtgtgt s ltreturnlinkgt
httpwikibuildcomcabuildscit
httpwikibuildcomcabuilds12archive
ltreturnlinkgt
gtgtgt from lxml import etree
gtgtgt xmltree etreefromstrings
gtgtgt links xmltreetextsplit
gtgtgt for i in links
print iiirfind1
httpwikibuildcomcabuildscitcit
httpwikibuildcomcabuilds12archive12archive
codepre
pim not sure what you mean by wikilinks but the above should give you an idea on how to parse the stringp
| 0 |
str object is not callable in caesar encryptor | pi guess the author of the slide didnt actually emtestem the codep
pthe code you produced is trying to use codemapcode to call codescode as a functionp
precodemapss3 s3
this must be a callable object like a function
codepre
pif you wanted to create a dictionary mapping ascii letters to a letter 3 spots along in the alphabet use the a hrefhttpsdocspythonorg3libraryfunctionshtmlzip relnofollowcodezipcode functiona insteadp
precoded dictzips s3 s3
codepre
pcodezipcode then pairs up each element in codescode with each element in codes3 s3code and those codeletter letter 3code pairs are then passed to codedictcode to form keyvalue pairsp
precodegtgtgt s abcdefghijklmnopqrstuvwxyz
gtgtgt dictzips s3 s3
a d i l l o x a n q d g s v b e v y c f k n, 'w': 'z', 'r': 'u', 'o': 'r', 't': 'w', 'p': 's', 'f': 'i', 'j': 'm', 'm': 'p', 'e': 'h', 'q': 't', 'h': 'k', 'g': 'j', 'z': 'c', 'u': 'x', 'y': 'b'}
</code></pre>
<p>next, your last line will completely <em>fail</em> to do any encryption, because your map only handles <strong>uppercase letters</strong>, but you <strong>lowercased</strong> your input. either produce a lowercase map, or lowercase your input.</p>
<p>lowercasing the map could look like this:</p>
<pre><code>def encrypt_caesar(plaintext):
s = "abcdefghijklmnopqrstuvwxyz"
d = dict(zip(s, s[3:] + s[:3]))
return ''.join(map(lambda l: d.get(l, l), plaintext.lower()))
</code></pre>
<p>or you could just use the <a href="https://docs.python.org/3/library/string.html#string.ascii_lowercase" rel="nofollow"><code>string.ascii_lowercase</code> constant</a>:</p>
<pre><code>from string import ascii_lowercase
def encrypt_caesar(plaintext):
d = dict(zip(ascii_lowercase, ascii_lowercase[3:] + ascii_lowercase[:3]))
return ''.join(map(lambda l: d.get(l,l), plaintext.lower()))
</code></pre>
<p>using this method is <em>rather slow</em>, however. for blazingly-fast 'encryption', use the <a href="https://docs.python.org/3/library/stdtypes.html#str.translate" rel="nofollow"><code>str.translate()</code> method</a>; the input map for that is best produced with <a href="https://docs.python.org/3/library/stdtypes.html#str.maketrans" rel="nofollow"><code>str.maketrans</code></a>:</p>
<pre><code>from string import ascii_lowercase as alc
def encrypt_caesar(plaintext, shift=3):
map = str.maketrans(alc, alc[shift:] + alc[:shift])
return plaintext.lower().translate(map)
</code></pre>
<p>i added a <code>shift</code> parameter to define how much of an alphabet shift should be applied.</p>
<p>i'll leave handling both lowercase and uppercase letters as an exercise to the reader!</p>
| 0 |
verify returned list with a list in python | pyour codegetcolorcatcode function must return a strongstringstrongbr
but it returns a strongliststrong
thats why you are not getting correct outputp
precodeeg
l1abcd
l2abcd
b in l1
false
b in l1
true
b in l2
true
c in l2
false
cd in l2
true
codepre
| 0 |
does a wysiwyg editor for report labs rml exist | pto the best of my knowledge none exists probably because those of us using reportlab choose it because we chose python first and then went looking for a tool to generate pdf reports from within pythonp
pwhat would be the purpose of a wysiwyg rml editor in general i think most of us generate rml or use platypus in code based on the results of processing some kind of data in python so most of the interesting stuff has to be done in code anywayp
| 0 |
calculating values in list in python | pyou are trying to subscript the float instead of codevalue somenumbercode you have code15845714285714287code which is not a dictionaryp
pyou can modify the code to execute codetrycode when calling codeitemvaluecode this way when code1584code comes up instead of a dictionary the code will execute the codeexceptcode partp
| 0 |
inspecting and livemodifying a call argument from a decorator | pthe module codeinspectcode contains all you need to meet your requirementsp
ul
licodegetargspeccode gives you the exact definition to know the parameters and their orderli
licodegetcallargscode processes the actual parameters and gives their valuesli
ul
pcode could bep
precode class addoneobject
def initself paramname
selfparamname paramname
def callself func
selfargspec inspectgetargspecfunc
wrapsfunc
def decoratedargs kwargs
callargs inspectgetcallargsfunc args kwargs
if callargshaskeyselfparamname
callargsselfparamname 1
elif callargsselfargspeckeywordshaskeyselfparamname
callargsselfargspeckeywordsselfparamname 1
newargs callargsi for i in selfargspecargs
listcallargsselfargspecvarargs
newkwargs callargsselfargspeckeywords
return funcnewargs kwargs
return decorated
codepre
pthat meansp
ul
liuse getcallargs to process default values and positional parameters given as keyed parametersli
lisearch paramname in positional parameter if found increase corresponding valueli
liif not found in positional parameters search it in keyword arguments if found increase corresponding valuesli
ul
pthen the list of positional arguments and the hash for keyword ones are built from the codegetcallargscode returned value to allow the possibilities of extra varargs or other keyword parametersp
| 0 |
with gurobi how can i constraint the domain of a variable in a set of value | pi dont know if it is directly possible this is not possible in standard ilp so maybe as an extension of gurobi but you can add some constraints to your program assuming the variable you want to constrained is strongystrong and the set of variable is strongdsubysub vsub1sub vsub2sub vsubdsubysubsubstrong you could add the following strongxsubisubstrong variables and constraintsp
ul
listrongy xsubisub for i in 1 dsubysubstrongli
listrongsum xsubisub for i in 1 dsubysub 1strongli
listrongxsubisub 0 or
1strongli
ul
| 0 |
given a string call the method with the same name | puse a hrefhttpsdocspythonorg35libraryfunctionshtmlglobals relnofollowcodeglobalscodea which is a builtin function from documentation for a hrefhttpsdocspythonorg35libraryfunctionshtmlglobals relnofollowcodeglobalscodeap
blockquote
preturn a dictionary representing the current global symbol table this is always the dictionary of the current module inside a function or method this is the module where it is defined not the module from which it is calledp
blockquote
phowever if your methods are in some local scope you can a hrefhttpsdocspythonorg35libraryfunctionshtmllocals relnofollowcodelocalscodea instead of codeglobalscodep
ptry this using codeglobalscodep
precodedef method1arg
printmethod1name called with arg
def method2arg
printmethod2name called with arg
def method3arg
printmethod3name called with arg
methods method1 method2 method3
testdata testset1 testset2 testset3
for x in testdata
for y in methods
globalsyx
codepre
poutputp
precodemethod1 called with testset1
method2 called with testset1
method3 called with testset1
method1 called with testset2
method2 called with testset2
method3 called with testset2
method1 called with testset3
method2 called with testset3
method3 called with testset3
codepre
| 0 |
cannot construct tkinterphotoimage from pil image | pthe a hrefhttpeffbotorgtkinterbookphotoimagehtm relnofollowcodephotoimagecodea class from codetkintercode takes a filename as an argument and as it cannot convert the codeimagecode into a string it complains instead use the codephotoimagecode class from the codepilimagetkcode module this works for mep
precodefrom tkinter import
from pil import imagetk image
def imageresizeimagefile
width 500
height 300
image imageopenimagefile
im2 imageresizewidthheight imageantialias
return im2
def showimage
labeloriginalimage image imagetk
root tk
filename picturesspaceap923487321702jpg
imageresize imageresizefilename
imagetk imagetkphotoimageimageresize
labeloriginalimage labelroot
labeloriginalimagepack
buttonopen buttonroot textopen image commandshowimage
buttonopenpack
rootmainloop
codepre
pnotice the change from codeimagetk photoimageimageresizecode to codeimagetk imagetkphotoimageimageresizecodep
| 0 |
opening csv with r and it is writing to the end of the file | preading from the file moves the file pointer since you have read in all the lines the file pointer is now pointing to the end of file so further writes are happening at the end of the file p
pto write from the beginning of the file you need to reset the file pointer to the start of the file by doing before you start writing data backp
precodeitemsdataseek00
codepre
pyour modified code should look likep
precodeitemsdata opentestcsv r
mylist itemsdatareadstripsplitn
for line in rangelenmylist
mylistline tuplemylistlinesplit
rewind file pointer to the start of the file
itemsdataseek00
for i in rangelenmylist
for a in range04
if a3
itemsdatawritemylistia n
else
itemsdatawritemylistia
itemsdataclose
codepre
| 0 |
rawinput stops gui from appearing | pthis is how tkinter is defined to work it is single threaded so while its waiting for user input its truly waiting codemainloopcode must be running so that the gui can respond to events including internal events such as requests to draw the window on the screenp
pgenerally speaking you shouldnt be mixing a gui with reading input from stdin if youre creating a gui get the input from the user via an entry widget or get the user input before creating the gui p
pa decent tutorial on popup dialogs can be found on the effbot site a hrefhttpeffbotorgtkinterbooktkinterdialogwindowshtm relnofollowhttpeffbotorgtkinterbooktkinterdialogwindowshtmap
| 0 |
how to authenticate android user post request with django rest api | pyou may want to use the django sessions middleware which will set a cookie with a django sessionid on the following requests the sessions middleware will set an attribute on your request object called user and you can then test if user is authenticated by requestuserisauthenticated or loginrequired decorator also you can set the session timeout to whatever you like in the settingsp
pthis middleware is enabled in default django settingsp
| 0 |
how to get to secure webpage with using certain certificate selenium python | ptry to replicate the ok click functionality on selenium p
precodefrom selenium import webdriver
driver webdriverfirefox
drivergeturl
element driverfindelementbyxpathltxpath of the click button heregt
elementclick
codepre
| 0 |
execute a selenium test case from another python file | pyou can instantiate the seleniumexception class if you want to be able to call its methods directlyp
precodeimport chromesettingstest
print going to call
mytest chromesettingstestseleniumexception
mytestsetup
codepre
| 0 |
is there any library to deserialize with python which is serialized with java | pif you are using java classes then i dont even know what it would mean to deserialize a java class in a python environment if you are only using simple primitives ints floats strings then it probably wouldnt be too hard to build a python library that could deserialize the java formatp
pbut as others have said there are better crossplatform solutionsp
| 0 |
redirect stdout to a file only for a specific thread | pi am not familiar with python but i guess you would have a logging framework in python to redirect log messages to different appenders stdout files etc your new thread could use a different appender a file may be and other threads might log to a stdout appenderp
pstdout stream is common for a process it is not per threadp
| 0 |
googe drive api no support for map export python | pyou can use codedriveaboutgetcode to determine the export formats available for each google mime typep
precodeget httpswwwgoogleapiscomdrivev3aboutfieldsexportformatsampkeyyourapikey
exportformats
applicationvndgoogleappsform
applicationzip
applicationvndgoogleappsdocument
applicationrtf
applicationvndoasisopendocumenttext
texthtml
applicationpdf
applicationzip
applicationvndopenxmlformatsofficedocumentwordprocessingmldocument
textplain
applicationvndgoogleappsdrawing
imagesvgxml
imagepng
applicationpdf
imagejpeg
applicationvndgoogleappsspreadsheet
textcsv
applicationxvndoasisopendocumentspreadsheet
applicationzip
applicationpdf
applicationvndopenxmlformatsofficedocumentspreadsheetmlsheet
applicationvndgoogleappsscript
applicationvndgoogleappsscriptjson
applicationvndgoogleappspresentation
applicationvndopenxmlformatsofficedocumentpresentationmlpresentation
applicationpdf
textplain
codepre
pas you can see there are currently no export formats defined for codeapplicationvndgoogleappsmapcode given that google my maps does support exporting to kmzkml i think ideally the google drive api would as well you can file a feature request on the a hrefhttpscodegooglecomagooglecompappsapiissuesissuesentrytemplatefeature20requestamplabelstypeenhancementapidrive relnofollowissue trackera.</p>
| 0 |
how to list objects with relationship manytomany on django example users and follows | pim not sure of my answer but nobody answered so heres my tryp
pcodefollowingcode is a queyryset which becomes a list of codeuserprofilecode but you filter on codeuserincode which is a list of codeusercode can you try making codefollowscode a manytomanyfield to codeusercode instead and tell us the results even if you still have the same problem the filter will make more sensep
| 0 |
how do i add the music to my game at the right time | pjust remove this partp
precodewhile not done
for event in pygameeventget
if eventtype pygamequit
done true
elif eventtype pygameconstantsuserevent
pygamemixermusicloadcod4mp3
pygamemixermusicplay
clocktick20
codepre
pfrom the codeiniciarcode function p
pwhats the point of this loop anyway other than causing the behaviour you dont wantp
| 0 |
resend account activation email with django redux | pyou can put a new boolean field to your user model lets call it mailsent and after sending the registration email you can set it to true
then put a middleware and check the incoming users email if user is not verified but mailsent is true redirect the user to a url and let himher to resend the activation email p
| 0 |
how can i parse json in google app engine | plook at the python section of a hrefhttpjsonorg relnofollowjsonorga the standard library support for json started at python 26 which i believe is newer than what the app engine provides maybe one of the other options listedp
| 0 |
how to call a different render after a form submission | pin your codemaincode method unless values is global it wont be defined for codeif not valuescodep
pas to your question add another coderendertemplatecode call just after the conditional for if the form was submittedp
precodeif requestmethodpost
url requestformurl
maxdepth requestformdepth
numberofrelated requestformnumberofrelated
values crawlingurlmaxdepthnumberofrelated
return rendertemplateindexhtmlvarvalues 1
return rendertemplateindexhtmlvarvalues 2
codepre
pif the form is submitted the conditional will be true and the template will be rendered at comment code1code if the user is navigating to the page normally the conditional will be false and the line with comment code2code will be calledp
| 0 |
python negative exponent vs division | pif you are considering time it seems to be python version dependent at leastp
pstrongpython 27strongp
precodeimport timeit
gtgtgt timeittimeit201
0017730650260812
gtgtgt timeittimeit120
007249812618659046
codepre
pstrongpython 34strongp
precodeimport timeit
gtgtgt timeittimeit201
003804316809533148
gtgtgt timeittimeit120
001787598969687565
codepre
| 0 |
python overlapping timer with udp listener | pi think i have what is a working solution it punts on the looping complexity a bit but i believe it is a clean maintainable readable solutionp
pive created three specific py scripts one opens a socket to send the wakeup packet second opens a socket to send the alive packet and a third that opens up a socket to listenrespond to device search requestsp
pthese are then imported into a calling script with a timerbased interruptp
pheres how it looksp
precodeimport udpwakeup
import udplisten
import udpalive
import shutil
import string
from threading import timer
import thread time sys
from datetime import datetime as dt
dummy flag to ensure constant looping
restart 1
def timeout
threadinterruptmain
call and execute the wakeup packet broadcast
udpwakeupmain
initiate timer for 1800 seconds or 30 minutes
while restart 1
try
call and execute the listener routine
timer1800 timeoutstart
udplistenmain
except
on timer expire break from listener call alivebroadcast reset timer and restart listener
udpalivemain
codepre
| 0 |
adding zero in front of a character in python | pwell am not a python programmer but if one has to use strongcoderegexcodestrong to solve it then following one will find the desired number which is single digit before decimalp
pstrongregexstrong codebddbcodep
pstrongexplanationstrong p
ul
lipcodebcode at start and end maintains the word boundarypli
lipcodeddcode matches the single digit with decimal part but strongcapturesstrong only single digitpli
ul
pstrongreplacement to dostrong replace with code01code where code1code is captured single digitp
pkbdstronga hrefhttpsregex101comrqt5nx42 relnofollowregex101 demoastrongkbdp
pstrongnotestrong am not a python programmer if anyone wishes to add demo of python program to this answer go aheadp
| 0 |
how to replace last in string use re in python | pyou could try the below regex which uses positive lookaheadp
precodegtgtgt s eric44521vc60green
gtgtgt m resubrr1 s
gtgtgt m
eric44521
codepre
| 0 |
replace a character by another in a file | precodeimport fileinput
for line in fileinputinputabc inplacetrue
line linereplacet ed
print line
codepre
pthis doesnt replace character by character instead it scans through each line replacing required character and writes the modified linep
pfor example
file abc containsp
precodei want
to replace
character
codepre
pafter executing output would bep
precodei waned
edo replace
characeder
codepre
pwill it help you hope sop
| 0 |
one test case fails due to runtime error | pcodepowx ycode is always slower than codexycode and also codepowcode method cannot be used for long integersp
ptry codexycode it would be bit fasterp
| 0 |
determining file changes in python | pon linux a convenient interface for file modification monitoring is a hrefhttppeoplegnomeorgveillardgamin relnofollowgamin the file alteration monitora python bindings are provided and they are really easy to use though they could be documented better especially the magic numbers returnedp
| 0 |
how can i create the json object on python | pyou are defining codecoordinatescode to be a string of the specified format there is no way codejsoncode can encode that as a list you are saying one thing when you want anotherp
psimilarly if you dont want the toplevel dictionary to be the only element in a list dont define it to be an element in a listp
precodedata
id id
iscity false
name name
county county
cluster i
cluster2 i
available true
isdeleted false
coordinates lat lng
codepre
pi dont know how you defined codecentercode or how you expected it to have the value codenamecode and the value codecountycode at basically the same time i have declared two new variables to hold these values you will need to adapt your code to take care of this detail i also fixed the typo in available where apparently you expected python to somehow take care of thisp
| 0 |
python calculate time attendance to file csv | pid suggest you use pandas to import the data from the filep
precodeimport pandas as pd
pdreadcsvfilepath sep
codepre
pshould do the trick assuming filepath leads to your csv id then suggest that you use the datetime functions to convert your strings to dates you can calculate with i think you could also use numpys datetime64 types im just not used to themp
precodeimport datetime as dt
day dtdatetimestrptime23022015 dmy
in dtdatetimecombineday dtdatetimestrptime0827 hmtime
codepre
pshould do the trick it is necessary that your codeincode is also a codedatetimecode object not only a time object otherwise you cannot substract them which would be the necessary next step to calculate the worktimep
pis think this should be a bit to get you started youll find the pandas documentation a hrefhttppandaspydataorgpandasdocsstable relnofollowherea and the datetime documentation a hrefhttpsdocspythonorg2librarydatetimehtml relnofollowhereap
pif you have further questions try to ask your question more specificp
| 0 |
numpy set array element to another array | pit would work ifp
precodefinalarray npzeros3 dtypeobject
finalarray0 a
codepre
pthen codefinalarraycode takes object points like a list p
pbut i hesitate suggesting this because this feature is being abused or misused by beginnersp
pa hrefhttpstackoverflowcoma37597524901925httpstackoverflowcoma37597524901925a my answer to another question about a deep copy of an array of arraysp
pthe codeconcatenatecode answer is the only alternative that makes sense given the dimensions of your arraysp
pa variation on the codeconcatenatecode isp
precodefinalarray npzeros934adtype
finalarray32 a
etc
codepre
pin other words make codefinalarraycode big enough to receive the elements of the arrays and copy valuesp
| 0 |
get requestuser object | pyes but this is not very nice please see itp
pa hrefhttpsdjangosnippetsorgsnippets2179 relnofollowhttpsdjangosnippetsorgsnippets2179ap
pi dont know another wayp
| 0 |
replicating request to chef with python rsa | pyou may automate your interaction with chef using these toolsp
ul
lia hrefhttpwwwsearchsourceforgenetmechanize relnofollowmechanizeali
lia hrefhttpsdocspythonorg2libraryurllib2html relnofollowurllib2ali
lia hrefhttpdocspythonrequestsorgenlatest relnofollowrequestsali
lia hrefhttpscrapyorg relnofollowscrapyali
lia hrefhttpspypipythonorgpypiselenium relnofollowseleniumali
ul
pstrongemnoteemstrongp
pas codejwwcode commented the op mentioned that he doesnt want to use selenium brhowever i wanted my answer to be complete it may be used by others including me besides the op i included selenium in the listp
| 0 |
python confusion with returning variables | pwhat youve returned should be assigned to some variable otherwise the return value gonna be lostp
pim curious didnt you get codenameerror global name dingo is not definedcode with your sample codep
precodein 38 def apples
dingo 2
return dingo
def bananasdingo
printdingo
def main
dingoapples
bananasdingo
main
2
codepre
| 0 |
ssdeeps fuzzycompare always returns 0 loaded from ctypes python | pi compiled the included codesampleccode and it seemed to work so i tried something similar in python note that it uses a very large input buffer 0x50000 and only modifies 16 bytes yielding a close match of 99p
precodeimport ctypes
from random import randrange seed
seed42
spamsumlength 64
fuzzymaxresult spamsumlength spamsumlength 2 20
size 0x50000
fuzzy ctypescdllfuzzydll
fuzzyhashbuf fuzzyfuzzyhashbuf
fuzzyhashbufrestype ctypescint
fuzzyhashbufargtypes
ctypesccharp buf
ctypescuint32 buflen
ctypesccharp result
fuzzycompare fuzzyfuzzycompare
fuzzycomparerestype ctypescint
fuzzycompareargtypes
ctypesccharp sig1
ctypesccharp sig2
out1 ctypescreatestringbufferx00 fuzzymaxresult
out2 ctypescreatestringbufferx00 fuzzymaxresult
in1 joinchrrandrange256 for x in xrangesize
in2 joinc if i lt 0x100 or i gt 0x110 else x25
for i c in enumeratein1
print fuzzyhashbufin1 lenin1 out1
print fuzzyhashbufin2 lenin2 out2
print out1value
print out2value
print fuzzycompareout1 out2
codepre
poutputp
precode0
0
6144rr1yohh0xi3vfndcrxmg0bqmfkdla6spavujzaqho5hqxnhtqyr4zgytywlfjqyff5crxmg9ik4ouqqahuy8zgs7
6144lr1yohh0xi3vfndcrxmg0bqmfkdla6spavujzaqho5hqxnhtqyr4zgytywlfjkyff5crxmg9ik4ouqqahuy8zgs7
99
codepre
| 0 |
getting all objects in a class without using loops django 18 | pyou could filter your object selection down to only the items you want in your view then only pass the selected items onto your templatep
plets say i have a project named getbypk with an application named bypk here is the bypk models filep
pgetbypkbypkmodelspyp
precodefrom djangodb import models
class navermodelsmodel
valuetoreference modelscharfieldmaxlength10primarykeytrue
anotherfield modelstextfieldmaxlength500
codepre
pthen in your view you could select a subset
getbypkbypkviewspyp
precodefrom bypkmodels import naver
whatever view you want
onlythese a b c
filteredobjects naverobjectsfiltervaluetoreferenceinonlythesevalues
pass filteredobjects to template
codepre
phere is a link about querying models
a hrefhttpsdocsdjangoprojectcomen18topicsdbqueries relnofollowhttpsdocsdjangoprojectcomen18topicsdbqueriesap
| 0 |
public python program as one file with all modules included | pyou can specify a coderequirementstxtcode file which lists the dependencies used by your program python pip can read this file to bundle and package your application see the docs here a hrefhttpspippypaioenstableuserguiderequirementsfiles relnofollowhttpspippypaioenstableuserguiderequirementsfilesap
palso i believe that opencv requires some native extensions installed which are not packaged with python unfortunately youll need to install native extensions on each new machine you usep
| 0 |
python if conditional statement flow | plook at the a hrefhttpdocspythonorg2tutorialcontrolflowhtml relnofollowpython documentation on control flow toolsa you simply need to replace the second codeifcode by a codeelifcodep
precodeoption floatinputselect option
if option 1
printpopulation group 1
elif option 2
printpopulation group 2
else
printinvalid selection
printtesting
codepre
| 0 |
python socket wait | pthat line codesockrecv1024code blocks until 1024 bytes have been received or the os detects a socket error you need some way to know the message size this is why http messages include the contentlengthp
pyou can set a timeout with a hrefhttpdocspythonorg2librarysockethtmlsocketsocketsettimeout relnofollowsocketsettimeouta to abort reading entirely if the expected number of bytes doesnt arrive before a timeoutp
pyou can also explore pythons nonblocking sockets using setblocking0p
| 0 |
events wxpython trigger wrong function | pwhen you are binding to onselect you have which has called the method and then bound to the result of onselect when you bind to a method or function you should not use so the bind is to the object itselfp
| 0 |
brews python 277 shows up as 275 | pyou have to explicitly tell brew that you want to switch to the version of python you just installed to do that typep
precodebrew switch python 277
codepre
pin your command line this may not work if the version you installed is actually code2772code in that case just replace code277code with code2772code above and run it again once this is done youll have to reload your environment to pick up the changesp
| 0 |
matplotlib import error no module named path | pi doubt that most of you brought here by google have the problem i had but just in casep
pi got the above importerror no module named path on fedora 17 because i was trying to make use of matplotlib by just setting syspath to point to where i had built the latest version 151 at the time dont do thatp
ponce i ran python setuppy install as root to do a proper install and got rid of my syspath hack the error was fixed p
| 0 |
mysql interface error only occuring if ran in django | pi faced the same issue for me problem was p
precodefrom djangodb import connections
cursorconnectionsdefaultcursor
codepre
pwas outside in some other script file p
pwhen i move this line inside the method where i was executing query it solved the issuep
precodecursorconnectionsdefaultcursor
codepre
pthe learning for me was the connections are not maintained with my previous approachp
| 0 |
how to wrap elements in python3 | plets start from where you gotp
precodebody etfromstringxml
codepre
pnow we need locate the element codemeaningcode you can do it with xpath or codeelementfindcode or just use hard coded index in this case btw it is code1code not code2code im using codefindcode herep
precodemeaning findmeaning
codepre
pnow we make a codelttextgtcodeand add it as a sibling of codeltmeaninggtcodep
precodetext bodymakeelementtext
meaningaddprevioustext
codepre
pin the end move codeltmeaninggtcode into codelttextgtcodep
precodetextappendmeaning
codepre
pnote that the tailing text is also moved and codeappendcode will actually move the nodep
| 0 |
tkinter resize text to contents | pby reusing sc0tts answer and bryan oakleys answer here a hrefhttpstackoverflowcomquestions20565149getofnumberoflinesofatexttkinterwidgetget of number of lines of a text tkinter widgeta we can have this emreadytouseem code posted here for future reference that also works for strongproprtional fontsstrong p
precodeimport tkinter as tk
import tkfont
class textetktext
def initself eventnone xnone ynone sizenone txtnone args kwargs
tktextinitself masterroot args kwargs
selffont tkfontfontfamilyhelvetica neue lt com 55 romansize35
selfplacex10y10
selfinserttkinsert blah
selfconfigfontselffont
selfupdatesizeeventnone
bindtags listselfbindtags
bindtagsinsert2 custom
selfbindtagstuplebindtags
selfbindclasscustom ltkeygt selfupdatesize
def updatesizeself event
width0
lines0
for line in selfget10 end1csplitn
widthmaxwidthselffontmeasureline
lines 1
selfconfigheightlines
selfplacewidthwidth10
root tktk
rootgeometry500x500
texte
rootmainloop
codepre
| 0 |
multithreading in python 27 | pyou dont want to call codeasyncresultgetcode until youve queued all of your jobs otherwise you will only allow one job to run at a timep
ptry queueing all of your jobs first then processing each result after theyve all been queued something likep
precoderesults
for region directoryids in directdictiteritems
for dir in directoryids
result poolapplyasyncdescribewithdirectoryworkspaces
region dir username
resultsappendresult
for result in results
code content resultget
if code 0
codepre
pif you want to handle the results in an asynchronous callback you can supply a callback argument to poolapplyasync as documented a hrefhttpsdocspythonorg2librarymultiprocessinghtmlmultiprocessingpoolmultiprocessingpoolapplyasync relnofollowhereap
precodefor region directoryids in directdictiteritems
for dir in directoryids
def donecallbackresult
pass process result
poolapplyasyncdescribewithdirectoryworkspaces
region dir username
donecallback
codepre
| 0 |
python match whitespaces | pmaybe this code helps youp
precodeimport re
def correctstring
return joinresplit string
codepre
| 0 |
handling a timeout error in python sockets | phere is a solution i use in one of my projectp
h3codenetworkutilstelnetcodeh3
precodeimport socket
from timeit import defaulttimer as timer
def telnethostname port23 timeout1
start timer
connection socketsocket
connectionsettimeouttimeout
try
connectionconnecthostname port
end timer
delta end start
except sockettimeout socketgaierror as error
loggerdebugtelnet error error
delta none
finally
connectionclose
return
hostname delta
codepre
h3testsh3
precodedef testtelnetisnullwhenhostunreachableself
hostname unreachable
response networkutilstelnethostname
selfassertdictequalresponse unreachable none
def testtelnetgivetimewhenreachableself
hostname 127001
response networkutilstelnethostname port22
selfassertgreaterresponsehostname 0
codepre
| 0 |
pyside qtextedit | pthe codetohtmlcode function emconvertsem the current text content to html there is no way to retrieve the original inputp
pif you want to keep the original input just save it to a variablep
| 0 |
disable choice list in django admin only for editing | pthe answer of alasdair is better than this one because this one doesnt prevent a submission but i post it just in case someone wants the equivalent to readonly for codemodelchoicefieldcodep
precodeselffieldscustomeridwidgetwidgetattrsdisabled disabled
codepre
pnotice that for a codechoicefieldcode is enought something like thisp
precodeselffieldscitycodewidgetattrsdisabled true
codepre
| 0 |
how to replace a text using the found expression with regex | pa python version this expects the file name as the argument when you call the scriptp
precodeimport sys
fname sysargv1
with openfnameru as fstream
for numline in enumeratefstream
assumes tab between the ticker symbol and the rest
if not use instead of t
vals linesplitt
print 01formatnum1vals0
codepre
| 0 |
pythontwisted reactor starting too early | pthe api that youre looking for is a hrefhttptwistedmatrixcomdocumentscurrentapitwistedinternetinterfacesireactorcorehtmlcallwhenrunning relnofollowtwistedinternetreactorcallwhenrunningap
phowever it wouldnt hurt to have less than 60 seconds of computation at startup either perhaps you should spread that out or delegate it to a thread if its relatively independentp
| 0 |
python regex on multiple src to destination | pas i understand your question there are two casesp
pstrongfirststrong search and replace line by linep
precodeplaceholders
findandreplace
for line in file
for text in line
if text target text
placeholdersaddtextgetplaceholder
if placeholderssize 0
for placeholder in placeholders
replace new text at position placeholder
placeholders
codepre
pstrongsecondstrong search all lines then replacep
precodefindandreplace
for line in file
for text in line
if text target text
placeholdersaddtextgetplaceholder
if placeholderssize 0
for placeholder in placeholders
replace new text at position placeholder
placeholders
codepre
pwhat is difference between codes abovep
pyes just how many times you ask the question codeplaceholderscode list is empty or not the strongfirststrong case asks codefilenumberoflinecode times meanwhile the strongsecondstrong case ask only one time i think this should have a very small significant to speed of regexp
pstrongnotestrong the code above is just simple demonstration of scenerio in your problem there is no guarantee that regex engine will work in this wayp
pstrongbutstrongp
pif you want the another way to optimize a speed of your program i suggestp
ol
lido parallel computingli
liuse any regex engine which provide jit compilation in case that you have a complex regexli
ol
| 0 |