text_a stringlengths 9 150 | text_b stringlengths 18 20.9k | labels int64 0 2 |
|---|---|---|
euler 3 python putting the prime numbers into a list | pthis will run quite slowly for large numbers consider the case in which the algorithm attempts to find the prime factors where num 1000000 your nested for loop will generate 1million operations before the next number is even consideredp
pconsider using the sieve of eratosthones to get all of the prime numbers up to ... | 0 |
trouble with named pipes | ptry to provide an absolute path tmptestpipe to be sure that both are looking to the same filep
| 0 |
how to re arrange this python code without breaking sqlalchemy relevant dependencies | pi dont have the capability to do any testing at my current location but i suggest moving all of that code to codemaincode as follows also codemytablecode subclasses codedeclarativebasecodep
precodefrom sqlalchemy import createengine column integer
from sqlalchemyorm import sessionmaker from sqlalchemyextdeclarative ... | 0 |
why is default variable off by one in function definition | pyour function definition wont work because the way you have defined your default arguments pythons default arguments are evaluated once when the function is defined not each time the function is called like it is in say ruby this means that if you use a mutable default argument and mutate it you will and have mutated ... | 0 |
python list segregation | pif the list is a text file you can use pandasp
precodedf pdreadcsvfilepathsep
codepre
pim going to use a dummy df to show queryingp
precodedf pddataframenparrayalaska12alabama12brooklyn12reshape33
ar2 dfvaluesn if dfvaluesn0startswitha else for n in rangelendfvalues
df3 pddataframenparrayar2
df3tocsvoutputfile... | 0 |
python define method outside of class definition | pnot sure if it fits you scenario but you ca derive from strongmyclassstrong and add the function you wantp
| 0 |
embed fckeditor in python app | pin order of difficultyp
pif you just need to support windows you can embed ie in wx see the docs and demosp
pwxwebkit is looking a bit more mature but its still in developmentp
pyou could just use the webbrowser using webbrowseropenurl things will be very crude and interaction will be a painp
pa fourth option yo... | 0 |
create pandas dataframe from uneven data | peditp
phere is a simple way to have what you want for one bearp
precode recreating your data
d meals425 children542 territory867
bear1 colorbrown
grownsize7ft
stats dataframed
def beartodfbeardict
df beardictstats
for kv in beardictiteritems
if k stats
pass
... | 0 |
fail to compile a python script with dependencies | ptry a hrefhttpsgithubcompyinstallerpyinstaller relnofollowpyinstallera it is very useful to make any executable and if you need a windows executable you have to compile it on windowsp
| 0 |
for every point in a list compute the mean distance to all other points | pbased on alims comment to the question take a look at scipyspatialdistancepdist i found a pure numpyscipy solutionp
precodefrom scipyspatialdistance import cdist
fct lambda p0p1 greatcircledistancep00p01p10p11
meandist npsortcdistpointspointsfct1mean1
codepre
pdefinitely
thats for sure an improvement over my list... | 0 |
singleton python generator or pickle a python generator | pthis may not be an option for you but stackless python a hrefhttpstacklesscom relnofollowhttpstacklesscoma emdoesem allow you to pickle things like functions and generators under certain conditions this will workp
pin foopyp
precodedef foo
with openfootxt as fi
buffer firead
del fi
for line in b... | 0 |
python process text file with these criteria | precodeblacklist set1234567890
with openreachtxt as infile openoutreachtxt w as outfile
for line in infile
line linestrip
if not line
continue
left line linesplit 1
parts prstriplstrip for p in linesplit
parts p for ip in enumerateparts if not allchar in blac... | 0 |
python decorator with options | pi like lennart regebro katrielalex and martineau answers above but at the risk of sounding very strongcornystrong i will risk writing a emstory basedem example p
pin this two part story we can have strongteachersstrong that teach strongstudentsstrong from experiencep
precodedef selftaughtteacherfn
i teach stude... | 0 |
how to sort a list with strings and integers | pi am not sure how exactly you want your arguments to be sorted but you can just call the builtin function codesortedcodep
precodedef paramstolistparams
return sortedlistparams
codepre
| 0 |
how to display object properties in python | ptry to use codevarscode it gives objects attributes as a dictionnaryp
blockquote
pvarsobject dictionaryp
pwithout arguments equivalent to codelocalscode
brwith an argument equivalent to codeobjectdictcodep
blockquote
pexamplep
precodegtgtgt class myobjobject
pass
gtgtgt obj myobj
gtgtgt varsobj
gtgt... | 0 |
dictreader is skipping two lines of my file | pif your file is really formatted as you describe you may need to put commas between the column namesp
precodedate open high low
codepre
| 0 |
i want to use python to list a directory then sort the filenames by size | pmaybe this will give you some ideas
a hrefhttpwikipythonorgmoinhowtosorting relnofollowhttpwikipythonorgmoinhowtosortingap
| 0 |
installing pyodbc fails on osx 109 mavericks | pi met the the same problem today on ubuntu 1404 i found some guy in below link said should install unixodbcdevp
pa hrefhttpscodegooglecomppyodbcissuesdetailid55 relnofollowhttpscodegooglecomppyodbcissuesdetailid55ap
pi did it and then the pip install success p
phope this helpfulp
| 0 |
how do i do tagbind on all tags in tkinter | puse a list or function assuming to you want to bind all tags the samep
precodefor thistag in tagname1 tagname2 tagname3
treeviewtagbindthistag eventsequence clickhandler
codepre
| 0 |
comparison of python and perl solutions to wide finder challenge | blockquote
pthe perl implementation uses the mmap system call p
blockquote
pthis it avoids buffer copying and provides async iop
| 0 |
there is an error with my python program and i dont know whats wrong | blockquote
ptypeerror unsupported operand types for str and intp
blockquote
pthis is telling you the operand codecode division is running into an error because it is trying to divide a codestrcode and an codeintcode you can check the type of variables with codetypecodep
precodegtgtgt typebase
ltclass strgt
codepr... | 0 |
regarding passing variables to an argument | pthe problem is that you dont need a codemaincode function just put the code unindented by itself and it will run when you run the programp
| 0 |
python how can i do a string find on a unicode character that is a variable | pin some cases i ignore when you will have to decode also the string that you are looking inp
precodesdecodeutf8finduu0101
codepre
| 0 |
python construct consume data for optional field | pperhaps you could use an adapter similar to the lengthvalueadapter for a sequencep
precodeclass lengthvalueadapteradapter
adapter for lengthvalue pairs it extracts only the value from the
pair and calculates the length based on the value
see prefixedarray and pascalstring
parameters
subcon the subcon returning a... | 0 |
speeding up timestamp operations | pi would give this a try in bash using the date command date proves to be faster than even gawk for routine conversions python may struggle with thisp
pto speed this up even faster export the column in a in one temp file column b in another ect you can even do this in python then run the 5 columns in parallel p
preco... | 0 |
using flask web app as windows application | pi do not currently have a windows client here so i cannot exactly test what i am suggestingp
pusing strongpywinautostrong you can check for a windows namep
pyou could build a script that checks this in background and kills your flask application when the requested browser window is not openedp
precodefrom pywinauto... | 0 |
best method of importing scapy | p
i often use when i do not want to overwrite my namespacep
precodefrom scapy import all as scapy
codepre
pafter that everything is accessible under codescapycodep
precodescapysendscapyipscapyicmp
codepre
| 0 |
installed module in pythonstill i got error | pthere is several relatedduplicated answers but i personally accidentally use codesudocode to install some python packagesformulas and massed up with the permission p
blockquote
p brew doctor p
blockquote
pis your friend and you will find some good suggestions to fix you problemsp
panother suggestion is use codevi... | 0 |
creating a csv file for movie review corpus in python | precodedirectory rawinputinput folder
output rawinputoutput folder
txtfiles ospathjoindirectory txt
for txtfile in globglobtxtfiles
with opentxtfile rb as inputfile
intxt csvreaderinputfile
filename ospathsplitextospathbasenametxtfile0 csv
with openbookcsv wb as outputfile
outcsv csvwriter... | 0 |
how can i filter a date of a datetimefield in django | pin django 176 worksp
precodemyobjectobjectsfilterdatetimeattrstartswithdatetimedate2009822
codepre
| 0 |
celery and signals | pif i understood correctly you want the same process to send ans receive the signal it sent if so why not usep
precodeoskillosgetpid signalsiguser1
codepre
pand define the handler for sigusr1 accordinglyp
pif you want another process to get it you have to have its pid anyway to send signals to it so just use the sam... | 0 |
moving items in a list a certain number of spaces | pi would use the lists slice notation a hrefhttpdocspythonorgtutorialintroductionhtmllists relnofollowhttpdocspythonorgtutorialintroductionhtmllistsap
pfor example lets say you have a list like thisp
precodel 1 2 3 4 5 6 7 8
codepre
pand you wanted to move the element code4code over 1 space you could do something l... | 0 |
python if element1 from list1 is equal to element2 from list2 change element1 | ptry this it worksp
h2solution 1h2
h2demo on a hrefhttpreplit0vg12 relnofollowreplitaeditedh2
h3codeh3
precodedef codeslst cods
toadd
c 0
for ind elem in enumeratelst
if elem4 not in cods
toaddappendelem strind c
lstremoveelem
c 1
for ind elem in en... | 0 |
boost python overriding equality operator | ptry thisp
precodedefself self
defself self
codepre
preference a hrefhttpwwwboostorgdoclibs1570libspythondoctutorialdochtmlpythonexposinghtmlpythonclassoperatorsspecialfunctions relnofollowhttpwwwboostorgdoclibs1570libspythondoctutorialdochtmlpythonexposinghtmlpythonclassoperatorsspecialfunctionsap
| 0 |
wx validate controls in a container stops after first invalid | pto do this you would need to override codevalidatecode in your dialog and iterate over all controls yourself without stopping at the first invalid one like the base class implementation doesp
punfortunately you will probably need to duplicate the a hrefhttpsgithubcomwxwidgetswxwidgetsblobwx302srccommonwincmncppl2026 ... | 0 |
installing psycopg2 postgresql in virtualenv on windows | pthere is an alternative to install python packages in your computer ie strongpipstrong you can download python packages by just executingp
precode pip install pyscopg2
codepre
pthe general format of the command isp
precode pip install packagename
codepre
pps to install python packages globally through pip p... | 0 |
running a python program on a web server | pyou could create a simple cgi script a hrefhttpwikipythonorgmoincgiscripts relnofollowhttpwikipythonorgmoincgiscriptsa using the python cgi modulep
peither as a wrapper around your python script or update the existing one put a text area box for pasting the contents or otherwise you need to upload the file and pass ... | 0 |
first python screen scraping and smtp script wont evaluate properly | phave you tried logging the value of resp20 to see what values you are getting a simple p
precodeprint resp20
codepre
pwhile debuggingp
| 0 |
finding last occurence of substring in string replacing that | pnave approachp
precodea a long string with a in the middle ending with
fchar
rchar
a1replacefchar rchar1 11
out2 a long string with a in the middle ending with
codepre
hr
paditya sihags answer with a single coderfindcodep
precodepos arfind
apos apos1
codepre
| 0 |
how to find a point inside an irregular polygon | phere is an algorithm i have used with successp
pfind a point outside your polygon just choose an codexcode or codeycode greater than your maxp
pdraw a line in your head from your point to the point outside your polygonp
pcount the number of intersections of this line with the line segments that make up the perimet... | 0 |
python dictionary pickling | ptry dumping each object in a separate filep
precodewith openuelestutxt wb as f
pickledumpuelestu f
with openeleplstutxt wb as f
pickledumpeleplstu f
codepre
| 0 |
dynamically setting tablename for sharding in sqlalchemy | ptry thisp
precodeimport zlib
from sqlalchemyextdeclarative import declarativebase
from sqlalchemy import column integer biginteger datetime string
from datetime import datetime
base declarativebase
entityclassdict
class absshardingclassbase
abstract true
def getclassnameandtablenamehashid
return sh... | 0 |
django orbitedstomp | pit seems that orbited is not suited for this kind of things i talked with orbited creator i switched to hookbox and it works fine p
| 0 |
python efficient way to read text file with varying delimiters spaces | puse re library with regex its an easy way to parse textp
precodeimport re
m researchltabcdef abcdef
mgroup0
def
codepre
| 0 |
python namespace elements visibility vs proper package structure | h2name and bindingh2
pyou can read a hrefhttpdocspythonorg2referenceexecutionmodelhtmlnamingandbinding relnofollowcodepython naming and bindingcodea and understand how python namespace worksp
pa scope defines the visibility of a name within a block if a local variable is defined in a block its scope includes that blo... | 0 |
timestamp from a txt file into an array | pa hrefhttppandaspydataorg relnofollowpandasa is supposed to be good at this sort of thing im no expert and had some trouble with the codeparsedatecode functionality of a hrefhttppandaspydataorgpandasdocsstableiohtmlioreadcsvtable relnofollowcodereadcsvcodea but the following seems to work reasonably well and fastp
pr... | 0 |
python metaclass properties override class attributes sometimes | phere is some very similar code that might help you understand whats happeningp
precodeclass myclassobject
def initself data
selfdictupdatedata this would fail if i had selfa a
property
def aself
return 1
myobject myclassa 2
print myobjecta
print objectgetattributemyobject a
print myo... | 0 |
python regex over list of strings | precodefor i in p
t refindallsrc alt i
print t
codepre
pupdatep
precodekrefindallsrc alti for i in p
item for sublist in k for item in sublist
codepre
pa hrefhttpwwwsamplecomtestjpg relnofollowhttpwwwsamplecomtestjpga a hrefhttpwwwsamplecomtest2jpg relnofollowhttpwwwsamplecomtest2jpgap
| 0 |
matplotlib surface plot extends past axis limits | pemmanual data clippingemp
pone approach ive seen that works is to emmanually clip the dataem eg your example would be updated to p
precodefrom matplotlib import
from mpltoolkitsmplot3d import axes3d
import matplotlibpyplot as plt
import numpy as np
from pylab import
import math
fig pltfigure
ax figaddsubplot111 ... | 0 |
pyside button auto repeat doesnt start until mouse is moved | pi was having a similar problem using normal qt4x on linux the issue was that something was connected to the clicked signal i think it was stealingchanging the focus of the mouse i just changed that item to connect to the the released signal that doesnt mean you cant connect to clicked but just be sure that there are n... | 0 |
python mechanize module selecting all input fields within a form | pfound something that might be of use herep
pa hrefhttpstockrtgithubcompemulatingabrowserinpythonwithmechanize relnofollowhttpstockrtgithubcompemulatingabrowserinpythonwithmechanizeap
precode select the first index zero form
brselectformnr0
codepre
| 0 |
why doesnt my code correctly create a list of tuples | pi would add on top of the other answers that this is not the best way to get the intersection of two sets why not simply use a hrefhttpdocspythonorg2librarysetshtmlsetobjects relnofollowpython setsa p
precode class lexiconobject
def barself sentence
return setsentencesplit amp setdirection
... | 0 |
python rectangle of asterisks | pthis doesnt sound much like a rectangle to me but the way i would do this is to use a conditional expression that selects the length of each row according to the remainder when the row number is divided by twop
pit would look like thisp
precoderows intinputnumber of rows for this design
stars intinputnumber of s... | 0 |
recursion none python | pmay i suggest that you use beautifulsoup it is easy to learn has good documentation a hrefhttpwwwcrummycomsoftwarebeautifulsoupbs4doc relnofollowhttpwwwcrummycomsoftwarebeautifulsoupbs4docap
pa soup object can be instantiated using the code below where markup is a string containing your xml or input file handle to th... | 0 |
why am i not getting the full text of this page | pthe problem is that youre trying to parse python source code as html and then strip the text back out of itp
pso line 318 isp
precode if sysversioninfo lt 2 6
codepre
pthis happens to be the first codeltcode character in the file since youre trying to parse it as html that means that the whole rest of the file i... | 0 |
python script working when run in cmd but not when run from file | ptry to put the lib in the same folder of the script and it should workp
| 0 |
facebook serverside login without php | pi have a python library that does thisp
ul
lia hrefhttpsgithubcomjvanascofacebookutils relnofollowhttpsgithubcomjvanascofacebookutilsali
ul
pits on pypi as well p
pthe main file shows how youd integrate it on the serverside and template for pyramid doing it in django flask whatever would be similarp
| 0 |
convert index of series object in panda | pdo you meanp
precodegtgtgt s
330 0064591
331 0705979
332 0516967
dtype float64
gtgtgt df
a
20131125 074952584591 0064591
20131126 074952584626 0705979
20131127 074952584633 1516967
gtgtgt dffroms pddataframes columnsdfcolumns
gtgtgt dffromsindex dfindex
gtgtgt df dffroms... | 0 |
python selenium questions href | pfor single elementp
pcodedriverfindelementbyxpathadataemberaction1517textcodep
pif you want to get text from all similar codeltagtcode elements on pagep
precodealist driverfindelementsbyxpathpclassinfoadataemberaction
for element in alist
print elementtext
codepre
| 0 |
editing form and saving into database | pupdate your view function like this to return form for get request as wellp
precodedef edititemrequest itemid
if requestmethod post
item itemobjectsgetiditemid
your existing code
else if its get request
item itemobjectsgetiditemid
form additeminstanceitem
r... | 0 |
regular expression to match start of filename and filename extension | pthis probably doesnt fully comply with filenaming standards but here it goesp
precoderunwpy
codepre
| 0 |
pyplot 3d scatter points at the back overlap points at the front | pthanks you so much for your explanation i thought it could be something like that indeed but i forgot to say in my question that the same thing happened no matter the order of the axscatter commands what is pretty weird i found out before reading your answer that that does not happen with the axplot command therefore... | 0 |
need help looping | pi am no expert in python but i think i see what your problem isp
paccording to your code here youre asking the user for a number of any size once theyve input this number then program proceeds to execute a for loop salary number of times this can be a problem if youve made the employees salary something huge like 100... | 0 |
format python code in spyder ide | pi tried this p
blockquote
psource fix indentation remove trailing spacesp
blockquote
pthis is not the most efficient way but it seems there are no key combinations to do these even in preferences they have not allowed to add new shortcut for thisp
| 0 |
python nan json encoder | punfortunately you probably need to use bramars suggestion youre not going to be able to use this directly a hrefhttpsdocspythonorg2libraryjsonhtml relnofollowthe documentationa for pythons json encoder statesp
blockquote
pif specified default is a function that gets called for objects that cant otherwise be seria... | 0 |
python regex to extract substring at start and end of string | pdo you need a regex herep
precodegtgtgt address myfile10456csv
gtgtgt splitbyperiods addresssplit
gtgtgt formataddress0 address1
gtgtgt myfilecsv
codepre
| 0 |
reconstruct python method with kwargs with marshal and types | pafter some more searching i discovered the dill package which allows you to pickle more things than cpickle the reason i was using marshal when you directly reconstruct a serialized function not using the funccode you avoid this keyword issue i was havingp
| 0 |
404 error with static files served through djangoapache bitnami | pfrom the documentation a hrefhttpswikibitnamicombitnamicloudhostingbasestack relnofollowhttpswikibitnamicombitnamicloudhostingbasestacka it seems like amazon ec2 uses apache version 2229 you should change codehttpdconfcode to cover both that version and the one in your other setupp
precodeltdirectory optbitnamiappsdj... | 0 |
fastest ways to keywise add a list of dicts together in python | pits simple but this could workp
precodea x 10 y 05 z 025
b w 05 x 02
ds a b
result
for d in ds
for k v in diteritems
resultk v resultgetk 0
n lends
result dictk amtn for k amt in resultiteritems
print result
codepre
pi have no idea how it compares to your method since you didnt post any ... | 0 |
amazon ses hide recipient email addresses | pwe use the sendrawemail function instead which gives more control over the make up of your message you could easily add bcc headers this wayp
pan example of the code that generates the message and how to send itp
precodefrom emailmimemultipart import mimemultipart
from emailmimetext import mimetext
msg mimemultipa... | 0 |
how to install and cron python3 scrapy on cloud linux | pit appears as though you do not have the bzip module installed on your cloud server it may very well be linked to a lack of the bzip2 library being missingp
pin order to install it you can typep
precodeaptget install bzip2
codepre
pyou may need to prefix that command with codesudocodep
pin all honesty it should b... | 0 |
cherrypy accessing the uriroute parameters inside a tool hook | pcherrypyurl will get you the complete uri but i suspect thats not quite what youre looking forwhy do you need it if youre trying to form your location variable based on the uri you probably want pathinfo instead of the complete urip
precodelocation sviews requestappconfigapplicationpath
if requestpathinfoendswith
... | 0 |
nlargest elements in an sequence need to retain duplicates | phows about this it doesnt emexactlyem return your desired result since it reversesorts on codeycodep
precode split lot by first element of values
lots defaultdictlist
for x y z in lot
lotsxappendy z
ans
for x l in lotsiteritems
find top3 unique values
top nlargest3 setz for y z in l
ans x y z f... | 0 |
django comparing datetimenow with pubdate | precodeimport datetime
if somedatetime gt datetimedatetimenow datetimetimedeltadays10
return somedate is greater than the current datetime plus 10 days
codepre
psee timedelta doc a hrefhttpdocspythonorglibrarydatetimehtmldatetimetimedelta relnofollowhttpdocspythonorglibrarydatetimehtmldatetimetimedeltaap
| 0 |
edit response logo in web2py | pjust change the content of the anchor tag to include the imagep
precoderesponselogo aimgsrcurlstatic imageslogolbpng
hrefurldefault index
codepre
pnote you dont really need to use coderesponselogocode at all you can instead just put the relevant html directly in the layouthtml viewp
| 0 |
method overriding | porder matters if names are samelast function you defined is processing in your case itsp
precodedef gxy
return xy
codepre
| 0 |
python 27 print error | pthe print function is specific to python 3
you have two solutions herep
pwritep
precodefrom future import printfunction
codepre
pso you can use it as specified by cdarkep
por you use print as a simple statement as it should be with older versions of python codeprint hello worldcodep
| 0 |
the dateaxisitem sometimes becomes invisible | pim not sure what happens with your dateaxisitem as you know its not yet merged into the main development branch of pyqtgraph however for your particular application it might be easier to start from scratch and define your own timeaxisitem if you start from the following code what functionality would be missingp
preco... | 0 |
issues with cors flask angularjs | pis the post sending content i had a similar issuee when the body was null if it is adding either an empty body when the object is falsy or adding the contentlength header as 0 both seemed to workp
precodescopesyncup function
var objtosend scopetransactions transactions scopetransactions
httpposthttpmoney... | 0 |
how can i create a folder system inside of my python program | pnot sure why writing to the file is a problem but you could basically have a tree type data structure to represent a file system for examplep
precodeclass file
def initself filename directoryfalse
selffilename filename
selfdirectory directory
selffiles if directory else none
codepre
p... | 0 |
redirect sysstdout to a file without buffering in python 3 | pthe issue seems to be in the way you open the file p
precodeopenlogfile w 0
codepre
pfrom a hrefhttpsdocspythonorg3libraryfunctionshtmlopen relnofollowpython 3x documentationa p
blockquote
popenfile moder strongbuffering1strong encodingnone errorsnone newlinenone closefdtrue openernonep
blockquote
pthe third arg... | 0 |
using web2py for a user frontend crud | blockquote
pthis doubleredundant way of talking to my db strikes me as odd and web2py does not support python3p
blockquote
pany abstraction you want to use to communicate with your database whether it be the web2py dal the django orm sqlalchemy etc will have to have some knowledge of the database schema in order to ... | 0 |
installing numpy for python 27 | pi generally just avoid the whole numpy install process by using the anaconda distribution from a hrefhttpcontinuumio relnofollowcontinuumioa no i am not a paid spokesperson haha but in reality whether you use anaconda or even the enthought distribution this is a lot easier than trying to install these packages with pi... | 0 |
filtering specific rows in a csv file in python | precodefor mycsvline in csvreader
if mycsvline4 abc
append to result
codepre
| 0 |
why is magicfrombuffer returning none | pim not sure the reason for the issue could be the version but ive been able to workaround it with something likep
precodemime magicfrombufferdata mimetrue
if mime none
workaround for issue with libmagic15092 in ubuntu 1204 fixed in libmagic 5112
filestr magicfrombufferdata
if filestrstartswithcomposit... | 0 |
split a string into exactly n pieces | pheres the pseudocode i dont know python but probably useful as a general purpose algorithmp
precodereglen lt intlenstrn the integer portion only
firstlen lenstr n reglen
output goes into output array of length n elements each a substring
output1 leftstr firstlen
for i lt 2 to n
startposition lt firstlen ... | 0 |
python embedding pyimportimport not from the current directory | pthere is a good way because this is the way it is frequently done with sitepackesp
precodeimport sys
syspathappenddirectory syspath is a list of all directories to import from
codepre
por you use p
precodeoscwddirectory change the working directory
codepre
pbefore the importp
pan other way is uglyp
precodeimpo... | 0 |
returning unique values in csv and unique strings in pythonpandas | pi think the following should work for almost any dataframe it will extract each value that is unique in the entire dataframep
ppost a comment if you encounter a problem ill try to solve itp
precode replace all nones nas by spaces so they wont bother us later
df dffillna
preparing a list
listsets
iterates al... | 0 |
what class to use for money representation | pit depends what youd like to use codemoneycode for p
pfor financial modelling of price and risk codedoublecode pythons codefloatcode is good enough because all models are inaccurate some of them are useful though so one doesnt get any useful extra precision by using infinite precision numbersp
pfor currency conversi... | 0 |
python extract time from date column to plot | pfirst convert your timestamps to python a hrefhttpsdocspythonorg2librarydatetimehtml relnofollowdatetimea using a hrefhttpsdocspythonorg2librarydatetimehtmlstrftimestrptimebehavior relnofollowdatetimestrptimedatestring formatap
precodeimport datetime
liststring 20160415 060001704
fmt ymd hmsf
listdatetimes dateti... | 0 |
python how to use part of function outside function | precodeclass movieobject
def initselftitletodayreturntimelt
selftitle title
def timeofreturnself
selftoday today
selfreturntime returntime
today datetimedatetimenow
returntime today datetimetimedeltadays30
def returnfeemovie
fee 2
delta today returntime
codepre
pthats becaus... | 0 |
shelveopen failing on creation | pi found out that when i was pushing to the repository git wasnt including the directory i was looking in because it was empty if you try to use codeshelveopencode with an argument that is in a directory that doesnt exist it will give you an io error i simply forced the creation of the directory and now it worksp
| 0 |
overriding a parents classmethod with an instance method | pi dont think the problem is with parents or inheritance but simply with calling an instance method from a class methodp
precodeclass barobject
def callerselfxcx
printbar callerself
selfmyfnx
classmethod
def classcallerclsxccx
printbar class callercls
clsmyfnx
def myfnse... | 0 |
how do i parse lines from a log file | pin perl this should do itp
precodeconsider the a variable has the log file my
a ltltlog filegtgt
my desiredanswer
regex
if a mproto ig
desiredanswer1
codepre
| 0 |
placing vertices of graphs wxpython | pyou want a graph drawing algorithm there is ongoing research in this area but a simple forcedirected algorithm can give good results for small graphs look at a hrefhttpenwikipediaorgwikiforcebasedalgorithms28graphdrawing29 relnofollowthis wikipediaa article for the algorithm you can also get some open source librarie... | 0 |
best way to replace x00 in python lists | ptry a unicode pattern like thisp
precoderesubux00 s
codepre
pit should give the following resultsp
precodel textx00x00x00 datax00x00x00 rsrcx00x00x00
for x in l
for s in l
print resubux00 s
count 1
text
data
rsrc
codepre
por using list comprehensionsp
precoderesubux00 s for s in x for x ... | 0 |
replacing all keys and values in nested python dictionary with new values | pi have taken a recursive approach which if the value of the data is dictionary try to replace the keys and values else it treats the data as a single value and try to convert itp
pcodereplacedictcode is the dictionary which points out how to convert values and codedatacode are the current valuesp
precodedef replac... | 0 |
create plot first then add inside a figure | pit isnt possible to move an codeaxescode from one figure to another the axes is linked to the figure upon creationp
pinstead youll have to first generate the figure and then the codeaxescodees within that figurep
| 0 |
how to modify query string in python cgi | ptry using urlparse module a hrefhttpdocspythonorglibraryurlparsehtml relnofollowhttpdocspythonorglibraryurlparsehtmlap
| 0 |
python derived class call a global variable which initialized in superclass | pfinally i edit my code like thisp
pbasepyp
precodeclass baseobject
def initself driver
selfdr driver
global dr
dr driver
codepre
ponepyp
precodeclass onebase
def initself driver
superinitdriver
global dr
dr selfdr
def funself
printdr
if namem... | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.