lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Python
Consider the following example : When I now try to parse that string back into a datetime with the exact format I used to serialize it in the first place , a ValueError is thrown at me : ValueError : time data ' 1-01-01T00:00:00 ' does not match format ' % Y- % m- % dT % H : % M : % S'Howeverworks as expected.I would h...
from datetime import datetimeFMT = `` % Y- % m- % dT % H : % M : % S '' original_date = datetime ( 1,1,1 ) s = original_date.strftime ( FMT ) # This is ' 1-01-01T00:00:00 ' datetime.strptime ( s , FMT ) datetime.strptime ( '0001-01-01T00:00:00 ' , FMT )
Parse dates from before the year 1000
Python
The way it is I get a 'NameError : name 'Interval ' is not defined ' . Can someone tell me which type would be correct here ?
class Interval ( object ) : def __sub__ ( self , other : Interval ) : pass
Type hint for 'other ' in magic methods ?
Python
Is there a way to get the output from a test that you run via pytest , using the call to main ? If this was a process I could get the output using communicate ( ) but I ca n't find the equivalent for pytest when running it as function from Python3 , instead than run it as standalone from terminal.EDIT : I did try to us...
string = `` -x mytests.py '' pytest.main ( string ) print ( ? ? ? ? ? ? ? ? )
Output stdio and stderr from pytest.main ( )
Python
When I edit a file with vi like : I have colors.When in python 's script I have : I don't.Why ( I 'm guessing that I open a different shell but I ca n't figure why the settings are different ) ? And how to solve this ? I am running fedora and my shell is bash.gives :
vi .bashrc os.system ( `` vi .bashrc '' ) vi -- version VIM - Vi IMproved 7.3
No color in vi when called from python 's script
Python
I am trying to create custom chunk tags and to extract relations from them . Following is the code that takes me to the cascaded chunk tree.Output - ( S ( NPH Mary/NN ) saw/VBD ( NPH the/DT cat/NN ) sit/VB on/IN ( NPH the/DT mat/NN ) ) Now I am trying to extract relations between the NPH tag values with the text in bet...
grammar = r '' '' '' NPH : { < DT|JJ|NN . * > + } # Chunk sequences of DT , JJ , NN PPH : { < IN > < NP > } # Chunk prepositions followed by NP VPH : { < VB . * > < NP|PP|CLAUSE > + $ } # Chunk verbs and their arguments CLAUSE : { < NP > < VP > } # Chunk NP , VP `` '' '' cp = nltk.RegexpParser ( grammar ) sentence = [ ...
Creating relations in sentence using chunk tags ( not NER ) with NLTK | NLP
Python
I have some text : I 'd like to parse this into its individual words . I quickly looked into the enchant and nltk , but did n't see anything that looked immediately useful . If I had time to invest in this , I 'd look into writing a dynamic program with enchant 's ability to check if a word was english or not . I would...
s= '' Imageclassificationmethodscan beroughlydividedinto two broad families of approaches : ''
Is there an easy way generate a probable list of words from an unspaced sentence in python ?
Python
Consider I have some data.Lets say it is weather data , of rainfall and temperature for each month.For this example , I will randomly generate is like so : So the data looks something like : I want to draw a Trellis chart of Box plots.I can draw a Trellis Chart of the means like so : And I can draw a box plot of each '...
def rand_weather ( n ) : month = n % 12+1 temp_ind = np.random.randint ( 0,4 ) temp = [ `` freezing '' , `` cold '' , `` moderate '' , `` hot '' , `` extreme '' ] [ temp_ind ] rain = np.random.normal ( 50 - 4*temp_ind , 25 ) + np.random.randint ( 0,20 ) return month , rain , tempdata = [ rand_weather ( n ) for n in ran...
Box Plot Trellis
Python
I have an image im which is an array as given by imread . Say e.g.I have another ( n,4 ) array of windows where each row defines a patch of the image as ( x , y , w , h ) . E.g.I 'd like to extract all of these patches from im as sub-arrays without looping through . My current looping solution is something like : But I...
im = np.array ( [ [ 1,2,3,4 ] , [ 2,3,4,5 ] , [ 3,4,5,6 ] , [ 4,5,6,7 ] ] windows = np.array ( [ [ 0,0,2,2 ] , [ 1,1,2,2 ] ] for x , y , w , h in windows : patch = im [ y : ( y+h ) , x : ( x+w ) ]
Extract multiple windows/patches from an ( image ) array , as defined in another array
Python
I 'm trying to learn python , and I 'm pretty new at it , and I ca n't figure this one part out.Basically , what I 'm doing now is something that takes the source code of a webpage , and takes out everything that is n't words.Webpages have a lot of \n and \t , and I want something that will find \ and delete everything...
def removebackslash ( source ) : while ( source.find ( '\ ' ) ! = -1 ) : startback = source.find ( '\ ' ) endback = source [ startback : ] .find ( ' ' ) + startback + 1 source = source [ 0 : startback ] + source [ endback : ] return source
Ca n't get single \ in python
Python
Say I have the following list of numbers : I would like to find every closed interval containing consecutive integers without gaps in this list . If for any number in the list there are multiple such intervals , we only retain the largest of any such intervals . The correct answer above should be : To see this , note f...
my_array = [ 0 , 3 , 4 , 7 , 8 , 9 , 10 , 20 , 21 , 22 , 70 ] [ 0 , 0 ] [ 3 , 4 ] [ 7 , 10 ] [ 20 , 22 ] [ 70 , 70 ]
Tuples of closed continuous intervals
Python
I am writing my doctests like this : This works fine for Python version 2.5 , 2.6 & 2.7 but fails for Python 3 with following error : Problem is that if I write my doctests like this : They will work only for Python3 and fail on Python2 version . My question is how do I make it cross version compatible ?
> > > some_function ( a=1 , b=2 ) { u'id ' : u'123 ' , u'name ' : u'abc ' } Expected : { u'id ' : u'123 ' , u'name ' : u'abc ' } Got : { 'id ' : '123 ' , 'name ' : 'abc ' } > > > some_function ( a=1 , b=2 ) { 'id ' : '123 ' , 'name ' : 'abc ' }
Multi version support for Python doctests
Python
I 'm writing a parser , and in the process of debugging it , I found that apparently , this is legal Python : and so is this ( ! ) : I do n't blame the parser for getting confused ... I 'm having trouble figuring out how to interpret it ! What exactly does this statement mean ?
for [ ] in [ [ ] ] : print 0 for [ ] [ : ] in [ [ ] ] : print 0
What does this Python statement mean ?
Python
I have a list : I want to iterate consecutive elements in the list such that , when it comes to last element i ' e 8 it pairs with the first element 1.The final output I want is : I tried using this way : But I am getting only this result : How do I make a pair of last element with first ? I have heard about the negati...
L = [ 1,2,3,4,5,6,7,8 ] [ 1,2 ] , [ 2,3 ] , [ 3,4 ] , [ 4,5 ] , [ 5,6 ] , [ 6,7 ] , [ 7,8 ] , [ 8,1 ] for first , second in zip ( L , L [ 1 : ] ) : print ( [ first , second ] ) [ 1,2 ] , [ 2,3 ] , [ 3,4 ] , [ 4,5 ] , [ 5,6 ] , [ 6,7 ] , [ 7,8 ]
Iterate consecutive elements in a list in Python such that the last element combines with first
Python
I have tried to somehow get a documentation for a partialmethod to work . My current code isBut if I runand Sphinx lists them using autoclass as undocumented members.I have read https : //docs.python.org/3/library/functools.html # partial-objects and https : //docs.python.org/3/library/functools.html # functools.partia...
from functools import partialmethodclass Fun ( object ) : def test ( self , num ) : `` '' '' I have a documentation `` '' '' return num test2 = partialmethod ( test , num=10 ) test2.__doc__ = `` '' '' Blub '' '' '' test3 = partialmethod ( test , num=20 ) a = Fun ( ) a.test2.__doc__ # only returns the partials documenta...
Documentation of functions defined with functools partialmethod
Python
I am reading about classes in Python ( 3.4 ) and from what I understand it seems that every new object has its own bound methods instances.The output of this is False.This seems to me as a waste of memory . I thought that internally a.foo and b.foo would point somehow internally to one function in memory : A.foo where ...
class A : def __init__ ( self , name ) : self.name = name def foo ( self ) : print ( self.name ) a = A ( 'One ' ) b = A ( 'Two ' ) print ( a.foo == b.foo )
Does Python really create all bound method for every new instance ?
Python
I have DataFrame in the following form : I would like to count the most common combination of two values from Product column grouped by ID.So for this example expected result would be : Is this output possible with pandas ?
ID Product1 A1 B2 A 3 A3 C 3 D 4 A4 B Combination CountA-B 2A-C 1A-D 1C-D 1
Counting most common combination of values in dataframe column
Python
I 'm sure there 's a way of doing this , but I have n't been able to find it . Say I have : Then how can I use map ( add , foo ) such that it passes num1=1 , num2=2 for the first iteration , i.e. , it does add ( 1 , 2 ) , then add ( 3 , 4 ) for the second , etc . ? Trying map ( add , foo ) obviously does add ( [ 1 , 2 ...
foo = [ [ 1 , 2 ] , [ 3 , 4 ] , [ 5 , 6 ] ] def add ( num1 , num2 ) : return num1 + num2
Unpack nested list for arguments to map ( )
Python
I am using plt.imshow ( ) to plot values on a grid ( CCD data in my case ) . An example plot : I need to indicate a barrier on it , to show which pixels I care about . This is similar to what I need : I know how to add squares to an image , gridlines to an image , but this knowledge does n't solve the issuue , nor addi...
X , Y = np.meshgrid ( range ( 30 ) , range ( 30 ) ) Z = np.sin ( X ) +np.sin ( Y ) selected1 = Z > 1.5 upperlim_selected2 = Z < 1.8selected2 = upperlim_selected2 > 0.2
How to encircle some pixels on a heat map with a continuous , not branched line using Python ?
Python
I have a pandas column with lists of values of varying length like so : I 'd like to convert them into a matrix format where each possible value represents a column and each row populates a 1 if the value exists and 0 otherwise , like so : I thought the term for this was one hot encoding , but I tried to use the pd.get...
idx lists 0 [ 1,3,4,5 ] 1 [ 2 ] 2 [ 3,5 ] 3 [ 2,3,5 ] idx 1 2 3 4 5 0 1 0 1 1 1 1 0 1 0 0 0 2 0 0 1 0 1 3 0 1 1 0 1 test_hot = pd.Series ( [ [ 1,2,3 ] , [ 3,4,5 ] , [ 1,6 ] ] ) pd.get_dummies ( test_hot ) Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > File `` /opt/anaconda3/lib/pyth...
Convert pandas column of lists into matrix representation ( One Hot Encoding )
Python
My challenge is to plot many sequences of data organized in the column ( where each column is the data for many simualtions for the same identificator ( ID ) ) and index of pandas dataframe is the months of simulation . The problem is in the line created by pandas linking the different simulations in the same column . ...
# import libraryimport numpy as npimport matplotlib.pyplot as pltimport pandas as pd # create da datasetcolumns = [ ' A ' , ' B ' ] data = np.array ( [ np.random.randint ( 10 , size=15 ) , np.random.randint ( 10 , size=15 ) ] ) .Tindex = list ( range ( 0,5 ) ) *3dataset = pd.DataFrame ( data , index=index , columns=col...
How to discontinue a line graph in the plot pandas or matplotlib python
Python
Why ca n't I use super to get a method of a class 's superclass ? Example : ( Of course this is a trivial case where I could just do A.my_method , but I needed this for a case of diamond-inheritance . ) According to super 's documentation , it seems like what I want should be possible . This is super 's documentation :...
Python 3.1.3 > > > class A ( object ) : ... def my_method ( self ) : pass > > > class B ( A ) : ... def my_method ( self ) : pass > > > super ( B ) .my_methodTraceback ( most recent call last ) : File `` < pyshell # 2 > '' , line 1 , in < module > super ( B ) .my_methodAttributeError : 'super ' object has no attribute ...
Python : Why ca n't I use ` super ` on a class ?
Python
Apologies if this is the wrong place to post this - I 'm unclear what the problem is.When using versions of Python built by Macports 2.3.3 running Mac OX 10.10 , I 'm seeing some really funny behavior . I 've fully re-installed Macports , and replicated this on an iMac as well as a Macbook Air , and created a new user ...
$ pythonPython 3.4.3 ( default , Aug 26 2015 , 18:29:14 ) [ GCC 4.2.1 Compatible Apple LLVM 6.0 ( clang-600.0.56 ) ] on darwinType `` help '' , `` copyright '' , `` credits '' or `` license '' for more information. > > > 1+1 > > > 2^D > > > $ this is ouput ; input is hidden $ Python 3.4.3 ( default , Aug 26 2015 , 18:2...
Python , Macports , and Buffer Problems
Python
consider the below pd.DataFrameI desire to set 'foo ' and all the sub-indices within it as index . How can I achieve this ? I am grappling with 'set_index'and pd.IndexSlice but still ca n't get to the solution
df_index = pd.MultiIndex.from_product ( [ [ 'foo ' , 'bar ' ] , [ 'one ' , 'two ' , 'three ' ] ] ) df = pd.DataFrame ( np.random.randint ( 0,10 , size=18 , dtype='int ' ) .reshape ( ( -1,6 ) ) , columns=df_index ) print ( df ) foo bar one two three one two three 0 7 3 8 3 6 0 1 2 5 9 4 3 6 2 4 2 6 6 4 5
pandas set index with multilevel columns
Python
I have a conceptual question about Python . This is the codeHere , I expect the list to be empty as none of the items satisfy the condition if sub1 and sub2 in item : But when I print the list I get the output # 1 as thisAlso , when I use or instead of and as given belowthe output # 2 I get isI saw a similar looking so...
list1= [ 'assistant manager ' , 'salesperson ' , 'doctor ' , 'production manager ' , 'sales manager ' , 'schoolteacher ' , 'mathematics teacher ' ] sub1 = `` teacher '' sub2 = `` sales '' ans= [ ] for item in list1 : if ( sub1 and sub2 ) in item : ans.append ( item ) > > > ans [ 'salesperson ' , 'sales manager ' ] # I ...
Why are 'and/or ' operations in this Python statement behaving unexpectedly ?
Python
Given the coming deprecation of df.ix [ ... ] How can i replace .ix in this piece of code ? For reference , this is some background on that piece of code
df_1 = df.ix [ : , : datetime.time ( 16 , 50 ) ] df_2 = df.ix [ : , datetime.time ( 17 , 0 ) : ] df_3 = df2.shift ( periods = 1 ) df_4 = pd.concat ( [ df3 , df1 ] , axis = 1 )
How to replace df.ix with df.loc or df.iloc ?
Python
( Please note that there 's a question Pandas : group by and Pivot table difference , but this question is different . ) Suppose you start with a DataFrameNow suppose you want to make the index a , the columns b , the values in a cell val , and specify what to do if there are two or more values in a resulting cell : Th...
df = pd.DataFrame ( { ' a ' : [ ' x ' ] * 2 + [ ' y ' ] * 2 , ' b ' : [ 0 , 1 , 0 , 1 ] , 'val ' : range ( 4 ) } ) > > > dfOut [ 18 ] : a b val0 x 0 01 x 1 12 y 0 23 y 1 3 b 0 1a x 0 1y 2 3 df.val.groupby ( [ df.a , df.b ] ) .sum ( ) .unstack ( ) pd.pivot_table ( df , index= ' a ' , columns= ' b ' , values='val ' , agg...
Is There Complete Overlap Between ` pd.pivot_table ` and ` pd.DataFrame.groupby ` + ` pd.DataFrame.unstack ` ?
Python
I have succesfully installed Adafruit_Gpio package and when i try to run the example file of the bme sensor provided by adafruit , i get the following error : I am on xubuntu for rpi-3 i have run apt-get udpate and restarted the machine neither worked .
Traceback ( most recent call last ) : File `` /home/rpi3/Adafruit_Python_BME280/example.py '' , line 3 , in < module > sensor = BME280 ( mode=BME280_OSAMPLE_8 ) File `` /home/rpi3/Adafruit_Python_BME280/Adafruit_BME280.py '' , line 88 , in __init__ self._device = i2c.get_i2c_device ( address , **kwargs ) File `` /usr/l...
Traceback ( most recent call last ) : Adafruit BME 280 Sensor
Python
I am porting code created in octave into pylab . One of the ported equations gives dramatically different results in python than it does in octave . The best way to explain is to show plots generated by octave and pylab from the same equation . Here is a simplified snippet of the original equation in octave . In this s...
clearclcclose allL1 = 4.25 ; % left servo arm lengthL2 = 5.75 ; % left linkage lengthL3 = 5.75 ; % right linkage lengthL4 = 4.25 ; % right servo arm lengthL5 = 11/2 ; % distance from origin to left servoL6 = 11/2 ; % distance from origin to right servotheta_array = [ -pi+0.1:0.01 : pi-0.1 ] ; phi = 0/180*pi ; for i = 1...
Same equation , different answers from Pylab and Octave
Python
So , in Python ( though I think it can be applied to many languages ) , I find myself with something like this quite often : Maybe I 'm being too picky , but I do n't like how the line the_input = raw_input ( `` what to print ? \n '' ) has to get repeated . It decreases maintainability and organization . But I do n't s...
the_input = raw_input ( `` what to print ? \n '' ) while the_input ! = `` quit '' : print the_input the_input = raw_input ( `` what to print ? \n '' ) while ( ( the_input=raw_input ( `` what to print ? \n '' ) ) ! = `` quit '' ) { print the_input } while 1 : the_input = raw_input ( `` what to print ? \n '' ) if the_inp...
small code redundancy within while-loops ( does n't feel clean )
Python
Say I 've gotFrom this I want to obtain a matrix X with shape ( len ( Y ) , 3 ) . In this particular case , the first row of X should have a one on the second index and zero otherwhise . The second row of X should have a one on the 0 index and zero otherwise . To be explicit : How do I produce this matrix ? I started w...
Y = np.array ( [ 2 , 0 , 1 , 1 ] ) X = np.array ( [ [ 0 , 0 , 1 ] , [ 1 , 0 , 0 ] , [ 0 , 1 , 0 ] , [ 0 , 1 , 0 ] ] ) X = np.zeros ( ( Y.shape [ 0 ] , 3 ) )
Construct two dimensional numpy array from indices and values of a one dimensional array
Python
After reading this and this , which are pretty similar to my question , I still can not understand the following behaviour : When printing id ( a ) and id ( b ) I can see that the variables , to which the values were assigned in separate lines , have different ids , whereas with multiple assignment both values have the...
a = 257b = 257print ( a is b ) # Falsea , b = 257 , 257print ( a is b ) # True a = 257b = 257print ( id ( a ) ) # 139828809414512print ( id ( b ) ) # 139828809414224a , b = 257 , 257print ( id ( a ) ) # 139828809414416print ( id ( b ) ) # 139828809414416 a , b = -1000 , -1000 print ( id ( a ) ) # 139828809414448print (...
Python3 multiple assignment and memory address
Python
For a new feature in PyInstaller , we need a command line option receiving a string with any separator in it . Here 's the discussion : https : //github.com/pyinstaller/pyinstaller/pull/1990.Example : ? is the separator here , this should be another character . It 's not guaranteed , that the string is quoted ! We 've ...
pyinstaller -- add-data= '' file.txt ? dir ''
Cross-platform , safe to use command line string separator
Python
Why do these dtypes compare equal but hash different ? Note that Python does promise that : The only required property is that objects which compare equal have the same hash value…My workaround for this problem is to call np.dtype on everything , after which hash values and comparisons are consistent .
In [ 30 ] : import numpy as npIn [ 31 ] : d = np.dtype ( np.float64 ) In [ 32 ] : dOut [ 32 ] : dtype ( 'float64 ' ) In [ 33 ] : d == np.float64Out [ 33 ] : TrueIn [ 34 ] : hash ( np.float64 ) Out [ 34 ] : -9223372036575774449In [ 35 ] : hash ( d ) Out [ 35 ] : 880835502155208439
Why do these dtypes compare equal but hash different ?
Python
The following codeproduces the following error : Traceback ( most recent call last ) : File `` C : \Program Files ( x86 ) \Google\google_appengine\google\appengine\tools\dev_appserver.py '' , line 4053 , in _HandleRequest self._Dispatch ( dispatcher , self.rfile , outfile , env_dict ) File `` C : \Program Files ( x86 )...
class Translation ( db.Model ) : origin = db.ReferenceProperty ( Expression , required=True ) target = db.ReferenceProperty ( Expression , required=True )
How to reference the same Model twice from another one ?
Python
Let 's say I have a model with a unique field email : Usually if a browser submits a form with email being a value that already exists , it would raise a ValidationError , due to the model form field validation.If two browsers submits the same email at the same time , with email being a value that does n't exist yet , ...
class MyModel : email = models.EmailField ( unique=True ) def save ( self ) : ... . # save model def clean ( self ) : ... . # validate model , make sure email does n't already exist .
Django locking between clean ( ) and save ( )
Python
I 'm fairly new to Python , and think this should be a fairly common problem , but ca n't find a solution . I 've already looked at this page and found it helpful for one item , but I 'm struggling to extend the example to multiple items without using a 'for ' loop . I 'm running this bit of code for 250 walkers throug...
[ [ x ] , [ y , y ] , [ z , z , z ] ] c = [ ] for i in range ( 0 , len ( a ) ) : c.append ( [ a [ i ] ] *b [ i ] )
Creating list of individual list items multiplied n times
Python
I tried this : And as a result I got this exception :
numbers_dict = dict ( ) num_list = [ 1,2,3,4 ] name_list = [ `` one '' , '' two '' , '' three '' , '' four '' ] numbers_dict [ name for name in name_list ] = num for num in num_list File `` < stdin > '' , line 1numbers_dict [ name for name in name_list ] = num for num in num_list
insert data from two lists to dict with for loop
Python
I have a list of lists , and I would like to duplicate the effect of itertools.product ( ) without using any element more than once.The list I need to use this on is too large to compute itertools.product and remove the unneeded elements . ( 25 billion permutations from itertools.product , while my desired output only ...
> > > list = [ [ ' A ' , ' B ' ] , [ ' C ' , 'D ' ] , [ ' A ' , ' B ' ] ] > > > [ `` .join ( e ) for e in itertools.product ( *list ) ] [ 'ACA ' , 'ACB ' , 'ADA ' , 'ADB ' , 'BCA ' , 'BCB ' , 'BDA ' , 'BDB ' ] > > > # Desired output : [ 'ACB ' , 'ADB ' , 'BCA ' , 'BDA ' ] [ [ ' A ' , ' H ' , ' L ' ] , [ ' X ' , ' B ' ,...
Python - itertools.product without using element more than once
Python
I 'm trying to generate dictionaries that include dates which can be asked to be given in specific locales . For example , I might want my function to return this when called with en_US as an argument : And this , when called with hu_HU : Now , based on what I 've found so far , I should be using locale.setlocale ( ) t...
{ 'date ' : 'May 12 , 2014 ' , ... } { 'date ' : '2014 . május 12 . ' , ... }
How do I get the correct date format string for a given locale without setting that locale program-wide in Python ?
Python
I do the followingAnd the following handling in script.py : Looks like something is wrong there .
- url : /user/ . * script : script.py class GetUser ( webapp.RequestHandler ) : def get ( self ) : logging.info ( ' ( GET ) Webpage is opened in the browser ' ) self.response.out.write ( 'here I should display user-id value ' ) application = webapp.WSGIApplication ( [ ( '/ ' , GetUser ) ] , debug=True )
How to configure app.yaml to support urls like /user/ < user-id > ?
Python
Possible Duplicate : Floating point equality in python I have a small `` issue '' about my Python code ( I use version 2.5 right now , in ika game engine ) . I currently script objects for my game , and i would like to know , if its safe to compare two floating point number This way : I will make a short example of wha...
speed = 4.83cord_x = 10.0cord_y = 10.0 target_x = 25.0target_x = 26.75movement = True # This represents if the object is moveing or not maximum_x_speed = abs ( cord_x-target_x ) maximum_y_speed = abs ( cord_y-target_y ) # Get the real X speed in this frameif maximum_x_speed < speed : real_x_speed = maximum_x_speedelse ...
Python floating point
Python
I found pandas read_csv method to be faster than numpy loadtxt . Unfortunatly now I find myself in a situation where I have to go back to numpy because loadtxt has the option of setting comments= [ ' # ' , ' @ ' ] . Pandas read_csv method can only take one comment string like comment= ' # ' as far as I can tell from th...
# save this in test.dat @ bla # bla1 2 3 4 # does work , but only one type of comment is accounted fordf = pd.read_csv ( 'test.dat ' , index_col=0 , header=None , comment= ' # ' ) # does not work ( not suprising reading the help ) df = pd.read_csv ( 'test.dat ' , index_col=0 , header=None , comment= [ ' # ' , ' @ ' ] )...
Why does pandas read_csv not support multiple comments ( # , @ , ... ) ?
Python
I am writing a function called zip_with with the following signature : It 's like zip , but allows you to aggregate with any arbitrary function . This works fine for an implementation of zip_with that only allows 2 arguments . Is there support for adding type hints for a variable number of arguments ? Specifically , I ...
_A = TypeVar ( `` _A '' ) _B = TypeVar ( `` _B '' ) _C = TypeVar ( `` _C '' ) def zip_with ( zipper : Callable [ [ _A , _B ] , _C ] , a_vals : Iterable [ _A ] , b_vals : Iterable [ _B ] ) - > Generator [ _C , None , None ] : ... def zip_with ( zipper : Callable [ ... , _C ] , *vals : Iterable ) - > Generator [ _C , Non...
Python type hints for generic *args ( specifically zip or zipWith )
Python
I was wondering whether there is a way to refer data from many different arrays to one array , but without copying it.Example : However , in the example above , c is a new array , so that if you modify some element of a or b , it is not modified in c at all.I would like that each index of c ( i.e . c [ 0 ] , c [ 1 ] , ...
import numpy as npa = np.array ( [ 2,3,4,5,6 ] ) b = np.array ( [ 5,6,7,8 ] ) c = np.ndarray ( [ len ( a ) +len ( b ) ] ) offset = 0c [ offset : offset+len ( a ) ] = aoffset += len ( a ) c [ offset : offset+len ( b ) ] = b
Is there any way to make a soft reference or Pointer-like objects using Numpy arrays ?
Python
Playing around in Python , I found that the following code works as I expected : From a list S , it will recursively drop the first element until the length of S equals b . For instance f ( [ 1,2,3,4,5,6 ] ,3 ) = [ 4,5,6 ] .However , much to my surprise the following solution , that uses the 'ternary hack ' [ a , b ] [...
f = lambda S , b : ( S if len ( S ) ==b else f ( S [ 1 : ] , b ) ) g = lambda S , b : ( g ( S [ 1 : ] , b ) , S ) [ len ( S ) ==b ]
Recursion with ternary operator 'hack ' in Python
Python
My code is as follows . I want the two sleep can share the same time frame and take 1+2*3=7 seconds to run the script.But it seems that something wrong happened so that it still takes 3* ( 1+2 ) second.Is there any idea how to modify the code ?
import asyncioasync def g ( ) : for i in range ( 3 ) : await asyncio.sleep ( 1 ) yield iasync def main ( ) : async for x in g ( ) : print ( x ) await asyncio.sleep ( 2 ) loop = asyncio.get_event_loop ( ) res = loop.run_until_complete ( main ( ) ) loop.close ( )
Python async-generator not async
Python
For older versions of pyramid the setup for sqlalchemy session was done with scooped_session similar to this However I see that newer tutorials as well the pyramid docs 'promotes ' sqlalchemy with no threadlocals where the DBSession is attached to the request object.Is the 'old ' way broken and what is the advantage of...
DBSession = scoped_session ( sessionmaker ( autoflush=True , expire_on_commit=False , extension=zope.sqlalchemy.ZopeTransactionExtension ( ) )
Pyramid with SQLAlchemy : scoped or non-scoped database session
Python
As a result of getting help with a question I had yesterday - Python 2.7 - find and replace from text file , using dictionary , to new text file - I started learning regular expressions today to understand the regular expressions code that @ Blckknght had kindly created for me in his answer . However , it seems to me t...
import rem = re.search ( r'\bfoo\b ' , 'bar foo baz ' ) m.group ( ) 'foo ' 'bar foo baz '
Python Docs Wrong About Regular Expression `` \b '' ?
Python
I 'm currently trying to calculate the sum of all sum of subsquares in a 10.000 x 10.000 array of values . As an example , if my array was : I want the result to be : So , as a first try i wrote a very simple python code to do that . As it was in O ( k^2.n^2 ) ( n being the size of the big array and k the size of the s...
1 1 1 2 2 23 3 3 1+1+1+2+2+2+3+3+3 [ sum of squares of size 1 ] + ( 1+1+2+2 ) + ( 1+1+2+2 ) + ( 2+2+3+3 ) + ( 2+2+3+3 ) [ sum of squares of size 2 ] + ( 1+1+1+2+2+2+3+3+3 ) [ sum of squares of size 3 ] ________________________________________68 def getSum ( tab , size ) : n = len ( tab ) tmp = numpy.zeros ( ( n , n ) )...
How can I vectorize and speed up this large array calculation ?
Python
I have a list which I want to sort by multiple keys , like : This works fine . However , this results with unnecessary calls to g , which I would like to avoid ( for being potentially slow ) . In other words , I want to partially and lazily evaluate the key.For example , if f is unique over L ( i.e . len ( L ) == len (...
L = [ ... ] L.sort ( key = lambda x : ( f ( x ) , g ( x ) ) )
Avoiding unnecessary key evaluations when sorting a list
Python
I 'm trying to build a simple helper utility that will look through my projects and find and return the open ones to me via command line . But my calls to os.listdir return gibberish ( example : '\x82\xa9\x82\xcc\x96I ' ) whenever the folder or filename is in Japanese , and said gibberish ca n't be passed to the call a...
'WindowsError : [ Error 3 ] 指定されたパスが見つかりません。 '
How can I traverse directories named in Japanese in Python ?
Python
I am trying to implement a Flask backend endpoint where two images can be uploaded , a background and a foreground ( the foreground has a transparent background ) , and it will paste the foreground on top of the background . I have the following Python code that I have tested with local files and works : However , when...
background_name = request.args.get ( `` background '' ) overlay_name = request.args.get ( `` overlay '' ) output_name = request.args.get ( `` output '' ) background_data = request.files [ `` background '' ] .read ( ) overlay_data = request.files [ `` overlay '' ] .read ( ) background = Image.open ( BytesIO ( background...
Alamofire Uploads PNG to Flask with White Background
Python
the insert works but multiple data enters , when two data are inserted when I try to update , it does not update the recordI just want that when the data is already have record in the database , just update . if not , it will insertthis is my models.pyUPDATEI tried this , the insert works fine , but the update does not...
def GroupOfProduct ( request ) : global productOrderList relatedid_id = request.POST.get ( `` relatedid '' ) groups = ProductRelatedGroup ( id=id ) productOrderList= [ ] try : for products_id in request.POST.getlist ( `` product '' ) : products = Product ( id=products_id ) insert_update_groupofproduct = ProductRelatedG...
django Insert or Update record
Python
In a Python script , mylibrary.py , I use Protocol Buffers to model data using the following approach : Defining message formats in a .proto file.Use the protocol buffer compiler.Use the Python protocol buffer API to write and read messages in the .py module.I want to implement Cloud Endpoints Framework on App Engine t...
from protorpc import messagesfrom protorpc import remote class MyMessageDefinition ( messages.Message )
Converting proto buffer to ProtoRPC
Python
I 'm really stuck on why the following code block 1 result in output 1 instead of output 2 ? Code block 1 : The goal of this code is to iterate through an array and wrap each in a parent object . This is a reduction of my actual code which adds all apples to a bag of apples and so forth . My guess is that , for some re...
class FruitContainer : def __init__ ( self , arr= [ ] ) : self.array = arr def addTo ( self , something ) : self.array.append ( something ) def __str__ ( self ) : ret = `` [ `` for item in self.array : ret = `` % s % s , '' % ( ret , item ) return `` % s ] '' % retarrayOfFruit = [ 'apple ' , 'banana ' , 'pear ' ] array...
Python Scoping/Static Misunderstanding
Python
I am working with Pycharm , trying to run scrapy unit tests - and it fails to run.The errors are for missing imports , seems like all imports are failing.e.g.what I did : Get scrapy from githubRun pip to install all dependencies from requirements.txtInstalled TOX , made sure I can run the tests using TOX.Configured Pyc...
Import error ... `` no module named mock ''
How to run Scrapy unit tests in Pycharm
Python
For example , I have an object x that might be None or a string representation of a float . I want to do the following : Except without having to type x twice , as with Ruby 's andand library :
do_stuff_with ( float ( x ) if x else None ) require 'andand'do_stuff_with ( x.andand.to_f )
Is there a Python library ( or pattern ) like Ruby 's andand ?
Python
In Python , I can create a class method using the @ classmethod decorator : Alternatively , I can use a normal ( instance ) method on a metaclass : As shown by the output of C.f ( ) , these two approaches provide similar functionality.What are the differences between using @ classmethod and using a normal method on a m...
> > > class C : ... @ classmethod ... def f ( cls ) : ... print ( f ' f called with cls= { cls } ' ) ... > > > C.f ( ) f called with cls= < class '__main__.C ' > > > > class M ( type ) : ... def f ( cls ) : ... print ( f ' f called with cls= { cls } ' ) ... > > > class C ( metaclass=M ) : ... pass ... > > > C.f ( ) f c...
What are the differences between a ` classmethod ` and a metaclass method ?
Python
In Python , suppose that I have continuous variables x and y , whose values are bounded between 0 and 1 ( to make it easier ) . My assumption has always been that if I want to convert those variables into ordinal values with bins going like 0,0.01,0.02 , ... ,0.98,0.99,1 one could simply round the original values to th...
import numpy as npimport matplotlib.pyplot as plt # number of points drawn from Gaussian dists . : n = 100000x = np.random.normal ( 0 , 2 , n ) y = np.random.normal ( 4 , 5 , n ) # normalizing x and y to bound them between 0 and 1 # ( it 's way easier to illustrate the problem this way ) x = ( x - min ( x ) ) / ( max (...
Binning continuous values with round ( ) creates artifacts
Python
Assuming a command similar to this : Is there any way to cancel that wait_for if the user sends the same command multiple times before actually reacting to the message ? So the bot stop waiting for reactions on previously sent messages and only waits for the last one .
@ bot.command ( ) async def test ( ctx ) : def check ( r , u ) : return u == ctx.message.author and r.message.channel == ctx.message.channel and str ( r.emoji ) == '✅ ' await ctx.send ( `` React to this with ✅ '' ) try : reaction , user = await bot.wait_for ( 'reaction_add ' , timeout=300.0 , check=check ) except async...
How to cancel a pending wait_for
Python
I need to take a csv file that looks like this ... and write it out to another csv file to make it look like this ... the spaces are suppose to be blank because nothing goes there and this is the code that I have so far I am new to python and I am not really sure how to use the cvs module . I was thinking of making an ...
Name , Price1 , Price2 , Date1 , Date2ABC,1000,7500,5/1,6/1DEF,3000,500,5/1,7/1GHI,5000,3500,6/1,8/1 Name , May , June , July , August ABC,7500,1000 , , DEF,500 , ,3000GHI , ,3500 , ,5000 import csv with open ( 'test-data.csv ' , 'rb ' ) as f : csv_file=csv.reader ( f ) data= [ row for row in csv_file ] with open ( 'cs...
writing csv output python
Python
I have a string where a character ( ' @ ' ) needs to be replaced by characters from a list of one or more characters `` in order '' and `` periodically '' .So for example I have'ab @ cde @ @ fghi @ jk @ lmno @ @ @ p @ qrs @ tuvwxy @ z'and want'ab1cde23fghi1jk2lmno312p3qrs1tuvwxy2z'for replace_chars = [ ' 1 ' , ' 2 ' , ...
result = `` replace_chars = [ ' 1 ' , ' 2 ' , ' 3 ' ] string = 'ab @ cde @ @ fghi @ jk @ lmno @ @ @ p @ qrs @ tuvwxy @ z ' i = 0for char in string : if char == ' @ ' : result += replace_chars [ i ] i += 1 else : result += charprint ( result )
What 's the best way to `` periodically '' replace characters in a string in Python ?
Python
I 'm trying to run some tests on the shiny new Python 3.8 and noticed an issue with math.hypot . From the docs : For a two dimensional point ( x , y ) , this is equivalent to computing the hypotenuse of a right triangle using the Pythagorean theorem , sqrt ( x*x + y*y ) .However , these are not equivalent in 3.8 : In 3...
> > > from math import hypot , sqrt > > > x , y = 95 , 168 > > > sqrt ( x*x + y*y ) , hypot ( x , y ) , sqrt ( x*x + y*y ) == hypot ( x , y ) ( 193.0 , 193.00000000000003 , False ) > > > sqrt ( x*x + y*y ) .is_integer ( ) , hypot ( x , y ) .is_integer ( ) ( True , False )
Why is sqrt ( x*x + y*y ) ! = math.hypot ( x , y ) in Python 3.8 ?
Python
I 'm moving a Google App Engine web application outside `` the cloud '' to a standard web framework ( webpy ) and I would like to know how to implement a memcache feature available on Gae.In my app I just use this cache to store a bunch of data retrieved from a remote api every X hours ; in other words I do n't stress ...
class TinyCache ( ) : class _Container ( ) : def __init__ ( self , value , seconds ) : self.value = value self.cache_age = datetime.now ( ) self.cache_time = timedelta ( seconds = seconds ) def is_stale ( self ) : return self.cache_age + self.cache_time < datetime.now ( ) def __init__ ( self ) : self.dict_cache= { } de...
Homemade tiny memcache
Python
I am using from tkinter.ttk import * to override the old windows 98 style with the new windows 8 styled widgets . When I create a menu , it is styled as a new menu : But when I add a submenu , it is styled as a old menu : It looks like this : What I would like is something like this : Am I missing a import here , or is...
menu = Menu ( master ) fileMenu = Menu ( self , tearoff=False ) menu.add_cascade ( label= '' Bestand '' , menu=fileMenu )
TKinter : Can I style submenus to look like normal menus
Python
I have this spark program and I 'll try to limit it to just the pertinent partsThis program works pretty well on my local machine , however , it does not behave as expected when run on a standalone cluster . It does n't necessarily throw an error , but what it does do it give different output than that which I receive ...
# Split by delimiter , # If the file is in unicode , we need to convert each value to a float in order to be able to # treat it as a numberpoints = sc.textFile ( filename ) .map ( lambda line : [ float ( x ) for x in line.split ( `` , '' ) ] ) .persist ( ) # start with K randomly selected points from the dataset # A ce...
Spark program gives odd results when ran on standalone cluster
Python
I have two strings of equal length and want to match words that have the same index . I am also attempting to match consecutive matches which is where I am having trouble . For example I have two stringsWhat I am looking for is to get the result : My current code is as follow : Which gives me : Any guidance or help wou...
alligned1 = ' I am going to go to some show'alligned2 = ' I am not going to go the show ' [ ' I am ' , 'show ' ] keys = [ ] for x in alligned1.split ( ) : for i in alligned2.split ( ) : if x == i : keys.append ( x ) [ ' I ' , 'am ' , 'show ' ]
Python matching words with same index in string
Python
Say you have some list L and you want to split it into two lists based on some boolean function P. That is , you want one list of all the elements l where P ( l ) is true and another list where P ( l ) is false.I can implement this in Python like so : My question : Is there a functional programming idiom that accomplis...
def multifilter ( pred , seq ) : trues , falses = [ ] , [ ] for x in seq : if pred ( x ) : trues.append ( x ) else : falses.append ( x ) return trues , falses
Is there a functional programming idiom for filtering a list into trues and falses ?
Python
I 'm using Neo4j 3.1.1 community edition . I 'm trying to fetch roughly 80 million entries from the db via python using the officialy supported python driver . The python script is running against localhost , i.e . on the same machine as Neo4j and not over network . Access to Neo4j works all fine until it comes to the ...
result = session.run ( `` match ( n : Label ) return n.Property as property '' ) property_list = [ record [ `` property '' ] for record in result ]
How to keep a Neo4j bolt session open ?
Python
In Matlab , one can evaluate an arbitrary string as code using the eval function . E.g.Is there any way to do the inverse operation ; getting the literal string representation of an arbitrary variable ? That is , recover s from c ? Something likeSuch a repr function is built into Python , but I 've not come across anyt...
s = ' { 1 , 2 , `` hello '' } ' % charc = eval ( s ) % cell s = repr ( c )
Matlab repr function
Python
Following Ned Batchelder 's Coverage.py for Django templates blog post and the django_coverage_plugin plugin for measuring code coverage of Django templates . I would really like to see template coverage reports , but the problem is - we have replaced the Django 's the template engine with jinja2 through the coffin ada...
from coffin.shortcuts import render_to_response python manage.py test_coverage project_name
Code coverage for jinja2 templates in Django
Python
The Story : When you parse HTML with BeautifulSoup , class attribute is considered a multi-valued attribute and is handled in a special manner : Remember that a single tag can have multiple values for its “ class ” attribute . When you search for a tag that matches a certain CSS class , you ’ re matching against any of...
# The HTML standard defines these attributes as containing a # space-separated list of values , not a single value . That is , # class= '' foo bar '' means that the 'class ' attribute has two values , # 'foo ' and 'bar ' , not the single value 'foo bar ' . When we # encounter one of these attributes , we will parse its...
Disable special `` class '' attribute handling
Python
Please consider the ( example ) code below before I get to my specific question regarding visitor pattern in python : When I run it , it traverse all the nodes-classes iteratively and returns the following : This is all fine but now to my question . You may have noticed that each check-method returns a Boolean ( lets s...
class Node : def __init__ ( self ) : self.children = [ ] def add ( self , node ) : self.children.append ( node ) def check ( self ) : print ( `` Node '' ) return True def accept ( self , visitor ) : visitor.visit ( self ) class NodeA ( Node ) : def check ( self ) : print ( `` NodeA '' ) return Trueclass NodeB ( Node ) ...
Visitor pattern ( from bottom to top )
Python
We use the AWS managed Elasticsearch service and recently upgraded from 1.5 to 2.3 . We use the elasticsearch-dsl package in python to build our queries and managed to migrate most of our queries , but geo_distance is broken no matter what I try . Mapping : Python code working with elasticsearch-dsl==0.0.11Query genera...
{ 'company ' : { 'properties ' : { 'id ' : { 'type ' : 'integer ' } , 'company_number ' : { 'type ' : 'string ' } , 'addresses ' : { 'type ' : 'nested ' , 'properties ' : { 'postcode ' : { 'type ' : 'string ' , 'index ' : 'not_analyzed ' } , 'location ' : { 'type ' : 'geo_point ' } } } } } } test_location = '53.5411062...
Unable to locate nested geopoint after updating to elasticsearch 2.3
Python
My code : I have several hundred pictures , and in hopes of making my code as concise as possible ( and to expand my python knowledge ) , I was wondering how I write code that automatically takes the files in a folder and makes them a list.I have done similar things in R , but I 'm not sure how to do it in python .
red_images = 'DDtest/210red.png'green_images = 'DDtest/183green.png ' b = [ red_images , green_images ] shuffle ( b )
Automatically creating a list in Python
Python
I have basically a list of all the files in a folder , which in a simplified version looks like : Another list : I want to combine these two list into a dictionary , such that : I thought of doing like this but got stuck ! What can I do after this to join the elements into a dictionary , or am I doing this completely w...
file_list = [ 'drug.resp1.17A.tag ' , 'drug.resp1.96A.tag ' , 'drug.resp1.56B.tag ' , 'drug.resp2.17A.tag ' , 'drug.resp2.56B.tag ' , 'drug.resp2.96A.tag ' ] drug_list = [ '17A ' , '96A ' , '56B ' ] dictionary = { '17A ' : [ 'drug.resp1.17A.tag ' , 'drug.resp2.17A.tag ' ] , '96A ' : [ 'drug.resp1.96A.tag ' , 'drug.resp...
combine two lists into a dictionary if a pattern matches
Python
I 'm trying to find the factor pair of a number with least sum in O ( 1 ) .Here is the explanation : Here the pair with least sum is 10,10 which is clearly the middle oneHere the required pair is either 3,4 or 4,3.If the given number is a perfect square then the task is pretty simple.The pair would be just sqrt ( numbe...
If number is 100 . Then all the possible pairs are :1 X 1002 X 504 X 255 X 2010 X 1020 X 525 X 450 X 2100 X 1 Similarly if number is 12 then pairs are as follows1 X 122 X 63 X 44 X 36 X 212 X 1 If a number has ' p ' pairs then the required one is always ceil ( p/2 ) . Now consider 102 . All pairs are :1 * 102.02 * 51.0...
Getting factors of a number with least sum in O ( 1 )
Python
I have a dataframe column with the following format : How can I transform it to the following ? I was thinking of using apply and lambda as a solution but I am not sure how . Edit : In order to recreate this dataframe I use the following code :
col1 col2 A [ { 'Id':42 , 'prices ' : [ '30 ' , ’ 78 ’ ] } , { 'Id ' : 44 , 'prices ' : [ '20 ' , '47 ' , ‘ 89 ’ ] } ] B [ { 'Id':47 , 'prices ' : [ '30 ' , ’ 78 ’ ] } , { 'Id':94 , 'prices ' : [ '20 ' ] } , { 'Id':84 , 'prices ' : [ '20 ' , '98 ' ] } ] col1 Id price A 42 [ '30 ' , ’ 78 ’ ] A 44 [ '20 ' , '47 ' , ‘ 89 ...
Pandas Dataframe split multiple key values to different columns
Python
I have a dataset in a textfile that looks like this.I read this usingAnd got the outputBut I want this read asI 've tried removing delim_whitespace = True and replacing it with delimiter = `` `` but that just combined the first four columns in the output shown above , but it did parse the rest of the data correctly , m...
0 0CF00400 X 8 66 7D 91 6E 22 03 0F 7D 0.021650 R 0 18EA0080 X 3 E9 FE 00 0.022550 R 0 00000003 X 8 D5 64 22 E1 FF FF FF F0 0.023120 R file_pandas = pd.read_csv ( fileName , delim_whitespace = True , header = None , engine = 'python ' ) 0 0 0CF00400 X 8 66 7D 91 6E 22 03 0F 7D 0.02165 1 0 18EA0080 X 3 E9 FE 0 0.022550 ...
Reading a text file using Pandas where some rows have empty elements ?
Python
I am trying to execute this post but I get server error 500 : I think I need to set cookies or something else . Thank you in advance for any help .
import requestsbase_url = `` https : //www.assurland.com/ws/CarVehiculeSearch.asmx '' url = `` % s/ % s '' % ( base_url , '' GetCarBodyTypeListByCarAlim '' ) pars = { `` CarAlim '' : '' DIES '' , '' CarType '' : `` A7 '' , `` CodeMake '' : `` AUDI '' , `` FirstDrivingDate '' : `` 2015-09-22 '' } with requests.Session (...
python requests post query fails : cookies ?
Python
Can you make this more pythonic by using the map and/or reduce functions ? it just sums the products of every consecutive pair of numbers .
topo = ( 14,10,6,7,23,6 ) result = 0for i in range ( len ( topo ) -1 ) : result += topo [ i ] *topo [ i+1 ]
Can this be written as a python reduce function ?
Python
I propose a example in which a tf.keras model fails to learn from very simple data . I 'm using tensorflow-gpu==2.0.0 , keras==2.3.0 and Python 3.7 . At the end of my post , I give the Python code to reproduce the problem I observed.DataThe samples are Numpy arrays of shape ( 6 , 16 , 16 , 16 , 3 ) . To make things ver...
def generate_fake_data ( ) : for j in range ( 1 , 240 + 1 ) : if j < 120 : yield np.ones ( ( 6 , 16 , 16 , 16 , 3 ) ) , np.array ( [ 0. , 1 . ] ) else : yield np.zeros ( ( 6 , 16 , 16 , 16 , 3 ) ) , np.array ( [ 1. , 0 . ] ) def make_tfdataset ( for_training=True ) : dataset = tf.data.Dataset.from_generator ( generator...
Keras model fails to decrease loss
Python
Comparison operators can be chained in python , so that for example x < y < z should give the result of ( x < y ) and ( y < z ) , except that y is guaranteed to be evaluated only once . The abstract syntax tree of this operation looks like : Pretty printed : But it seems to parse as something like 0 < < 1 2 and I 'm no...
> > > ast.dump ( ast.parse ( ' 0 < 1 < 2 ' ) , annotate_fields=0 ) 'Module ( [ Expr ( Compare ( Num ( 0 ) , [ Lt ( ) , Lt ( ) ] , [ Num ( 1 ) , Num ( 2 ) ] ) ) ] ) ' Module Expr Compare Num Lt Lt Num Num
How to explain the abstract syntax tree of chained comparison operations ?
Python
I have a very simple function like this one : To which I passI expected that function will modify data z column in place like this : This works fine most of the time , but somehow fails to modify data in others.I double checked things and : I have n't determined any problems with data points which could cause this prob...
import numpy as npfrom numba import jitimport pandas as pd @ jitdef f_ ( n , x , y , z ) : for i in range ( n ) : z [ i ] = x [ i ] * y [ i ] f_ ( df.shape [ 0 ] , df [ `` x '' ] .values , df [ `` y '' ] .values , df [ `` z '' ] .values ) df = pd.DataFrame ( { `` x '' : [ 1 , 2 , 3 ] , `` y '' : [ 3 , 4 , 5 ] , `` z ''...
Inconsistent behavior of jitted function
Python
I am trying to vectorize a loop iteration using NumPy but am struggling to achieve the desired results . I have an array of pixel values , so 3 dimensions , say ( 512,512,3 ) and need to iterate each x , y and calculate another value using a specific index in the third dimension . An example of this code in a standard ...
for i in xrange ( width ) : for j in xrange ( height ) : temp = math.sqrt ( ( scalar1-array [ j , i,1 ] ) **2+ ( scalar2-array [ j , i,2 ] ) **2 ) temp = np.sqrt ( ( scalar1-array [ : , : ,1 ] ) **2+ ( scalar2-array [ : , : ,2 ] ) **2 ) temp = np.sqrt ( ( cb_key-fg_cbcr_array [ : , : ,1 ] ) **2+ ( cr_key-fg_cbcr_array ...
Vectorizing loops in NumPy
Python
This is probably a kinda commonly asked question but I could do with help on this . I have a list of class objects and I 'm trying to figure out how to make it print an item from that class but rather than desplaying in the ; but instead to show a selected attribute of a chosen object of the class . Can anyone help wit...
< __main__.evolutions instance at 0x01B8EA08 >
python - readable list of objects
Python
I need to write a function that calculates the sum of all numbers n.It helps to imagine the above rows as a 'number triangle . ' The function should take a number , n , which denotes how many numbers as well as which row to use . Row 5 's sum is 65 . How would I get my function to do this computation for any n-value ? ...
Row 1 : 1 Row 2 : 2 3 Row 3 : 4 5 6 Row 4 : 7 8 9 10 Row 5 : 11 12 13 14 15 Row 6 : 16 17 18 19 20 21
Sum of all numbers
Python
I 'm am attempting to setup some import hooks through sys.meta_path , in a somewhat similar approach to this SO question . For this , I need to define two functions find_module and load_module as explained in the link above . Here is my load_module function , which works fine for most modules , but fails for PyQt4.QtCo...
import impdef load_module ( name , path ) : fp , pathname , description = imp.find_module ( name , path ) try : module = imp.load_module ( name , fp , pathname , description ) finally : if fp : fp.close ( ) return module name = `` QtCore '' path = [ '/usr/lib64/python2.7/site-packages/PyQt4 ' ] mod = load_module ( name...
Import hooks for PyQt4.QtCore
Python
I 'm using argparse with several subparsers . I want my program to take options for verbosity anywhere in the args , including the subparser.By default , options for the main parser will throw an error if used for subparsers : I looked into parent parsers , from this answer.For some reason though , none of the shared f...
from argparse import ArgumentParserp = ArgumentParser ( ) p.add_argument ( ' -- verbose ' , '-v ' , action='count ' ) sub = p.add_subparsers ( ) a = sub.add_parser ( ' a ' ) print ( p.parse_args ( ) ) $ python tmp.py -v aNamespace ( verbose=1 ) $ python tmp.py a -vusage : tmp.py [ -h ] [ -- verbose ] { a } ... tmp.py :...
Argparse : options for subparsers override main if both share parent
Python
How can I remove the NaN rows from the array below using indices ( since I will need to remove the same rows from a different array.I get the indices of the rows to be removed by using the commandBut using what I would normally use on a 2D array does not produce the desired result , losing the array structure.How can I...
array ( [ [ [ nan , 0. , 0. , 0 . ] , [ 0. , 0. , 0. , 0 . ] , [ 0. , 0. , 0. , 0 . ] ] , [ [ 0. , 0. , 0. , 0 . ] , [ 0. , nan , 0. , 0 . ] , [ 0. , 0. , 0. , 0 . ] ] ] ) a [ np.isnan ( a ) .any ( axis=2 ) ] a [ ~np.isnan ( a ) .any ( axis=2 ) ] array ( [ [ 0. , 0. , 0. , 0 . ] , [ 0. , 0. , 0. , 0 . ] , [ 0. , 0. , 0...
Removing NaN rows from a three dimensional array
Python
I have a simple test : My problem is that coverage still shows get_approved_member_count line as NOT tested : How do I satisfy the above for coverage ? To run the tests I 'm using Django Nose with Coverage : Console :
class ModelTests ( TestCase ) : def test_method ( self ) : instance = Activity ( title= '' Test '' ) self.assertEqual ( instance.get_approved_member_count ( ) , 0 ) TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'NOSE_ARGS = [ ' -- with-coverage ' , ' -- cover-html ' , ' -- cover-package=apps.users , apps.activities ' ,...
Using coverage , how do I test this line ?
Python
I 'm trying to change the length of a Primary Key field from 3 to 6.Model : Migration : However I 'm getting this error message , which I do n't quite understand , why it thinks that I 'm changing it to null . _mysql_exceptions.DataError : ( 1171 , 'All parts of a PRIMARY KEY must be NOT NULL ; if you need NULL in a ke...
class Server ( db.Model ) : country_code = db.Column ( db.String ( 6 ) , primary_key=True ) def upgrade ( ) : op.alter_column ( 'server ' , 'country_code ' , existing_type=mysql.VARCHAR ( length=3 ) , type_=sa.String ( length=6 ) )
Alembic : How to change the length of a Primary Key field ?
Python
I wrote a small script in python where I 'm trying to extract or crop the part of the playing card that represents the artwork only , removing all the rest . I 've been trying various methods of thresholding but could n't get there . Also note that I ca n't simply record manually the position of the artwork because it ...
from matplotlib import pyplot as pltimport cv2img = cv2.imread ( filename ) gray = cv2.cvtColor ( img , cv2.COLOR_BGR2GRAY ) ret , binary = cv2.threshold ( gray , 0 , 255 , cv2.THRESH_OTSU | cv2.THRESH_BINARY ) binary = cv2.bitwise_not ( binary ) kernel = np.ones ( ( 15 , 15 ) , np.uint8 ) closing = cv2.morphologyEx ( ...
Extract artwork from table game card image with OpenCV
Python
I use Tensorflow 1.14.0 and Keras 2.2.4 . The following code implements a simple neural network : The final val_loss after 20 epochs is 0.7751 . When I uncomment the only comment line to add the batch normalization layer , the val_loss changes to 1.1230.My main problem is way more complicated , but the same thing occur...
import numpy as npnp.random.seed ( 1 ) import randomrandom.seed ( 2 ) import tensorflow as tftf.set_random_seed ( 3 ) from tensorflow.keras.models import Model , Sequentialfrom tensorflow.keras.layers import Input , Dense , Activationx_train=np.random.normal ( 0,1 , ( 100,12 ) ) model = Sequential ( ) model.add ( Dense...
batch normalization , yes or no ?
Python
I 've switched to Python pretty recently and I 'm interested to clean up a very big number of web pages ( around 12k ) ( but can be considered just as easily text files ) by removing some particular tags or some other string patterns . For this I 'm using the re.sub ( .. ) function in Python.My question is if it 's bet...
re.sub ( r '' < [ ^ < > ] * > '' , content ) re.sub ( r '' some_other_pattern '' , content ) re.sub ( r '' < [ ^ < > ] * > |some_other_pattern '' , content )
Replacement using multiple regexes or a bigger one in Python
Python
A Java application sends an XML to a Python application . They are both on the same machine.When I open the received file I can see extra lines ( because of extra CRs ) . What could be the reason for this ? This is the receiver : This is the sender : This is the original file : This is the received :
f = open ( ' c : /python/python.xml ' , ' w ' ) while 1 : print ( `` xxx '' ) data = socket.recv ( recv_frame ) remain_byte = remain_byte - len ( data ) print ( remain_byte ) f.write ( data ) if ( something ) : break while ( ( bytesRead = file_inp.read ( buffer ) ) > 0 ) { output_local.write ( buffer , 0 , bytesRead ) ...
Python Adds An Extra CR At The End Of The Received Lines
Python
I 'd like to dynamically import various settings and configurations into my python program - what you 'd typically do with a .ini file or something similar.I started with JSON for the config file syntax , then moved to YAML , but really I 'd like to use Python . It 'll minimize the number of formats and allow me to use...
account_config = __import__ ( settings.CONFIG_DIR + '.account_name ' , fromlist= [ settings.CONFIG_DIR ] )
Using Python as the config language for a Python program
Python
I have this code in a fileWhen I run python broken.py , I get the traceback : I do n't really see the problem here . Is n't x defined in the comprehension ? What 's stranger is how this seems to execute without an error when pasted directly into the python interpreter ... EDIT : This works if I use a list comprehension...
class Sudoku ( dict ) : COLUMNS = [ { ( x , y ) for y in xrange ( 9 ) } for x in xrange ( 9 ) ] Traceback ( most recent call last ) : File `` U : \broken.py '' , line 1 , in < module > class Sudoku ( dict ) : File `` U : \broken.py '' , line 3 , in Sudoku { ( x , y ) for y in xrange ( 9 ) } for x in xrange ( 9 ) File `...
NameError in nested comprehensions
Python
I want to apply a `` black box '' Python function f to a large array arr . Additional assumptions are : Function f is `` pure '' , e.g . is deterministic with no side effects.Array arr has a small number of unique elements.I can achieve this with a decorator that computes f for each unique element of arr as follows : M...
import numpy as npfrom time import sleepfrom functools import wrapsN = 1000np.random.seed ( 0 ) arr = np.random.randint ( 0 , 10 , size= ( N , 2 ) ) def vectorize_pure ( f ) : @ wraps ( f ) def f_vec ( arr ) : uniques , ix = np.unique ( arr , return_inverse=True ) f_range = np.array ( [ f ( x ) for x in uniques ] ) ret...
Vectorizing a `` pure '' function with numpy , assuming many duplicates
Python
Suppose I have a pandas dataframe with two columns : ID and Days . DataFrame is sorted by ascending order in both variables . For example : I want to add a third column , which would give a `` session '' number for every ID*day . By `` session '' i mean a sequence of days with difference less than 2 days between days o...
# Initial datasetdata = pd.DataFrame ( { 'id ' : np.repeat ( [ 1 , 2 ,3 ] , 4 ) , 'day ' : [ 1 , 2 , 10 , 11 , 3 , 4 , 12 , 15 , 1 , 20 , 21 , 24 ] } ) id day0 1 11 1 22 1 103 1 114 2 35 2 46 2 127 2 158 3 19 3 2010 3 2111 3 24 id day session0 1 1 01 1 2 02 1 10 13 1 11 14 2 3 05 2 4 06 2 12 17 2 15 2 8 3 1 09 3 20 110...
Fast looping through Python dataframe with previous row reference