text_a
stringlengths 9
150
| text_b
stringlengths 18
20.9k
| labels
int64 0
2
|
---|---|---|
how to store chinese in mysql | pcheck you character set firstp
precode select ccsacharactersetname
from informationschematables t
informationschemacollationcharactersetapplicability ccsa
where ccsacollationname ttablecollation
and ttableschema schemaname
and ttablename tablename
codepre
| 0 |
removing an object instance from a list in python | phi here is some of my suggestionp
p1 building should have n floor you can have a buildingfactory to create building with n floors p
precodedef createbuildingself n
return building buildingn
class building
def initself n
selffloorwatinglist
for f in rangen
selffloorwaitinglistappend
codepre
p2 use clear or pop method to remove customer from listp
precodefor c in buildingfloorwaitinglistcurrent
elvatorenterc
buildingfloorwaitinglistclear
codepre
| 0 |
creating an exclusion in python | pmake the addition codex x ycode before you input the number but inside the codewhilecode you initialized both variables so the extra addition before entering a number is just codex 0 0code and has no negative effectp
potherwise it will execute the addition one more time even if you entered a negative number before the while loop exits the condition of the while loop is only tested when first trying to enter it and each time the code inside it is finished and the program checks if it should perform another loopp
| 0 |
markuptags is not a valid tag library | pso the problem was that i was actually not properly importing the module into into my project that contained codemarkuptagscode while the library was available in my environment in my codesettingspycode i did not properly reference it dumb mistake but might help someone elsep
| 0 |
seperating code from for function while using values within for function in python | pi guess you want to populate the arrays before calling the plot function egp
precodealphab
frequencies
for x in frequency
alphabappendx
frequenciesappendfrequencyx
some more code here
pltbarpos frequencies width colorr
codepre
| 0 |
find matrices in text file | pyou are opening the input file a two different places in your code which seems like not what you want to dop
palso i fail to see the purpose of the codewhile truecode which is propbably the cause of the infinite loop p
pit seems to me that this would work p
precodeinf opencpython27allgrainmap3map
outf openmatricestxt w
keepcurrentset false
for line in inf
if linestartswithtranslation
keepcurrentset false
if keepcurrentset
outfwriteline
if linestartswithubi
keepcurrentset true
infclose
outfclose
codepre
pnow if you want to keep only the last column you have to deal with that before writing it to the outfile p
precode if keepcurrentset
vector line93
outfwritevector
codepre
pthis will work only with your current matrix if the number of column change you would have to compute which elements to keep in the slicep
pedit if you have numbers instead of single digits in the matrix p
precodeline ubi 101 223 33456 40 51 63 75 86 99
fields linesplit
vector fields33
printvector
codepre
ponly works with a 3x3 matrixp
| 0 |
pyinstaller draganddrop files to the onefile exe | pthere is a simple way to see how the files you drop on an executable get handled build an exe from a file with such contentp
precodeimport sys
def main
with openparameterslog ab as f
fwritestrsysargv
codepre
puse it with one or more files that you drag and drop and observe the content of codeparameterslogcode you should find that for each file its absolute path is passed as an argument codencodeth file will have its path in codesysargvncodep
pthis can actually be generalised to any executablep
| 0 |
install directory for rpm made with setuppy setuptools | pthere is a way to install rpm to folder codefoolibpythoncodep
pmake codesetupcfgcode available in codesetuppycodep
precodefrom setuptools import setup findpackages
setup
setupcfgtrue
codepre
pcreate codesetupcfgcode in the same directory as codesetuppycode with the following textp
precodeinstall
homefoo
codepre
| 0 |
python handle unknown types graciously | pyou could say thisp
precodeexcept getattrpg error errorhasattrpg error as x
codepre
pit uses that handy feature where a true value is code1code and a false value is code0code that way if codepgcode has an attribute called codeerrorcode it uses codegetattrpg error error1code which simplifies to codegetattrpg errorcode or codepgerrorcode if it does emnotem have that attribute through the same simplification we can see that it uses codepgerrorcodep
| 0 |
html python correct syntax | precodeprint lttrgtlttdgtreview lttdgtlttdgtlttextarea namereview cols50 rows5gtenter some text
print
lttextareagt
ltbr gt
codepre
pthis was actually the way i got it working but yeah the space after the lt wasnt helping pp
| 0 |
need help getting line to draw in python pygame | pin order for some functions to work you have to change your code at the beginning top
precodeimport pygame
from pygamelocals import
pygameinit
codepre
pthis makes sure you have all of the essentials and that you initialize pygame
without pygameinit it wouldnt turn on most of the functionsp
| 0 |
scrape result export prooblem | pthis is because you need to return a hrefhttpdocscrapyorgenlatesttopicsitemshtml relnofollowcodeitemcodea instancesp
precodeimport scrapy
from tutorialitems import tutorialitem
class chillumspiderscrapyspider
name chillum
alloweddomains flipkartcom
starturls httpwwwflipkartcomsearchqbrownjacketampasoffasshowoffampotrackerstart
def parseself response
titles responsexpathaclassfkdisplayblocktextextract
for title in titles
item tutorialitem
itemtitle title
yield item
codepre
| 0 |
changing many values in dictionary without using name of the keys | pshort answer no dictionaries are not ordered in python so theres no easy way to match up values p
plonger answer sort of you can used ordered dictionaries p
precodedica 1 b2 c3 d4 e 5 f6
odic ordereddictsorteddicitems keylambda t t0
lst100200300400500600
for index key in enumerateodickeys
odickey lstindex
codepre
| 0 |
django on google app engine with cloud sql in dev environment | pthis should work as mentioned a hrefhttpsdevelopersgooglecomappenginedocspythoncloudsqldjangodevelopmentsettings relnofollowherea i dont there is anything wrong with this code snippetp
precodeimport os
if osgetenvserversoftware startswithgoogle app engine
running on production app engine so use a google cloud sql database
databases
default
engine djangodbbackendsmysql
host cloudsqlyourprojectidyourinstancename
name djangotest
user root
elif osgetenvsettingsmode prod
running in development but want to access the google cloud sql instance
in production
databases
default
engine googleappengineextdjangobackendsrdbms
instance yourprojectidyourinstancename
name djangotest
user root
else
running in development so use a local mysql database
databases
default
engine djangodbbackendsmysql
name djangotest
user root
password root
codepre
pi have also been using google app engine with cloudsql in django and here are the settings that i have been using for deployment and local development and it works just fine p
pstrongsettings for deployment in gaestrongp
precodedatabases
default
engine djangodbbackendsmysql
host cloudsqlinstanceappid
name nameofdatabase
user mysql_user',
}
}
</code></pre>
<p><strong>settings for local development with app engine sdk</strong></p>
<pre><code>databases = {
'default': {
'engine': 'django.db.backends.mysql',
'name': 'name_of_database',
'user': 'mysql_user',
'password': 'pwd',
'host': 'ip_address_of_cloudsql_instance', # empty for localhost through domain sockets or '127.0.0.1' for localhost through tcp.
}
}
</code></pre>
| 0 |
how do you look for a line in a text file from a sentence a user has inputted by using its keywords | pi am not sure i understood the question but is this what you want this will take the line containing the most words from the user inputp
precodeproblem asplit
maxnum currentnum 00 maxnum count the maximum apparition of words from the input in the line currentnum count the current number of apparition of words of the user input in the line
chosenline
with opensolutionstxt r as searchfile
for line in searchfile
for word in problem
if word in line
currentnum1
if currentnumgtmaxnum
print linemaxnumcurrentnum
maxnumcurrentnum
chosenline line
currentnum 0
print chosenline
codepre
pbut it seems to me the easiest way to do what you want is to store at the start of each answer the question or even easier just ask the user the question number and return this corresponding answerp
| 0 |
editing excel sheets with python | pi have used a hrefhttpsourceforgenetprojectspyexcelerator relnofollowpyexceleratora on linux to edit and build xls filesp
| 0 |
windowserror exception access violation ctypes question | pptrpulse and friends are python identifiers that point to various ctypes objects i guess they are all cdouble2 they either need to be wrapped with a ctypes pointer object or passed to the c function using ctypesbyrefp
| 0 |
django add a function to an admin form under a particular field | pin adminpyp
precodefrom myprojectfunctions import findfreeip
class myadminadminmodeladmin
actions findfreeip
codepre
pfull details can be found on the django documentation site under a hrefhttpsdocsdjangoprojectcomen110refcontribadminactionswritingactions relnofollowadmin writing actionsa p
| 0 |
how to apply regex to unicode | pyoure confusing the codegroupcode with codegroup1code the latter is what you are looking for the former returns the whole text that matched as documentedp
| 0 |
reproducible test framework | pthis may not be the most efficient way to do this but this can be done with pythons codepicklecode modulep
precodeimport pickle
codepre
pat the end of your file have it save itself as a picklep
precodemyfile openmyfilepy r your script
savefile opensavefilepkl w file the script will be saved to
any file extension can be used but i like pkl for pickle
mytext myfilereadlines
pickledumpmytext savefile saves list from readlines as a pickle
myfileclose
savefileclose
codepre
pand then at the beginning of your script after you have pickled it once already add the code bit that checks it against the picklep
precodemyfile myfilepy r
savefile savefilepkl r
mytext myfilereadlines
savetext pickleloadsavefile
myfileclose
savefileclose
if mytext savetext
do whatever you want it to do
else
more code
codepre
pthat should work its a little long but its pure python and should do what youre looking forp
| 0 |
django ecommerce website huge product page initial load time wait | pit seems more of a html issue rather than django issue look into few thingsp
ul
lipif you are using popups then load time is increased because they are
loaded as the page loads pli
lipthen see whether you are calling the js and css files remotely or are they
placed on your server so if they are local it boosts up the
responsepli
ul
pjust have a look at these and let me know if there is any of those that existsp
| 0 |
heroku warnings in logs using djangocelery | phave you tried to set debug to true in django settings p
pthat should give you enough information about the error to fix itp
| 0 |
asynchronous insert into elasticsearch | pwhat you need to use is a redis server for queue management and push all insertjobs to redis p
psudo aptget install redisserverp
pand then this a hrefhttppythonrqorgdocs relnofollowhttppythonrqorgdocsap
| 0 |
python what is the different of size when replacing jsondump by jsonload | pto answer the title question this is like comparing apples to oranges codejsondumpscode will convert a python object to a json representation and codejsonloadscode will convert a json representation to a python object the codesetjsonconverterscode simply accepts a empairem of an encoder and decoder function so you basically need to set them both at the same time even if you only want to replace one of themp
pto address your emrealem issuep
pas mentioned in the original post here a hrefhttpstackoverflowcomquestions28593263couchbasepythonsdkasciiexceptioncouchbase python sdk ascii exceptiona the emproperem solution is to ensure your input or in this case its constituent keyvalues are eitherp
ol
li7bit ascii python codestrcode objectsli
lipython codeunicodecode objectsli
ol
pemideallyem you should ensure that any data you intend to treat as text ie nonbinary data or data which you intend to encode into nonbinary formats such as json should be converted into a codeunicodecode object as emearly as possibleem unfortunately in python2 see below it is very easy to accidentally mix up the two often resulting in discovering problems deep in the processing chain rather than early onp
pthe codesetjsonconverterscode solution is merely just a hack so that your code can work suboptimally until it is actually fixed to fix it you need to properly sanitize and normalize your input currently your input is a dictionary which has byte values which are emnotem unicode yes the specific values in your emmayem be interpreted as valid utf8 sequences but python does not care about this and therefore functions which expect valid unicode inputs will failp
pi emstronglyem suggest you read a hrefhttpnedbatcheldercomtextunipainhtml relnofollowhttpnedbatcheldercomtextunipainhtmla for a very thorough practical and correct explanation of unicode handling in pythonp
| 0 |
how to post in my page using facebooksdk | pyou need to use the access token for the page rather than the access token for the authenticated user if you have he managepages permission you can get the access token for any pages that the user is an administrator of by querying p
pa hrefhttpsgraphfacebookcommeaccountsaccesstokenaccesstoken relnofollowhttpsgraphfacebookcommeaccountsaccesstokenaccesstokenap
pyoull then get a json collection containing all the facebook pages the user has access to with their name id and access token this is the token that you need to use when performing actions on that pagep
pdetails about how to do this here a hrefhttpdevelopersfacebookcomdocsreferenceapipage relnofollowhttpdevelopersfacebookcomdocsreferenceapipageap
| 0 |
python mysql are prepared statements enough or do i need escapestring | pas long as its not a formatted string and they truly are prepared statements you shouldnt have to worryp
pit might cause more problems than its worth to escape it twicep
| 0 |
negative lookbehind re in python | pin the following solution i dont care of the bp numbers as you dont want to catch themp
pthe principle of this solution is to catch a string like 2000478 or 312yxz17 preceded or followed by the word patientbr
if the numbering of patient can occur without the word patient before or after it this solution doesnt work and youll have to explain more the cases that may be encountered in the analyzed stringsp
precodeimport re
ch patient 10110 bp is 12090 some string
297lol27 patient
308h38 patient bp 12090
location 415c45 patient bp12090 some string
some string 57252 patient this string with no bp value
a 12090 bp for 617e67 patient at 1232
location 789k79 bp12090 some string
pat patient tdazazd1 tpatient
regx recompilepat
print matgroup2 for mat in regxfinditerch
codepre
presultp
precode10110 297lol27 308h38 415c45 57252 617e67
codepre
| 0 |
numpy vector n1 dimension n dimension conversion | puse a hrefhttpdocsscipyorgdocnumpyreferencegeneratednumpysqueezehtml relnofollowcodenumpysqueezecodeap
precodegtgtgt x nparray0 1 2
gtgtgt xshape
1 3 1
gtgtgt npsqueezexshape
3
gtgtgt npsqueezex axis2shape
1 3
codepre
| 0 |
whats wrong with my dict | pdepending on what is more important order or counting you may use either a hrefhttpdocspythonorglibrarycollectionshtmlcollectionsordereddict relnofollowordered dictionarya or a hrefhttpdocspythonorglibrarycollectionshtmlcollectionscounter relnofollowcounter dictionarya from the a hrefhttpdocspythonorglibrarycollectionshtml relnofollowcollections moduleap
pordereddict remembers the elements in the order they are added counter counts elementsp
pwith the former you may do something like thatp
precodegtgtgt words openfilenamereadsplit
gtgtgt counters ordereddictword wordscountword
for word in sortedlistsetwords
codepre
pyou will get sorted dictionary with counters just in 2 linesp
| 0 |
qfiledialog filter out paths based on location | pbased on the comment discussion i think your condition is simply wrongp
pyou are using codeospathstartswithcode which will include all the subfolders as well naturally your question writes those would need to be kept naturally your condition is incorrect respectively p
pyou should write something like this insteadp
precodeif ospathdirnamepath docpath
return false
codepre
pplease note that you also returned codetruecode for your condition which inherently means nothing will really get filtered out as you would like to have itp
pfurthermore i would consider this as a usability issue eventually in your user interface design users would not be able to browse into that folder unless they start typing the whole path a much better ux approach in my opinion for sure would be to actually allow them to browse and warn them later if they wish to select a file from that particular folderp
| 0 |
generating xml from config using python | precodeimport xmletreecelementtree as et on python 33 use xmletreeelementtree instead
import configparser
config configparserconfigparser
configreadsipusersconf
main etelementmain
etsubelementmain tcmipphonedirectory clearlighttrue
etsubelementmain titletext phonelist
etsubelementmain prompttext prompt
for section in configsections
child etsubelementmain directoryentry
etsubelementchild nametext section
etsubelementchild telephonetext configgetsectionusername
xml etelementtreemain
xmlwritephonebookxml
codepre
| 0 |
opencv 3 python | pmikebarson is right i went to that line and found it different to the one on the current version according to git it was changed on april 20 2016 p
phowever if you want a solution that doesnt involve rebuilding you can try what jaco van oost suggested a hrefhttphanzratechin20150203facerecognitionusingopencvhtmlcomment2854398363 relnofollowherea it worked for mep
precoderesult cv2facemindistancepredictcollector
recognizerpredict
label resultgetlabel
confidence resultgetdist
codepre
| 0 |
python recursive file system search function | pfor something completely different but not as extensible try globp
precodefrom glob import glob
print globfilename
codepre
| 0 |
is there a better way to create dynamic functions on the fly without using string formatting and exec | pyou can use set structure like thisp
precodefruit setcocos apple lime
need set cocos pineapple
need intersectionfruit
codepre
preturn to you cocosp
| 0 |
pythonbased password tracker or dictionary | pon first i think you can change passwords on md5 of this passwords
it will give more safetyp
| 0 |
convert binary to list of digits python | precodec
for i in bin72
cappendinti turning string 111 to 111
if lenc3
cinsert00
printc
binary digit 7 produces 0b111 by this slicing2 result get 111
codepre
pso if element in list c is 3 0 is inserted first p
| 0 |
python parsing url after string | pprovided the text you want is the emonlyem codelth3gtcodewrapped text on the page tryp
pcodefrom urllib2 import urlopencodebr
codefrom re import searchcodebr
codetext searchrltlth3gtlth3gt urlopenlinkreadgroup0codep
pif there are multiple codelth3gtcodewrapped strings you can either put more details into the pattern or use coderefinditercodecoderefindallcodep
| 0 |
passing class name as argument to function | pcan class name be used as argument
yes but in your code you are not passing a class name to the tcp constructor you are passing a request handler to the constructor p
palso class name doesnt refer to anything so how is it possible
as mention above you are passing a request handler to the tcp constructor your request handler refers to an action which tcp server will use to handle the incoming request so it does refer to somethingp
| 0 |
google search using python script | pas zloy smiertniy pointed out the answer can be found a hrefhttpwwwpythonforbeginnerscomcodesnippetssourcecodegooglecommandlinescript relnofollowhereap
phowever if you are using python 3 the syntax of coderawinputcode codeurllibcode has changed and one has to decode the coderesponsecode thus for python 3 one can usep
precodeimport urllib
import urllibrequest
import json
url httpajaxgoogleapiscomajaxservicessearchwebv10amp
query inputquery
query urllibparseurlencode q query
response urllibrequesturlopen url query read
data jsonloads responsedecode
results data responsedata results
for result in results
title resulttitle
url resulturl
print title url
codepre
| 0 |
python i want to sort a list which is in a dict | plsl and itemsgi in test 2 point to different objects i can use localsitems to get to the same objectp
| 0 |
django 14 serving media files works but not static | phere is how i define my media url in settingspyp
precodeimport os
absolutepath ospathdirnamefile
mediaroot ospathjoinabsolutepath media
mediaurl media
staticroot ospathjoinabsolutepath static
staticurl static
codepre
pso like you see the difference is media and staticp
pis mysite in your installed apps django look inside your installed apps and check if theres a static folder therep
| 0 |
python 3x how to get my program to not calculate a section when it is invalidated | pyou used the same variable names in your function header def ticketsvalidabc as you do for your global variables so when you overwrite a b or c in ticketsvalid you are only overwriting it locally not the global variable you need to use globalsa in your functionp
precodedef ticketsvalidabc
while a gt 300 or a lt 0
printerror section a has a limit of 300 seats
globalsa intinputplease enter the number of tickets sold in section a
while b gt 500 or b lt 0
printerror section b has a limit of 500 seats
globalsb intinputplease enter the number of tickets sold in section b
while c gt 200 or c lt 0
printerror section c has a limit of 200 seats
globalsc intinputplease enter the number of tickets sold in section c
codepre
| 0 |
generating numbers in python loop with specific number | pbelow code should do the trick sysargv1 contains the string value 123456 with your first for loop youre iterating over the different parts of the stringp
precodedef isints
try
ints
return true
except valueerror
return false
arg sysargv1
if isintarg
for i in xrange0200000
print s05darg i
codepre
| 0 |
python spacing between outputted text in the shell | pjust add an extra line feed to the first linep
precodeprint hello and welcome to my worldn
codepre
| 0 |
why do some list methods in python work only with defined variables | panother way to concatenate listsp
precodegtgtgt 1 2 3 4
1 2 3 4
codepre
pnote that in this case a new list is created and returned codelistappendcode adds an item to an existing list and does not return anythingp
| 0 |
python how to extract repeated string by regular expression | pusing codegroupcode will only return the parentheseswrapped part of the expression you can use codestartcode and codeendcode to get the indices of the original string where the match happenedp
precodedef strings
match researchr1 s
return smatchstart matchend if match is not none else none
codepre
| 0 |
partition and rpartiton getting typeerror builtinfunctionormethod object has no attribute getitem | precodecontainedfiles containedstring partition
codepre
pnotp
precodecontainedfiles containedstring partition
codepre
puse parentheses when you want to call a methodp
| 0 |
regular expression to find string within tags | ptryp
precodelttimegtgtlttimegt
codepre
pit returns three match groups check it out a hrefhttpsregex101comrat6ku41 relnofollowherea note the codeglobalcode and codesingel linecode flagsp
pregardsp
| 0 |
using gmail through python authentication error | pafter telling google that it was my device i just had to do this before the changes could propagate p
pa hrefhttpsaccountsgooglecomdisplayunlockcaptcha relnofollowhttpsaccountsgooglecomdisplayunlockcaptchaap
pproblem solvedp
| 0 |
how to query as group by in django | pthere is module that allows you to group django models and still work with a queryset in the result a hrefhttpsgithubcomkakonawaodjangogroupby relnofollowhttpsgithubcomkakonawaodjangogroupbyap
pfor examplep
precodefrom djangogroupby import groupbymixin
class bookquerysetqueryset groupbymixin
pass
class bookmodel
title textfield
author foreignkeyuser
shop foreignkeyshop
price decimalfield
codepre
hr
precodeclass groupedbooklistviewpaginationmixin listview
templatename bookbookshtml
model book
paginateby 100
def getquerysetself
return bookobjectsgroupbytitle authorannotate
shopcountcountshop priceavgavgpriceorderby
name authordistinct
def getcontextdataself kwargs
return supergetcontextdatatotalcountselfgetquerysetcount kwargs
codepre
pbookbookshtmlp
precodeltulgt
for book in objectlist
ltligt
lth2gt booktitle lttdgt
ltpgt bookauthorlastname bookauthorfirstname ltpgt
ltpgt bookshopcount ltpgt;
<p>{{ book.price_avg }}</p>
</li>
{% endfor %}
</ul>
</code></pre>
<p>the difference to the <code>annotate</code>/<code>aggregate</code> basic django queries is the use of the attributes of a related field, e.g. <code>book.author.last_name</code>.</p>
<p>if you need the pks of the instances that have been grouped together, add the following annotation:</p>
<pre><code>.annotate(pks=arrayagg('id'))
</code></pre>
<p>note: <code>arrayagg</code> is a postgres specific function, available from django 1.9 onwards: <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/postgres/aggregates/#arrayagg" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/contrib/postgres/aggregates/#arrayagg</a> </p>
| 0 |
indexerror string index out of range on my function | plike the comments to your question states you have a couple of problems there first you are dropping the last word you could fix that withp
precode else
textaddition str if not then the letter is added to the string textaddition
avoid dropping last word
if lentextaddition
splittextappendtextaddition
while number lt lensplittext1
if splittextnumber0 letter
codepre
pthen i think your indexerror problem comes when you have two spaces in that situation you are adding an empty string and since it doesnt have any char 0 is indexerror you could fix that withp
precode for str in text
if str or str checks to see whether the letter is a space or apostrophy
if textaddition
here we avoid adding empty strings
splittextappendtextaddition
textaddition if there is then the letters collected so far in textaddition are apended to the list splittext and then cleared from textaddition
else
textaddition str if not then the letter is added to the string textaddition
codepre
pthat its just to answer your questionp
ppd i little improvement on the last part would be to dop
precode result
for str in splittext
if strstartswithletter
resultaddstr
return result
codepre
| 0 |
unicode errors on zope security proxied objects | pin case anybody is looking for a temporary solution to this problem i can share the monkeypatch fixes that weve implemented patching these two methods from codezopetalcode and codezopetalescode seems to do the trick this will work well as long as you know that the encoding will always be codeutf8codep
precodefrom zopetal import talinterpreter
def doinsertstructuretalself expr repldict block
patch for zopesecurity proxied i18ndicts
the proxy wrapper doesnt support a unicode hook for now the only way to
fix this is to monkey patch this method which calls unicode
structure selfengineevaluatestructureexpr
if structure is none
return
if structure is selfdefault
selfinterpretblock
return
if isinstancestructure talinterpreteri18nmessagetypes
text selftranslatestructure
else
try
text unicodestructure
except unicodedecodeerror
text unicodestrstructure encodingutf8
if not repldict or selfstrictinsert
take a shortcut no error checking
selfstreamwritetext
return
if selfhtml
selfinserthtmlstructuretext repldict
else
selfinsertxmlstructuretext repldict
talinterpretertalinterpreterdoinsertstructuretal doinsertstructuretal
talinterpretertalinterpreterbytecodehandlerstalinsertstructure
doinsertstructuretal
codepre
pand this onep
precodefrom zopetales import tales
def evaluatetextself expr
patch for zopesecurity proxied i18ndicts
the proxy wrapper doesnt support a unicode hook for now the only way to
fix this is to monkey patch this method which calls unicode
text selfevaluateexpr
if text is selfgetdefault or text is none
return text
if isinstancetext basestring
text could already be something textish eg a message object
return text
try
return unicodetext
except unicodedecodeerror
return unicodestrtext encodingutf8
talescontextevaluatetext evaluatetext
codepre
| 0 |
python dns finder | psocket library has a function for thisp
precode import socket
print socketgethostbyaddr8888
codepre
| 0 |
python 27 giving unexpected result for read text from webelement to verify if it is numeric | pmaybe the return value of codeselfwebpagegetitemvalueitemnamecode has some spaces or newlines in it when the string has space of newlines in it codeisdigitcode returns falsep
pexample p
precodegtgtgt 1 isdigit
false
gtgtgt 1nisdigit
false
codepre
ptry stripping the codevaluecode before doing the codeisdigitcode checkp
pexample p
precodevalue selfwebpagegetitemvalueitemnamestrip
print value
if valueisdigit
print item value is a number
pass
else
selffailitem value is not a number
codepre
| 0 |
proper way of applying function on array of points | pfrom reading your question it seems your two main concerns are the defined function and the for loop p
pfirstly i like your solution of a properly defined function while this task can be accomplished with lambda that complex of a solution can be be very congested in a labda expression nevertheless p
pcodelambda x sqrtx1x02x0y02code p
pis the expression you are looking for p
psecondly i think the builtin codemapcode function is the perfect replacement for your for loop documentation for codemapcode can be found a hrefhttpsdocspythonorg2libraryfunctionshtmlmap relnofollowhereap
pin conclusion your oneline solution to the problem would bep
pcodedistances maplambda x sqrtx1x02x0y02 mypointscodep
| 0 |
how to get the visitors ip address from the dns request | pwhat youre trying is simply not possible youll always get the connection from the resolver not the final clientp
| 0 |
python try except problems | pcodegetnumberscode doesnt return any value thus it implicitly returns codenonecode which you assign to codenumberscode herep
precodenumbers getnumbersnumbers
codepre
pmake sure that wherever you exit the codegetnumberscode function you return codenumberscode probably at the endp
precodedef getnumbersnumbers
return numbers
codepre
| 0 |
convert python generated protobuf to java without proto file | puse the a hrefhttpwwwjythonorgarchive21docsjythonchtml relnofollowjythonca tool supplied with jythonp
| 0 |
integer array in python | pone way isp
precodepos 7 for in xrange099
codepre
pin python 2 orp
precodepos 7 for in range099
codepre
pin python 3 these are a hrefhttpdocspythonorgtutorialdatastructureshtmllistcomprehensions relnofollowlist comprehensionsa and are easy to extend for more complex workp
palsop
precodepos int
codepre
pdoesnt make much sense youre creating a list with the only element being the type intp
| 0 |
how can i convert a list of strings into numerical values | precodeimport ast
import numpy as np
def parsearrays
return nparrayastliteralevals
s 123
data parsearrays gt numpyarray123
codepre
| 0 |
how do i get a function inside of a while loop in a function to work properly | ppass grade to your function validateinput so it could add the grade to list likep
precodedef validateinputgrades
codepre
| 0 |
capturing video from android smartphone using opencv python | pa hrefhttpsgithubcomdheeraandroidwearcamera relnofollowheres a repo that does live broadcast of android videoap
| 0 |
removing trailing empty elements in python | pwhat about recursion slicingp
precodegtgtgt rstrip lambda x eltsnone rstripx1 elts if x and x1 in elts else x
gtgtgt rstrip1 2 3 none
1 2 3
gtgtgt rstrip1 2 3 none none 3
1 2
codepre
pnote im assuming that youre not looking for the most computationally efficient solution herep
| 0 |
how to input a list of tuples | precodepoints maplambda xmapfloatxsplit
iterlambdarawinputenter xy coordinates or nothing to continuestrip
print points
codepre
| 0 |
making a python interpreter using javascript | pyou can use pypyjs and the detailed procedure is also available
a hrefhttpsgithubcompypyjspypyjsreleases relnofollowhttpsgithubcompypyjspypyjsreleasesap
| 0 |
python subprocess on remote ms windows host | pi will recommend using strongema hrefhttpwwwfabfileorg relnofollowfabricaemstrong its a powerful python tool with a suite of operations for executing local or remote shell commands as well as auxiliary functionality such as prompting the running user for input or aborting executionp
ol
liinstall fabric codepip install fabriccodeli
liwrite the following script named strongremotecmdpystrongli
ol
pre classlangpy prettyprintoverridecode
usage
python remotecmdpy ipaddress username password yourcommand
from sys import argv
from fabricapi import run env
def sethostconfigip user password
envhoststring ip
envuser user
envpassword password
def cmdyourcommand
executes command remotely
output runyourcommand
return output
def main
sethostconfigargv1 argv2 argv3
cmdargv4
if name main
main
codepre
pstrongusagestrongp
precodepython remotecmdpy ipaddress username password command
codepre
| 0 |
variable expansion in python regex | precodeimport re
fp openliner
for line in fp
pattern rematchr09line
if pattern
print patterngroup1
else
print line
codepre
| 0 |
how can i get rid of unicode encode error while trying to output web scraping result in a txt file | pstrongupdatestrongp
psince you dont want the codeucode characters in your string
this should work p
precodehtml urlopenhttpwwwimdbcomnewstop
winereviews beautifulsouphtml
lines
for headline in imdbnewsfindallh2
imdbnews headlinegettext
linesappendimdbnewsencodeascii ignore
f openoutputtxt a
fwriteimdbnewsencodeascii ignore
fclose
codepre
piep
pencode the codeunicodecode characters to codeasciicode before writing to the filep
pwhat you were doing wrong is this p
precodeheadlineencodeascii ignore
codepre
pthis will not modify the codeheadlinecode you need to assign this value to codeheadlinecode like this p
precodeheadline headlineencodeascii ignore
codepre
| 0 |
how to login into a website wifi login page using python | pin my opinion you first need to find out how the website does the login i see it calls a function codechecksubmitcodep
pwhat we know it does it via a http post p
precodeltform namefrmhttpclientlogin targetparent methodpost onsubmitreturn checksubmit actionhttpclienthtml idfrmhttpclientlogingt
codepre
pso you should make a post request to the website the parameters are probably the login and password so the next task is to find out the keynames look for codenamecode username and password you have to supply in the postp
precodeltinput typetext nameusername maxlength50 styleborder 1px solid ccccccpaddingtop3pxpaddingbottom 3pxwidth 200px gt
ltinput typepassword namepassword autocompleteoff styleborder 1px solid ccccccpaddingtop3pxpaddingbottom 3pxwidth 200px gt
codepre
pthere are other codeinputcode elements i have no clue if you need to supply thosep
pso how do you make the callp
precodepayload username value1 password value2
r requestsgettheurl paramspayload
codepre
pnext step is to parse the html returned you can use the library beautifulsoup for this in pythonp
| 0 |
ruby equivalent of pythons subprocesscheckcallcheckoutput | pthe basicinbuilt methods are supplanted by the a hrefhttppopen4rubyforgeorgclassespopen4html relnofollowpopen4a gem and the a hrefhttpshellexecuterrubyforgeorg relnofollowshellexecutora gem provides further awesomenessp
| 0 |
file names have a hidden m character prepended | pyou have a file with some special characters in the name which is confusing the terminal output what happens if you do codels lcode or if possible use a graphical file manager basically find a different way of listing the files so you can see whats going on another possibility would be to do codels gt someotherfilenamecode and then look at the file with a hex editorp
| 0 |
where does nlpnet get its metadata pickle file from | pyou need to download nlpnetdatamodels for pos srl and dependency it is available on a hrefhttpnilcicmcuspbrnlpnetmodelshtml relnofollowhttpnilcicmcuspbrnlpnetmodelshtmla pos tag model file metadatapospickle is available in a hrefhttpnilcicmcuspbrnlpnetdatapospttgz relnofollowhttpnilcicmcuspbrnlpnetdatapospttgzap
| 0 |
python read array from file | pyoure only referencing a file pointer youre not actually loading in the datap
precodemyfile openliststxtread
codepre
pthat should give you your string which you can then load into an object using jsonp
| 0 |
how does python sort a list of tuples | ptry using the internal list sort method and pass a lambda if your tuples first element is a integer this should workp
precode l is the list of tuples
lsortlambda xy xy
codepre
pyou can use any callable for the compare function not necessarily a lambda however it needs to return 1 less than 0 equal or 1 greater thanp
| 0 |
how do i get the selected text in desktop application using pythondbus | pa hrefhttpscodelaunchpadnetdo relnofollowgnome doa has a few plugins that use the selected text im not sure how it is implemented and if it uses dbus but the code should reveal all p
| 0 |
get last n lines of a file with python similar to tail | pon second thought this is probably just as fast as anything herep
precodedef tail f window20
lines window
count 0
for l in f
linescountwindow l
count 1
print linescountwindow linescountwindow
codepre
pits a lot simpler and it does seem to rip along at a good pace p
| 0 |
obtain string from file using partial string | precodea solyc01g094920
solyc01g094930
b solyc01g09441021
solyc01g09482012
solyc01g09490012
solyc01g09491011
solyc01g09492021
solyc01g09493012
aa xstrip for x in asplit
for line in bsplit
for aaa in aa
if linestartswith aaa
printline
codepre
poutputp
precodesolyc01g09492021
solyc01g09493012
codepre
| 0 |
unbounded local error | pi assume that this is an exercise exploration in handling variables in recursive functionsp
pyou can pass codectrcode as an argument in the recursive calls and you can initialize it with a default value so you dont need to supply codectrcode in the original callp
precodedef myfnn ctr0
if n 0
return ctr
elif n 10 2
ctr 1
a n10
print a
return myfna ctr
else
a n10
return myfna ctr
print myfn1233252672
codepre
pstrongoutputstrongp
precode123325267
123325
1233
1
4
codepre
pif you need to pass more complex objects around then you have to be careful see a hrefhttpstackoverflowcomq11329414014959least astonishment in python the mutable default argumenta for detailsp
phowever its simpler to just use a codewhilecode loop for this task recursion is not efficient in python so you should only use it when its appropriate to the problem domain eg working with recursive data structures like treesp
precodedef myfnn
ctr 0
while n
a n 10
if n 10 2
ctr 1
print a
n a
return ctr
codepre
| 0 |
measuring the distance between points and groups | pi ended up using a different data structure and in the end looks like thisp
precodecontacts
for i row in scwalkbookiterrows
if contactsgetrowregion0 0
contactsrowregion
contactsrowregionrowsubregion
contactsrowregionrowsubregioncoords
contactsrowregionrowsubregiondistances
elif contactsrowregiongetrowsubregion0 0
contactsrowregionrowsubregion
contactsrowregionrowsubregioncoords
contactsrowregionrowsubregiondistances
else
pass
contactsrowregionrowsubregioncoordsappendrowtlatituderowtlongitude
for region in contactsitervalues
for subregion in regionitervalues
for a b in itertoolscombinationssubregioncoords 2
subregiondistancesappendeuclideana b
codepre
| 0 |
django 19 web page doesnt redirect or change | pyour first url is catching everything essentially its saying if the url has a start to it send to indexp
psince its the first url in the list its always going to catch that first since it goes through the url patterns and finds the first one it matches as youve found out in the comment if you move it to the bottom when you go to either codehomecode or codecontactcode it will catch those firstp
phowever you still will have a problem with that because if you go to codeasdfblahblahcode or anything its still going to catch that what you should do is add a codecode to show that there should be nothing in the url to route to index that regex says if there is a start and an end and nothing in between route to indexp
precodeurlpatterns
urlr viewsindex name index
urlrhome viewsindex name home
urlrcontact viewscontact name iletisim
codepre
| 0 |
email migration and multidomain account | pfirst off you really should be using the a hrefhttpsdevelopersgooglecomadminsdkemailmigration relnofollownew email migration apia along with the a hrefhttpscodegooglecompgoogleapipythonclient relnofollowgoogleapipythonclienta for this rather than the a hrefhttpsdevelopersgooglecomadminsdkemailmigrationv1index relnofollowold and deprecated gdatabased apiap
phaving said that it should just be a matter of setting the domain value to that of the user mailbox you wisht to migrate mail into rather than the admin domainp
precodeuser userexamplefr
admin adminexamplecom
adminpwd hackme
srv servicemigrationserviceemail admin password adminpwd domain examplefr
codepre
| 0 |
python 3x how to compare two lists containing dictionaries where order doesnt matter | pif the elements in both lists are shallow the idea of sorting them and then comparing with equality can work the problem with alexs solution is that he is only using id but if instead of id one uses a function that will sort dictionaries properly things shuld just workp
precodedef sortkeyelement
if isinstanceelement dict
element sortedelementitems
return reprelement
sortedtesta keysortkey sortedtestb keysotrkey
codepre
pi use an codereprcode to wrap the key because it will cast all elements to string before comparison which will avoid typerror if different elements are of unorderable types which would almost certainly happen if you are using python 3xp
pjust to be clear if your dictionaries and lists have nested dictionaries themselves you should use the answer by mcallens if your inner lists are also unorderd you can fix this to work jsut sorting them inside the key function as wellp
| 0 |
change user agent for selenium driver | pwebdriver lacks http response header and status code methods for more info check this a hrefhttpcodegooglecompseleniumissuesdetailid141 relnofollowlinkap
| 0 |
how are keys stored and accessed in python 2 | pcodestarttraversalcode is not where the adjacent key is chosen thats the part in codetraversecode specifically codefor othernodes in gnodecode since codegnodecode contains only adjacent nodes all of them will be iterated overp
pwhat codefor node in gkeyscode does is select a random node to start from and following nodes just in case theres a number of disconnected subgraphs in codegcodep
pchoosing the adjacent node does not have anything to do with hash order in this case which you should never rely onp
| 0 |
im having trouble printing a file in python | pread is a strongmethodstrong from file class so you must add p
precodedataread
codepre
| 0 |
tkinter example for multiple frames grid error | pyou cannot mix codepackcode and codegridcode together within the same emcontainerem it is empossibleem to mix them in different containers but id stronghighlystrong recommend staying with strongonlystrong one of these geometry managerp
psee this a hrefhttpstackoverflowcomquestions17267140pythonpackandgridmethodstogetherquestiona for some more helpp
| 0 |
does posterencode module supported in python appengine | pfrom what i see in a hrefhttpsbitbucketorgchrisatleepostersrcbd5ab4c5005cposterencodepy relnofollowhttpsbitbucketorgchrisatleepostersrcbd5ab4c5005cposterencodepya i doesnt see any class that would be forbidden by google app engine just upload it as any of your own codep
| 0 |
program web applications in python without a framework | pfor a php programmer i think a hrefhttpwwwmodpythonorg relnofollowmodpythona is a good way to get started without any framework it can be used directly as apache 2 module you can have code tags like codelt gtcode in php and even conditional html output html inside if statementp
precodelt
if x y
begin
gt
some html
lt
end
gt
codepre
psimplified example taken from emonlampcomems a hrefhttponlampcompubapython20040226pythonserverpageshtml relnofollowpython server pages tutorialap
| 0 |
detecting change in the value of python variables | pfor this case and i cant believe im saying the words sounds like situation for settersp
precodedef setmyvarx
myvar x
somefunction
return myvar
codepre
| 0 |
running json through pythons eval | pcodeevalcodeing json is a bit like trying to run xml through a c compiler p
pcodeevalcode is meant to evaluate python code although there are some syntactical similarities strongjson isnt python codestrong heck not only is it not empythonem code its not code to begin with therefore even if you can get away with it for your usecase id argue that its a bad idea conceptually python is an apple json is orangeflavored sodap
| 0 |
plone store form inputs in a lightweight way | pone approach is to create a browser view that accepts and retrieves json data and then just do all of the form handling in custom html the json could be stored in an annotation against the site root or you could create a simple content type with a single field for holding the json and create one per record youll need to produce your own list and item view templates which would be easier with the itemperjsonrecord approach but thats not a large taskp
pif you dont want to store it in the zodb then pick whatever file store you want like codeshelfcode and dump it there insteadp
| 0 |
how to print the original encoded string for serial programming in python | ptry adding an extra slashp
precodeprint x55
codepre
pif you cant edit the string try thisp
precodeprint hexordx55
0x55
this will still be stored a a hexadecimal answer
put str around it to make it a string
codepre
por a longer version based on the previous answerp
precodeprint joinxstrhexordx552
x55
this will be stored a a string on the other hand
codepre
por if you are working with a line of input try thisp
precodedef hextostringlst
temp
for v in lst
s strhexordv
tempappendjoinx04lenss2
return jointemp
codepre
| 0 |
where is the huey consumer configuration | pi think you need to add an codeinitpycode file to the folder that contains mainpy else you cannot import anything as python will not consider this folder as a modulep
pa hrefhttpstackoverflowcomquestions7948494whatsthedifferencebetweenapythonmoduleandapythonpackagewhat39s the difference between a python module and a python packageap
psee comment by giuliopiancastellip
| 0 |
problem accessing attributes in beautifulsoup | pto just scan for an element by tag name a pyparsing solution might be more readable and without using deprecated apis like codehaskeycodep
precodefrom pyparsing import makexmltags
makexmltags creates a pyparsing expression that matches tags with
variations in whitespace attributes etc
elelend makexmltagsel
scan the input text and work with eltags
for eltag tagstart tagend in elscanstringxmltext
if eltagat
print eltagat
codepre
pfor an added refinement pyparsing allows you to define a filtering parse action so that tags will only match if a particular attributevalue or attributeanyvalue is foundp
precode import parse action that will filter by attribute
from pyparsing import withattribute
only match el tags having the at attribute with any value
elsetparseactionwithattributeatwithattributeanyvalue
now loop again but no need to test for presence of at
attribute there will be no match if at is not present
for eltag tagstart tagend in elscanstringxmltext
print eltagat
codepre
| 0 |
separate line output by groups | plooks like you want to group the output of the script rather than log the info as it comes while searching
easiest would be to maintain 4 lists on each for empty not empty and so on in the script add the db names to appropriate list instead of logging and then dump the lists one by one into the file with appropriate prefixesnot empty for dbname
for example remove all the logfailwrite from the functions and replace them with listappend and write a separate function that writes to the log file as you likep
padd listsp
precodedbdumpisoldlist
dbdumpisemptylist
dbdumpisnotcompletelist
dbdumpdoesnotexistlist
codepre
pmodify the functionsp
precodedef dumphealthlastdumprow filenamedb
lastrow lastdumprowrsplit
tms joinlastrow45
status lastrow13
if status and tms today
dbdumpisoldlistappendstrdb
logfailwritendb is old for strdb strfilename ndump finished at strjointms
logfailwriten
elif not status and tms none
dbdumpisnotcompletelistappendstrdb
logfailwritendump is not complete for strdb strfilename end of file is not correct
logfailwriten------------------------------------")
def dump_size(dump_file, file_name,db):
size = os.path.getsize(dump_file)
if (size < 1024):
human_readable = humansize(size)
db_dump_is_empty_list.append(str(db))
#log_fail.write("\ndump is empty for " +str(db) + "\n" +"\t" + str (file_name)+", file size is " + str(human_readable))
#log_fail.write("\n-------------------------------------------")
if db_file_does_not_exist and db_file2_does_not_exist:
db_dump_does_not_exist_list.append(str(db))
#log_fail.write("\nmysql dump does not exist for " + str(db) + "\n" + "\t" + str(db_backup_file2) + "\n" + "\t" + str(db_backup_file))
#log_fail.write("\n-------------------------------------------")
continue
</code></pre>
<p>and add a logger function:</p>
<pre><code>def dump_info_to_log_file():
log_dump_fail = '/tmp/mysqldump_fail'
log_fail = open(log_dump_fail,'w').close()
log_fail = open(log_dump_fail, 'a')
for dbname in db_dump_is_old_list:
log_fail.write("dump is old for" + str(dbname))
log_fail.write("\n\n")
for dbname in db_dump_is_empty_list:
log_fail.write("dump is empty for" + str(dbname))
log_fail.write("\n\n")
for dbname in db_dump_is_not_complete_list:
log_fail.write("dump is not complete for" + str(dbname))
log_fail.write("\n\n")
for dbname in db_dump_does_not_exist_list:
log_fail.write("dump does not exist for" + str(dbname))
log_fail.close()
</code></pre>
<p>or you could simply log as you are doing, and then read in the file, sort and write back the file.</p>
| 0 |
how to make a python script do something before exiting | pyou could use codeatexitregistercode from module codeatexitcode to register cleanup functions if you register functions codefcode codegcode codehcode in that order at program exit these will be executed in the reverse order codehcode codegcode codefcodep
pbut one thing to note these functions will be invoked upon emnormalem program exit emnormalem means exits handled by python so wont work in weird casesp
| 0 |
how can i get the django splitdatetimewidget to recognize ampm inputs | pultimately after poking around a lot in the source for the codesplitdatetimewidgetcode i didnt see a way to pass codeinputtimeformatscode into the widget perhaps there is a way i dont understand the common lineage between fields and widgets well enough to say for sure one way or another but i couldnt find itp
phowever i was able to get it working by overriding the fields and using codesplitdatetimefieldcode in the modelform original fields in model are codedatetimecode type i then needed to pass the codedatetimecode from the codesplitdatetimefieldcode back to the original model since the form field and the model field were unlinked since i overrode itp
precodeclass myformformsmodelform
startdatetimeformssplitdatetimefieldinputtimeformatsim p
enddatetimeformssplitdatetimefieldinputtimeformatsim p
class meta
modelmymodel
excludestartdatetimeenddatetime
def cleanself
selfinstancestartdatetimeselfcleaneddatagetstartdatetime
selfinstanceenddatetimeselfcleaneddatagetenddatetime
codepre
| 0 |
python make asterisk graphic whith integers list | psimplest solution will bep
precodegtgtgt numlist 5 1 2 3
gtgtgt for x in numlist
print x
codepre
| 0 |
python error with decode utf8 and japanese characters | puse a hrefhttpdocspythonrequestsorgenlatest relnofollowrequestsa and a hrefhttpwwwcrummycomsoftwarebeautifulsoupbs4doc relnofollowbeautifulsoupap
precodeimport requests
r requestsgethttpswwwgooglecojp
soup beautifulsouprcontent
print soupfindallp
ltp stylecolor767676fontsize8ptgt 2013 lta hrefintljapoliciesgtltagtltpgt
codepre
| 0 |
summation of a list using eval | pits pretty straighforwardp
precodegtgtgt yy a1 b1 c1
gtgtgt ff
a1 10
b1 20
c1 30
gtgtgt sumffi for i in yy
60
codepre
pbut if you somehow need to use eval i dont know whyp
precodegtgtgt evaljoinyy ff
60
codepre
pbut really theres no reason to use codeevalcode for this it is neither fast nor secure p
| 0 |
Subsets and Splits