text_a
stringlengths 9
150
| text_b
stringlengths 18
20.9k
| labels
int64 0
2
|
---|---|---|
how do i alternate between different marker colors on matplotlib | psimplest might be to use a scatter plotp
precodex range20
y 2nparrayx
pylabscatterx y colorrgb
codepre
pa hrefhttpistackimgurcomaey5rpng relnofollowimg srchttpistackimgurcomaey5rpng altenter image description hereap
pi think what tcaswell is suggesting as an alternative in his comment is using codeplotcode three times with different colors on the appropriate slicesp
precodepylabplotx3 y3 ro
pylabplotx13 y13 go
pylabplotx23 y23 bo
codepre
| 2 |
copydeepcopy raises typeerror on objects with selfdefined new method | pone problem is that codedeepcopycode and codecopycode have no way of knowing which arguments to pass to codenewcode therefore they only work with classes that dont require constructor argumentsp
pthe reason why you can have codeinitcode arguments is that codeinitcode isnt called when copying an object but codenewcode must be called to create the new objectp
pso if you want to control copying youll have to define the special codecopycode and codedeepcopycode methodsp
precodedef copyself
return self
def deepcopyself memo
return self
codepre
pby the way a hrefhttptechpuredangercom20070703patternhatesingletonsingletonsa are a hrefhttpblogsmsdncombscottdensmorearchive20040525140827aspxevila and not really needed in pythonp
| 2 |
where to put freezesupport in a python script | pon windows strongallstrong of your codemultiprocessingcodeusing code must be guarded by codeif name maincodep
pso to be safe i would put all of your the code currently at the toplevel of your script in a codemaincode function and then just do this at the toplevelp
precodeif name main
main
codepre
psee the safe importing of main module subsection a hrefhttpsdocspythonorg2librarymultiprocessinghtmlwindowsherea for an explanation of why this is necessary you probably dont need to call codefreezesupportcode at all though it wont hurt anything to include itp
pnote that its a best practice to use the codeif name maincode guard for scripts anyway so that code isnt unexpectedly executed if you find you need to codeimportcode your script into another script at some point in the futurep
| 2 |
django authentication and ajax urls that require login | pi would agree with a hrefhttpstackoverflowcomquestions312925djangoauthenticationandajaxurlsthatrequirelogin313015slottap
pmake a check in the template if the user is logged in just put the link as usual if not put something like p
precodelta hreflink onclickreturn loginpopupgt
codepre
pwhere loginpopup would return false if the user says cancelp
pthis could be probably be done much easier in a hrefhttpjinjapocooorg2jinja2a through its a hrefhttpjinjapocooorg2documentationtemplatesmacrosmacrosap
pif the template doesnt know which urls require the user to login you probably need to reconsider your designp
pif you must i guess you can do the same thing that the django url dispatcher does to discover the view function br
see codedjangocoreurlresolverscodep
ponce youve grabbed the view function you can check if its decorated with loginrequired p
pthis would be done in a custom tag probably br
if you use jinja2 you wont need the tag just implement the function and expose it to the environment its simple but youll have to do a bit of reading on the api of jinja2p
| 2 |
python is there a wellknown function to normalize json representation of data | pto compare these objects you need to compare loaded dictsp
precodeassert jsonloadss1 jsonloadss2
codepre
pto ensure serializations are consistent with each other you may use a hrefhttpsdocspythonorg2libraryjsonhtmlbasicusagekeyword argument codesortkeyscodeap
blockquote
pif sortkeys is codetruecode default codefalsecode then the output of dictionaries will be sorted by keyp
blockquote
precodeassert jsondumpsd1 sortkeystrue jsondumpsd2 sortkeystrue
codepre
pif coded1 d2code equality above holds for any serializable data including nested structuresp
| 2 |
pandas how do i split text in a column into multiple rows | precodeimport pandas as pd
import numpy as np
df pddataframeitemqty 0 3 1 25
seatblocks 0 22181046 1 11336112 11337113
itemext 0 60 1 300
customername 0 mccartney paul 1 lennon john
custnum 0 32363 1 31316
item 0 f04 1 f01
columnscustnumcustomernameitemqtyitemseatblocksitemext
print df
custnum customername itemqty item seatblocks itemext
0 32363 mccartney paul 3 f04 22181046 60
1 31316 lennon john 25 f01 11336112 11337113 300
codepre
panother similar solution with chaining is use a hrefhttppandaspydataorgpandasdocsstablegeneratedpandasdataframeresetindexhtml relnofollowcoderesetindexcodea and a hrefhttppandaspydataorgpandasdocsstablegeneratedpandasseriesrenamehtml relnofollowcoderenamecodeap
precodeprint dfdropseatblocks axis1
join
dfseatblocks
str
splitexpandtrue
stack
resetindexdroptrue level1
renameseatblocks
custnum customername itemqty item itemext seatblocks
0 32363 mccartney paul 3 f04 60 22181046
1 31316 lennon john 25 f01 300 11336112
1 31316 lennon john 25 f01 300 11337113
codepre
hr
<p>if in column are <strong>not</strong> <code>nan</code> values, the fastest solution is use <code>list</code> comprehension with <code>dataframe</code> constructor:</p>
<pre><code>df = pd.dataframe(['a b c']*100000, columns=['col'])
in [141]: %timeit (pd.dataframe(dict(zip(range(3), [df['col'].apply(lambda x : x.split(' ')[i]) for i in range(3)]))))
1 loop, best of 3: 211 ms per loop
in [142]: %timeit (pd.dataframe(df.col.str.split().tolist()))
10 loops, best of 3: 87.8 ms per loop
in [143]: %timeit (pd.dataframe(list(df.col.str.split())))
10 loops, best of 3: 86.1 ms per loop
in [144]: %timeit (df.col.str.split(expand=true))
10 loops, best of 3: 156 ms per loop
in [145]: %timeit (pd.dataframe([ x.split() for x in df['col'].tolist()]))
10 loops, best of 3: 54.1 ms per loop
</code></pre>
<p>but if column contains <code>nan</code> only works <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.series.str.split.html" rel="nofollow"><code>str.split</code></a> with parameter <code>expand=true</code> which return <code>dataframe</code> (<a href="http://pandas.pydata.org/pandas-docs/stable/text.html#splitting-and-replacing-strings" rel="nofollow">documentation</a>), and it explain why it is slowier:</p>
<pre><code>df = pd.dataframe(['a b c']*10, columns=['col'])
df.loc[0] = np.nan
print (df.head())
col
0 nan
1 a b c
2 a b c
3 a b c
4 a b c
print (df.col.str.split(expand=true))
0 1 2
0 nan none none
1 a b c
2 a b c
3 a b c
4 a b c
5 a b c
6 a b c
7 a b c
8 a b c
9 a b c
</code></pre>
| 2 |
numpy generating a sequence with a higher resolution within certain bounds | pyou could construct such a sequence by first making an array containing the spacings between each pair of points then taking a cumsum over thisp
pfor example lets suppose i want to go from 0 to 50 everywhere in steps of 1 except between 20 and 30 where i want steps of 025p
precodeimport numpy as np
deltas nprepeat0 1 025 1 1 20 40 20
pts npcumsumdeltas
codepre
pplottingp
precodefrom matplotlib import pyplot as plt
fig ax pltsubplots1 1
axeventplotpts
axmarginsx005
codepre
pa hrefhttpistackimgurcomibinipng relnofollowimg srchttpistackimgurcomibinipng altenter image description hereap
hr
h3edith3
pid totally forgotten about a hrefhttpdocsscipyorgdocnumpyreferencegeneratednumpyrhtml relnofollowcodenprcodea which offers a very nice compact way to achieve the same thingp
precodepts2 npr0201 2030025 30511
codepre
pas well as specifying a step size manually you can also use an imaginary number as the step size which is equivalent to using codenplinspacecode to specifying the number of steps to take eg codenpr01020jcode is the same as codenplinspace0 10 20codep
| 2 |
how to parse sentences into tokens with either regex or toolkits | plook how easy it is using codebeautifulsoupcodep
precodefrom bs4 import beautifulsoup
data yesterdayltpersongtpeter smithltpersongtdrove toltlocationgtnew yorkltlocationgt
soup beautifulsoupdata htmlparser
for item in soup
print item
codepre
pprintsp
precodeyesterday
ltpersongtpeter smithltpersongt
drove to
ltlocationgtnew yorkltlocationgt
codepre
pupd splitting nontag items into spaces and print every part on a new linep
precodesoup beautifulsoupdata htmlparser
for item in soup
if not isinstanceitem tag
for part in itemsplit
print part
else
print item
codepre
pprintsp
precodeyesterday
ltpersongtpeter smithltpersongt
drove
to
ltlocationgtnew yorkltlocationgt
codepre
phope that helpsp
| 2 |
using global variables between files | pthe problem is you defined codemylistcode from mainpy but subfilepy needs to use it here is a clean way to solve this problem move all globals to a file i call this file codesettingspycode this file is responsible for defining globals and initializing themp
precode settingspy
def init
global mylist
mylist
codepre
pnext your subfile can import globalsp
precode subfilepy
import settings
def stuff
settingsmylistappendhey
codepre
pnote that subfile does not call init that task belongs to mainpyp
precode mainpy
import settings
import subfile
settingsinit call only once
subfilestuff do stuff with global var
print settingsmylist0 check the result
codepre
pthis way you achieve your objective while avoid initializing global variables more than oncep
| 2 |
function name not defined | blockquote
phave i not defined the name in the first line of the function def mainp
blockquote
pyes but python hasnt executed that definition yet put the function definition before the callp
| 2 |
python concatented string allow this to call a tuple | pthats not really what variable names are meant for the numbers 1 and 2 in codetuple1code and codetuple2code either mean something eg the code1code really means 1 person and the code2code 2 people or they dont theyre only placeholdersp
pif they emdoem mean something you should probably use a dictionaryp
precodegtgtgt mydata 1 123 2 456
gtgtgt mydata
1 1 2 3 2 4 5 6
gtgtgt mydata1
1 2 3
gtgtgt mydata2
4 5 6
codepre
pif they dont and you simply have two tuples then you might as well use a listp
precodegtgtgt mydata 123 456
gtgtgt mydata0
1 2 3
gtgtgt mydata1
4 5 6
gtgtgt for tup in mydata
print tup
1 2 3
4 5 6
codepre
pyou definitely dont need to use evalp
| 2 |
python method be aware the selfvariable changed | psince codevarcode is a class attribute you could simply check if the value for the instance is different from the parent classp
precodeclass pobject
var original
def funcself
if selfvar pvar
print do a
else
print do b
class c1p
var changed
class c2p
pass
c1 c1
c2 c2
c1func do a
c2func do b
codepre
panother more general option might be to define a subclass of codepcode with the codefunccode method and use that as the parent for codec1code and codec2code classes then we can make use of a hrefhttpsdocspythonorg2libraryfunctionshtmlsuper relnofollowsupera to access the parent attribute as followsp
precodeclass pobject
var original
class pchildp
def funcself
if selfvar superpchild selfvar
print do a
else
print do b
class c1pchild
var changed
class c2pchild
pass
c1 c1
c2 c2
c1func
c2func
codepre
| 2 |
how to declare member variable in python base class which can be accessed in derived | pinstance variables are always accessed through the class instance itself inside the method this is by convention known as codeselfcode so you need to use codeselfheaderscode etcp
pnote though that by defining codeheaderscode at the top of the class you have defined a emclassem variable which is shared by all members you dont want this and there is no need to define codeheaderscode there just assign it within codeinitcodep
pplus as storyteller points out youll need to call the superclass codeinitcode method manually inside the derived class methods since that defines the attribute in the first placep
precodesuperposthttprequest selfinit
codepre
pand in order for that to work as abarnert points out youll need to inherit your base class from codeobjectcodep
pfinally please do use pep8compliant names codeposthttprequestcode etcp
| 2 |
use glob to find arbirary length numbers | pyou are probably confusing regular expression syntax with glob constructs code09code in globbing means a single digit followed by zero or more of emanyem character so drop the codecodep
pin emextended globbingem there is a qualifier of one or more but that is not supported by codeglobcode so there is little choice but to use a regular expression ie do your own filename pattern matching there are several ways to do this here is onep
precodeimport os
import re
files
for fname in oslistdir
if rematchrmyfile09txt fname
filesappendfname
print files
codepre
pnote that the re is not exactly the same as yours i use codecode which means one of more of the preceding pattern an codecode would mean zero or more so the digits would be optional which could be what you want im not surep
pthe bulk of the code could be done as a list comprehension but that would arguably loose some readabilityp
precodefiles fname for fname in oslistdir
if rematchrmyfile09txt fname
codepre
| 2 |
doing shell backquote in python | pthe a hrefhttpdocspythonorglibrarysubprocesshtmlreplacingbinshshellbackquote relnofollowossubprocess documentationa describes how to replace backquotesp
precodeoutputmycmd myarg
gt
output popenmycmd myarg stdoutpipecommunicate0
codepre
| 2 |
anagrams code resulting in infinite results | pthis is not an infinity of results this is 13 words a bit over 6 billions you are facing a combinatorial explosionp
p 13 factorialp
| 2 |
combine multiple text files line by line in python | pin the command linep
precode paste a b c
1 a x
2 b y
3 c z
codepre
| 2 |
how to load python script in interactive shell | pfrom the docsp
precode python help
usage usrbinpython27 option c cmd m mod file arg
options and arguments and corresponding environment variables
b dont write pyco files on import also pythondontwritebytecodex
c cmd program passed in as string terminates option list
d debug output from parser also pythondebugx
e ignore python environment variables such as pythonpath
h print this help message and exit also help
i inspect interactively after running script forces a prompt even
if stdin does not appear to be a terminal also pythoninspectx
codepre
puse codeicode optionp
| 2 |
fill between two vertical lines in matplotlib | pit sounds like you want a hrefhttpmatplotliborgapipyplotapihtmlmatplotlibpyplotaxvspancodeaxvspancodea rather than one of the fill between functions the differences is that codeaxvspancode and a hrefhttpmatplotliborgapipyplotapihtmlmatplotlibpyplotaxhspancodeaxhspancodea will fill up the entire y or x extent of the plot regardless of how you zoomp
pfor example lets use codeaxvspancode to highlight the xregion between 8 and 14p
precodeimport matplotlibpyplot as plt
fig ax pltsubplots
axplotrange20
axaxvspan8 14 alpha05 colorred
pltshow
codepre
pimg srchttpistackimgurcomjaq9lpng altenter image description herep
pyou could use codefillbetweenxcode to do this but the extents both x and y of the rectangle would be in emdata coordinatesem with codeaxvspancode the yextents of the rectangle default to 0 and 1 and are in emaxes coordinatesem in other words percentages of the height of the plot p
pto illustrate this lets make the rectangle extend from 10 to 90 of the height instead of taking up the full extent try zooming or panning and notice that the yextents say fixed in display space while the xextents move with the zoompanp
precodeimport matplotlibpyplot as plt
fig ax pltsubplots
axplotrange20
axaxvspan8 14 ymin01 ymax09 alpha05 colorred
pltshow
codepre
pimg srchttpistackimgurcomwwzzipng altenter image description herep
| 2 |
assigning a value to a string item in list | pyou simply define a list of stringsp
precodecardnames ace2345678910jackqueenking
codepre
pnow if the card has value codevcode you can get the corresponding name with codecardnamesv1code for instancep
precodev 5
printi have a scardnamesv1
codepre
pin that case the value for the jack is 11 for queen 12 and for king 13 for instance using codepythoncodes interactive shellp
precode python
python 279 default apr 2 2015 153321
gcc 492 on linux2
type help copyright credits or license for more information
gtgtgt cardnames ace2345678910jackqueenking
gtgtgt v12
gtgtgt printi have a scardnamesv1
i have a queen
gtgtgt v7
gtgtgt printi have a scardnamesv1
i have a 7
gtgtgt v1
gtgtgt printi have a scardnamesv1
i have a ace
gtgt;> v=13
>>> print("i have a %s"%cardnames[v-1])
i have a king
</code></pre>
<p>or using <code>python3</code>:</p>
<pre><code>$ python3
python 3.4.3 (default, mar 26 2015, 22:03:40)
[gcc 4.9.2] on linux
type "help", "copyright", "credits" or "license" for more information.
>>> cardnames = ["ace","2","3","4","5","6","7","8","9","10","jack","queen","king"]
>>> v=12
>>> print("i have a %s"%cardnames[v-1])
i have a queen
>>> v=7
>>> print("i have a %s"%cardnames[v-1])
i have a 7
>>> v=1
>>> print("i have a %s"%cardnames[v-1])
i have a ace
>>> v=13
>>> print("i have a %s"%cardnames[v-1])
i have a king
</code></pre>
| 2 |
stack of 2d plot | pthis can be done with the simple a hrefhttpmatplotlibsourceforgenetmpltoolkitsmplot3dtutorialhtmlmpltoolkitsmplot3daxes3dplot relnofollowplot commandap
precodefrom mpltoolkitsmplot3d import axes3d
import matplotlibpyplot as plt
import numpy as np
nangles 200
fig pltfigure
ax figaddsubplot111 projection3d
nvals 0 2 4 10 20 40 100
for iy in rangelennvals
n nvalsiy
x nparangenangles floatnangles
y nponesnanglesiy set y position to same value with regular step
z npsinnxnppi
axplotx y z
axsetylabeln
axsetyticklabelsnvals update y ticks set at regular step to your vals
pltsavefigstackedplotpng
pltshow
codepre
pwhat ive shown is a simple start and adjusting the cosmetic aspects of the plot is probably a good challenge to learnexplore more of pythonmatplotlibp
pimg srchttpistackimgurcomulzkhpng altenter image description herep
| 2 |
python mystery infinite loop | premember array indices start from 0 so ifp
precodea 0 4 0 3 2
codepre
pthen codea3 3codep
pso this linep
precodex ax
codepre
pnever sets codexcode to anything other than 3p
| 2 |
how do i import data with different types from file into a python numpy array | puse a hrefhttpdocsscipyorgdocnumpyreferencegeneratednumpygenfromtxthtmlcodenumpygenfromtxtcodeap
precodeimport numpy as np
npgenfromtxtfilename dtype none
array1 20 bucklemyshoe 3 40 margerydoor
dtypef0 lti4 f1 ltf8 f2 s14
codepre
| 2 |
how to use bulk api to store the keywords in es by using python | pthe current approaches mentioned here use python list for the es update its not a good solution today especially when you need to add millions of data to esp
pbetter approach is using python generators process gigs of data without going out of memory or compromising much on speedp
pbelow is an example snippet from a practical use case adding data from nginx log file to es for analysisp
precodedef decodenginxlognginxfd
for eachline in nginxfd
filter out the below from each log line
remoteaddr
timestamp
index for elasticsearch typically timestamp
idx
esfieldskeys remoteaddr timestamp url status
esfieldsvals remoteaddr timestamp url status
we return a dict holding values from each line
esnginxd dictzipesfieldskeys esfieldsvals
return the row on each iteration
yield idx esnginxd lt note the usage of yield
def esaddbulknginxfile
the nginx file can be gzip or just text open it appropriately
es elasticsearchhosts host localhost port 9200
note the round brackets this is for a generator
k
index nginx
type logs
id idx
source esnginxd
for idx esnginxd in decodenginxlognginxfd
helpersbulkes k
now just run it
esaddbulknginx1loggz
codepre
pthis skeleton demonstrates the usage of generators you can use this even on a bare machine if you need to and you can go on expanding on this to tailor to your needs quicklyp
ppython elasticsearch reference a hrefhttpelasticsearchpyreadthedocsioenmasterhelpershtml relnofollowhereap
| 2 |
functional way to create new list by processing elements of another list | blockquote
pwhat is the simplest way of creating one list from anotherp
blockquote
puse a a hrefhttpsdocspythonorg2tutorialdatastructureshtmllistcomprehensions relnofollowlist comprehensionap
precodeans myreadfunctionfilename for filename in filenames
codepre
| 2 |
slice specific characters in csv using python | pnumpy is great when you want to load in an array of numbers
the format you have here is too complicated for numpy to recognize so you just get an array of strings thats not really playing to numpys strengthp
pheres a simple way to do it without numpyp
precoderesult
with opencsvfiler as f
for line in f
row
for text in linesplitt
matchresearch0909text
if match
rowappendmatchgroup1
else
rowappendna
resultappendrow
printresult
codepre
pyieldsp
precode 00 01 00 na 01 00
codepre
pon this datap
precode002310379483756915 01341011124127519900 00741022328301819900
2310379483756915 01341011124127519900 00741022328301819900
codepre
| 2 |
how to search backwards in python | puse strrfind method to search for the occurence of a string in the reverse direction a hrefhttpstackoverflowcomquestions3537717pythonreversefindinstringthisa question should also give you some insight on how to go aboutp
| 2 |
storing username and password into a dictionary | pyou dont you save a hash into a dictionary a hash is simpley a non reversable encodingp
peg
codemd5password 5f4dcc3b5aa765d61d8327deb882cf99code p
phowever there is no real way to go from that back to the password p
pcodenothingdoesthis5f4dcc3b5aa765d61d8327deb882cf99 passwordcode p
pnot entirely true but close enough fo the conceptp
precodeimport hashlib
def createusers
users
while true
username rawinputenter username
password rawinputenter password
usersusername hashlibmd5passwordhexdigest
if rawinputcontinue0lower y
return users
def loginuserdict
username rawinputusername
password rawinputpassword
return userdictgetusernamenone hashlibmd5passwordhexdigest
users createusers
if loginusers
print double winning
else
print you lose sucka
codepre
pas pointed out md5 is not a very secure hash there are much better ones to use sha256 is pretty good still i think bcrypt is even better for some definition of better however md5 is a simple hash to help with understanding what they arep
| 2 |
how do i split words in python while keeping in consideration words with hyphens | pno need for a regexp
precodegtgtgt fatfree milksplit
fatfree milk
codepre
pif you want to split on any nonword character that is not a hyphen you can use a negated character group like in johns answer or a negative lookahead which might be slightly more flexiblep
precodegtgtgt resplitrw fatfree milk with cream
fatfree milk with cream
codepre
| 2 |
what is the elegantpythonic way to keep variables in scope yet also catch exceptions | pthe obvious alternative would be to do the false initialization in the codeexceptcode blockp
precodetry
proxytest isproxyworkingproxy
except timeouterror
proxytest none
codepre
pwhether this is easiermore appropriate than your constructions depends on how complicated the logic is in the middle thoughp
| 2 |
python looping to other functions using one function | pat the bottom where you call codegame1code add calls for codegame2code etcp
precodegame1
game2
game3
codepre
| 2 |
how to show chinese word not unicode word | pby default printing a larger builtin structure gives the codereprcode of each of the elements if you want the codestrcodecodeunicodecode instead then you need to iterate over the sequence yourselfp
precodea u u jointokentext for token in u
print a
codepre
| 2 |
find minimum window substring | passume that string s and t only contains codeazcode characters 26 charactersp
ul
lipfirst create an array codecountcode which store the frequency of each characters in codetcodepli
lipprocess each character in s maintaining a window codel rcode which will be the current minimum window that contains all characters in tpli
lipwe maintain an array codecurcode to store the current frequency of characters in window if the frequency of the character at the left end of the window is greater than needed frequency we increase codelcodepli
ul
psample codep
precode intcount new int26
forint i 0 i lt tlength i
countti a
int need 0number of unique characters in t
forint i 0 i lt 26 i
ifcounti gt 0
need
int l 0 r 0
int count 0
int result
intcur new int26
forint i 0 i lt slength i
cursi a
r i
ifcursi a countsi a
count
update the start of the window
whilecursl a gt countsl a
cursl a
l
ifcount need
result minresult r l 1
codepre
peach character in s will be processed at most two times which give us on complexity.</p>
| 2 |
how to get all keys from dictionary that specified values | pyou can do it like thisp
precodekey for key value in somedictitems if value 2
codepre
pthis uses a list comprehension to iterate through the pairs of codekey valuecode items selecting those keys whose value equals 2p
pnote that this requires a linear search through the dictionary so it is emonem if this performance is not acceptable you will probably need to create and maintain another data structure that indexes your dictionary by valuep
| 2 |
getting html stripped of script and style tags with beautifulsoup | pcodeunicode soup code gives you the htmlp
palso what you want is thisp
precodefor elem in soupfindallscript style
elemextract
codepre
| 2 |
import order coding standard | phave a look at a hrefhttpspypipythonorgpypiisort relnofollowhttpspypipythonorgpypiisorta or a hrefhttpsgithubcomtimothycrosleyisort relnofollowhttpsgithubcomtimothycrosleyisortap
blockquote
pisort parses specified files for global level import lines imports outside of try excepts blocks functions etc and puts them all at the top of the file grouped together by the type of importp
ul
lifuture li
lipython standard library li
lithird party li
licurrent python project li
liexplicitly local before import as in from import x li
ul
pcustom separate sections defined by forcedseparate list in configuration file
inside of each section the imports are sorted alphabetically isort automatically removes duplicate python imports and wraps long from imports to the specified line length defaults to 80p
blockquote
pa hrefhttpspypipythonorgpypiflake8isort relnofollowhttpspypipythonorgpypiflake8isorta plugs this functionality into flake8p
| 2 |
assign next n iterations to tuple | pyou can use codeitertoolsislicecode to select items from an iterable note that iterators are iterable but not every iterable is an iterator with a codenextcode or codenextcode in python3 methodp
precodegtgtgt from itertools import islice
gtgtgt iterator x for x in a b c d e
gtgtgt tupleisliceiterator 3
a b c
codepre
palternatively a simple comprehensionp
precodegtgtgt iterator x for x in a b c d e
gtgtgt tuplenextiterator for in range3
a b c
codepre
pthe name codecode has no special meaning for the interpreter outside of interactive sessions where it stores the result of the last executed statement but is noticed as the name for a throwawayvariable by python programmersp
| 2 |
how to automate my three bash scripts over several folders with files | pon linux use a a hrefhttpman7orglinuxmanpagesman5crontab5html relnofollowcrontab5a to schedule your various shell scripts they could run in parallelp
pyou might also look into a hrefhttpswwwgnuorgsoftwareparallel relnofollowgnu parallela but i guess you dont need itp
pat last a shell script could schedule another one using a hrefhttpwwwcomputerhopecomunixuathtm relnofollowata or codebatchcode for example codedecodeshcode might perhaps end with codebatch f sortshcode or codeat f sortsh now 10 minutescode p
pand you might use some more powerful scripting language eg python guile perl p
pbtw be sure to test success of every script and even parts inside them use a hrefhttpman7orglinuxmanpagesman1logger1html relnofollowlogger1a to emit log messages perhaps after every step or command which lasts more than half an a hour and at start and end of every script check daily the logsp
pat last i dont understand why only one database script can run at a time most real dbms postgresql mongodb mariadb etc but not sqlite can run or be configured to run several database clients concurrently accessing the same database or of course different ones read more about a hrefhttpsenwikipediaorgwikiacid relnofollowacida propertiesp
pdoing that on some external usb hard disk is imho a mistake because such hardware has limited reliability and is often slow you should consider having some server perhaps a good desktop might have such a role you might need an a hrefhttpsenwikipediaorgwikiuninterruptiblepowersupply relnofollowupsa to avoid power glitchesp
pif this complex processing and the processed data has some value to you you should upgrade both the hardware get a server machine possibly with an ups and a hrefhttpsenwikipediaorgwikieccmemory rel="nofollow">ecc ram</a> and, if the data fits, an <a href="https://en.wikipedia.org/wiki/solid-state_drive" rel="nofollow">ssd</a>) and the software (use real dbms, care for failure). estimate the cost of failure and/or data loss (remember to take into account your time). perhaps renting some cloud computing or storage could be interesting (or simply a <a href="https://en.wikipedia.org/wiki/virtual_private_server" rel="nofollow">vps</a> hosted linux system with backup, you can get one for about two dozens of dollars or euros every month: <a href="https://www.kimsufi.com/" rel="nofollow">kimsufi</a>, <a href="https://www.ovh.com/" rel="nofollow">ovh</a>, <a href="http://www.rackspace.com/" rel="nofollow">rackspace</a>, <a href="http://aws.amazon.com" rel="nofollow">aws</a>, ...)...</p>
| 2 |
singular matrix issue with numpy | pby definition by multiplying a 1d vector by its transpose youve created a singular matrixp
peach row is a linear combination of the first row p
pnotice that the second row is just 8x the first rowp
plikewise the third row is 50x the first rowp
ptheres only one independent row in your matrixp
| 2 |
outofcore training of scikits linearsvc classifier | pas far as i know nonincremental implementations like linearsvc would need the entire data set to train on unless you create an incremental version of it you might be unable to use linearsvcp
pthere are classifiers in scikitlearn that can be used incrementally just like in the guide you found wherein it was using an sgdclassifier the sgdclassifier has the partialfit method which allows you to train it in batches there are a couple of other classifiers that support incremental learning such as a hrefhttpscikitlearnorgstablemodulesgeneratedsklearnlinearmodelsgdclassifierhtml relnofollowsgdclassifiera a hrefhttpscikitlearnorgstablemodulesgeneratedsklearnnaivebayesmultinomialnbhtml relnofollowmultinomial naive bayesa and a hrefhttpscikitlearnorgstablemodulesgeneratedsklearnnaivebayesbernoullinbhtml relnofollowbernoulli naive bayesap
| 2 |
python34 on sublime text 3 | pyou need to provide the full path to python3 since sublime text does not read your codebashprofilecode file open up terminal type codewhich python3code and use that full pathp
precode
cmd pathtopython3 file
selector sourcepython
fileregex file line 09
codepre
| 2 |
matplotlib wont write approx latex character in legend | ptry using a raw string literal coderuc approx 01fcodep
precodein 8 pltscatter05 05 05 05 labelruc approx 01f22
out8 ltmatplotlibcollectionspathcollection at 0x7f799249e550gt
in 9 pltlegendfancyboxtrue locbest
out9 ltmatplotliblegendlegend at 0x7f79925e1550gt
in 10 pltshow
codepre
pimg srchttpistackimgurcomrd1okpng altenter image description herep
pthe reason this is happening is as follows p
ul
lipwithout the codercode infront of the string literal the string is interpreted by the interpreter as p
puc a pprox 220pli
lipthe codeacode is a special escaped character for the ascii bell codebelcodepli
lithis interpreted string is then passed to the tex parser however because codeapproxcode got mashed up the tex parser doesnt know how to convert your string to proper tex li
ul
pto make sure backslashes codecode in the string arent creating weird escaped characters add the codercode out frontp
| 2 |
getting a list of child entities in app engine using getbykeyname python | pjust create a key list and do a get on itp
precodeentities modelgetbykeynamekeynames
contentkeys dbkeyfrompathmodel name contentmodel name
for name in keynames
contententities contentmodelgetcontentkeys
codepre
pnote that i assume the keyname for each contentmodel entity is the same as its parent model for a 11 relationship it makes sense to reuse the keynamep
| 2 |
what language could i use for fast execution of this database summarization task | pyou could use smarter data structures and still use python
ive ran your reference implementation and my python implementation on my machine and even compared the output to be sure in resultsp
pthis is yoursp
precode time python refpy lt datalargetxt gt reflargetxt
real 1m57689s
user 1m56104s
sys 0m0573s
codepre
pthis is minep
precode time python mypy lt datalargetxt gt mylargetxt
real 1m35132s
user 1m34649s
sys 0m0261s
diff mylargetxt reflargetxt
echo
0
codepre
pand this is the sourcep
precodeusrbinpython
coding utf8
import sys
import heapq
top5
for line in sysstdin
aa bb cc linesplit
we want the top 5 for each distinct value of aa there are
hundreds of thousands of values of aa
bb floatbb
if aa not in top5 top5aa
current top5aa
if lencurrent lt 5
heapqheappushcurrent bb cc
else
if current0 lt bb cc
heapqheapreplacecurrent bb cc
for aa in top5
current top5aa
while lencurrent gt 0
bb cc heapqheappopcurrent
print aa bb cc
codepre
pstrongupdatestrong know your limits
ive also timed a noop code to know the fastest possible python solution with code similar to the originalp
precode time python nooppy lt datalargetxt gt nooplargetxt
real 1m20143s
user 1m19846s
sys 0m0267s
codepre
pand the nooppy itselfp
precodeusrbinpython
coding utf8
import sys
import heapq
top5
for line in sysstdin
aa bb cc = line.split()
bb = float(bb)
if aa not in top_5: top_5[aa] = []
current = top_5[aa]
if len(current) < 5:
current.append((bb, cc))
for aa in top_5:
current = top_5[aa]
current.sort()
for bb, cc in current[-5:]:
print aa, bb, cc
</code></pre>
| 2 |
humanize numbers with python | pthis library doesnt seem to support your particular use case but you could add the functionality by editing codenumberspycode lines 54 and 55 top
precodepowers 10 x for x in 3 6 9 12 15 18 21 24 27 30 33 100
humanpowers nthousand nmillion nbillion ntrillion nquadrillion
nquintillion nsextillion nseptillion
noctillion nnonillion ndecillion ngoogol
codepre
| 2 |
why unittest2 methods are camelcase if nameswithunderscores are prefered | pfrom a hrefhttpspypipythonorgpypiunittest2unittest2 websiteap
blockquote
punittest2 is a backport of the new features added to the unittest
testing framework in python 27 it is tested to run on python 24
27p
pto use unittest2 instead of unittest simply replace import unittest
with import unittest2p
blockquote
pits a bit confusing as from a version 2 is not expected to be a backport but a new major release with probably new features anyway the main idea is creating a backport where all the user has to do is changing the import statement for this they could not change their method signaturesp
palso from a hrefhttpdocspythonorg2libraryunittesthtmlunittest websiteap
blockquote
pthe python unit testing framework sometimes referred to as pyunit
is a python language version of junit by kent beck and erich gamma
junit is in turn a java version of kents smalltalk testing
framework each is the de facto standard unit testing framework for
its respective languagep
blockquote
pso this explains the whole resemblance between the frameworks and emprobablyem the camel case notationp
| 2 |
imported a python module why does a reassigning a member in it also affect an import elsewhere | ptest2pyp
precodeimport config as conf
def test2
printidconftestvar
printconftestvar
codepre
ptest1pyp
precodeimport config as conf
def test1
conftestvar test1
printidconftestvar
codepre
pchange code like this p
pand run codemainpycodep
precodeinitialvalue
140007892404912
test1
140007892404912
test1
codepre
pso you can see that in both cases you are changing value of the same variable see these codeidcodes are same p
| 2 |
pandas read excel do not parse numbers | paccording to a hrefhttpsgithubcompydatapandasissues5891 relnofollowthis issuea its a known problem with pandasp
| 2 |
print r correctly in console | pthis is because print always generates a new line whenever you use r or not try sysstdout insteadp
precodeimport time sys
for i in range101
sysstdoutwritestri r
sysstdoutflush
timesleep3
codepre
| 2 |
how to find element attribute using lxml | pyou need to retrieve the node itself not its textp
precoderating nodexpathtrating namespaces thttpexamplenamespace
print rating0attribsystem
codepre
| 2 |
dividing dataframe columns and getting zerodivisionerror float division by zero | pyou can initially set all values to zero then create a mask locating all rows with a valid denominator ie where codepowercode is greater than zero codegt0code finally use the mask together with codeloccode to calculate codesecondsteppowercodep
precodedfsecondsteppower 0
mask dfaveragepowergt0
dflocmask secondsteppower
dflocmask firstpower dflocmask averagepower
codepre
| 2 |
create a slightly modified copy of a python tuple | pi would be inclined to use a a hrefhttpsdocspythonorg2librarycollectionshtmlcollectionsnamedtuple relnofollowcodenamedtuplecodea instead and use the a hrefhttpsdocspythonorg2librarycollectionshtmlcollectionssomenamedtuplereplace relnofollowcodereplacecode methodap
precodegtgtgt from collections import namedtuple
gtgtgt test namedtupletest foo bar baz
gtgtgt t1 test1 2 3
gtgtgt t1
testfoo1 bar2 baz3
gtgtgt t2 t1replacebart1bar1
gtgtgt t2
testfoo1 bar3 baz3
codepre
pthis also gives semantic meaning to the individual elements in the tuple ie you refer to codebarcode rather than just the code1codeth elementp
| 2 |
how do you retrieve items from a dictionary in the order that theyre inserted | pive used stabledict before with good successp
pa hrefhttppypipythonorgpypistabledict02 relnofollowhttppypipythonorgpypistabledict02ap
| 2 |
pythondetect if the current line in file read is the last one | precodeimport os
path myfiletxt
size ospathgetsizepath
with openpath as f
for line in f
size lenline
if not size
printthis is the last line
printline
codepre
| 2 |
python script to convert from numbers to words for printing cheques | phave written a custom converter with the foll featuresp
ul
linumber to word converter that can be used for numbers from 0 to 999999999
catering to indian subcontinent ie lacs and crore the range is big
enough to accomodate lot of use casesli
liincludes paisa support upto 2 decimal places roundedli
liinspired by the post at a hrefhttpwwwblogpythonlibraryorg20101021pythonconvertingnumberstowords relnofollowhttpwwwblogpythonlibraryorg20101021pythonconvertingnumberstowordsali
lipprofiling information this script has lesser performace in terms of execution time of 0458 seconds against 0237 seconds of the above script for exactly 10000 runsp
precodeclass number2wordsobject
def initself
initialise the class with useful data
selfwordsdict 1 one 2 two 3 three 4 four 5 five 6 six 7 seven
8 eight 9 nine 10 ten 11 eleven 12 twelve 13 thirteen
14 fourteen 15 fifteen 16 sixteen 17 seventeen
18 eighteen 19 nineteen 20 twenty 30 thirty 40 forty
50 fifty 60 sixty 70 seventy 80 eighty 90 ninty
selfpowernamelist thousand lac crore
def convertnumbertowordsself number
check if there is decimal in the number if yes process them as paisa part
formstring strnumber
if formstringfind 1
withoutdecimal decimalpart formstringsplit
paisapart strroundfloatformstring 2)).split('.')[1]
inpaisa = self._formulatedoubledigitwords(paisapart)
formstring, formnumber = str(withoutdecimal), int(withoutdecimal)
else:
# process the number part without decimal separately
formnumber = int(number)
inpaisa = none
if not formnumber:
return 'zero'
self._validatenumber(formstring, formnumber)
inrupees = self._convertnumbertowords(formstring)
if inpaisa:
return 'rs. %s and %s paisa' % (inrupees.title(), inpaisa.title())
else:
return 'rs. %s' % inrupees.title()
def _validatenumber(self, formstring, formnumber):
assert formstring.isdigit()
# developed to provide words upto 999999999
if formnumber > 999999999 or formnumber < 0:
raise assertionerror('out of range')
def _convertnumbertowords(self, formstring):
msbs, hundredthplace, teens = self._getgroupofnumbers(formstring)
wordslist = self._convertgroupstowords(msbs, hundredthplace, teens)
return ' '.join(wordslist)
def _getgroupofnumbers(self, formstring):
hundredthplace, teens = formstring[-3:-2], formstring[-2:]
msbunformattedlist = list(formstring[:-3])
#---------------------------------------------------------------------#
msbs = []
tempstr = ''
for num in msbunformattedlist[::-1]:
tempstr = '%s%s' % (num, tempstr)
if len(tempstr) == 2:
msbs.insert(0, tempstr)
tempstr = ''
if tempstr:
msbs.insert(0, tempstr)
#---------------------------------------------------------------------#
return msbs, hundredthplace, teens
def _convertgroupstowords(self, msbs, hundredthplace, teens):
wordlist = []
#---------------------------------------------------------------------#
if teens:
teens = int(teens)
tensunitsinwords = self._formulatedoubledigitwords(teens)
if tensunitsinwords:
wordlist.insert(0, tensunitsinwords)
#---------------------------------------------------------------------#
if hundredthplace:
hundredthplace = int(hundredthplace)
if not hundredthplace:
# might be zero. ignore.
pass
else:
hundredsinwords = '%s hundred' % self.wordsdict[hundredthplace]
wordlist.insert(0, hundredsinwords)
#---------------------------------------------------------------------#
if msbs:
msbs.reverse()
for idx, item in enumerate(msbs):
inwords = self._formulatedoubledigitwords(item)
if inwords:
inwordswithdenomination = '%s %s' % (inwords, self.powernamelist[idx])
wordlist.insert(0, inwordswithdenomination)
#---------------------------------------------------------------------#
return wordlist
def _formulatedoubledigitwords(self, doubledigit):
if not int(doubledigit):
# might be zero. ignore.
return none
elif self.wordsdict.has_key(int(doubledigit)):
# global dict has the key for this number
tensinwords = self.wordsdict[int(doubledigit)]
return tensinwords
else:
doubledigitstr = str(doubledigit)
tens, units = int(doubledigitstr[0])*10, int(doubledigitstr[1])
tensunitsinwords = '%s %s' % (self.wordsdict[tens], self.wordsdict[units])
return tensunitsinwords
if __name__ == '__main__':
wgenerator = number2words()
print wgenerator.convertnumbertowords(100000)
</code></pre></li>
</ul>
| 2 |
python nameerror self is not defined | pjust in case someone happens upon this and is looking for a solution not having to do with indentation this is a good reference for how when to use codeselfcodep
pa hrefhttpstackoverflowcomquestions1802971nameerrornameselfisnotdefinednameerror name 39self39 is not definedap
| 2 |
wrong output when adding list to dict | pyoure always appending to the same list thus all the dictionary values end up pointing to the same list you want to append to a different list each timep
precoded
a numpyarray6 12 18 24 30
for monthstomaturity in a
l
for i in range6 354 6
if i lt monthstomaturity
lappendmonthstomaturity i
else
lappend0
dmonthstomaturity l
codepre
| 2 |
more efficient way split quoted string by space with python | pthis looks a bit like csv i wonder if the csv module can be abused into working with thisp
precodegtgtgt for row in csvreaderline delimiter
print reprrow
0278 0264 11311652174 101034120080 08apr2012235908 0800 shenzhenanjukecom get ajaxpropextproid104178677ampcommid97047ampbrokerid262646amprand0905798233768953 http10 200 10914 httpshenzhenanjukecompropview104178677 mozilla40 compatible msie 60 windows nt 51 sv1 360se 11480230198 026af756c5df3edab96af31a39f7c65e
codepre
| 2 |
organising my python project | ppython doesnt force you into javas nasty oneclassperfile style in fact its not even considered good style to put each class in a separate file unless they are huge if they are huge you probably have to do refactoring anyway instead you should group similar classes and functions in modules for example if you are writing a gui calculator your package layout might look like thisp
precodeamazingcalc
initpy this makes it a python package and importable
evaluatepy contains the code to actually do calculations
mainpy starts the application
uipy contains the code to make a pretty interface
codepre
| 2 |
appengine can i fetch an internal url | pthis will not work at all with the development server it is singlethreaded so trying to load one of your apps urls while inside one of its request handlers will hang until the urlfetch times outp
pit should work with no problems at all in productionp
pto get around the development server limitation you should run two instances on different portsp
| 2 |
antlr4 and the python target | pi hear you having the same issues right now the python documentation for v4 is useless and v3 differs to much to be usable im thinking about switching back to java to implement my stuffp
pregarding your code i think your own custom listener has to inherit from the generated hellolistener you can do the printing therep
palso try parsing invalid input to see if the parser starts at all im not sure about the line with getattrparser rulename though i followed the steps in the unfortunately very short documentation for the antlr4 python target a hrefhttpstheantlrguyatlassiannetwikidisplayantlr4pythontarget relnofollowhttpstheantlrguyatlassiannetwikidisplayantlr4pythontargetap
pyou can also find some documentation about the listener stuff there hope it helpsp
| 2 |
why does my code work from interactive shell but not when run from a file | pyou named your program pprintpy so at the line codeimport pprintcode it tries to import itself it succeeds but emyourem pprintpy doesnt contain anything called prettyprinterp
pchange your codes name and to be clear delete any pprintpyc or pprintpyo filesp
| 2 |
numpy find first index of value fast | pin case of sorted arrays codenpsearchsortedcode worksp
| 2 |
pep 8 why no spaces around in keyword argument or a default parameter value | pimo leaving out the spaces for args provides cleaner visual grouping of the argvalue pairs it looks less clutteredp
| 2 |
how to use variables in sql statement in python | precodecursorexecuteinsert into table values s s s var1 var2 var3
codepre
pnote that the parameters are passed as a tuplep
pthe database api does proper escaping and quoting of variables be careful not to use the string formatting operator codecode becausep
ol
liit does not do any escaping or quotingli
liit is prone to uncontrolled string format attacks eg a hrefhttpenwikipediaorgwikisqlinjectionsql injectionali
ol
| 2 |
xarraydatasetwhere method forcechanges dtype of dataarrays to float | pthats because with numpy which xarray uses underthehood ints dont have a way of representing codenancodes so with most codewherecode results the type needs to be coerced to floatsp
pif codedroptruecode and every value that is masked is dropped thats not actually a constraint you could have the new array retain its dtype because theres no need for codenancode values thats not in xarray at the moment but could be an additional featurep
| 2 |
python fill hollow object | pif you use a hrefhttpwwwscipyorg relnofollowcodescipycodea you can do this in one line with a hrefhttpdocsscipyorgdocscipyreferencegeneratedscipyndimagemorphologybinaryfillholeshtmlscipyndimagemorphologybinaryfillholes relnofollowcodebinaryfillholescodea strongand this works in ndimensionsstrong with your examplep
precodeimport numpy as np
from scipy import ndimage
shapenparray
000000000000
000111111000
001100011100
000100100000
001000010000
001000010000
001111110000
000000000000
shapendimagebinaryfillholesshape 1
output
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 1 1 1 1 1 1 0 0 0
0 0 1 1 1 1 1 1 1 1 0 0
0 0 0 1 1 1 1 0 0 0 0 0
0 0 1 1 1 1 1 1 0 0 0 0
0 0 1 1 1 1 1 1 0 0 0 0
0 0 1 1 1 1 1 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
codepre
| 2 |
typeerror unbound method when trying to mock a classmethod | ppython functions are a hrefhttpsdocspythonorg2howtodescriptorhtml relnofollowdescriptorsa and python binds these to the instance they are looked up on or in the case of codeclassmethodcode to the class because you didnt use the codeclassmethodcode decorator on the replacement function it is being bound wrongly as a regular method instead so no codeclscode is being passed inp
psimply wrap the target in a codeclassmethodcode decorator manuallyp
precodewith mockpatchobjectmyclass mymethod classmethodmockedmethod
myclassmymethod
codepre
phere i applied the codeclassmethodcode decorator manually but you could also just use it as intended as a decorator directly on the target functionp
precodeclassmethod
def mockedmethodcls
printi want this method to get called
with mockpatchobjectmyclass mymethod mockedmethod
myclassmymethod
codepre
pdemop
precodegtgtgt import mock
gtgtgt class myclassobject
classmethod
def mymethodcls
printmymethod
gtgtgt def mockedmethodcls
printi want this method to get called
gtgtgt with mockpatchobjectmyclass mymethod classmethodmockedmethod
myclassmymethod
i want this method to get called
codepre
| 2 |
how to make a function print many times on the same line eg printtest3 | pyou can change your code to this onep
precodedef myprinttimes
printtimesfoobar
foo randomrandint1 6
myprintfoo
codepre
| 2 |
python postgres can i fetchall 1 million rows | pthe solution burhan pointed out reduces the memory usage for large datasets by only fetching single rowsp
blockquote
prow cursorfetchonep
blockquote
phowever i noticed a significant slowdown in fetching rows onebyone i access an external database over an internet connection that might be a reason for itp
phaving a server side cursor and fetching bunches of rows proved to be the most performant solution you can change the sql statements as in alecxe answers but there is also pure python approach using the feature provided by psycopg2p
precodecursor conncursornameofthenewserversidecursor
cursorexecute select from table limit 1000000
while true
rows cursorfetchmany5000
if not rows
break
for row in rows
do something with row
pass
codepre
pyou find more about server side cursors in the a hrefhttpwikipostgresqlorgwikiusingpsycopg2withpostgresqlfetchrecordsusingaserversidecursor relnofollowpsycopg2 wikiap
| 2 |
using requests with tls doesnt give sni support | plukasa answer is correct with the present from github requests remember to add openssl in your system too apart from the pip dependencies he mentionsp
pif for deployment reasons you prefer a stable requests version like the 123 in pip you can monkey patch that one to work with sni like thisp
precodeimport requests
def filenoself
return selfsocketfileno
def closeself
return selfconnectionshutdown
requestspyopensslwrappedsocketclose close
requestspyopensslwrappedsocketfileno fileno
codepre
| 2 |
how do i find the time difference between two datetime objects in python | pjust subtract one from the other you get a codetimedeltacode object with the differencep
precodegtgtgt import datetime
gtgtgt d1 datetimedatetimenow
gtgtgt d2 datetimedatetimenow after a 5second or so pause
gtgtgt d2 d1
datetimetimedelta0 5 203000
codepre
pyou can convert codedddayscode codeddsecondscode and codeddmicrosecondscode to minutesp
| 2 |
what is the best data structure for storing a set of four or more values | pthere isnt a single data structure built into python that does everything you want but its fairly easy to use a combination of the ones it has to achieve your goals and do so fairly efficientlyp
pfor example say your input was the following data in a commaseparatedvalue file called codeemployeescsvcode with field names defined as shown by the first linep
pre classlangnone prettyprintoverridecodenameageweightheight
bob barker251756ft 2in
ted kingston281635ft 10in
mary manson271405ft 6in
sue sommers271325ft 8in
alice toklas241245ft 6in
codepre
pthe following is working code which illustrates how to read and store this data into a list of records and automatically create separate lookup tables for finding records associated with the values of contained in the fields each of these recordp
pthe records are instances of a class created by codenamedtuplecode which is a very memory efficient because each one lacks a codedictcode attribute that class instances normally contain using them will make it possible to access the fields of each by name using dot syntax like coderecordfieldnamecodep
pthe lookup tables are codedefaultdictlistcode instances which provide dictionarylike o1 lookup times on average and also allow multiple values to be associated with each one so the lookup key is the value of the field value being sought and the data associated with it will be a list of the integer indices of the codepersoncode records stored in the codeemployeescode list with that value so theyll all be relatively smallp
pnote that the code for the class is completely datadriven in that it doesnt contain any hardcoded field names which instead are all taken from the first row of csv data input file when its read in when an instance is used any actual coderetrievecode method calls must of course contain valid field name keyword argumentsp
pstrongupdatestrongp
pmodified to not create a lookup table for every unique value of every field when the data file is first read now the coderetrievecode method creates them only as needed and savescaches the result for future usep
precodefrom collections import defaultdict namedtuple
import csv
class databaseobject
def initself csvfilename recordname
read data from csv format file into a list of namedtuples
with opencsvfilename rb as inputfile
csvreader csvreaderinputfile delimiter
selffields csvreadernext read header row
selfrecord namedtuplerecordname selffields
selfrecords selfrecordrow for row in csvreader
selfvalidfieldnames setselffields
create an empty table of lookup tables for each field name that maps
each unique field value to a list of recordlist indices of the ones
that contain it
selflookuptables defaultdictlambda defaultdictlist
def retrieveself kwargs
""" fetch a list of records with a field name with the value supplied
as a keyword arg (or return none if there aren't any). """
if len(kwargs) != 1: raise valueerror(
'exactly one fieldname/keyword argument required for function '
'(%s specified)' % ', '.join([repr(k) for k in kwargs.keys()]))
field, value = kwargs.items()[0] # get only keyword arg and value
if field not in self.valid_fieldnames:
raise valueerror('keyword arg "%s" isn\'t a valid field name' % field)
if field not in self.lookup_tables: # must create field look up table
for index, record in enumerate(self.records):
value = getattr(record, field)
self.lookup_tables[field][value].append(index)
matches = [self.records[index]
for index in self.lookup_tables[field].get(value, [])]
return matches if matches else none
if __name__ == '__main__':
empdb = database('employees.csv', 'person')
print "retrieve(name='ted kingston'):", empdb.retrieve(name='ted kingston')
print "retrieve(age='27'):", empdb.retrieve(age='27')
print "retrieve(weight='150'):", empdb.retrieve(weight='150')
try:
print "retrieve(hight='5ft 6in'):", empdb.retrieve(hight='5ft 6in')
except valueerror as e:
print "valueerror('{}') raised as expected".format(e)
else:
raise type('noexceptionerror', (exception,), {})(
'no exception raised from "retrieve(hight=\'5ft\')" call.')
</code></pre>
<p>output:</p>
<pre class="lang-none prettyprint-override"><code>retrieve(name='ted kingston'): [person(name='ted kingston', age='28', weight='163', height='5ft 10in')]
retrieve(age='27'): [person(name='mary manson', age='27', weight='140', height='5ft 6in'),
person(name='sue sommers', age='27', weight='132', height='5ft 8in')]
retrieve(weight='150'): none
retrieve(hight='5ft 6in'): valueerror('keyword arg "hight" is an invalid fieldname')
raised as expected
</code></pre>
| 2 |
how can i obtain the models name or the content type of a django object | pyou can get the model name from the object like thisp
precodeselfclassname
codepre
pif you prefer the content type you should be able to get that like thisp
precodecontenttypeobjectsgetformodelself
codepre
| 2 |
using pythons list index method on a list of tuples or objects | pyou can do this with a list comprehension and indexp
precodetuplelist pineapple 5 cherry 7 kumquat 3 plum 11
x0 for x in tuplelistindexkumquat
2
x1 for x in tuplelistindex7
1
codepre
| 2 |
reading from database with sqlite and python incorrect number of binding supplied | pyou must supply a sequence of values for the binding codeidcode is a string so it looks like a sequence of 8 values p
pyoure probably thinking that codeidcode should be a tuple with one element but it isnt parenthesis arent the tuplemaking syntax in python except for the empty tuple commas are use codeidcode instead to get a tuple with one element alternatively use a list codeidcodep
| 2 |
print range of numbers on same line | pcodestrjoincode would be appropriate in this casep
precodegtgtgt print joinstrx for x in xrange111
1 2 3 4 5 6 7 8 9 10
codepre
| 2 |
is there any pythonic way to combine two dicts adding values for keys that appear in both | pa more generic solution which works for nonnumeric values as wellp
precodea a foo bbar c baz
b a spam cham x blah
r dictaitems bitems
k ak bk for k in setb amp seta
codepre
por even more genericp
precodedef combinedictsa b opoperatoradd
return dictaitems bitems
k opak bk for k in setb amp seta
codepre
pfor examplep
precodegtgtgt a a 2 b3 c4
gtgtgt b a 5 c6 x7
gtgtgt import operator
gtgtgt print combinedictsa b operatormul
a 10 x 7 c 24 b 3
codepre
| 2 |
tee does not show output or write to file | pheres a simpler way of reproducing your issuep
precode cat foopy
from time import sleep
while true
sleep2
print hello
python foopy
hello
hello
python foopy tee log
no output
codepre
pthis happens because codepythoncode buffers stdout when its not a terminal the easiest way to unbuffer it is to use codepython ucodep
precode python u foopy tee log
hello
hello
codepre
pyou can also set the shebang to codeusrbinpython ucode this does not work with codeenvcodep
| 2 |
plotting curved line in python basemap | pthis is a very old question but i thought it might be good to answer anyway when you said curved lines i assumed you meant drawing a a hrefhttpenwikipediaorgwikigreatcircle relnofollowgreat circlea there is an example of doing exactly that in the a hrefhttpmatplotlibgithubcombasemapusersexampleshtml relnofollowbasemap documentationa which i have modified to make a little more easy to modify yourselfp
precodefrom mpltoolkitsbasemap import basemap
import numpy as np
import matplotlibpyplot as plt
m basemapprojectioncyl
p0ll 7398 4078
p1ll 008 5153
mdrawgreatcirclep0ll0 p0ll1 p1ll0 p1ll1
linewidth2 colorb
mdrawcoastlines
mfillcontinents
pltshow
codepre
pimg srchttpistackimgurcomecvvypng altenter image description herep
pnote that the great circle method cannot handle the crossing of the edges of the map a hrefhttpmatplotlibgithubcombasemapapibasemapapihtmlmpltoolkitsbasemapbasemapdrawgreatcircle relnofollowas mentioned in the documentationa which although clearly documented is a pretty major flaw imho p
phope that helps somebodyp
| 2 |
python if not statement with 00 | psince you are using codenonecode to signal this parameter is not set then that is exactly what you should check for using the codeiscode keywordp
precodedef squarexnone
if x is none
print you have not entered x
else
yx2
return y
codepre
pchecking for type is cumbersome and error prone since you would have to check for emall possible input typesem not just codeintcodep
| 2 |
object class override or modify | pno pythons internals take great care to make builtin types not mutable very different design choices from rubys its not possible to make object monkeypatchable without deeply messing with the ccoded internals and recompiling the python runtime to make a very different version this is for the classic cpython but i believe exactly the same principle holds for other good implementations such as jython and ironpython just scjava and scc respectivelyp
| 2 |
moon lunar phase algorithm | pif youre like me you try to be a careful programmer so it makes you nervous when you see random code scattered across the internet that purports to solve a complex astronomical problem but doesnt explain why the solution is correctp
pyou believe that there must be authoritative sources such as embooksem which contain careful and complete solutions for instancep
blockquote
pmeeus jean astronomical algorithms richmond willmannbell 1991 isbn 0943396352p
pduffettsmith peter practical astronomy with your calculator 3rd ed cambridge
cambridge university press 1981 isbn 0521284112p
blockquote
pyou place your trust in widelyused welltested open source libraries which can have their errors corrected unlike static web pages here then is a python solution to your question based on the a hrefhttprhodesmillorgpyephempyephema library using the a hrefhttprhodesmillorgpyephemquickhtmlphasesofthemoonphases of the moona interfacep
precodeusrbinpython
import datetime
import ephem
def getphaseondayyearmonthday
returns a floatingpoint number from 01 where 0new 05full 1new
ephem stores its date numbers as floating points which the following uses
to conveniently extract the percent time between one new moon and the next
this corresponds somewhat roughly to the phase of the moon
use year month day as arguments
dateephemdatedatetimedateyearmonthday
nnm ephemnextnewmoon date
pnm ephempreviousnewmoondate
lunationdatepnmnnmpnm
note that there is a ephemmoonphase command but this returns the
percentage of the moon which is illuminated this is not really what we want
return lunation
def getmoonsinyearyear
returns a list of the full and new moons in a year the list contains tuples
of either the form datefull or the form datenew
moons
dateephemdatedatetimedateyear0101
while datedatetimeyearyear
dateephemnextfullmoondate
moonsappend datefull
dateephemdatedatetimedateyear0101
while date.datetime().year==year:
date=ephem.next_new_moon(date)
moons.append( (date,'new') )
#note that previous_first_quarter_moon() and previous_last_quarter_moon()
#are also methods
moons.sort(key=lambda x: x[0])
return moons
print get_phase_on_day(2013,1,1)
print get_moons_in_year(2013)
</code></pre>
<p>this returns</p>
<pre><code>0.632652265318
[(2013/1/11 19:43:37, 'new'), (2013/1/27 04:38:22, 'full'), (2013/2/10 07:20:06, 'new'), (2013/2/25 20:26:03, 'full'), (2013/3/11 19:51:00, 'new'), (2013/3/27 09:27:18, 'full'), (2013/4/10 09:35:17, 'new'), (2013/4/25 19:57:06, 'full'), (2013/5/10 00:28:22, 'new'), (2013/5/25 04:24:55, 'full'), (2013/6/8 15:56:19, 'new'), (2013/6/23 11:32:15, 'full'), (2013/7/8 07:14:16, 'new'), (2013/7/22 18:15:31, 'full'), (2013/8/6 21:50:40, 'new'), (2013/8/21 01:44:35, 'full'), (2013/9/5 11:36:07, 'new'), (2013/9/19 11:12:49, 'full'), (2013/10/5 00:34:31, 'new'), (2013/10/18 23:37:39, 'full'), (2013/11/3 12:49:57, 'new'), (2013/11/17 15:15:44, 'full'), (2013/12/3 00:22:22, 'new'), (2013/12/17 09:28:05, 'full'), (2014/1/1 11:14:10, 'new'), (2014/1/16 04:52:10, 'full')]
</code></pre>
| 2 |
queryset in view or in template | pif codeprofilegetsomestuffcode is an expensive operation and you call it multiple times in the template and yes you should call that in the view once and pass the result to the template via codecontextcodep
precodedef viewrequest
stuff requestuserprofilegetsomestuff
return renderrequest pagehtml stuff stuff
codepre
palternatively you can use a hrefhttpsdocsdjangoprojectcomen18reftemplatesbuiltinswith relnofollowcode with codea tag to create a scope containing the value in its own contextp
precode with stuffuserprofilegetsomestuff
stuffinfo
stuffotherinfo
do some other things with stuff
endwith
codepre
ppersonally i would go with the first option because with the help of codedjangodbconnectionqueriescode it is relatively easier to monitor db queries you make in the view make sure you avoid sending template querysets lazy expressions etc as much as possiblep
pbtw please note that codedebugcode must be set to codetruecode for codeconnectionqueriescode to workp
| 2 |
installing python imaging libary pil on ubuntu | pi had to install pythondev then install pil inside my virtualenvp
pall working nowp
pthanks for your help all p
| 2 |
pyside pyqt mainwindow or central widget access from deeply nested widgets | pyou can always get to the current application instance via codepysideqtcoreqcoreapplicationinstancecode in c the global codeqappcode variable provides the same functionalityp
pso whether you set python attributes or qt properties on the global application instance you can always get to it without having to go through any hierarchiesp
| 2 |
python regex how to match a string at the end of a line in a file | pyou need to use coderesearchcode function since match tries to match the string from the beginningp
precodevar1 network1
printresearchrs var1 r linegroup1
codepre
pstrongexamplestrongp
precodegtgtgt import re
gtgtgt s foo network1 network1
gtgtgt var1 network1
gtgtgt printresearchrs var1 r sgroup1
network1
gtgtgt printresearchrs var1 r sgroup1 to check whether it fetches the last string or not
1 network1
codepre
pso you should do likep
precodewith openfile as f
for line in f
if var1 in line
printresearchrs var1 r sgroup1
codepre
| 2 |
getting pyside to work with matplotlib | pi had similar goals lgpl potential commercial use and heres how i ended up getting it to workp
pcreate a matplotlib widget see a hrefhttpcodegooglecomppythonxysourcebrowsesrcpythonmatplotlibqtdesignerpluginsmatplotlibwidgetpyr640d80c9867ba5f00cd0734c87da0ebd938b5d76herea for a more detailed one for pyqtp
precodeimport matplotlib
matplotlibuseqt4agg
matplotlibrcparamsbackendqt4pyside
from matplotlibfigure import figure
from matplotlibbackendsbackendqt4agg import figurecanvasqtagg as figurecanvas
class matplotlibwidgetfigurecanvas
def initself parentnonexlabelxylabelytitletitle
supermatplotlibwidget selfinitfigure
selfsetparentparent
selffigure figure
selfcanvas figurecanvasselffigure
selfaxes selffigureaddsubplot111
selfaxessetxlabelxlabel
selfaxessetylabelylabel
selfaxessettitletitle
codepre
pin qt designer i created a blank widget to hold my plot and then when i codeinitcode the main window i call setupplotp
precodedef setupplotself
create a matplotlib widget
selfdataplot matplotlibwidget
create a layout inside the blank widget and add the matplotlib widget
layout qtguiqvboxlayoutselfuiwidgetplotarea
layoutaddwidgetselfdataplot1
codepre
pthen i call plotdatapoints as neededp
precodedef plotdatapointsselfxy
selfdataplotaxesclear
selfdataplotaxesplotxybo
selfdataplotdraw
codepre
pnote this clears and redraws the entire plot every time since the shape of my data keeps changing and so isnt fastp
| 2 |
how to print a string of variables without spaces in python minimal coding | ptry using codejoincodep
precodeprint njoinidvar1var2var3var4
codepre
por if the variables arent already stringsp
precodeprint njoinmapstridvar1var2var3var4
codepre
pthe benefit of this approach is that you dont have to build a long format string and it basically works unchanged for an arbitrary number of variablesp
| 2 |
calling an overridden method from base class | pyes youre missing thisp
precodebbar echoes bfoo
codepre
pcodebcode has no codebarcode method of its own just the one inherited from codeacode codeacodes codebarcode calls codeselffoocode but in an instance of codebcode ends up calling codebcodes codefoocode and not codeacodes codefoocodep
plets look at your quote againp
blockquote
pa method of a base class that calls
another method defined in the same
base class may in fact end up calling
a method of a derived class that
overrides itp
blockquote
pto translate p
blockquote
pcodebarcode method of codeacode the base class
calls codeselffoocode but may in fact end up
calling a method of the derived class
that overrides it codebfoocode that
overrides codeafoocodep
blockquote
| 2 |
python json encoding | pi think you are simply exchanging emdumpsem and emloadsem p
precodegtgtgt import json
gtgtgt data apple cat banana dog pear fish
codepre
pthe first returns as a json encoded string its data argumentp
precodegtgtgt encodedstr jsondumps data
gtgtgt encodedstr
apple cat banana dog pear fish
codepre
pthe second does the opposite returning the data corresponding to its json encoded string argumentp
precodegtgtgt decodeddata jsonloads encodedstr
gtgtgt decodeddata
uapple ucat ubanana udog upear ufish
gtgtgt decodeddata data
true
codepre
| 2 |
should i make my python code less foolproof to improve readability | pyour code is too emparanoidem especially when you want to protect only against yourselfp
pin python circles lbyl is generally but not always frowned upon strongbutstrong theres also the often unstated assumption that one has good unit testsp
pme personally i think readability is of paramount importance i mean if you emyourselfem think its hard to read what will others think and less readable code is also more likely to catch bugs not to mention making working on it hardermore time consuming you have to dig to find what the code actually emdoesem in all that lbylingp
| 2 |
deleting multiple elements from a list | pim a total beginner in python and my programming at the moment is crude and dirty to say the least but my solution was to use a combination of the basic commands i learnt in early tutorialsp
precodesomelist 1234567810
rem 057
for i in rem
somelisti mark for deletion
for i in range0somelistcount
somelistremove remove
print somelist
codepre
pobviously because of having to choose a markfordeletion character this has its limitations p
pas for the performance as the size of the list scales im sure that my solution is suboptimal however its straightforward which i hope appeals to other beginners and will work in simple cases where somelist is of a wellknown format eg always numericp
| 2 |
how do i pass a method as a parameter in python | pyes functions and methods are first class objects in python the following worksp
precodedef foof
print running parameter f
f
def bar
print in bar
foobar
codepre
poutputsp
precoderunning parameter f
in bar
codepre
pthese sorts of questions are trivial to answer using the python interpreter or for more features the a hrefhttpipythonscipyorgmoin relnofollowipythona shellp
| 2 |
how to map f4 run a no name file on vim | phow about using codew cmdcode this does not require you to save before run the commandp
precodemap ltf4gt w pythonltcrgt
codepre
paccording to vim codehelp wccodep
blockquote
pcoderangewrite opt cmdcodep
precode execute cmd with range lines as standard input
note the space in front of the cmd is
executed like with cmd any is replaced with
the previous command
codepre
blockquote
pstrongnotestrong this will not work as expected if the python program itself use filename for example codefilecode will yield codeltstdingtcodep
| 2 |
python operator | pcodegtgtcode and codeltltcode are the strongrightshiftstrong and strongleftshiftstrong bitoperators ie they alter the binary representation of the number it can be used on other data structures as well but python doesnt implement that they are defined for a class by codershiftself shiftcode and codelshiftself shiftcodep
pstrongexamplestrongp
precodegtgtgt bin10 10 in binary
1010
gtgtgt 10 gtgt 1 shifting all the bits to the right and discarding the rightmost one
5
gtgtgt bin 5 in binary you can see the transformation clearly now
0101
gtgtgt 10 gtgt 2 shifting all the bits right by two and discarding the tworightmost ones
2
gtgtgt bin
0010
codepre
pstrongshortcutstrong just to perform an integer division ie discard the remainder in python youd implement it as codecode on a number by 2 raised to the number of bits you were shiftingp
precodegtgtgt def rshiftno shift 1
return no 2shift
this func will now be equivalent to gtgt operator
codepre
| 2 |
getting deprecation warning in sklearn over 1d array despite not having a 1d array | pthe error is coming from the predict method numpy will interpret 11 as a 1d array so this should avoid the warningp
pcodeclfpredictnparray11codep
pnotice thatp
precodein 14 p1 nparray11
in 15 p1shape
out15 2
in 16 p2 nparray11
in 17 p2shape
out17 1 2
codepre
palso note that you cant use an array of shape 21p
precodein 21 p3 nparray11
in 22 p3shape
out22 2 1
in 23 clfpredictp3
valueerror traceback most recent call last
ltipythoninput23e4070c037d78gt in ltmodulegt
gt 1 clfpredictp3
homejuananaconda3libpython35sitepackagessklearnsvmbasepy in predictself x
566 class labels for samples in x
567
gt 568 y superbasesvc, self).predict(x)
569 return self.classes_.take(np.asarray(y, dtype=np.intp))
570
/home/juan/anaconda3/lib/python3.5/site-packages/sklearn/svm/base.py in predict(self, x)
303 y_pred : array, shape (n_samples,)
304 """
--> 305 x = self._validate_for_predict(x)
306 predict = self._sparse_predict if self._sparse else self._dense_predict
307 return predict(x)
/home/juan/anaconda3/lib/python3.5/site-packages/sklearn/svm/base.py in _validate_for_predict(self, x)
472 raise valueerror("x.shape[1] = %d should be equal to %d, "
473 "the number of features at training time" %
--> 474 (n_features, self.shape_fit_[1]))
475 return x
476
valueerror: x.shape[1] = 1 should be equal to 2, the number of features at training time
</code></pre>
| 2 |
python list concatenation with strings into new list | puse string concatenation in a list comprehensionp
precodegtgtgt list1 item1 item2 item3 item4
gtgtgt string example
gtgtgt x string for x in list1
item1example item2example item3example item4example
codepre
| 2 |
if python doesnt support method overloading then why does this method overload work while this other does not | pyou arent overloading youre hiding one thing behind another by using the same name for different objects tryp
precodesum 42
codepre
pand see how codeprintsum3 5code ceases to workp
| 2 |
not getting exact result in python with the values leading zero please tell me what is going on there | pin python 2x number with a leading zero is interpreted as octal baseeight python 3x requires a leading 0o to indicate an octal number you probably want to treat a zipcode as a string to keep the leading zeroes intactp
| 2 |
Subsets and Splits