text_a
stringlengths
9
150
text_b
stringlengths
18
20.9k
labels
int64
0
2
sum consecutive numbers in a list python
pwith numpycumsump precodein1 import numpy as np in2 x 51015 in3 x nparrayx in4 y xcumsum in5 y out6 array 5 15 30 codepre pi am using python 34p
0
using dataframe in a class to filter results
pyoure doing this emwayem wrong youre subclassing from dataframe but then youre storing your data inside a special dataframe property no buenop pyou should be subclassing if you want to have a class that quacks like a dataframe but you want to add some other behavior thats not availablep pif you want to subclass you should be doing it like thisp precodeclass dataframedataframe def initself args kwargs superdataframe selfinitargs kwargs def filterprivself return selfselfprivid gt 1 selfrestrictionlevel gt 0 not sure if you can create a dataframe from another df1 dataframedf codepre pbut thats really probably not even what you want its probably better to just havep precodedef filterprivdf return dfdfprivid gt 1 dfrestrictionlevel gt 0 df1 filterprivdf codepre
0
how to get more than 100 tweets from the twitter search or streaming api using twython
pper a hrefhttpsdevtwittercomdocsapi11getsearchtweets relnofollowhttpsdevtwittercomdocsapi11getsearchtweetsap blockquote pstrongcountstrong optionalp pthe number of tweets to return per page up to a maximum of 100 defaults to 15 this was formerly the rpp parameter in the old search apip pexample values 100p blockquote pit looks like you can only retrieve a maximum of 100 p
0
python parsing syntax tree in nlp
pnltk is the most popular package for parse trees see a hrefhttpnltkorgbookch08html relnofollowchapter 8 in the bookap
0
remove quotations with conditions
ptry thisp precodewords dont hello world quotes output list for word in words if word1 in quotes word word lenword 1 outputappendword print output gt dont hello world codepre pim assuming youll also want to handle the case where the unwanted quote could be a also be double quote codecode in addition to a single quote if not you could just usep precodeif word1 codepre
0
transposing one column in python pandas with the simplest index possible
pim thinking you want a pivot table check this link for more information a hrefhttppandaspydataorgpandasdocsstablereshapinghtml relnofollowhttppandaspydataorgpandasdocsstablereshapinghtmlap pdo you find the output from this acceptablep pcodedatacurrentpivotindexmedicine columnsdisease valuesdiseasecodep
0
comparing columns function
pso you get a list index is out of range of that line codeif rowj0 and aij0code codejcode is by construction in coderangelenrowcode so the error should not come from coderowjcode on previous line you allready have codeif row0ai0code so it should not come from aip pi suspect it comes from codeaicode having less elements that coderowcode you should add a test to be sure p precodedef compcolsrow a for i in rangelen a if lenai lt lenrow raise exceptionline d lenai d lenrow d i lenai lenrow for j in rangelenrow if row0ai0 if rowj0 and aij0 print row codepre
0
installing django and python suds without admin rights
h1a complete guide to setup django in other pathh1 hr h2installing django through piph2 pwell many use pip package manager for their install purpose not my favoritebr to install django through pip you do something likep precodepip install django codepre pit will install django in a path which is not accessible by nonroot usersbr so you must first add the installation place for itp precodepip install django installoptionprefixsomeplacewehaveaccessto django codepre pthis codesomeplacewehaveaccesstocode can be codehomeusercode directorybr now login to python and do the importp precodeimport django traceback most recent call last file ltstdingt line 1 in ltmodulegt importerror no module named django codepre pwhat are we doing wrongp h3pythonpathh3 pwell as long as you have not installed django in pythonpath python doesnt know where to import the module do this two stepsp blockquote pbash p blockquote precodeecho pythonpath codepre blockquote ppythonp blockquote precodeimport sys print syspath codepre pwell syspath show the path of packages locations installed in python and pythonpath is emptyp pthe only thing you have to do is to add the path of django egg file to pythonpath for example in mine itsbr codeusrlocallibpython27distpackagesdjango19py27eggcodebr to add it to pythonpath do this p blockquote pbash p blockquote pcodeexport pythonpathegg pathcodebr which egg path} is the location of your django egg.<br> <strong>what about django-admin</strong>?<br> well you have to run it from the place that django has set it up in somewhere it has been installed called <code>bin</code> for that you can add the path of that bin (think it might be ~/bin or any_place_you_installed/bin) to $path...<br> just like pythonpath we do:</p> <pre><code>export path=$path:~/bin </code></pre> <p><em>attention</em> >> : after $path is essential!!! to know why do a: <code>echo $path</code><br> <em>attention</em> >> ~/bin must be django bin directory so pay attention to that.</p> <h2>installing django through source</h2> <p>oh my god that's my <strong>favorite</strong>. there is nothing difference with the thing up there just insted pip use setup.py...</p> <p>for that you must have setuptools installed... (i think pip will install that itself if pip raises error for setuptools you must do the whole thing i told up there for django for setuptools too.)</p> <p>after you installed setuptools you must do this:</p> <pre><code>./setup.py install --prefix=$path_you_desire </code></pre> <p>the rest is the same...</p> <hr> <p><strong>references</strong><br> <a href="http://stackoverflow.com/questions/2915471/install-a-python-package-into-a-different-directory-using-pip">1</a> : installing package through pip in other location. </p> <p><a href="http://unix.stackexchange.com/questions/26047/how-to-correctly-add-a-path-to-path">2</a> : how to add a path to $path.</p>
0
how to add index into a dict
pall you need is to do is use right strongdatatypestrong for you check this link python doc good luck hope this helpsp psource a hrefhttpsdocspythonorg2librarycollectionshtmlcollectionsordereddict relnofollowhttpsdocspythonorg2librarycollectionshtmlcollectionsordereddictap precodegtgtgt regular unsorted dictionary gtgtgt d banana 3 apple4 pear 1 orange 2 gtgtgt dictionary sorted by key gtgtgt ordereddictsortedditems keylambda t t0 ordereddictapple 4 banana 3 orange 2 pear 1 codepre
0
run a python image processing script in an android app
patm you cant p pyou would have to recompile the cv2 module for android first in a similar way python4android does itredirecting system calls to java rmi tough jobp
0
pip install traceback error while installing packages in python
paccording to this a hrefhttpsbugslaunchpadnetubuntusourcepythonpipbug1306991 relnofollowbuga you likely have a bad version of requests installed it sounds like you need to remove requests completely and any reference to it and reinstall it using something other than pip otherwise pip may reinstall the old version using its cache p
0
complete python noob
pgiven that you are confusedstudent i am not going to give you the code directly but you are halfway there you have the lines stored in lines this is iterableie you can loop over these lines now you just need to figure out how to loop over them one hint is that you dont have to increment by one as you loop look at the documentation for coderangecodewhich can be used with a for loop alternatively you can use a while loop if the usual while loop is something along the lines of p precodex0 while xlt10 x1 do somethinglike concatenatehint google this strings together codepre pthen how might you increment by more than 1 finally in order to put all of the lines back into another file you will to open again but this time with the w optional parameter which allows you to write to a file use close to close the file you will probably need to look at the documentation and some examples section 72 on this link is a good place to start a hrefhttpsdocspythonorg2tutorialinputoutputhtml relnofollowhttpsdocspythonorg2tutorialinputoutputhtmlap
0
python rumps not working on os x 1010 attributeerror module object has no attribute app
pnothing to do with coderumpscode but rather that you copied the demo into a a file named rumpspy the same error will happen in any other module you are trying to import from a file named the same thingp precode echo import math mathsqrt42 gt mathpy python python 275 default mar 9 2014 221505 gcc 421 compatible apple llvm 50 clang500068 on darwin type help copyright credits or license for more information gtgtgt import math traceback most recent call last file ltstdingt line 1 in ltmodulegt file mathpy line 1 in ltmodulegt import math mathsqrt42 attributeerror module object has no attribute sqrt codepre
0
specify what database to use when adding relation
pyou have the codezoocode and codeanimalcode model which you codegetcode by specifying the database relations cannot exist across different databases so the codemanytomanycode add implictly implies that codeadd the relation to the same database as the zoo and animal instances which need to belong to the same databasecodep
0
what is the difference between randomsample and randomshuffle in python
precodefrom random import shuffle from random import sample x i for i in range10 shufflex samplex10 codepre blockquote pshuffle update the output in same list but sample return the update list sample provide the no of argument in pic facility but shuffle provide the list of same length of inputp blockquote
0
get array row and column number according to values in python
pto get the range based on a condition you can either apply the condition directly or use a hrefhttpsdocsscipyorgdocnumpy1101referencegeneratednumpywherehtml relnofollowcodenpwherecodea p precodegtgtgt a array 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 gtgtgt a lt 15 array true true true true true true true true true true true true true true false false false false false false false false false false false dtypebool gtgtgt npwherea lt 15 array0 0 0 0 0 1 1 1 1 1 2 2 2 2 array0 1 2 3 4 0 1 2 3 4 0 1 2 3 codepre pin the latter case the return value is a tuple of the matching indicesp pto achieve the opposite operation you can simply slice your array p precodegtgtgt ar14 14 array 7 8 9 12 13 14 17 18 19 codepre
0
python exception no template named index in lpthwweb framework
pi am doing the same exercise and i simply go on cmd cd to my lpthw directory which contains the folders of the project skeleton inside and dop precodegt python binapppy codepre pi think you have to put all your files from the project skeleton in one folder and run your app from there hope this helps p
0
how to initialize variables to noneundefined and compare to other variables in python
pi just tried your code in the shell and i didnt get an error it should work maybe post the entire code you can also use trycatchp por maybe localshaskeyoriginaltime p
0
how to use scrapy to crawl data from multipages which are implemented by javascript
pwhen link parsing and request yielding is added to your parse function your example just works for me maybe the page uses some serverside cookies but using a proxy service like a hrefhttpcrawleracom relnofollowscrapys crawleraa which downloads from multiple ips it fails thoughp pthe solution is to enter the textquery parameter manually into the request urlp precodeimport urlparse from urllib import urlencode from scrapy import request from scrapyspiders import spider from scrapyselector import selector class epgdspiderspider name epgd alloweddomains epgdbiosinoorg term calb baseurl httpepgdbiosinoorgepgdsearchtextsearchjspcurrentindex0amptextquerys starturls baseurl term def updateurlself url params urlparts listurlparseurlparseurl query dicturlparseparseqslurlparts4 queryupdateparams urlparts4 urlencodequery url urlparseurlunparseurlparts return url def parseself response sel selectorresponse genes selxpathtrclassoddtrclasseven for gene in genes item itemgenid mapunicodestrip genexpathtd1atextextract yield item urls selxpathdividnvirecordsspanidquickpageahrefextract for url in urls url responseurljoinurl url selfupdateurlurl paramstextquery selfterm yield requesturl codepre pupdateurl function details from lukasz solutionbr a hrefhttpsstackoverflowcomquestions2506379add-params-to-given-url-in-python">add params to given url in python</a></p>
0
change ip with python mechanize
pyou dont fake your ip details setproxy is to configure a http proxy you still need legitimate access to the ipp
0
joining the previous and next sentence using python
precodereturn joinsentlistmax0ind1minlenindind2 codepre
0
if im only planning to use mysql and if speed is a priority is there any convincing reason to use sqlalchemy
psqlalchemy provides more than just an orm you can selectinsertupdatedelete from table objects join them etc the benefit of using those things over building strings with sql in them is guarding against sql injection attacks for one you also get some decent connection management that you dont have to write yourself p pthe orm part may not be appropriate for your application but rolling your own sql handling and connection handling would be really really stupid in my opinionp
0
how can i compress a folder and email the compressed file in python
pyou can use a hrefhttpwwwpythonorgdoc252libmodulezipfilehtml relnofollowzipfilea that ships with python and a hrefhttpsnippetsdzonecompostsshow2038 relnofollowherea you can find an example of sending an email with attachments with the standard smtplibp
0
python merging doc files into 1 doc file
pyou can open and read contents of each files and write them in a separate file you can file io functionsp
0
django making block div conditional with a conditional extends
pmy solution p precode extends xyesnostampedblankhtmlstampedhomehtml codepre pwhere codeblankhtmlcode containsp precode block results endblock lt to allow for corrected shared rendering with ajax posts and normal django rendering gt codepre pand codehomehtmlcode is my standard app page with a results block to extend p
0
python replace unicode characters
pwhat about thisp precodeline 13xc2xb5xc2xb1xc2xbexc3xa2pxc3xb4xc2x8d5example3com0 pattern rx resubpattern r line codepre
0
about min values in list
precodedef minvaluel return mini for i in l if i gt 1 or 1 codepre
0
pythonapache wsgi application app broken 500s after failed plugin install
pon the off chance it is a bug i would download codepylintcode and run it on the wsgi application to ensure there are no errorsp precodepylint optmediacore0103mediacorewsgi codepre pyou can also pipe that command to codegrep ecode to quickly look for error lines pylint will not autocomplete on codewsgicode files you will need to specify them explicitly on the command linep pedit also please verify that your wsgi plugin is python 26 compatible if the plugin is python3 or python 27 that could explain the errors also do you have the libapache2modwsgi plugin installed not sure if that is the exact name for redhatp
0
can a class in python behave like a specified class based on a passed parameter
pthe thing youd probably want to do factorydispatch function is already outlined in other answerscomments here but if you actually wanted to return a different class instance and make it look like youre only making a codemagicclasscode you could do something fancyawful with the codenewcode method like so p precodeclass magicclassobject def newcls args kwargs if argswhatever square return squareargs kwargs codepre por something like that its not good practice but it emisem doable p
0
tips for debugging list comprehensions
puse a debugger like codepdbcode to walk through or break the list comprehension into a full for loopp
0
global name bluetooth is not defined
pits generally better to let the import fail if something is wrong so i would remove the codetryexceptcode and just do a normal importp pthe only reason to use it in an import if you are indifferent about what library you want to usep precodetry import json except importerror import simplejson as json codepre
0
best practice to write generic numerical functions that work with both ndarray and maskedarray
pcodeisinstancecode is fine as it is herep pyou could make it implicit if youd like using a a hrefhttpdocspythonorg34libraryfunctoolsfunctoolssingledispatch relnofollowsingledispatch generic functionap precodefrom pkgutil import simplegeneric import numpy as np from numpy import ma simplegeneric def pkgobj return np use numpy by default pkgregistermamaskedarray def x return ma def foox return pkgxapplyalongaxisbar 1 x codepre pheres another example of a hrefhttpstackoverflowcoma171017114279generic function in pythonap
0
save a deque in a text file
psome things that come to my mindp ul lileave the file handle open dont close the file everytime you wrote somethingli lior write the file every n items and catch a close signal to write the current nonwritten itemsli ul
0
variables and memory allocated for them
pyou assign new obj to a at second timep precodegtgtgt gtgtgt a 123 gtgtgt ida 4353139632 gtgtgt b a gtgtgt idb 4353139632 gtgtgt a 45 gtgtgt ida 4353139776 gtgtgt idb 4353139632 codepre
0
how do i make a scatter plot with these data
pto be able to fully determine if your way of storing data is correct you should consider how you use it if youre using it only want to use it for plotting as described here then for the sake of the simplicity you can just use three 1d arrays if however you wish to achieve tighter structure you might consider using a 2d array with a hrefhttpdocsscipyorgdocnumpyreferencearraysdtypeshtml relnofollowcustom dtypeap phaving this in mind you can easily create a 2d scatter plot with different colors where exact color is determined by the value associated with each pair letter numberp precodeimport numpy as np from matplotlib import pyplot as plt from matplotlib import cm you might note that in this simple case using numpy for creating array was actually unnecessary as simple lists would suffice letters nparraya a a b b b numbers nparray1 2 3 1 2 3 values nparray1 2 3 15 35 45 items lenletters x and y should be numbers so we first feed it some integers parameter c defines color values and cmap defines color mappings pltscatterxrangeitems numbers cvalues cmapcmjet now that data is created we can reset xticks pltxticksxrangeitems letters codepre pimg srchttpistackimgurcomwo7djpng altcode resultp phopefully this should be enough for a good startp
0
python matlab difference in matrix calculation for nesting loop
pyou overwrite your matricies try this p precodeimport numpy as np x 2061075875 2061801 206115425 206160575 2061314375 y 10638640 10639060 10638727 10639118 10638802 st 7392976 7113528 6440809 7180971 7272918 l 25496384 23915473 20020001 21891659 18549989 deltal10 nnpfloornpdivideldeltal pxdown npzeroslenxmaxnpfloorn2 pydown npzeroslenxmaxnpfloorn2 for i in range0lenx if intni2ni2 for j in range0intni2 pxdownijxideltaljnpsinstinppi180 pydownijyideltaljnpcosstinppi180 else for j in range0intni12 pxdownijxideltaljnpsinstinppi180 pydownijyideltaljnpcosstinppi180 codepre
0
how can i stay logged in to a website and send a cookie or http header or something for my python program
pyou might try a hrefhttppycurlsourceforgenet relnofollowpycurla which will allow you to interact with web pages without using a browser p ppycurl allows cookie storage and reuse form submission including login as well as page navigation from python your code above already seems to retrieve the resources you want via urllib you can easily adapt your code by following the pycurl tutorials at the pycurl sitep pregarding your comment about the need to handle javascript please elaborate about the context of thatp pa different but related post a hrefhttpstackoverflowcomquestions3057276pycurlscriptcantlogintowebsitehere at stackoverflowa addresses a javascript question with pycurl as well as showing code to initiate a pycurl connectionp
0
get user input without interrupting program execution
precodefrom threading import thread import shlex def endlessjob while true pass job threadtargetendlessjob jobstart while true userinput inputgt printshlexsplituserinput codepre pshlex module helps you to parse the command line entered by the user p pif you need to pass arguments to the endlessjob function you can do something likep precodejob threadtargetendlessjob args1a kwargsa 1 b 2 codepre pwhere codeargscode and codekwargscode stands for positional and named arguments respectivelyp
0
saleor django apache modwsgi will not serve staticadmin
pi did not understand the documentation on a hrefhttpsdocsdjangoprojectcomen19howtodeploymentwsgimodwsgiservingtheadminfiles relnofollowserving the admin filesa or a hrefhttpsdocsdjangoprojectcomen19refcontribstaticfilesdjangoadmincollectstatic relnofollowdjangoadmin collectstaticap pthe documentation for serving the admin files indicated that if one has djangocontribstaticfiles enabled in the installedapps portion of settingspy then it is recommended the staticfilesdirs list in settingspy shall contain the paths to the static directory djangocontribadminstaticadmin provided by django for its development serverp pone is told to use the collectstatic management command which will physically copy the files to a static directory in what you will configure as serverroot in your sitenameconf file for apache to servep pmy problem was pretty much a noob error i followed the instructions without knowing that there is some sort of received wisdom about what actually is used to run the collectstatic commandp prather thanp precodedjangoadmin collecstatic codepre pone needs to in my case ymmvp precodepython managepy collectstatic codepre pwhen invoking collectstatic with djangoadmin i got the maddening errorp precodeimporterror no module named saleorsettings codepre pwhich was very confusing to me as i had set that enivronment variable in both my env file and in my wsgipy file i figured this might be some sort of quirk with virtualenv setting this variable on the command line resulted inp precodedjangocoreexceptionsimproperlyconfigured requested setting installedapps but settings are not configured you must either define the environment variable djangosettingsmodule or call settingsconfigure before accessing settings codepre pwhich led me down a very disgusting rabbithole vis my virtualenv setup and every config file i had ever edited they were fine fortunately the actual invocation was with p precode python managepy collectstatic you have requested to collect static files at the destination location as specified in your settings homeadminprojectstatic this will overwrite existing files are you sure you want to do this type yes to continue or no to cancel codepre pwhich then proceeds to magically copy what i need i hope into my projectstatic directoryp pmy noob mistake was not reading a hrefhttpsdocsdjangoprojectcomen19refdjangoadmin relnofollow>django-admin and manage.py</a> first, thus discovering that the convenience script has a convenience script. <em>rimshot</em></p> <p>another bit of confusion (for me, anyway) is the assertion that one should not serve static files from the "app" or the "admin app". a simpler way for me to think about it is: "one must run a script that appears either wrap or replicate rsync, thus copying static files from myapp/static and ~/project/venv/lib/python2.7/contrib/admin so that apache will not be able to play silly buggers with important files". this does not mean that one does not put a path to /static/ in the sitename.conf file. there is no magic here, just copying static files.</p> <p>therefore:</p> <pre><code>wsgipythonpath /home/admin/project/saleor:/home/admin/project/venv/lib/python2.7/site-packages &lt;virtualhost *:80&gt; servername example.com serveradmin email@example.com documentroot "/home/admin/project" alias /media/ /home/admin/project/media/ &lt;directory /home/admin/project/media/&gt; require all granted &lt;/directory&gt; alias /static/ /home/admin/project/static/ &lt;directory /home/admin/project/static/&gt; require all granted &lt;/directory&gt; wsgidaemonprocess example.com python-path=/home/admin/project/saleor:/home/admin/project/venv/lib/python2.7/site-packages wsgiprocessgroup example.com wsgiscriptalias / /home/admin/project/saleor/wsgi.py &lt;directory /home/admin/project&gt; &lt;files wsgi.py&gt; require all granted &lt;/files&gt; &lt;/directory&gt; errorlog ${apache_log_dir}/error.log customlog ${apache_log_dir}/access.log combined &lt;/virtualhost&gt; # vim: syntax=apache ts=4 sw=4 sts=4 sr noet </code></pre> <p>i now have static files being served from ~/project/static/ directory!</p> <p>/me wipes away sweat.</p> <p>thanks daniel!</p>
0
python creating a basic enter your password program
pthis is a great way to learn about while loopsp pask for the valuesp precodepasswordrawinputplease select a password passwordagainrawinputplease retype your password codepre ploop until they match p precodewhile passwordagain password print they dont match please try again passwordrawinputplease select a password passwordagainrawinputplease retype your password codepre
0
searching a dictionary for a key adding the value of that keys value to another key value pair
pis this what you had in mindp precodefor wordcategory in worddictitems categorycountscategory 1 codepre
0
determining if an input is a number
pstring rawinputplease enter a numberp pchecking if a character is a digit is easy once you realize that characters are just ascii code numbers the character 0 is ascii code 48 and the character 9 is ascii code 57 18 are in between so you can check if a particular character is a digit by writingp blockquote pvalidnumberfalsep pwhile not validnumberp pstring rawinputplease enter a numberp pi0p pvalidnumbertruep pwhile i pif not stringi0 and stringilt9p pvalidnumberfalsep pprint you entered an invalid number please try againp pbreakp pii1p blockquote
0
plot graph in python with data from file
pso obviously you will need to know the structure of the data within the file you can read data from a file very easilyp precodewith openfilenamer as f data fread or you can use freadline format the data codepre pthe matplotlib library is what you want for graphing the datap pa hrefhttpmatplotliborg relnofollowhttpmatplotliborgap pthe documentation is very thoroughp pyou may find this so answer very useful as wellp pa hrefhttpsstackoverflowcomquestions24807726howtoplotdatawithpythonfromtextfilerq1how to plot data with python from text fileap
0
dynamically import a method in a file from a string
pthe way i tend to to this as well as a number of other libraries such as pylons and paste if my memory serves me correctly is to separate the module name from the functionattribute name by using a between them see the following examplep pcodeabcdefghijklmyfilemymethodcodep pthis makes the codeimportfrompathcode function below a little easier to usep precodedef importfrompath import an attribute function or class from a module attr path a path descriptor in the form of pkgmodulesubmoduleattribute type path str pathparts pathsplit if lenpathparts lt 2 raise importerrorpath must be in the form of pkgmodulesubmoduleattribute module importpathparts0 fromlistpathparts1 return getattrmodule pathparts1 if namemain func importfromabcdmyfilemymethod func codepre
0
syntax error near unexpected token in alchemyapi python sdk
pthe error message codesyntax error near unexpected tokencode is a bash error not a python one you appear to be typing this code into the bash shell rather than into pythonp
0
openerp invalid xml for view architecture
pwhen you inherit a model to new one then you have to define new view for the new one you cannot inherit the view of that model here you are inheriting the view defined for respartner please create a new view for mypartnerp
0
i need to understand the error in my speed program
pthe number of seconds returned by codetimeclockcode is a floatingpoint number the likelihood that it will happen to be equal to codet1code is low enough that your point very rarely moves instead of using codecode use codegtcodep precodeif time gt t 1 t 1 pointmovespeed1 0 codepre
0
how to handle exception using suds in python if the method is not found
pyou dont have any loop to keep the user entering new data try something likep precodemethods listclientwsdlservices0ports0methodsvalues print existing methods are 0 and 1format joinmapstr methods1 strmethods1 while true s rawinputenter the name of the method you want to scan if s not in methods print not a valid method please try again else break valid method continue rest of your code goes here codepre
0
why django and python mysqldb have one cursor per database
pone cursor per database is not necessarily preferable its just the default behaviorp pthe rationale is that different databases are more often than not on different servers use different engines andor need different initialization options otherwise why should you be using different databases in the first placep pin your case if your two databases are just namespaces of tables what should be called schemas in sql jargon but reside on the same mysql instance then by all means use a single connection how to configure django to do so is actually an altogether different questionp pyou are also right that a single connection is better than two if you only have a single thread and dont actually need two database workers at the same timep
0
send commands to the terminalubuntu from ipython notebook
pi was able to solve this question by doing the followingp precodeimport os import subprocess oschdirpath subprocesscallcommandshelltrue codepre pthis does access the bashrc file as intendedp
0
what do you mean by dispatch function and forwarding function in boostpython
pthe dispatch function is the implementation which switches on the derived class type to find out which implementation of a virtual function should execute like a pure virtual function the forwarding function seems to refer to the default base class implementation of the virtual functionp pi too find this terminology a bit confusing but its only used in passing in the boost documentation and i dont think its very important in the grand scheme of things try not to get hung up on itp
0
python if var false
pi think what you are looking for is the not operatorp precodeif not var codepre preference page a hrefhttpwwwtutorialspointcompythonlogicaloperatorsexamplehtm relnofollowhttpwwwtutorialspointcompythonlogicaloperatorsexamplehtmap
0
plotting multiple timeseries power data using matplotlib and pandas
pid rather plot the typical way smth likep precodeimport matplotlibpyplot as plt pltplot1234 14916 ro pltaxis0 6 0 20 pltsavefig codepre p a hrefhttpmatplotliborguserspyplottutorialhtml relnofollowhttpmatplotliborguserspyplottutorialhtmla p pre more subplots simply call codepltplotcode multiple times once for each data seriesp pps you can set xticks this way a hrefhttpstackoverflowcomquestions12608788changingthetickfrequencyonxoryaxisinmatplotlibchanging the quottick frequencyquot on x or y axis in matplotlibap
0
how could i print source files from github in pdf with syntaxic highlighting
pcodepy2pdfcode should do what you need a hrefhttppythonnetghermanpy2pdfhtml relnofollowhttppythonnetghermanpy2pdfhtmlap
0
show non printable characters in a string
pmodifying ecatmurs solution to handle nonprintable nonascii characters makes it less trivial and more obnoxiousp precodedef escapec if cprintable return c c ordc if c lt 0xff return rx002xformatc elif c lt uffff return ru004xformatc else return ru008xformatc def hexescapes return joinescapec for c in s codepre pof course if codestrisprintablecode isnt exactly the definition you want you can write a different function note that its a very different set from whats in codestringprintablecodebesides handling nonascii printable and nonprintable characters it also considers codencode codercode codetcode codex0bcode and codex0ccode as nonprintablep pyou can make this more compact this is explicit just to show all the steps involved in handling unicode strings for examplep precodedef escapec if cprintable return c elif c lt xff return rx002xformatordc else return cencodeunicodeescapedecodeascii codepre preally no matter what you do youre going to have to handle codercode codencode and codetcode explicitly because all of the builtin and stdlib functions i know of will escape them via those special sequences instead of their hex versionsp
0
is it possible to access gpio pins from a python script and a c program at the same time
pif you clean up the gpio headers in both scripts it should be possible otherwise it wont workp pyou can clean up in python by using gpiocleanup then it sould work cause it is clean again to your c codep
0
append csv by row from two lists in python
precodeimport csv away away1 away2 away3 home home1 home2 home3 recordlist listitem for item in listzipaway home print recordlist with opensamplecsv a as fp writer csvwriterfp writerwriterowsrecordlist recordlist away1 home1 away2 home2 away3 home3 codepre pyou should use strongwriterowsstrong method to write multiple list at a time to each rowp pimg srchttpistackimgurcomfkyx3jpg altenter image description herep
0
matrix with given numbers in random places in pythonnumpy
pto generate the indices of the elements for where to add ones and twos what about thisp precode assuming n n and m exist in 1 import random in 3 indices m n for m in rangen for n in rangen in 4 randomindices randomsampleindices n m in 5 ones randomindicesn in 6 twos randomindicesn codepre pcorrected as commented by petr viktorin in order not to have overlapping indexes in codeonescode and codetwoscodep pan alternate way to generate the indicesp precodein 7 import itertools in 8 indices listitertoolsproductrangen rangen codepre
0
pylint ignores pylintrc when run from textmate
pa somewhat educated guess try replacing codehomecode by the absolute path to your home directory shell variables like codehomecode are probably not available to use in textmates control panelp pupdate looking at the codepycheckmatepycode script included with the codepythontmbundlecode included with the version of textmate i have it appears that it is not possible to include arguments like codercfile pathtorcfilecode the value of codetmpycheckercode is expected to only be the path to the checker binary with no arguments but if you make your own copy of the pythontmbundle you should be able to edit codepycheckmatepycode to do as you wishp
0
printing long string with a single write call
pmaybe a problem of buffer p ptry this pleasep precodefrom os import fsync fh opentestdatw s a5000 fhwrites fhwriten fhflush fsyncfhfileno fhclose codepre ptheres no reason that closing the filehandler wouldnt empty the buffer and write in the file as far as i know but who knows p
0
i need to overwrite the stdout for one line and then revert the change
pyou can solve this by calling the script that redirect the stdout to a file and gets the relevant values as arguments and then continue the flow in the calling script without redirecting the stdoutp pstrongtest1pystrongp precode import sys cfd1sysargv1 sysstdout opencorpusnameposwordfreqtxtw cfd1tabulate codepre pstrongtest2pystrongp precodecfd1 nltkconditionalfreqdistbiglisttagged execfiletest1py cfd1 printhelloword codepre
0
handle case where a function is called without parameters
pgiven codewordscode is meant to be a string you can use a default argument of an empty string codecode then you can simplify your code btw a common idiom in python is a hrefhttpsdocspythonorg2glossaryhtml relnofolloweafpa and is generally used instead of lbflp precodedef getcountwords result vowels0 consonants0 try for letter in wordslower if letter in aeiou resultvowels 1 elif letterisalpha resultconsonants 1 except attributeerror pass return result codepre pand if you want to totally overengineer it you can use the codepartitioncode codeitertoolscode recipep precodeimport itertools as it def partitionpred iterable t1 t2 itteeiterable return filterpred t1 itfilterfalsepred t2 def getcountwords p partitionlambda c c in aeiou filterstrisalpha wordslower return k sum1 for in v for k v in zipvowels consonants p gtgtgt getcounthello world consonants 7 vowels 3 codepre pemsorry i was boredemp
0
simulating sub packages using python import hook
poh ive got a solution though more test cases may be needed for my real project the basic opinion is to carry out codeimpfindmodulecode at the codefindmodulecode stage not the codeloadmodulecode stage so that we can avoid the system to use our customized loader to load emnonexistem modulesp phere goes the solutionp precodeclass moduleimportutilityobject staticmethod def innamespacenamespace fullname whether the given paramfullname is or within the attrnamespace if not fullnamestartswithnamespace return false nslen lennamespace return lenfullname nslen or fullnamenslen staticmethod def parentnamefullname get the parent name of paramfullname return joinfullnamersplit 11 staticmethod def findmodulesnamespace nameparts rootpath find the modules along paramnameparts according to paramrootpath return classlist of fullname file filename options as methodimpfindmodule or valuenone if not found try ret ns namespace path rootpath for n in nameparts ns ss ns n fp filename options impfindmodulen path retappendns fp filename options path filename return ret except importerror return none class namespacesplitterobject strip the parent namespace and split the subname to pieces def initself namespace selfnamespace namespace selfcutoff lennamespacesplit def cutself fullname return fullnamesplitselfcutoff class dirmodulefinderobject " find a module under particular namespace in a given directory. we assume that :attr:`root_path` is not a package, and that it contains the packages to be imported. """ def __init__(self, namespace, root_path): self.namespace = namespace self.root_path = root_path self.ns_splitter = namespacesplitter(namespace) def install(self): sys.meta_path[:] = [x for x in sys.meta_path if self != x] + [self] def find_module(self, fullname, path=none): # we should deal with all the parent packages of namespace, because # some of the intermediate packages may not exist, and need to be # created manually if moduleimportutility.in_namespace(fullname, self.namespace): return defaultnewmoduleloader() # if not a parent of the namespace, we try to find the requested # module under the given :attr:`root_path` if moduleimportutility.in_namespace(self.namespace, fullname): ns = self.namespace parts = self.ns_splitter.cut(fullname) root = self.root_path if moduleimportutility.find_modules(ns, parts, root): return dirmoduleloader(ns, root) class defaultnewmoduleloader(object): """ load the requested module via standard import, or create a new module if not exist. """ def load_module(self, fullname): import sys import imp class fakepackage(object): def __init__(self, path): self.__path__ = path # if the module has already been loaded, then we just fetch this module # from the import cache if fullname in sys.modules: return sys.modules[fullname] # otherwise we try perform a standard import first, and if not found, # we create a new package as the required module m = none try: m = fakepackage(none) parts = fullname.split('.') for i, p in enumerate(parts, 1): ns = '.'.join(parts[:i]) if ns in sys.modules: m = sys.modules[ns] else: if not hasattr(m, '__path__'): raise importerror() fp, filename, options = imp.find_module(p, m.__path__) m = imp.load_module(p, fp, filename, options) sys.modules[ns] = m except importerror: m = imp.new_module(fullname) m.__name__ = fullname m.__path__ = [fullname] m.__loader__ = self m.__file__ = '&lt;dummy package "%s"&gt;' % fullname m.__package__ = moduleimportutility.parent_name(fullname) # now insert the loaded module into the cache, and return the result sys.modules[fullname] = m return m class dirmoduleloader(object): """ load the requested module under a directory (simulate the system import), all the intermediate modules will also be loaded. """ def __init__(self, namespace, root_path): self.namespace = namespace self.root_path = root_path self.ns_splitter = namespacesplitter(namespace) def load_module(self, fullname): import imp name_parts = self.ns_splitter.cut(fullname) for (ns, fp, filename, options) in \ moduleimportutility.find_modules(self.namespace, name_parts, self.root_path): if ns not in sys.modules: sys.modules[ns] = imp.load_module(ns, fp, filename, options) return sys.modules[fullname] loader = dirmodulefinder( 'parent.intermediate', os.path.realpath(os.path.join(os.path.dirname(__file__), '..')) ) loader.install() </code></pre> <p>feel free to comment on my solution, and if you guys find any potential bugs, be free to notify me.</p>
0
regular expression to match a string only when certain characters dont exist
pthis expression should be what youre looking forp precodehttpwwwexamplecomsubdirectory codepre p will match anything except for the characters you specifiedp pfor examplep ul lia hrefhttpwwwexamplecomsubdirectory relnofollowhttpwwwexamplecomsubdirectorya strongmatchstrongli lia hrefhttpwwwexamplecomsubdirectoryindexphp relnofollowhttpwwwexamplecomsubdirectoryindexphpa strongmatchstrongli lia hrefhttpwwwexamplecomsubdirectorysomepageparam1ampparam5print relnofollowhttpwwwexamplecomsubdirectorysomepageparam1ampparam5printa strongno matchstrongli lia hrefhttpwwwexamplecomsubdirectoryindexphpparam1 relnofollowhttpwwwexamplecomsubdirectoryindexphpparam1a strongno matchstrongli ul
0
python remove space from string make it into int
pintbalancenewtextreplace p
0
fabric equivalent of try finally
pyou could always use the new execute and wrap that in a tryexcept or just look at the return codes from your runsp
0
accessing the default argument values in python
pthis isnt very elegant at all but it does what you wantp precodedef testarg1foo printtestdefaults testarg1bar codepre pworks with python 3x toop
0
converting a list into columns in python
pyou can use pandas dataframes hope this is a tab separated filep precodeimport pandas as pd import numpy as np import csv df pdreadcsvtexttxt sept headernone print df codepre pthen you can rename the columnsp
0
insert new row every 2nd element of python list
precodelist abcdefgh for x in list with opencsvfile w as output index 0 writer csvwriteroutput writerwriterowlistindexindex 2 however many values you want to write as one line index 2 codepre
0
convert numpy array into orange table of discrete values
pyou can mmap your array to a file and then have orange read your mmaped file alternatively you may have some luck converting your np array to a python array and then reading that from orangep
0
django forms extra empty radio button
pa work around is to hide it with cssp precodeiddocumenttype lifirstchild displaynone codepre
0
virtualenv does not include pip
blockquote ol licodevirtualenvcode executable is not placed in codeusrlocalbincode after codepipcode makes its job so i need to codeln scode it by hand it may indicate that there is something wrong with installation on this stepli ol blockquote pdont do that that will only hide the bug and not solve the problem heres a short guide how to debug this kind of issuesp ul lipstart with codewhich a pythoncode the first path you see should be codeusrlocalbinpythoncode if not check your codepathcode variablepli lipnext check codewhich a pipcode again the first path should be codeusrlocalbinpipcode if not run codepython m ensurepipcode and recheck pli lipnow install codevirtualenvcode using codepip install virtualenvcode after that check the output of codewhich a virtualenvcode the first path should be codeusrlocalbinvirtualenvcode if not check the output of codeenv grep pythoncode for unexpected environment variablespli lipfinally check the output of codevirtualenv versioncode to make sure you have the latest versionpli ul
0
python hsaudiotag for wma files always returns 0
pthe solution was to go into the code and change the following lines to emline 118em strongselftrack ustrong emlines 149152em strongselftrack intselffieldsgettrack u 1strong p
0
tornado helloworld test returns 599
pit looks like youve mistakenly indented the code in codehellopycode this line should not be indented at allp precodedef makeapp codepre pthat is to say in the tornado docs codemakeappcode is a modulelevel function but in your code youve made it a member of mainhandlerp
0
pythons jsonloadsysstdin gets me u instead of double quotes around strings
puse python 3x and the error will disappearp
0
get the second largest number in a list in linear time
precoden intrawinput x intrawinputsplit a listmapint x y maxa k1 list for values in rangelena if yai k1appendai z maxk1 print z codepre
0
trying to get manytomany related data in django
pyou should add a function within codetagcode rather than codemessagecodep precodeclass tagmodelsmodel tagid modelsbigintegerfieldprimarykeytrue tagname modelscharfieldmaxlength100 datecreated modelsdatetimefieldautonowaddtrue def getmsgsself return messageobjectsfiltertagstagidtagid codepre phence the template should bep precode for q in populartags lttrgt lttd alignleftgtlth5gt qtagname lth5gt lttdgt for m in qgetmsgs lttd alignleftgtlth5gt mtitle lth5gtlttdgt endfor lttrgt endfor codepre
0
check if date is in daylight savings time for timezone without pytz
pinstall a hrefhttpsgithubcomnewvempytz relnofollowpytza without using pipp pdst is arbitrary and chosen by legislation in different regions you cant really calculate it look at a hrefhttpsgithubcomnewvempytzblobmasterpytzzoneinfouseasternpy relnofollowthe pytz source for useastern for examplea its literally a list of hardcoded dates when dst changes for the next twenty yearsp pyou could do that yourself pulling the data from the same source that pytz does a hrefhttpwebcsuclaedueggerttztzlinkhtm relnofollowzoneinfoa or this link a hrefhttpwwwianaorgtimezones relnofollowhttpwwwianaorgtimezonesa or from your os implementation of tz if it has onep pbut unless its a licensing reason get your employer to look at the pytz source and confirm that its acceptably harmless and approve it for usep
0
wxpython how to get menuitem from event
puse the event to access the data you want p precodeprint eventid print eventselection returns 1 if checked 0 if not checked print eventischecked returns true if checked false if not checked codepre pprint out all of the attributes withp precodeprint direvent codepre
0
weighted counting in python
puse the dictionaries codegetcode methodp precodegtgtgt d gtgtgt for item in l ditem0 dgetitem0 0 item1 gtgtgt d a 5 b 2 codepre
0
custom sorting on custom field in django
pcould you store it with leading zeros in the databasep peg 02 minp pthat way it would sort correctly and when you parse it out again the leading zeros should not matterp
0
resource utokenizerspunktenglishpickle not found
pfor me nothing of the above worked so i just downloaded all the files by hand from the web site a hrefhttpwwwnltkorgnltkdata relnofollowhttpwwwnltkorgnltkdataa and i put them also by hand in a file tokenizers inside of nltkdata folder not a pretty solution but still a solution p
0
django orm grouping by birthdates
pmaybe try something like this not testedp precodecasewhenquery case when extractend your case when query here extraqs readerobjectsextraselectcount count1 age casewhenquery queryset extraqsvaluescount age querysetquerygroupby age codepre
0
i need to extract dom element of main contents in python
pif you mean getting whole dom node with img src then i believe beautifulsoup4 can do thatp pa hrefhttpwwwcrummycomsoftwarebeautifulsoupbs4doc relnofollowhttpwwwcrummycomsoftwarebeautifulsoupbs4docap pbut with actual image i dont know you have to make separate request for imagep por you can use selenium a hrefhttpspypipythonorgpypiselenium relnofollowhttpspypipythonorgpypiseleniuma it will use your browser firefox chrome so can do anything with extracting web contentsp
0
encrypt decrypt data in python with salt
pyou dont need anything else than a hrefhttpsgithubcomrncryptorrncryptorpython relnofollowrncryptorap blockquote precodeimport rncryptor data password rncryptorrncryptors methods cryptor rncryptorrncryptor encrypteddata cryptorencryptdata password decrypteddata cryptordecryptencrypteddata password assert data decrypteddata rncryptors functions encrypteddata rncryptorencryptdata password decrypteddata rncryptordecryptencrypteddata password assert data decrypteddata codepre blockquote pit provides semantically secure random salt and iv for each encryption encryption and includes secure integrity checking ciphertext cannot be manipulated without noticing through hmacp prncryptor also has a specific data format so you dont have to think about that and implementations a hrefhttpsgithubcomrncryptor relnofollowin many languagesap
0
cascaded library dependencies
pwhen you link libaso shared libraries you use should be specified as dependencies codelsomedirectory lcudacode then the dependecies become visible with codeldd libasocode as they should and then codeldlibrarypathcode will helpp pundefined symbols are allowed in shared libraries so its up to you to provide enough dependencies when youre building one if the same thing doesnt happen with codelibmysqlclientcode its probably because codelibmysqlclientcode is loaded due to some other dependency or dynamically with codertldglobalcode and embeforeem codelibasocode then its probably not what you want even though the problem is not immediately visiblep ppsp ol liyou may want to read something on emsonamesem starting from codeman ldcode to decide whether you really want to link against codelibcudasocode and not against codelibcudasoncode as i would preferli lifor quick and dirty workaround if youre still with me in this place try codeldpreloadfullpathtolibcudaso yourprogramcodeli ol
0
how might i resize the window of my tkinter program
pyou already resized the app window from its default withp precodeappgeometry75x1001010 codepre prepeat this with a different sizep
0
python remove between indexes of two values if it occurs twice in a list
pemthis probably isnt the most efficient way but hopefully it helpsemp pcouldnt you just check if something appears twice if it does you have firstindex secondindex thenp pre classlangpython prettyprintoverridecodea123451789 b do a method to get the first and second index of the repeated number then for index in range0 lena print index if indexgtfirstindex and indexltsecondindex print we removed straindex else bappendaindex print b codepre pthe output is code11789code which seems to be what you wantp
0
python lists and loops
pyoure over writing h every time you run this your for loop it will return noon because noon is the last n in your loop p
0
odoo doesnt restart after update
pthe line codeoserror errno 13 permission denied optodoocode would seem to indicate that its a filesystem permissions issue you mentioned that you deleted codeoptodoocode when it was recreated it likely didnt have the correct permissions for it to runp pyour odoo config file commonly at codeetcodooserverconfcode should have a line like codeuserodoocode which is the local account that odoo will run under that account needs access to the codeoptodoocode director and its contentsp prunning codechown odooodoo optodoo rcode should provide permissions for the odoo account to work with the odoo directoryp
0
sending c over pyserial
psendbreakself is the answer im so stupidp
0
starting a dwolla payment processor with django do use an app or send post get requests directly
pyes the workflow is basically the same as with any other payment web service just read the docs a good starting point maybe a hrefhttpswwwdwollacomdevelopersoffsitegateway relnofollowoffsite gatewayap pthere is also a a hrefhttpsgetsatisfactioncomdwolla relnofollowdeveloper forumap
0
print list as array python
pa hrefhttpdocspythonorg2librarypprinthtml relnofollowcodepprintcodea or pretty print is pretty fantastic for this type of thing out of the box it wont give you output exactly like you are asking about but its flexible enough to work for a lot of other situations as wellp precodefrom pprint import pprint pprintl widthwidth codepre
0
reading a file to a dictionary and trying to rank
precoded sortedditems keylambda x x1 reversetrue codepre
0
how can i make a play two musical notes simultaneously in python
puse codemultiprocesscode and codewinsoundcode module to do sop
0
why do i get two different outputs when merging two sorted lists python
pwhy dont usep precodegtgtgt listone 136911 gtgtgt listtwo 245781012 gtgtgt merge listone listtwo gtgtgt mergesort codepre presultp precode1 2 3 4 5 6 7 8 9 10 11 12 codepre
0
python connect to a remote host from tkinter script
pyou want to use a hrefhttpdocsfabfileorgen110usageenvhtmlhoststring relnofollowcodehoststringcodea to dynamically specify what the destination is change it before executing commandsp pan example would bep precodefrom fabricapi import run env envhoststring userhostcom def ls runls codepre
0
returning all the elements of a list without knowing their number python
ptake a look at codeargscode and codekwargscode a hrefhttppythontipscom20130804argsandkwargsinpythonexplained relnofollowhereap precodedef testargs kwargs return a for a in args gtgtgttestone two none 6 one two none 6 codepre
0
python encoding two letters
pmay be thisp precodegtgtgt from itertools import chain gtgtgt cla b c d e f g h i y k l m n o p q r s t u v w x z gtgtgt m listchaincl gtgtgt n lencl0 gtgtgt def ea b iaib mindexa mindexb arac ia n ia n brbc ib n ib n return marn bc mbrn ac gtgtgt ebn d l codepre
0
funny issue localstorage and mongodb
pits nothing about mongodb its the ajax callp pthe string in response of an ajax call will be converted to character entities or they will break ur dom with characters like lt all u need to do is converted them backp
0