lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Python
Using vim searching capabilities , is it possible to avoid matching on a comment block/line.As an example , I would like to match on 'image ' in this python code , but only in the code , not in the comment : Using regular expressions I would do something like this : /^ [ ^ # ] .* ( image ) . */gm But it does not seem t...
# Export the imageif export_images and i + j % 1000 == 0 : export_image ( img_mask , `` images/image { } .png '' .format ( image_id ) ) image_id += 1
Vim searching : avoid matches within comments
Python
Output : Joe is ( 42+10 ) years oldExpected output : Joe is 52 years old
print ( ' % s is ( % d+10 ) years old ' % ( 'Joe ' , 42 ) )
How to perform action on a integer placeholder in python ?
Python
The majority of my programming experience has been with C++ . Inspired by Bjarne Stroustrup 's talk here , one of my favorite programming techniques is `` type-rich '' programming ; the development of new robust data-types that will not only reduce the amount of code I have to write by wrapping functionality into the t...
class BoundInt : def __init__ ( self , target = 0 , low = 0 , high = 1 ) : self.lowerLimit = low self.upperLimit = high self._value = target self._balance ( ) def _balance ( self ) : if ( self._value > self.upperLimit ) : self._value = self.upperLimit elif ( self._value < self.lowerLimit ) : self._value = self.lowerLim...
Pythonic way to Implement Data Types ( Python 2.7 )
Python
I have data with a MultiIndex , like this : Here is the result for summing by group over the first index level : Seems reasonable -- I summed over the first level of the index , so the 2nd level is gone . But if instead I use the rolling method : I getwhere for some reason pandas has decided to return a 3-level index ,...
import itertoolsidx1 = list ( 'XYZ ' ) idx2 = range ( 3 ) idx = pd.MultiIndex.from_tuples ( list ( itertools.product ( idx1 , idx2 ) ) ) df = pd.DataFrame ( np.random.rand ( 9,4 ) , columns=list ( 'ABCD ' ) , index=idx ) A B C Dfirst second X 0 0.808432 0.708881 0.411515 0.704168 1 0.322688 0.093869 0.651238 0.146480 2...
How to control index returned by pandas groupby with rolling summary function
Python
I am doing scrapy tutorial in scrapy documentation .This is my current directory looks like : The dmoz_spider.py is the same as described in scrapy tutorial page.Then I run this command from current directoryBut I get the error message : Is there any suggestions which part did I do wrong ? I have checked similar questi...
.├── scrapy.cfg└── tutorial ├── __init__.py ├── __init__.pyc ├── items.py ├── pipelines.py ├── settings.py ├── settings.pyc └── spiders ├── __init__.py ├── __init__.pyc └── dmoz_spider import scrapyclass DmozSpider ( scrapy.Spider ) : name = `` dmoz '' allowed_domains = [ `` dmoz.org '' ] start_urls = [ `` http : //www...
Scrapy can not find spider
Python
Consider the following code : You 'd expect it to print hey However It raises a SyntaxError , The same error I 'm trying to avoid . So Can all Exceptions be handled using a try-except block ? Well If SyntaxError 's were an exception why is it included in the built-in exceptions ? and finally how can I fix the above pie...
try : if True a = 1 # It 's missing a colon So it 's a SyntaxError ! ! ! ! ! ! ! except SyntaxError : print 'hey '
Can Syntax Errors be handled ?
Python
Define a procedure , same_structure , that takes two inputs . It should outputTrue if the lists have the same structure , and Falseotherwise . Two values , p and q have the same structure if : EDIT : To make the picture clear the following are the expected outputI thought recursion would be best to solve this problem i...
Neither p or q is a list.Both p and q are lists , they have the same number of elements , and eachelement of p has the same structure as the corresponding element of q. same_structure ( [ 1 , 0 , 1 ] , [ 2 , 1 , 2 ] ) -- - > Truesame_structure ( [ 1 , [ 0 ] , 1 ] , [ 2 , 5 , 3 ] ) -- - > Falsesame_structure ( [ 1 , [ 2...
How to find out two lists with same structure in python ?
Python
I try to use numpy with nptyping 's Array to do my typehinting.I tried the following : I get an typerror : Expected Type 'Array [ float , Any ] ' , got 'ndarray ' insteadas far as I understand from this : https : //pypi.org/project/nptyping/ thats how it should look .
enemy_hand : Array [ float , 48 ] = np.zeros ( 48 )
Numpy Typehint with nptyping and Array in PyCharm
Python
I am writing a python script to parse the content of Wordpress Export XML ( wp xml ) to generate a LaTex document . So far the wp xml is parsed via lxml.etree and the code generates a new xml tree to be processed by texml , which in turn generates the tex file.Currently I extract each post along with certain metadata (...
args = [ 'pandoc ' , '-f ' , 'html ' , '-t ' , 'latex ' ] p = Popen ( args , stdout=PIPE , stdin=PIPE , stderr=PIPE ) tex_result = p.communicate ( input= ( my_html_string ) .encode ( 'utf-8 ' ) ) [ 0 ] < strong > Lorem ipsum dolor < /strong > sit amet , consectetur adipiscing elit. < a href= '' http : //link_to_source_...
Convert HTML img tags into figures with caption in LaTeX
Python
I have the need to ensure that a dict can only accept a certain type of objects as values . It also have to be pickable.Here is my first attempt : If I test it with the following code ( python 3.5 ) I get the error : TypeError : isinstance ( ) arg 2 must be a type or tuple of types . It seems that it is not loading the...
import pickleclass TypedDict ( dict ) : _dict_type = None def __init__ ( self , dict_type , *args , **kwargs ) : super ( ) .__init__ ( *args , **kwargs ) self._dict_type = dict_type def __setitem__ ( self , key , value ) : if not isinstance ( value , self._dict_type ) : raise TypeError ( 'Wrong type ' ) super ( ) .__se...
Pickle a dict subclass without __reduce__ method does not load member attributes
Python
I have a many long strings ( 9000+ characters each ) that represent mathematical expressions . I originally generate the expressions using sympy , a python symbolic algebra package . A truncated example is : I end up copying the text in the string and then using is as code ( i.e . copy the text between ' and ' and then...
a = 'm [ i ] **2* ( zb [ layer ] *m [ i ] **4 - 2*zb [ layer ] *m [ j ] **2*m [ i ] **2 + zb [ layer ] *m [ j ] **4 - zt [ layer ] *m [ i ] **4 + 2*zt [ layer ] *m [ j ] **2*m [ i ] **2 - zt [ layer ] *m [ j ] **4 ) ** ( -1 ) *ab [ layer ] *sin ( m [ i ] *zb [ layer ] ) *sin ( m [ j ] *zb [ layer ] ) ' def foo ( args )...
How to put appropriate line breaks in a string representing a mathematical expression that is 9000+ characters ?
Python
I have a Pandas data frame created the following way : It looks like this : Then I have a function that takes the values of each genes ( row ) to compute a certain score : In reality I need to apply this function on 40K over rows . And currently it runsvery slow using Pandas 'apply ' : What 's the faster alternative to...
import pandas as pddef create ( n ) : df = pd.DataFrame ( { 'gene ' : [ `` foo '' , `` bar '' , `` qux '' , `` woz '' ] , 'cell1 ' : [ 433.96,735.62,483.42,10.33 ] , 'cell2 ' : [ 94.93,2214.38,97.93,1205.30 ] , 'cell3 ' : [ 1500,90,100,80 ] } ) df = df [ [ `` gene '' , '' cell1 '' , '' cell2 '' , '' cell3 '' ] ] df = p...
Fast alternative to run a numpy based function over all the rows in Pandas DataFrame
Python
I have different formats of date prefixes and other prefixes . I needed to create a grammar which can skip this prefixes and obtain the required data . But , when I use SkipTo and Or ( ^ ) operator , I am not able to get the desired results.File Contents : OUTPUT : Desired output : Can anyone help me understand this ?
from pyparsing import *import pprintdef print_cal ( v ) : print vf=open ( `` test '' , '' r '' ) NAND_TIME= Group ( SkipTo ( Literal ( `` NAND TIMES '' ) , include=True ) + Word ( nums ) +Literal ( `` : '' ) .suppress ( ) +Word ( nums ) ) .setParseAction ( lambda t : print_cal ( 'NAND TIME ' ) ) TEST_TIME= Group ( Skip...
PyParsing : how to use SkipTo and OR ( ^ ) operator
Python
I want to send a HTML email to the users after they signup to the website . Earlier I wrote this script to send But instead of placing the HTML directly in the main code , I want to have a separate HTML file which would be used as a body . I tried to do it as follows : but in vain . How can I use a HTML file in the pla...
from google.appengine.api import mailmessage = mail.EmailMessage ( sender= '' Example.com Support < support @ example.com > '' , subject= '' Your account has been approved '' ) message.to = `` Albert Johnson < Albert.Johnson @ example.com > '' message.body = `` '' '' Dear Albert : Your example.com account has been appr...
Send HTML email in Appengine [ PYTHON ] using HTML file
Python
I have a Dataframe likeI need to assign random value for each pair between 0 and 1 but have to assign the same random value for both similar pairs like `` 1-3 '' , `` 3-1 '' and other pairs . I 'm expecting a result dataframe likeHow to assign same random value similar pairs like `` A-B '' and `` B-A '' in python panda...
Sou Des 1 3 1 4 2 3 2 4 3 1 3 2 4 1 4 2 Sou Des Val 1 3 0.1 1 4 0.6 2 3 0.9 2 4 0.5 3 1 0.1 3 2 0.9 4 1 0.6 4 2 0.5
Assign same random value to A-B , B-A pairs in python Dataframe
Python
I have this small snippet of python code that I wrote . It works , but I think there should be a more streamlined method to achieve the same results . I 'm just not seeing it . Any ideas ?
if tx_avt > = 100 : tx = 1 elif tx_avt < 100 and tx_avt > = 50 : tx = 2 elif tx_avt < 50 and tx_avt > = 25 : tx = 3elif tx_avt < 25 and tx_avt > = 12.5 : tx = 4 else : tx = 5
Is there a better way to write this `` if '' boolean evaluation ?
Python
So recently I understand the concept of function closure.As much as I understand , the objective of function closure is to keep an active reference to the object , in order to avoid garbage collection of this object . This is why the following works fine : The thing is ( always as much as I understood ) before the exec...
def outer ( ) : somevar = [ ] assert `` somevar '' in locals ( ) and not `` somevar '' in globals ( ) def inner ( ) : assert `` somevar '' in locals ( ) and not `` somevar '' in globals ( ) somevar.append ( 5 ) return somevar return innerfunction = outer ( ) somevar_returned = function ( ) assert id ( somevar_returned ...
Where does Python store the name binding of function closure ?
Python
Django allows me to do this : But I want to do this : I know that the lookup __isendof does n't exist . But I want something like this . I want it to be the converse of __endswith . It should find all chairs such that 'hello'.endswith ( chair.name ) .Possible in Django ? ORM operations are preferable to SQL ones .
chair = Chair.objects.filter ( name__endswith='hello ' ) chair = Chair.objects.filter ( name__isendof='hello ' )
Django : Converse of ` __endswith `
Python
My question is similar to one asked here . I have a dataframe and I want to repeat each row of the dataframe k number of times . Along with it , I also want to create a column with values 0 to k-1 . SoCommand below does half of the job . I am looking for pandas way of adding the repeat_id column .
import pandas as pddf = pd.DataFrame ( data= { 'id ' : [ ' A ' , ' B ' , ' C ' ] , ' n ' : [ 1 , 2 , 3 ] , ' v ' : [ 10 , 13 , 8 ] } ) what_i_want = pd.DataFrame ( data= { 'id ' : [ ' A ' , ' B ' , ' B ' , ' C ' , ' C ' , ' C ' ] , ' n ' : [ 1 , 2 , 2 , 3 , 3 , 3 ] , ' v ' : [ 10 , 13 , 13 , 8 , 8 , 8 ] , 'repeat_id ' ...
Replicating rows in pandas dataframe by column value and add a new column with repetition index
Python
I have a onehot-encoded columns , df with zeros as `` nan '' . I 'm trying to convert onehot encoded columns to a single column.Assume the below dataframe , dfRequired Output
p1 | p2 | p3 | p4 | p5 | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -0 cat nan nan nan nan1 nan dog nan nan nan2 nan nan horse nan nan3 nan nan nan donkey nan4 nan nan nan nan pig animals -- -- -- -- -- -- -- -- -0 cat1 dog2 horse3 donkey4 pig
How to convert multiple columns to single column ?
Python
I 've observed this behavior and I do n't quite understand . Let say I make a query : And I get : Then I want to check if a certain value is in the list of pks returned : This will return True , but if instead I change result to : I still get : But when I do : I get False . I tried using select_related instead , and th...
result = model.objects.all ( ) result_pks = result.values_list ( `` id '' , flat=True ) print result_pks [ 1,2,3,4 ] val = 2print val in result_pks result = model.objects.prefetch_related ( `` related_field '' ) .all ( ) result_pks = result.values_list ( `` id '' , flat=True ) print result_pks [ 1,2,3,4 ] val=2print va...
Django : check if value in values_list with & without prefetch_related/select_related
Python
I 've been bashing my head against this brick wall for what seems like an eternity , and I just ca n't seem to wrap my head around it . I 'm trying to implement an autoencoder using only numpy and matrix multiplication . No theano or keras tricks allowed.I 'll describe the problem and all its details . It is a bit comp...
def cost ( x , xhat ) : return ( 1.0/ ( 2 * m ) ) * np.trace ( np.dot ( x-xhat , ( x-xhat ) .T ) ) import numpy as npdef g ( x ) : # sigmoid activation functions return 1/ ( 1+np.exp ( -x ) ) # same shape as x ! def gGradient ( x ) : # gradient of sigmoid return g ( x ) * ( 1-g ( x ) ) # same shape as x ! def cost ( x ...
Stuck implementing simple neural network
Python
Let 's get right into the question . The following is the daily data : I want to select the rows starting from the first row with a monthly increment , that is , the rows whose index is 2012-04-16 , 2012-05-16 , 2012-06-16 , ... . I can just use relativedelta and manually add them but I 'm wondering if there is a more ...
AAA BBB CCCdate 2012-04-16 44.48 28.48 17.652012-04-17 44.59 28.74 17.652012-04-18 44.92 28.74 17.722012-04-19 44.92 28.62 17.722012-04-20 45.09 28.68 17.712012-04-23 45.09 28.40 17.762012-04-24 45.09 28.51 17.732012-04-25 45.01 28.76 17.732012-04-26 45.40 28.94 17.762012-04-27 45.57 29.02 17.792012-04-30 45.45 28.90 1...
Python DataFrame selecting the rows with monthly increment from daily data
Python
I am performing hyperparameter tuning of RandomForest as follows using GridSearchCV.The result I got is as follows.Afterwards , I reapply the tuned parameters to x_test as follows.However , I am still not clear how to use GridSearchCV with 10-fold cross validation ( i.e . not just apply the tuned parameters to x_test )...
X = np.array ( df [ features ] ) # all featuresy = np.array ( df [ 'gold_standard ' ] ) # labelsx_train , x_test , y_train , y_test = train_test_split ( X , y , test_size=0.3 , random_state=42 ) param_grid = { 'n_estimators ' : [ 200 , 500 ] , 'max_features ' : [ 'auto ' , 'sqrt ' , 'log2 ' ] , 'max_depth ' : [ 4,5,6,7...
How to perform GridSearchCV with cross validation in python
Python
I wrote a ternary search tree in Python and I 've noticed that when the tree gets very deep , attempting to delete it causes Python to hang indefinitely . Here is a stripped version of the code that produces this behaviour : This prints out `` This gets printed '' , but not `` This does n't get printed '' . Trying to d...
import randomimport sysfrom collections import dequeclass Node ( ) : __slots__ = ( `` char '' , `` count '' , `` lo '' , `` eq '' , `` hi '' ) def __init__ ( self , char ) : self.char = char self.count = 0 self.lo = None self.eq = None self.hi = Noneclass TernarySearchTree ( ) : `` '' '' Ternary search tree that stores...
Python hangs indefinitely trying to delete deeply recursive object
Python
Problem : What 'd I like to do is step-by-step reduce a value in a Series by a continuously decreasing base figure.I 'm not sure of the terminology for this - I did think I could do something with cumsum and diff but I think I 'm leading myself on a wild goose chase there ... Starting code : Desired output : Rationale ...
import pandas as pdALLOWANCE = 100values = pd.Series ( [ 85 , 10 , 25 , 30 ] ) desired = pd.Series ( [ 0 , 0 , 20 , 30 ] )
Calculate new value based on decreasing value
Python
Here 's what I 'm trying to do : go here , then hit `` search '' . Grab the data , then hit `` next '' , and keep hitting next until you 're out of pages.Everything up to hitting `` next '' works . Here 's my code.The format of r.content is radically different the two times I print it , indicating that something differ...
< input type= '' hidden '' name= '' __VIEWSTATEGENERATOR '' id= '' __VIEWSTATEGENERATOR '' value= '' 4424DBE6 '' > < input type= '' hidden '' name= '' __VIEWSTATEENCRYPTED '' id= '' __VIEWSTATEENCRYPTED '' value= '' '' > < input type= '' hidden '' name= '' __EVENTVALIDATION '' id= '' __EVENTVALIDATION '' value= '' TlIg...
Making subsequent POST request in session does n't work - web scraping
Python
Why is this working ? Should n't be this a SyntaxError : Non-ASCII character '\xc3 ' in file ... ? There are unicode literals in the string.When I prefix it with u , the results are different : Why ? What is the difference between the internal representations in python ? How can I see it myself ? : )
# -*- coding : utf-8 -*-a = 'éáűőúöüó€'print type ( a ) # < type 'str ' > print a # éáűőúöüó€print ord ( a [ -1 ] ) # 172 # -*- coding : utf-8 -*-a = u'éáűőúöüó€'print type ( a ) # < type 'unicode ' > print a # éáűőúöüó€print ord ( a [ -1 ] ) # 8364
How are these strings represented internally in Python interpreter ? I do n't understand
Python
I have some arguments taken from the user and passed along function to function ( each function in a different class ) , until it eventually gets to a function that does some processing and then the solution is returned up the chain . Up the chain , the functions become more and more abstract merging results from multi...
def top_level ( a=1 , b=1 , c=1 , d=1 , e=1 ) : `` '' '' Compute sum of five numbers . : param a : int , a : param b : int , b : param c : int , c : param d : int , d : param e : int , e : return : int , sum `` '' '' return mid_level ( a , b , c , d , e ) def mid_level ( *args , **kwargs ) : return bottom_level ( *args...
What 's the pythonic way to pass arguments between functions ?
Python
I noticed something odd with the scipy.misc.resize -- it seems using any interpolation method other than 'nearest ' results in a roughly 1x1 pixel shift away from ( 0,0 ) in the resulting image . Here 's a totally synthetic example of taking a 3x3 image to 6x6 : Now it seems that the center of mass moves for bilinear a...
> > > srcarray ( [ [ 0. , 0. , 0 . ] , [ 0. , 64. , 0 . ] , [ 0. , 0. , 0 . ] ] ) > > > imresize ( src , ( 6 , 6 ) , interp='bicubic ' , mode= ' F ' ) array ( [ [ 1. , 0. , -5. , -8. , -5. , 0 . ] , [ 0. , 0. , 0. , 0. , 0. , 0 . ] , [ -5. , 0. , 25. , 40. , 25. , 0 . ] , [ -8. , 0. , 40. , 64. , 40. , 0 . ] , [ -5. , ...
SciPy image resizing shift - expected behavior or bug ?
Python
I 've got some tests that need to count the number of warnings raised by a function . In Python 2.6 this is simple , usingUnfortunately , with is not available in Python 2.4 , so what else could I use ? I ca n't simply check if there 's been a single warning ( using warning filter with action='error ' and try/catch ) ,...
with warnings.catch_warnings ( record=True ) as warn : ... self.assertEquals ( len ( warn ) , 2 )
Count warnings in Python 2.4
Python
I want to add an argument named 'print ' to my argument parserYields :
arg_parser.add_argument ( ' -- print ' , action='store_true ' , help= '' print stuff '' ) args = arg_parser.parse_args ( sys.argv [ 1 : ] ) if args.print : print `` stuff '' if args.print : ^SyntaxError : invalid syntax
argparse argument named `` print ''
Python
I have a dataframe that looks like this : How do I divide all elements of df by df [ `` three '' ] ? I tried df.div ( df [ `` three '' ] , level= [ 1,2 ] ) with no luck .
one two three 1 2 1 2 1 2 X Y X Y X Y X Y X Y X Ya 0.3 -0.6 -0.3 -0.2 1.5e+00 0.3 -1.0e+00 1.2 0.6 -9.8e-02 -0.4 0.4b -0.6 -0.4 -1.1 2.3 -7.4e-02 0.7 -7.4e-02 -0.5 -0.3 -6.8e-01 1.1 -0.1
Performing arithmetic with a multi-index pandas dataframe that needs broadcasting at several levels
Python
I have an Organization database in MongoDB . I am trying to save data in that database using mongoengine . I am using Djnago server . when i am creating the object then its working fine but after editing its giving some error .
class Organization ( Document ) : username= StringField ( ) ancestors = ListField ( ReferenceField ( 'Organization ' , dbref=False ) , default = list ) parents = ListField ( ReferenceField ( 'Organization ' , dbref=False ) , default = list ) descendants = ListField ( ReferenceField ( 'Organization ' , dbref=False ) , d...
OperationError : Could not save document ( LEFT_SUBFIELD only supports Object : ancestors.0 not : 7 )
Python
Please take a look the comment inside __getattr__ . How do I do that ? I am using Python 3 . The reason is I want to create attribute dynamically but I do n't want to do that when using hasattr . Thanks .
class a_class : def __getattr__ ( self , name ) : # if called by hasattr ( a , ' b ' ) not by a.b # print ( `` I am called by hasattr '' ) print ( name ) a = a_class ( ) a.b_attrhasattr ( a , 'c_attr ' )
How to differentiate between hasattr and normal attribute access in __getattr__ ?
Python
Assume a script that initiates a TKinter GUI ( e.g. , scripts/launch_GUI.py ) and is part of a PyPI package ( e.g. , MyPackage ) .The launch script is very minimalistic : What unittest would you recommend to evaluate if the TKinter GUI is properly started upon initiating launch_GUI.py ? Note : I only wish to evaluate i...
.├── appveyor.yml├── MyPackage│ ├── TkOps.py│ └── CoreFunctions.py├── README.md├── requirements.txt├── scripts│ ├── launch_CLI.py│ └── launch_GUI.py├── setup.py└── tests └── MyPackage_test.py # ! /usr/bin/env python2if __name__ == '__main__ ' : import sys , os sys.path.append ( os.path.join ( os.path.dirname ( __file__...
Unittest for invoking a TKinter GUI
Python
In Python 3.4.3 , I was trying to width-align some fields using the string.format ( ) operator , and it appears to count zero-length control characters against the width total . Sample code : This will output : ( with the second output having '12 ' in red , but I ca n't reproduce that in SO ) In the second case , I 've...
ANSI_RED = `` \033 [ 31m '' ANSI_DEFAULT= '' \033 [ 39m\033 [ 49m '' string1 = `` 12 '' string2 = ANSI_RED+ '' 12 '' +ANSI_DEFAULTprint ( `` foo { :4s } bar '' .format ( string1 ) ) print ( `` foo { :4s } bar '' .format ( string2 ) ) foo12 barfoo12bar
Python counting zero-length control characters in string formatting width field ?
Python
Yesterday I came across this odd unpacking difference between Python 2 and Python 3 , and did not seem to find any explanation after a quick Google search.Python 2.7.8Python 3.4.2I know it probably does not affect the correctness of a program , but it does bug me a little . Could anyone give some insights about this di...
a = 257b = 257a is b # Falsea , b = 257 , 257a is b # False a = 257b = 257a is b # Falsea , b = 257 , 257a is b # True
What is with this change of unpacking behavior from Python2 to Python3
Python
I 'm a bit confused about modifying tuple members . The following does n't work : But this does work : Also works : Does n't work , and works ( huh ? ! ) : Seemingly equivalent to previous , but works : So what exactly are the rules of the game , when you can and ca n't modify something inside a tuple ? It seems to be ...
> > > thing = ( [ ' a ' ] , ) > > > thing [ 0 ] = [ ' b ' ] TypeError : 'tuple ' object does not support item assignment > > > thing ( [ ' a ' ] , ) > > > thing [ 0 ] [ 0 ] = ' b ' > > > thing ( [ ' b ' ] , ) > > > thing [ 0 ] .append ( ' c ' ) > > > thing ( [ ' b ' , ' c ' ] , ) > > > thing [ 0 ] += 'd'TypeError : 'tu...
a mutable type inside an immutable container
Python
I 'm using the connexion framework for flask . I 'd like to group several related functions into a class and I 'm wondering whether methods of a class can be used for operationId instead of functions.Something likein the describing yaml file :
class Job : def get ( ) : `` something '' def post ( ) : `` something '' paths : /hello : post : operationId : myapp.api.Job.post
Connexion class based handling
Python
A Python HOMEWORK Assignment asks me to write a function “ that takes as input a positive whole number , and prints out a multiplication , table showing all the whole number multiplications up to and including the input number. ” ( Also using the while loop ) I know how to start , but don ’ t know what to do next . I j...
# This is an example of the output of the functionprint_multiplication_table ( 3 ) > > > 1 * 1 = 1 > > > 1 * 2 = 2 > > > 1 * 3 = 3 > > > 2 * 1 = 2 > > > 2 * 2 = 4 > > > 2 * 3 = 6 > > > 3 * 1 = 3 > > > 3 * 2 = 6 > > > 3 * 3 = 9 def print_multiplication_table ( n ) : # n for a number if n > =0 : while somehting : # The c...
Writing a simple function using while
Python
I have a large list of lists and need to remove duplicate elements based on specific criteria : Uniqueness is determined by the first element of the lists.Removal of duplicates is determined by comparing the value of the second element of the duplicate lists , namely keep the list with the lowest second element . [ [ 1...
sorted ( sorted ( the_list , key=itemgetter ( 1 ) , reverse=True ) , key=itemgetter ( 0 ) ) [ ... [ 33554432 , 50331647 , 1695008306 ] , [ 33554432 , 34603007 , 1904606324 ] , [ 33554432 , 33554687 , 2208089473 ] , ... ]
Removing duplicates from a list of lists based on a comparison of an element of the inner lists
Python
Edit : This will be fixed in a new version of pythonnet ( when this pull request is merged ) .I have a problem with Python.NET inheritance . I have a DLL which consists of the following code : I would expect a call to the Transmit method of an instance of InheritedClass to write to the console and return true and the T...
using System ; namespace InheritanceTest { public class BaseClass { public bool Transmit ( ) { throw new NotImplementedException ( ) ; } } public class InheritedClass : BaseClass { public new bool Transmit ( ) { Console.WriteLine ( `` Success ! `` ) ; return true ; } } } # # setupimport clrimport osclr.AddReference ( o...
Why does Python.NET use the base method instead of the method from a derived class ?
Python
I know that I can interleave two python lists with : Now I need to interleave a list with a fixed element like :
[ elem for pair in zip ( *lists ) for elem in pair ] list = [ 1 , 2 , 3 , 4 ] # python magic output = [ 1 , 0 , 2 , 0 , 3 , 0 , 4 ]
Interleave list with fixed element
Python
I have a sparse matrix that I arrived at through a complicated bunch of calculations which I can not reproduce here . I will try to find a simpler example of this.For now , does anyone know how it might be ( even remotely ) possible that I could have a sparse matrix X with the property that : My only guess is that if I...
In [ 143 ] : X.sum ( 0 ) .sum ( ) Out [ 143 ] : 131138In [ 144 ] : X.sum ( ) Out [ 144 ] : 327746In [ 145 ] : X.sum ( 1 ) .sum ( ) Out [ 145 ] : 327746In [ 146 ] : type ( X ) Out [ 146 ] : scipy.sparse.csr.csr_matrix In [ 164 ] : X.tocsr ( ) .sum ( 0 ) .sum ( ) Out [ 164 ] : 131138In [ 165 ] : X.tocsc ( ) .sum ( 0 ) .s...
Scipy Sparse Matrices - Inconsistent Sums
Python
So weakref.proxy objects do n't at all seem to work like weakref.ref objects when it comes to checking if the reference is live , or 'dereferencing ' them , or really in just about any way at all , actually . : PThey do still seem to have their place - such as maintaining a list of objects which respond to events . Sin...
> > > mylist # note the object at mylist [ 1 ] is already dead ... [ < weakproxy at 0x10ccfe050 to A at 0x10ccf9f50 > , < weakproxy at 0x10ccfe1b0 to NoneType at 0x10cb53538 > ] > > > for i in mylist [ : ] : ... try : ... getattr ( i , 'stuff ' ) # the second arg could be any sentinel ; ... # I just want to hit a Refer...
Python - how to moderate list of weakproxy objects
Python
I am currently trying to implement basic matrix vector multiplication in Cython ( as part of a much larger project to reduce computation ) and finding that my code is about 2x slower than Numpy.dot.I am wondering if there is something that I am missing that is resulting in the slowdown . I am writing optimized Cython c...
import numpy as npcimport numpy as npcimport cythonDTYPE = np.float64 ; ctypedef np.float64_t DTYPE_T @ cython.boundscheck ( False ) @ cython.wraparound ( False ) @ cython.nonecheck ( False ) def matrix_vector_multiplication ( np.ndarray [ DTYPE_T , ndim=2 ] A , np.ndarray [ DTYPE_T , ndim=1 ] x ) : cdef Py_ssize_t i ,...
What is causing the 2x slowdown in my Cython implementation of matrix vector multiplication ?
Python
I just realized there is something mysterious ( at least for me ) in the way you can add vertex instructions in Kivy with the with Python statement . For example , the way with is used goes something like this : At the beginning I thought that it was just the with Python statement that I have used occasionally . But su...
... some codeclass MyWidget ( Widget ) ... some code def some_method ( self ) : with self.canvas : Rectangle ( pos=self.pos , size=self.size ) with open ( 'output.txt ' , ' w ' ) as f : f.write ( 'Hi there ! ' ) class MyWidget ( Widget ) ... some code def some_method ( self ) : with self.canvas as c : c.add ( Rectangle...
how does ` with canvas : ` ( Python ` with something ( ) as x : ` ) works implicitly in Kivy ?
Python
I would like to replace all occurrences of 3 or more `` = '' with an equal-number of `` - '' .becomesMy working but hacky solution is to pass a lambda to repl from re.sub ( ) that grabs the length of each match : Can I do this without needing to pass a function to re.sub ( ) ? My thinking would be that I 'd need r ' ( ...
def f ( a , b ) : `` ' Example ======= > > > from x import y `` ' return a == b def f ( a , b ) : `` ' Example -- -- -- - > > > from x import y `` ' return a == b # do n't touch > > > import re > > > s = `` '' '' ... def f ( a , b ) : ... `` ' ... Example ... ======= ... > > > from x import y ... `` ' ... return a == b...
Variable-length replacement with ` re.sub ( ) `
Python
In the following code I want to get just the digits between '- ' and ' u'.I thought i could apply regular expression non capturing groups format ( ? : … ) to ignore everything from '- ' to the first digit . But output always include it . How can i use noncapturing groups format to generate correct ouput ?
df = pd.DataFrame ( { ' a ' : [ 1,2,3,4 ] , ' b ' : [ '41u -428u ' , '31u - 68u ' , '11u - 58u ' , '21u - 318u ' ] } ) df [ ' b ' ] .str.extract ( ' ( ( ? : - [ ] * ) [ 0-9 ] * ) ' , expand=True )
How to use regex non-capturing groups format in Python
Python
I have the following structure for my views directory.and __init__.py starts with the following : In each of the files ( a_management.py , b_management.py ... ) I need to write the same code importing modules : Is it possible to perform all the module imports only in __init__.py ? When I tried , it still seems like the...
views| -- __init__.py| -- a_management.py| -- b_management.py| -- c_management.py| -- d_management.py| -- e_management.py from a_management import *from b_management import *from c_management import *from d_management import *from e_management import * ... ... ... ... etc ... ... ... ... import sys , osfrom django.shor...
Django/Python : Import once , use everywhere
Python
How do I access the constants available as file formats when saving a Powerpoint presentation through comtypes ? In the following example 32 is used as the format but I would like to use the constants listed here ) or at least find a documented list with value for each constant.For Word there is this list that also con...
import comtypes.clientpowerpoint = comtypes.client.CreateObject ( `` Powerpoint.Application '' ) pres = powerpoint.Presentations.Open ( input_path ) pres.SaveAs ( output_path , 32 )
Using file format constants when saving PowerPoint presentation with comtypes
Python
Mark Ransom answered on a SO question about hashes here in SO : [ ... ] An object is hashable if it has a hash value which never changes during its lifetime . So by the official definition , anything mutable ca n't be hashable , even if it has a __hash__ ( ) function . My statement about both requirements being necessa...
class Author ( object ) : def __init__ ( self , id , name , age ) : self.id = id self.name = name self.age = age def __eq__ ( self , other ) : return self.id==other.id\ and self.name==other.name def __hash__ ( self ) : return hash ( ( 'id ' , self.id , 'name ' , self.name ) )
Explanation needed regarding explanation of hashable objects
Python
I have data like thisFor each unique pair ( location , store ) , there are 1 or more sales . I want to add a column , pcnt_sales that shows what percent of the total sales for that ( location , store ) pair was made up by the sale in the given row.This works , but is slowBy comparison , R 's data.table does this super ...
location sales store0 68 583 171 28 857 22 55 190 593 98 517 644 94 892 79 ... location sales store pcnt_sales0 68 583 17 0.2543631 28 857 2 0.3465432 55 190 59 1.0000003 98 517 64 0.2721054 94 892 79 1.000000 ... import pandas as pdimport numpy as npdf = pd.DataFrame ( { 'location ' : np.random.randint ( 0 , 100 , 100...
How to speed up pandas groupby - apply function to be comparable to R 's data.table
Python
I 'd like to be able to dispatch different implementations of a function , based not only on the type of the first parameter , but based on arbitrary predicates . Currently I have to do it like so : Here 's something in the spirit of what I 'd like to be able to do : It is similar to Python 3 's singledispatch , howeve...
def f ( param ) : try : if param > 0 : # do something except TypeError : pass try : if all ( isinstance ( item , str ) for item in param ) : # do something else except TypeError : raise TypeError ( 'Illegal input . ' ) @ genericdef f ( param ) : raise TypeError ( 'Illegal input . ' ) # default @ f.when ( lambda param :...
Function pattern/predicate matching in Python
Python
I know this is bad practice : Out of curiosity , if an int object does n't have __iadd__ , then how does += work ?
> > > a = 5 > > > a.__radd__ ( 5 ) 10 > > > a5 > > > a.__iadd__ ( 5 ) Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > AttributeError : 'int ' object has no attribute '__iadd__ '
python int does n't have __iadd__ ( ) method ?
Python
My view code looks basically like this : I would like my template code to look like this : And I would expect this to output : Is this possible ? I 'm finding that my `` with '' statement is actually working , but then using that variable as a reference is n't working . I suspect that for { { other_values.index } } it ...
context = Context ( ) context [ 'some_values ' ] = [ ' a ' , ' b ' , ' c ' , 'd ' , ' e ' , ' f ' ] context [ 'other_values ' ] = [ 4 , 8 , 15 , 16 , 23 , 42 ] { % for some in some_values % } { % with index as forloop.counter0 % } { { some } } : { { other_values.index } } < br/ > { % endwith % } { % endfor % } a : 4 < ...
Accessing parallel arrays in Django templates ?
Python
This is my first post so hopefully I do n't botch the question and I 'm clear.Basically , this is a two part question . I need to set up code that first checks whether or not Column A = `` VALID '' . If this is true , I need to extract the substring from column B and place it in a new column , here labeled `` C '' . If...
| A | B || -- -- -- -- -- -- -| -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -|| VALID |asdfafX'XextractthisY'Yeaaadf || INVALID |secondrowX'XsubtextY'Yelakj || VALID |secondrowX'XextractthistooY'Yelakj | | A | B | C || -- -- -- -- -- -- -| -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -| -- -- -- -- -- -...
How to conditionally copy a substring into a new column of a pandas dataframe ?
Python
I 'm attempting to write a Python function that will recursively delete all empty directories . This means that if directory `` a '' contains only `` b '' , `` b '' should be deleted , then `` a '' should be deleted ( since it now contains nothing ) . If a directory contains anything , it is skipped . Illustrated : Giv...
top/a/b/top/c/d.txttop/c/foo/ for root , dirs , files in os.walk ( `` . `` , topdown=False ) : contents = dirs+files print root , '' contains : '' , contents if len ( contents ) == 0 : print 'Removing `` % s '' ' % root shutil.rmtree ( root ) else : print 'Not removing `` % s '' . It has : ' % root , contents ./c/foo c...
Why does python 's os.walk ( ) not reflect directory deletion ?
Python
BACKGROUNDI 've been trying to work out why my AI has been making some crazy moves and I traced the problem back to the following behaviour when using Python 2.7.2It seems to behave as if lists are always less than tuples.This is not what I expected from the documentation Tuples and lists are compared lexicographically...
> > > print [ 2 ] > [ 1 ] True > > > print ( 2 , ) > ( 1 , ) True > > > print [ 2 ] > ( 1 , ) False ( WHY ? ) > > > print [ 2 ] < [ 1 ] False > > > print ( 2 , ) < ( 1 , ) False > > > print [ 2 ] < ( 1 , ) True ( WHY ? )
In Python why is [ 2 ] less than ( 1 , ) ?
Python
Assume I have a very big numpy memory mapped array : Now after some manipulation , etc , I want to remove column 10 : This results in a out of memory error , because ( ? ? ) the returned array is an in memory array . What I want is a pure memory mapped delete operation . What is the most efficient way to delete columns...
fp = np.memmap ( `` bigarray.mat '' , dtype='float32 ' , mode= ' w+ ' , shape= ( 5000000,5000 ) ) fp = np.delete ( fp,10,1 )
Numpy : delete column from very big memory mapped Numpy Array
Python
I am working with small numbers in tensorflow , which sometimes results in numerical instability.I would like to increase the precision of my results , or at the very least determine bounds on my result.The following code shows a specific example of numerical errors ( it outputs nan instead of 0.0 , because float64 is ...
import numpy as npimport tensorflow as tf # setupeps=np.finfo ( np.float64 ) .epsv=eps/2x_init=np.array ( [ v,1.0 , -1.0 ] , dtype=np.float64 ) x=tf.get_variable ( `` x '' , initializer=tf.constant ( x_init ) ) square=tf.reduce_sum ( x ) root=tf.sqrt ( square-v ) # runwith tf.Session ( ) as session : init = tf.global_v...
Setting tensorflow rounding mode
Python
So I am trying to train a simple recurrent network to detect a `` burst '' in an input signal . The following figure shows the input signal ( blue ) and the desired ( classification ) output of the RNN , shown in red . So the output of the network should switch from 1 to 0 whenever the burst is detected and stay like w...
import torchimport numpy , mathimport matplotlib.pyplot as pltnofSequences = 5maxLength = 130 # Generate training datax_np = numpy.zeros ( ( nofSequences , maxLength,1 ) ) y_np = numpy.zeros ( ( nofSequences , maxLength ) ) numpy.random.seed ( 1 ) for i in range ( 0 , nofSequences ) : startPos = numpy.random.random ( )...
Recurrent network ( RNN ) wo n't learn a very simple function ( plots shown in the question )
Python
I am new to numpy/pandas and vectorized computation . I am doing a data task where I have two datasets . Dataset 1 contains a list of places with their longitude and latitude and a variable A. Dataset 2 also contains a list of places with their longitude and latitude . For each place in dataset 1 , I would like to calc...
id lon lat varA1 20.11 19.88 1002 20.87 18.65 903 18.99 20.75 120 placeid lon lat a 18.75 20.77b 19.77 22.56c 20.86 23.76d 17.55 20.74 dataset2 [ 'count ' ] = dataset1.apply ( lambda x : haversine ( x [ 'lon ' ] , x [ 'lat ' ] , dataset2 [ 'lon ' ] , dataset2 [ 'lat ' ] ) .shape [ 0 ] , axis = 1 )
Vectorization to calculate many distances
Python
I tried to install venv with pip , and it gave me the following error message : this is the command : and the error : os : linux ubuntu 18.04python 3.7Thank you !
$ pip install venv Collecting venvException : Traceback ( most recent call last ) : File `` /usr/lib/python2.7/dist-packages/pip/basecommand.py '' , line 215 , in main status = self.run ( options , args ) File `` /usr/lib/python2.7/dist-packages/pip/commands/install.py '' , line 353 , in run wb.build ( autobuilding=Tru...
How to install venv with pip on linux ubuntu 18.04 python 3.7
Python
I have datetime object and my users provide their own format string to format the time in the way they like.One way I find is to use ' { : ... } '.format ( mydatetime ) .English users may provide ' { datetime : % B % d , % Y } ' , which formats to December 24 , 2013.Chinese users may provide ' { datetime : % Y年 % m月 % ...
lt = time.localtime ( time.time ( ) ) d = datetime . datetime.fromtimestamp ( time.mktime ( lt ) ) print ( userString.format ( datetime=d ) )
Python3.3 : .format ( ) with unicode format_spec
Python
I want to test an unknown value against the constraints that a given NumPy dtype implies -- e.g. , if I have an integer value , is it small enough to fit in a uint8 ? As best I can ascertain , NumPy 's dtype architecture does n't offer a way to do something like this : My little fantasy API is based on Django 's model-...
# # # FICTIONAL NUMPY CODE : I made this up # # # try : numpy.uint8.validate ( rupees ) except numpy.dtype.ValidationError : print `` Users ca n't hold more than 255 rupees . '' > > > nd = numpy.array ( [ 0,0,0,0,0,0 ] , dtype=numpy.dtype ( 'uint8 ' ) ) > > > nd [ 0 ] 0 > > > nd [ 0 ] = 1 > > > nd [ 0 ] = -1 > > > ndar...
Validation against NumPy dtypes -- what 's the least circuitous way to check values ?
Python
I 'm trying to understand the coroutines in Python ( and in general ) . Been reading about the theory , the concept and a few examples , but I 'm still struggling . I understand the asynchronous model ( did a bit of Twisted ) but not coroutines yet.One tutorial gives this as a coroutine example ( I made a few changes t...
async def download_coroutine ( url , number ) : `` '' '' A coroutine to download the specified url `` '' '' request = urllib.request.urlopen ( url ) filename = os.path.basename ( url ) print ( `` Downloading % s '' % url ) with open ( filename , 'wb ' ) as file_handle : while True : print ( number ) # prints numbers to...
How is this a coroutine ?
Python
If I have an integer i , it is not safe to do i += 1 on multiple threads : However , if I have a list l , it does seem safe to do l += [ 1 ] on multiple threads : Is l += [ 1 ] guaranteed to be thread-safe ? If so , does this apply to all Python implementations or just CPython ? Edit : It seems that l += [ 1 ] is threa...
> > > i = 0 > > > def increment_i ( ) : ... global i ... for j in range ( 1000 ) : i += 1 ... > > > threads = [ threading.Thread ( target=increment_i ) for j in range ( 10 ) ] > > > for thread in threads : thread.start ( ) ... > > > for thread in threads : thread.join ( ) ... > > > i4858 # Not 10000 > > > l = [ ] > > >...
Is extending a Python list ( e.g . l += [ 1 ] ) guaranteed to be thread-safe ?
Python
I have some data like this : and am looking for an output like this ( group-id and the members of that group ) : First row because 1 is `` connected '' to 2 and 2 is connected to 6.Second row because 3 is connected to 4 and 3 is connected to 7This looked to me like a graph traversal but the final order does not matter ...
1 23 45 92 63 7 1 : 1 2 62 : 3 4 73 : 5 9 1 271 1341 1371 1611 1711 2751 3091 4131 4641 6271 7442 1352 3982 4372 5482 5942 7172 7382 7832 7982 9125 745 2237 537 657 1227 2377 3147 7017 7307 7557 8217 8757 8847 8987 9007 9308 1159 2079 3059 3429 3649 4939 6009 6769 8309 94110 16410 28310 38010 42310 46810 57711 7211 132...
Trying to group values ?
Python
The following script executes very slow . I just want to count the total number of lines in the twitter-follwer-graph ( textfile with ~26 GB ) .I need to perform a machine learning task . This is just a test on accessing data from the hdfs by tensorflow.The process needs about 40 secs for the first 100000 lines.I tried...
import tensorflow as tfimport timefilename_queue = tf.train.string_input_producer ( [ `` hdfs : //default/twitter/twitter_rv.net '' ] , num_epochs=1 , shuffle=False ) def read_filename_queue ( filename_queue ) : reader = tf.TextLineReader ( ) _ , line = reader.read ( filename_queue ) return lineline = read_filename_que...
How to speedup my tensorflow execution on hadoop ?
Python
I try to iter over this class . It is said in this doc that implementing __getitem__ should be enough to iter over my Test class . Indeed , when I try to iter over it , it does not tell me that I ca n't , but I 've got a KeyError : Do you know where this 0 come from ? ( what 's going on under the hood ) I know I can so...
class Test ( object ) : def __init__ ( self , store ) : assert isinstance ( store , dict ) self.store = store def __getitem__ ( self , key ) : return self.store [ key ] In [ 10 ] : a = Test ( { 1:1,2:2 } ) In [ 11 ] : for i in a : print i -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ...
python iter over dict-like object
Python
This is my code.In this code , KeyboardInterrupt exception does n't work.Thank you
def getch ( ) : fd = sys.stdin.fileno ( ) old_Settings = termios.tcgetattr ( fd ) try : tty.setraw ( sys.stdin.fileno ( ) ) sys.stdin.flush ( ) except KeyboardInterrupt : print ( `` [ Error ] Abnormal program termination '' ) finally : termios.tcsetattr ( fd , termios.TCSADRAIN , old_settings ) return ch
python tty.setraw Ctrl + C does n't work ( getch )
Python
I 'm trying to implement `` phase scrambling '' of a timeseries in Python using Scipy/Numpy . Briefly , I 'd like to : Take a timeseries.Measure the power and phase in the frequency domain using FFT.Scramble the existing phase , randomly reassigning phase to frequency.Return a real-valued ( i.e. , non-complex ) timeser...
% matplotlib inlineimport matplotlibimport numpy as npimport matplotlib.pyplot as pltfrom scipy.fftpack import fft , ifftdef phaseScrambleTS ( ts ) : `` '' '' Returns a TS : original TS power is preserved ; TS phase is shuffled . '' '' '' fs = fft ( ts ) pow_fs = np.abs ( fs ) ** 2. phase_fs = np.angle ( fs ) phase_fsr...
Returning a real-valued , phase-scrambled timeseries
Python
I 'd like to accelerate the code written in Python and NumPy . I use Gray-Skott algorithm ( http : //mrob.com/pub/comp/xmorphia/index.html ) for reaction-diffusion model , but with Numba and Cython it 's even slower ! Is it possible to speed it up ? Thanks in advance ! Python+NumPyNumbaCythonUsage example :
def GrayScott ( counts , Du , Dv , F , k ) : n = 300 U = np.zeros ( ( n+2 , n+2 ) , dtype=np.float_ ) V = np.zeros ( ( n+2 , n+2 ) , dtype=np.float_ ) u , v = U [ 1 : -1,1 : -1 ] , V [ 1 : -1,1 : -1 ] r = 20 u [ : ] = 1.0 U [ n/2-r : n/2+r , n/2-r : n/2+r ] = 0.50 V [ n/2-r : n/2+r , n/2-r : n/2+r ] = 0.25 u += 0.15*np...
Numba or Cython acceleration in reaction-diffusion algorithm
Python
I 'm trying to optimize a polynomial implementation of mine . In particular I 'm dealing with polynomials with coefficients modulo n ( might be > 2^64 ) and modulo a polynomial in the form x^r - 1 ( r is < 2^64 ) . At the moment I represent the coefficient as a list of integers ( * ) and I 've implemented all the basic...
def _coefs_to_long ( coefs , window ) : `` 'Given a sequence of coefficients *coefs* and the *window* size return a long-integer representation of these coefficients. `` ' res = 0 adder = 0 for k in coefs : res += k < < adder adder += window return res # for k in reversed ( coefs ) : res = ( res < < window ) + k is slo...
Optimize conversion between list of integer coefficients and its long integer representation
Python
So I have a string : amélieIn bytes it is b'ame\xcc\x81lie'In utf-8 the character is combining acute accent for the previous character http : //www.fileformat.info/info/unicode/char/0301/index.htmu'ame\u0301lie'When I do : 'amélie'.title ( ) on that string , I get 'AméLie ' , which makes no sense to me.I know I can ...
In [ 1 ] : [ ord ( c ) for c in 'amélie'.title ( ) ] Out [ 1 ] : [ 65 , 109 , 101 , 769 , 76 , 105 , 101 ] In [ 2 ] : [ ord ( c ) for c in 'amélie ' ] Out [ 2 ] : [ 97 , 109 , 101 , 769 , 108 , 105 , 101 ]
Python3 .title ( ) of utf-8 strings
Python
Given this set of files : foo.h : foo.cpp : foo.i ( Attempt1 ) : setup.py : test.py : I build the extension running : but when i try to run test.py i 'll get : The statement extend in foo.i is the answer suggested on any other SO related threads , that means I 'm using it incorrectly here . Could anyone explain how to ...
# pragma once # include < stdio.h > template < class T0 > class Foo { public : T0 m [ 3 ] ; Foo ( const T0 & a , const T0 & b , const T0 & c ) { m [ 0 ] = a ; m [ 1 ] = b ; m [ 2 ] = c ; } void info ( ) { printf ( `` % d % d % d\n '' , m [ 0 ] , m [ 1 ] , m [ 2 ] ) ; } // T0 & operator [ ] ( int id ) { return ( ( T0 * ...
swig/python : object does not support indexing
Python
Consider the following Python project skeleton : In this case foo holds the main project files , for exampleAnd scripts holds auxiliary scripts that need to import files from foo , which are then invoked via : There are two ways of importing Foo which both fail : If a relative import is attempted from ..foo import Foo ...
proj/├── foo│ └── __init__.py├── README.md└── scripts └── run.py # foo/__init__.pyclass Foo ( ) : def run ( self ) : print ( 'Running ... ' ) [ ~/proj ] $ python scripts/run.py import syssys.path.append ( ' . ' ) from foo import FooFoo ( ) .run ( )
How to properly structure internal scripts in a Python project ?
Python
scikit-learn suggests the use of pickle for model persistence . However , they note the limitations of pickle when it comes to different version of scikit-learn or python . ( See also this stackoverflow question ) In many machine learning approaches , only few parameters are learned from large data sets . These estimat...
from sklearn import datasetsfrom sklearn.linear_model import LogisticRegressiontry : from sklearn.model_selection import train_test_splitexcept ImportError : from sklearn.cross_validation import train_test_splitiris = datasets.load_iris ( ) tt_split = train_test_split ( iris.data , iris.target , test_size=0.4 ) X_train...
Can I safely assign to ` coef_ ` and other estimated parameters in scikit-learn ?
Python
I want to generate a large sparse matrix and sum it but I encounter MemoryError a lot . So I tried the operation via scipy.sparse.csc_matrix.sum instead but found that the type of data changed back to a numpy matrix after taking the sum.So I generated mat as zeros matrix just to test the result when mat_head is all zer...
window = 10 np.random.seed = 0mat = sparse.csc_matrix ( np.random.rand ( 100 , 120 ) > 0.5 , dtype='d ' ) print type ( mat ) > > > < class 'scipy.sparse.csc.csc_matrix ' > mat_head = mat [ : ,0 : window ] .sum ( axis=1 ) print type ( mat_head ) > > > < class 'numpy.matrixlib.defmatrix.matrix ' > mat = sparse.csc_matrix...
Why does the result of scipy.sparse.csc_matrix.sum ( ) change its type to numpy matrix ?
Python
So I have many pandas data frames with 3 columns of categorical variables : The first and second columns can take one of three values . The third one is binary . So there are a grand total of 18 possible rows ( not all combination may be represented on each data frame ) . I would like to assign a number 1-18 to each ro...
D F False T F False D F False T F False import pandas , itertoolsdef expand_grid ( data_dict ) : `` '' '' Create a dataframe from every combination of given values . '' '' '' rows = itertools.product ( *data_dict.values ( ) ) return pandas.DataFrame.from_records ( rows , columns=data_dict.keys ( ) ) all_combination_df ...
assign hash to row of categorical data in pandas
Python
I am developing a Flask application and leveraging blueprints . I plan to use celery task queues.I am trying to understand the benefit or reason to use something likeand then doing and importing it into my tasks.py versus just importing and creating a celery instances in my tasks.py like
def make_celery ( app ) : celery = Celery ( app.import_name , broker=app.config [ 'CELERY_BROKER_URL ' ] ) celery.conf.update ( app.config ) TaskBase = celery.Task class ContextTask ( TaskBase ) : abstract = True def __call__ ( self , *args , **kwargs ) : with app.app_context ( ) : return TaskBase.__call__ ( self , *ar...
Celery factory function vs importing celery
Python
I have a GIN index set up for full text search . I would like to get a list of records that match a search query , ordered by rank ( how well the record matched the search query ) . For the result , I only need the record and its columns , I do not need the actual rank value that was used for ordering.I have the follow...
SELECT * , ts_rank ( ' { 0.1,0.1,0.1,0.1 } ' , users.textsearchable_index_col , to_tsquery ( 'smit : * | ji : * ' ) ) AS rankFROM usersWHERE users.authentication_method ! = 2 AND users.textsearchable_index_col @ @ to_tsquery ( 'smith : * | ji : * ' ) ORDER BY rank desc ; proxy = self.db_session.query ( User , text ( ``...
Returning ranked search results using gin index with sqlalchemy
Python
How would you convert a nesting of Python frozenset objects into a unique integer that was the same across Python sessions and platforms ? e.g . I get different values from hash ( ) on different platforms32-bit64-bit
Python 2.6.5 ( r265:79063 , Apr 16 2010 , 13:09:56 ) [ GCC 4.4.3 ] on linux2Type `` help '' , `` copyright '' , `` credits '' or `` license '' for more information. > > > a=frozenset ( [ frozenset ( [ 1,2,3 ] ) , frozenset ( [ ' a ' , ' b ' , ' c ' ] ) ] ) ; > > > hash ( a ) 1555175235 Python 2.6.5 ( r265:79063 , Apr 1...
Persistent Hashing of Python Frozen Sets
Python
So , I saved a list to a file as a string . In particular , I did : But , later when I open this file again , take the ( string-ified ) list , and want to change it back to a list , what happens is something along these lines : Could I make it so that I got the list [ 1,2,3 ] from the file ?
f = open ( 'myfile.txt ' , ' w ' ) f.write ( str ( mylist ) ) f.close ( ) > > > list ( ' [ 1,2,3 ] ' ) [ ' [ ' , ' 1 ' , ' , ' , ' 2 ' , ' , ' , ' 3 ' , ' ] ' ]
Change string list to list
Python
I have an array like this as the label column ( 2 labels : 0 and 1 ) , for example : Supposed that I want to convert this array to a numpy matrix with the shape ( 5,2 ) ( 5 elements , 2 labels ) . How can I do that in a trivial way by using any util library ? The outcome I want is like this :
[ 0,1,0,1,1 ] [ [ 0,1 ] [ 1,0 ] , [ 0,1 ] , [ 1,0 ] , [ 1,0 ] ]
How to convert a binary classes column to numpy array
Python
I 'm writing a library which is using Tornado Web 's tornado.httpclient.AsyncHTTPClient to make requests which gives my code a async interface of : I want to make this interface optionally serial if the user provides a kwarg - something like : serial=True . Though you ca n't obviously call a function defined with the a...
async def my_library_function ( ) : return await ... async def here_we_go ( ) : result = await my_library_function ( ) result = my_library_function ( serial=True ) import asynciofrom functools import wrapsdef serializable ( f ) : @ wraps ( f ) def wrapper ( *args , asynchronous=False , **kwargs ) : if asynchronous : re...
Optional Synchronous Interface to Asynchronous Functions
Python
I 've seen a lot of very helpful posts on using prettyprint and such ; they have been very helpful -- thanks.What I 'm wondering if there is anyway to print a dataframe from a function and have it output as `` prettily '' as Jupyter notebook does : My main reason is I would like to use pandas 's styling functions to hi...
> Year Month Mean Maximum Temperature Albury \ > 672 1955 January 30.8 > 673 1955 February 27.9 > 674 1955 March 26.7 > 675 1955 April 22.1 > ... . historic_dataframe
Printing a dataframe from a function nicely as in Jupyter
Python
I have found a very strange problem about using the python scripts under Python Windows command line prompt , to reproduce this issue , you can simply do those steps : start a Python command line prompt ( this is usually to hit the Start Menu- > Python 2.7- > Python ( command line ) . type the following text , and hit ...
import ctypes ctypes.windll.user32.MessageBoxA ( 0 , `` Your text '' , `` Your title '' , 1 ) ctypes.windll.user32.MessageBoxA ( 0 , `` Your text '' , `` Your title '' , 1 )
Windows+Python : Why is the first opened window not shown active ?
Python
I found this code snippet in the help of python 2.7.5 , which is a chapter about exposing a C-API to other modules in the Extending Python with C and C++ section : Providing a C API for an Extension ModuleThis snipped is for function capsules . A capsule is used to pass functions between two modules.But what 's the mea...
/* C API functions */ # define PySpam_System_NUM 0 # define PySpam_System_RETURN int # define PySpam_System_PROTO ( const char *command ) // ... static PySpam_System_RETURN PySpam_System PySpam_System_PROTO ; // ... static void **PySpam_API ; # define PySpam_System \ ( * ( PySpam_System_RETURN ( * ) PySpam_System_PROTO...
Python Function Capsules
Python
I have lists such as : I want to sort these two lists by this custom ordered list : [ 'red ' , 'blue ' , 'green ' , 'alpha ' ] so that mylist1 = [ 'green ' , 'alpha ' ] and mylist2 = [ 'red ' , 'blue ' , 'alpha ' ] How can i do this in Python ?
mylist1 = [ 'alpha ' , 'green ' ] mylist2 = [ 'blue ' , 'alpha ' , 'red ' ]
Custom sort order of list
Python
I want to initialise a sparse matrix ( for use with scipy minimum_spanning_tree if that matters ) from a list of matrix coordinates and values.That is , I have : I have tried to use lil_matrix to create this array usingwhich is unbearably slow . It 's actually faster to loop over the array and set each element one at a...
coords - Nx2 array of coordinates to be set in matrixvalues - Nx1 array of the values to set . A = lil_matrix ( ( N , N ) ) A [ coords [ : ,0 ] , coords [ : ,1 ] ] = values for i in xrange ( N ) : A [ coords [ i,0 ] , coords [ i,1 ] ] = values [ i ]
Scipy quickly initialise sparse matrix from list of coordinates
Python
I get the following behavior . Given this settings.py snippet , hitting ' o ' from line 33I get thisWhat I really want would be one indent , or a total of 4 spaces , in line with the rest of the list . What gives ? I 'm using the following .vimrc which I mostly cribbed from here .
31 # Application definition32 33 INSTALLED_APPS = [ 34 'rest_framework ' , 31 # Application definition32 33 INSTALLED_APPS = [ 34 | < -cursor is here , two indents , 8 spaces35 'rest_framework ' , set nocompatible `` requiredfiletype off `` required '' set the runtime path to include Vundle and initializeset rtp+=~/.vi...
Vim double-indents python files
Python
I was just toying around in the interpreter and ran across something that I do not understand . When I create a tuple with a list as one the elements and then try to update that list , something strange happens . For example , when I run this : I get : Which is exactly what I expected . However then when I reference th...
tup = ( 1,2,3 , [ 4,5 ] ) tup [ 3 ] += [ 6 ] TypeError : 'tuple ' object does not support item assignment > > > tup ( 1 , 2 , 3 , [ 4 , 5 , 6 ] )
Updating a list within a tuple
Python
I am trying to apply feature-wise scaling and shifting ( also called an affine transformation - the idea is described in the Nomenclature section of this distill article ) to a Keras tensor ( with TF backend ) .The tensor I would like to transform , call it X , is the output of a convolutional layer , and has shape ( B...
for b in range ( B ) : for f in range ( F ) : X [ b , : , : , f ] = X [ b , : , : , f ] * gamma [ b , f ] + beta [ b , f ] TypeError : 'Tensor ' object does not support item assignment import numpy as npimport keras as ksimport keras.backend as Kprint ( ks.__version__ ) # Load example data ( here MNIST ) from keras.dat...
Feature-wise scaling and shifting ( FiLM layer ) in Keras
Python
This obviously is n't simple exchange of keys with values : this would overwrite some values ( as new keys ) which is NOT what I 'm after.If 2 or more values are the same for different keys , keys are supposed to be grouped in a list . The above function works , but I wonder if there is a smarter / faster way ?
def revert_dict ( d ) : rd = { } for key in d : val = d [ key ] if val in rd : rd [ val ] .append ( key ) else : rd [ val ] = [ key ] return rd > > > revert_dict ( { 'srvc3 ' : ' 1 ' , 'srvc2 ' : ' 1 ' , 'srvc1 ' : ' 2 ' } ) { ' 1 ' : [ 'srvc3 ' , 'srvc2 ' ] , ' 2 ' : [ 'srvc1 ' ] }
smarter `` reverse '' of a dictionary in python ( acc for some of values being the same ) ?
Python
I want to kill a process from another function in the class attending to the fact that it was initiated by another function . Here 's an example : How should I define foo_stop ?
import time class foo_class : global foo_global def foo_start ( self ) : import subprocess self.foo_global =subprocess.Popen ( [ ' a daemon service ' ] ) def foo_stop ( self ) : self.foo_start.foo_global.kill ( ) self.foo_start.foo_global.wait ( ) foo_class ( ) .foo_start ( ) time.sleep ( 5 ) foo_class ( ) .foo_stop ( ...
How to kill a subprocess initiated by a different function in the same class
Python
When I try to run this test : I get AssertionError : No templates used to render the response.It 's my view : and urls.py :
from django.test import TestCasefrom django.core.urlresolvers import reversefrom django.test import Clientclass StatisticTest ( TestCase ) : def setUp ( self ) : self.client = Client ( ) def test_schedule_view ( self ) : url = reverse ( 'schedule ' ) response = self.client.get ( url ) self.assertEqual ( response.status...
Django assertTemplateUsed ( ) throws exception with Jinja templates
Python
I have written an implementation of the VideoCapture class that works with Basler cameras . It is used like this : My Cython file looks like this : And I have used the cv2.cpp file from OpenCV : https : //github.com/Itseez/opencv/blob/master/modules/python/src2/cv2.cppNow , everything works , I am getting the video str...
import cv2import PyBaslerCameravideo = PyBaslerCamera.PyBaslerCamera ( ) video.open ( 0 ) while True : ret , image = video.read ( ) cv2.imshow ( `` Test '' , image ) cv2.waitKey ( 1 ) # distutils : language = c++ # distutils : sources = BaslerCamera.cppfrom cython.operator cimport dereference as dereffrom cpython.ref c...
OpenCV Cython bridge leaking memory