lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Python
I have a largely empty dataframe of poorly formatted dates that I converted into DateTime format.Which producesI 'd expect that I could use df.any ( ) to find whether there was a value in a row or column . axis=0 behaves as expected : But axis=1 just returns false for all rows all the time .
from io import StringIOdata = StringIO ( `` '' '' issue_date , issue_date_dt , ,19600215.0,1960-02-15 , , '' '' '' ) df = pd.read_csv ( data , parse_dates= [ 1 ] ) issue_date issue_date_dt0 NaN NaT1 NaN NaT2 19600215.0 1960-02-153 NaN NaT4 NaN NaT df.any ( axis=0 ) issue_date Trueissue_date_dt Truedtype : bool df.any (...
Pandas any ( ) returning false with true values present
Python
I have a line of code in my script that has both these operators chained together . From the documentation reference BOOLEAN AND has a lower precedence than COMPARISON GREATER THAN . I am getting unexpected results here in this code : I was expecting Second or Third test to happen before the fist one , since > operator...
> > > def test ( msg , value ) : ... print ( msg ) ... return value > > > test ( `` First '' , 10 ) and test ( `` Second '' , 15 ) > test ( `` Third '' , 5 ) FirstSecondThirdTrue
Python operator precedence - and vs greater than
Python
What is the best technique with rethinkb and python to deal with empty result.I try this , but catching exceptions is not satisfactory.If anyone has tried other techniques , I am very interested.Thanks for your help .
@ staticmethoddef get_by_mail ( mail ) : try : return User ( r.table ( 'users ' ) .filter ( { `` mail '' : mail } ) .limit ( 1 ) .nth ( 0 ) .run ( ) ) except RqlRuntimeError : return None
Rethinkdb python handle empty result
Python
It seems that the Python C API is not consistent with the const correctness of character arrays . For example , PyImport_ImportFrozenModule accepts a char* , whereas PyImport_ImportModule accepts a const char* . The implication of all this is that in my C++ application that I am writing with an embedded Python interpre...
PyObject *os = PyImport_ImportModule ( `` os '' ) ; // Works without the const_castPyObject *cwd = PyObject_CallMethod ( os , const_cast < char* > ( `` getcwd '' ) , NULL ) ; // Accepts char* , not const char* // Method 1 ) Use const_cast < char* > PyImport_ImportFrozenModule ( const_cast < char* > ( `` mymodule '' ) )...
Const correctness of Python 's C API
Python
How do you `` disable '' the __call__ method on a subclass so the following would be true : This and other ways of trying to set __call__ to some non-callable value still result in the child appearing as callable .
class Parent ( object ) : def __call__ ( self ) : returnclass Child ( Parent ) : def __init__ ( self ) : super ( Child , self ) .__init__ ( ) object.__setattr__ ( self , '__call__ ' , None ) > > > c = Child ( ) > > > callable ( c ) False
How to make an Python subclass uncallable
Python
I have a mix-in class called WithAutoNumbering for classes that need a special numbering of a given attribute . Appart from that I have a nice class mix-in called WithIndexing for those classes that need indexing capabilities ... which needs the capabilities of WithAutoNumbering.Some classes need numbering but not inde...
class WithAutoNumbering ( object ) : ... class WithIndexing ( WithAutoNumbering ) : ... class CoolClass ( WithIndexing ) : ... class WithAutoNumbering ( object ) : ... class WithIndexing ( object ) : ... class CoolClass ( WithIndexing , WithAutoNumbering ) : ...
Should python mix-in classes inherit only from object ?
Python
I am looking to vectorize a nested loop , which will work on a list of 300,000 lists , with each of these lists containing 3 values . The nested loop compares the values of each of the lists with the corresponding values in the other lists , and will only append the list indices which have corresponding values having a...
import numpy as npvariable = np.random.random ( ( 300000,3 ) ) .tolist ( ) out1=list ( ) out2=list ( ) for i in range ( 0:300000 ) : for j in range ( 0:300000 ) : if ( ( i < j ) and ( ( abs ( variable [ i ] [ 0 ] -variable [ j ] [ 0 ] ) ) < 0.1 ) and ( ( abs ( variable [ i ] [ 1 ] -variable [ j ] [ 1 ] ) ) < 0.1 ) and ...
Vectorizing a Nested Loop
Python
I understand that because Python has first-class functions , using the Strategy pattern is usually just a matter of passing a function as an argument , and does n't require futzing with classes . But what if the `` strategies '' are n't single functions , but rather groups of related functions that logically should be ...
class HexFormatter ( object ) : `` '' '' Base class for strategies to format hexadecimal numbers . '' '' '' passclass Motorola ( HexFormatter ) : `` '' '' Format Motorola style ( e.g . $ 1234 ) '' '' '' @ staticmethod def formatbyte ( n ) : return `` $ % 02X '' % n @ staticmethod def formatword ( n ) : return `` $ % 04...
Strategy pattern in Python when a `` strategy '' consists of more than one function
Python
This is my second attempt at implementing gradient descent in one variable and it always diverges . Any ideas ? This is simple linear regression for minimizing the residual sum of squares in one variable.Result :
def gradient_descent_wtf ( xvalues , yvalues ) : tolerance = 0.1 # y=mx+b # some line to predict y values from x values m=1 . b=1 . # a predicted y-value has value mx + b for i in range ( 0,10 ) : # calculate y-value predictions for all x-values predicted_yvalues = list ( ) for x in xvalues : predicted_yvalues.append (...
Why does simple gradient descent diverge ?
Python
I want to split a string on any combination of delimiters I provide . For example , if the string is : And the delimiters are \. , , , and \s . However I want to capture all delimiters except whitespace \s . The output should be : My solution so far is is using the re module : However , this captures whitespace as well...
s = 'This , I think , . , کباب MAKES , some sense ' [ 'This ' , ' , ' , ' I ' , 'think ' , ' , . , ' , 'کباب ' , 'MAKES ' , ' , ' , 'some ' , 'sense ' ] pattern = ' ( [ \. , \s ] + ) ' re.split ( pattern , s )
How to split up a string on multiple delimiters but only capture some ?
Python
In the following example I use a twitter dataset to perform sentiment analysis . I use sklearn pipeline to perform a sequence of transformations , add features and add a classifer . The final step is to visualise the words that have the higher predictive power . It works fine when I do n't use feature selection . Howev...
from sklearn.base import BaseEstimator , TransformerMixinfrom sklearn.pipeline import Pipeline , FeatureUnionfeatures= [ c for c in df.columns.values if c not in [ 'target ' ] ] target = 'target ' # train test splitX_train , X_test , y_train , y_test = train_test_split ( df [ features ] , df [ target ] , test_size=0.2 ...
Sentiment analysis Pipeline , problem getting the correct feature names when feature selection is used
Python
SymPy comes equipped with the nice sympify ( ) function which can parse arbitrary strings into SymPy expressions . But it has two major drawbacks : It is not safe , as it relies on the notorious eval ( ) It automatically simplifies the read expression . e.g . sympify ( 'binomial ( 5,3 ) ' ) will return the expression 1...
latex ( parse ( 'binomial ( 5,3 ) ' ) ) # returns ' { \\binom { 5 } { 3 } } '
SymPy : Safely parsing strings
Python
The GNU C Library has the function drem ( alias remainder ) .How can I simulate this function just using the modules supported by Google App Engine Python 2.7 runtime ? From the GNU manual for drem : These functions are like fmod except that they round the internal quotient n to the nearest integer instead of towards z...
def drem ( x , y ) : n = round ( x / y ) return x - n * y
How can I simulate GNU C Library drem / remainder function in Google App Engine Python 2.7 runtime ?
Python
I have a dict , that looks like this : And I need to get it to look like : I should point out that there can and will be multiple top-level keys ( 'foo ' in this case ) . I could probably throw something together to get what i need , but I was hoping that there is a solution that 's more efficient .
{ 'foo ' : { 'opt1 ' : 1 , 'opt2 ' : 2 , } , 'foo/bar ' : { 'opt3 ' : 3 , 'opt4 ' : 4 , } , 'foo/bar/baz ' : { 'opt5 ' : 5 , 'opt6 ' : 6 , } } { 'foo ' : { 'opt1 ' : 1 , 'opt2 ' : 2 , 'bar ' : { 'opt3 ' : 3 , 'opt4 ' : 4 , 'baz ' : { 'opt5 ' : 5 , 'opt6 ' : 6 , } } } }
Need to create a layered dict from a flat one
Python
Running this code multiple times could print something like : ( If you are using the console to replicate it , make sure you click Rerun every time before you re-paste the code and execute it . If you still ca n't replicate , perhaps you have hash randomization not equal to random . On Python 3.3 and greater , hash ran...
t = { ' a ' , ' b ' , ' c ' , 'd ' } print ( t ) { ' c ' , ' b ' , ' a ' , 'd ' } { 'd ' , ' b ' , ' c ' , ' a ' } # different { 'd ' , ' b ' , ' c ' , ' a ' } # same { ' a ' , 'd ' , ' b ' , ' c ' } # different { ' a ' , ' b ' , ' c ' , 'd ' } # different # etc s = { 1 , 6 , 3.3 , 4 } print ( s ) # prints : # { 1 , 3....
Why does a set of numbers appear to be sorted ?
Python
I 'm trying to implement an unsupervised ANN using Hebbian updating in Keras . I found a custom Hebbian layer made by Dan Saunders here - https : //github.com/djsaunde/rinns_python/blob/master/hebbian/hebbian.py ( I hope it is not poor form to ask questions about another person 's code here ) In the examples I found us...
from keras import backend as K from keras.engine.topology import Layer import numpy as np import tensorflow as tf np.set_printoptions ( threshold=np.nan ) sess = tf.Session ( ) class Hebbian ( Layer ) : def __init__ ( self , output_dim , lmbda=1.0 , eta=0.0005 , connectivity='random ' , connectivity_prob=0.25 , **kwarg...
Custom Hebbian Layer Implementation in Keras - input/output dims and lateral node connections
Python
I 'm implementing a rudimentary version of LISP in Ruby just in order to familiarize myself with some concepts . I 'm basing my implementation off of Peter Norvig 's Lispy ( http : //norvig.com/lispy.html ) .There 's something I 'm missing here though , and I 'd appreciate some help ... He subclasses Python 's dict as ...
class Env ( dict ) : `` An environment : a dict of { 'var ' : val } pairs , with an outer Env . '' def __init__ ( self , parms= ( ) , args= ( ) , outer=None ) : self.update ( zip ( parms , args ) ) self.outer = outer def find ( self , var ) : `` Find the innermost Env where var appears . '' return self if var in self e...
Help me write my LISP : ) LISP environments , Ruby Hashes
Python
I am trying to create a wrapper class that behaves almost like the wrapped object . So far , I have come up with the following code : I tried testing it with : However it comes up with the following error message : __init__ is being properly dispatched by isinstance ( attr , ( types.MethodType , method_wrapper ) ) , an...
import functoolsimport typesmethod_wrapper = type ( ( None ) .__str__ ) class Box : def __new__ ( cls , obj ) : attrs = { } attr_names = dir ( obj ) for attr_name in attr_names : attr = obj.__getattribute__ ( attr_name ) if isinstance ( attr , ( types.MethodType , method_wrapper ) ) : `` Attr is a bound method , ignore...
Python Object Wrapper
Python
Suppose I have : Suppose I already have an Level1 object : level1 , how can get all Level4 objects of Level1 ? Like the meaning : level1.level2_set.level3_set.level4_set .
Class Level1 : name = CharField ( ) Class Level2 : name = CharField ( ) level1 = ForeignKey ( Level1 ) Class Level3 : name = CharField ( ) level2 = ForeignKey ( Level2 ) Class Level4 : name = CharField ( ) level3 = ForeignKey ( Level3 )
How to reverse query objects for multiple levels in django ?
Python
I have a subplot of 28 lines x 2 columns ( it can change , actually ) . The yaxis scale of all the lines of the 1st column is supposed to be the same ( that must work for that 2nd column as well ) ... .All the xaxis are supposed to be the same.What I want to do is to make something inside the output figure that shows w...
def pltconc ( conc , self ) : t=self.tidx1=0conc=conc*1000000c=len ( find ( self.ml [ : ,3 ] ==1 ) ) from scipy.stats import scoreatpercentile # To adjust the scalesymin1 = max ( [ median ( scoreatpercentile ( conc [ : ,i , : ] ,0.05 ) ) for i in range ( 28 ) ] ) ymax1 = max ( [ median ( scoreatpercentile ( conc [ : ,i...
Help with making a big subplot look nicer and clearer
Python
I think this is perfectly valid.However , it gives me an invalid syntax error in Python REPL.Why is it ? On Python 3.6.5 ( x64 ) , Windows 10 RS4
if False : print ( 1 ) print ( 2 )
Why am I getting an invalid syntax error in Python REPL right after IF statement ?
Python
Suppose I have successfully trained a XGBoost machine learning model in python.I want to port this model to another system which will be writte in C/C++ . To do this , I need to know the internal logic of the XGboost trained model and translate them into a series of if-then-else statements like decision trees , if I am...
x_train , x_test , y_train , y_test = train_test_split ( x , y , test_size=0.2 , random_state=7 ) model = XGBClassifier ( ) model.fit ( x_train , y_train ) y_pred = model.predict ( x_test )
Port XGBoost model trained in python to another system written in C/C++
Python
I 've got an array of dates that can contain multiple date ranges in it.In this example , the list contains 2 separate consecutive date ranges ( 2020-01-01 to 2020-01-03 & 2020-01-06 to 2020-01-08 ) I 'm attempting to figure out how I would loop through this list and find all the consecutive date ranges.One of the arti...
dates = [ '2020-01-01 ' , '2020-01-02 ' , '2020-01-03 ' , '2020-01-06 ' , '2020-01-07 ' , '2020-01-08 ' ]
Split a list of dates into subsets of consecutive dates
Python
start.py code is as below.Start it with python for two times.run.py code is as below.run.py is only one line different from start.py.Now start run.py for two times.startandrun.py code is as below.Now start startandrun.py for two times also.As JohanL say : When running two separate threads , all bets are off as to which...
import threadingclass myThread ( threading.Thread ) : def __init__ ( self , threadID , name ) : threading.Thread.__init__ ( self ) self.threadID = threadID self.name = name def run ( self ) : currentThreadname = threading.currentThread ( ) print `` running in `` , currentThreadnamethread = myThread ( 1 , '' mythrd '' )...
same program different output in threading module
Python
In order to investigate some Selenium test failures I would like to automatically enable the pause on exception feature in the Chrome Devtools when running the tests.There is the -- auto-open-devtools-for-tabs command line option for automatically opening the DevTools pane which I am already using but apparently there ...
driver.execute_cdp_cmd ( `` Debugger.setPauseOnExceptions '' , { `` state '' : `` all '' } ) unhandled inspector error : { `` code '' : -32000 , '' message '' : '' Debugger agent is not enabled '' }
Break on exception in Chrome using Selenium
Python
I found the following mistake in my code this week : Yes , it should be d.isoweekday ( ) instead.I know , if I had had a test-case for this I would have been saved.Comparing a function with 5 is not very useful . Oh , I 'm not blaming Python for this.My question : Are there tools that can spot errors like this one ?
import datetimed = datetime.date ( 2010,9,24 ) if d.isoweekday == 5 : pass
Are there tools that can spot errors like this one ?
Python
Under Ubuntu Desktop ( Unity ) when a script marked as executable and then I click on the file I get pop-up window like the one here in the image : pyscript.py is an executable Python script file with a shebang : # ! /usr/bin/python where /usr/bin/python is the path to the Python interpreter . Since I 'm not running th...
# ! /usr/bin/python3import sys , osf = file=open ( `` output.txt '' , `` w '' ) print ( sys.stdout , sys.stdin , sys.stderr , sep='\n ' , file=f ) < _io.TextIOWrapper name= ' < stdout > ' mode= ' w ' encoding='UTF-8 ' > < _io.TextIOWrapper name= ' < stdin > ' mode= ' r ' encoding='UTF-8 ' > < _io.TextIOWrapper name= ' ...
What are exactly the standard streams if there 's no terminal/console window open for the python interpreter ?
Python
I would like to compute the maximum of `` a_priority '' for each group of ( b , c ) pairs.a_priority is an annotation based on a case/when mapping strings to priority values.I get the following error : I believe the qs.values ( `` b '' , `` c '' ) filters out my annotation a_priority . Behavior is different with any ac...
from django.db.models import Max , Case , When , IntegerFieldqs = MyObject.objects.all ( ) qs = qs.annotate ( a_priority=Case ( When ( a= ' A ' , then=1 ) , When ( a= 'S ' , then=2 ) , When ( a= ' Q ' , then=3 ) , output_field=IntegerField ( ) ) ) qs = qs.values ( `` b '' , `` c '' ) .annotate ( Max ( `` a_priority '' ...
Maximum of an annotation after a group by
Python
I 'm not good enough with decorators yet to do this ... Is it possible to define a decorator live_doc that allows me to get an interpolated doc string after a method or function call , filled in with the actual arguments and return value.After the code below : d should be `` f was called with 3 , `` marty '' , and retu...
@ live_doc ( `` f was called with % d , % s and returned % d '' ) def f ( x , y ) : x + len ( y ) f ( 3 , `` marty '' ) d = f.doc
How to define a decorator that will provide an interpolated doc string for a function/method call
Python
I am using Popen to start a telnet process over ssh , send commands through the telnet and check the process for output to monitor the state of the telnet . The weird thing I encountered is that the code works fine with Python 3.2.3 but when I run it in Python 3.6.5 with no code changes , it fails to get the output.I h...
def nonblockingread ( sout ) : fd = output.fileno ( ) fl = fcntl.fcntl ( fd , fcntl.F_GETFL ) try : return sout.read ( ) except : return `` '' process = Popen ( shlex.split ( `` ssh anon @ server \ '' telnet 0 2323\ '' '' ) , stdin=subprocess.PIPE , stdout=subprocess.PIPE , stderr=subprocess.PIPE ) print ( nonblockingr...
Popen.stdout.readline ( ) works in Python 3.2 but returns empty string in Python 3.6
Python
The program in question prints stuff first thing . When I connect to it , via raw sockets , it does n't send anything . Here 's the output : Am I missing anything ? Thanks in advance .
print 'Preall test works ! 'from twisted.internet import reactor , protocolfrom twisted.python import logimport sysprint 'Imports done'class PrgShell ( protocol.Protocol ) : data = `` class PrgProto ( protocol.ProcessProtocol ) : def __init__ ( self , out ) : print 'Prgproto instance made ' self.transportout = out.tran...
What 's wrong with my twisted server that 's supposed to take a .exe and send its stdio to anyone who asks . Instead , it does n't send anything
Python
Is there a way to get back from a return value from inspect.getcallargs ( func ) to a *args , **kw pair that can actually be used to call the func ? Use case : say I am writing a decorator , and I want to change a particular argument of a function by name . Here 's the beginning of some code to do this : ( I 'm actuall...
@ fix_xdef a ( x ) : print x @ fix_xdef b ( **q ) : print q [ ' x ' ] def fix_x ( func ) : def wrapper ( *args , **kw ) : argspec = inspect.getargspec ( func ) callargs = inspect.getcallargs ( func , *args , **kw ) if ' x ' in callargs : callargs [ ' x ' ] += 5 elif ' x ' in callargs [ argspec.keywords ] : callargs [ a...
Is there an inverse operation to Python inspect.getcallargs in the standard library ?
Python
Would what mentioned in the title be possible ? Python module style that is . See this example for what I exactly mean.index.phpHello/World.phpWould this be possible ?
< ? phpuse Hello\World ; World : :greet ( ) ; < ? phpnamespace Hello\World ; function greet ( ) { echo 'Hello , World ! ' ; }
Is it possible to autoload a file based on the namespace in PHP ?
Python
I 'm writing a test for a program that will be used in multiple locales . While running the test in German , i got the errorDigging into this , i discovered that using locale.nl_langinfo ( locale.T_FMT ) while in German or Spanish ( and potentially other languages ) produces the format string ' % T ' . This is not reco...
Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > File `` /usr/local/lib/python2.7/_strptime.py '' , line 454 , in _strptime_time return _strptime ( data_string , format ) [ 0 ] File `` /usr/local/lib/python2.7/_strptime.py '' , line 317 , in _strptime ( bad_directive , format ) ) Valu...
Why does Python store German and Spanish ( and other ? ) time format strings as % T in the locale module ?
Python
It is design problem.Let 's assume that we have this kind of model in Django : We have also another file called actions.py and we implementthere others actions.Our problem is to determine which kind of methods should be placed in models.py , which in actions.py.Do you know any common approach , guide or something like ...
class Payment ( models.Model ) : purchase = ForeignKeyField ( Purchase ) net_price = DecimalField ( ) is_accepted = BooleanField ( ) def set_accept ( self ) : # there will be some logic , which touch purchase , send emails etc . def price_with_tax ( self ) : return net_price * ( 1 . + TAX )
What kind of methods should be method of model class ?
Python
I want to use the in operator in my Google App Engine project which was introduced in Django 1.2 : I found out that is possible to use version 1.0 or 1.1on GAE , but nothing for 1.2 . Is it possible ?
{ % if `` bc '' in `` abcdef '' % } This appears since `` bc '' is a substring of `` abcdef '' { % endif % }
Is it possible to use Django 1.2 on Google App Engine ?
Python
I have a strange problem with using mmap in python when writing to memory ( /dev/mem ) .To be clear , reading is done in the same manner and it works OK.But when it comes to writing , it seems that every second byte is unwritable.ex.When I try to write byte by byte , the same happens.ex.Code : Example run ( I prepared ...
when I read i get addr 0x200 val 0x1234 but when I try to write addr 0x200 val 0x4321 what really is written is addr 0x200 val 0x0021 write : addr 0x200 0x43addr 0x201 0x21I getaddr 0x200 0x00addr 0x201 0x21 class Pydump : def __init__ ( self , addr , length = 1 , word_size = 4 , filename = '/dev/mem ' ) : if addr < 0 ...
python mmap skipping every second byte when writing
Python
I came across some urwid tutorial , which included an example with code such as this : That u'\N { MEDIUM SHADE } ' string literal drove me nuts for almost the entire day until I found out it was included — as comments ! — in files under /usr/lib/python3.5/encodings/ ... But nowhere did I find any hint as to using such...
... main = urwid.Padding ( menu ( u'Pythons ' , choices ) , left=2 , right=2 ) top = urwid.Overlay ( main , urwid.SolidFill ( u'\N { MEDIUM SHADE } ' ) , align='center ' , width= ( 'relative ' , 60 ) , valign='middle ' , height= ( 'relative ' , 60 ) , min_width=20 , min_height=9 ) urwid.MainLoop ( top , palette= [ ( 'r...
Where does `` \N { SPECIAL CHARACTER } '' in Python come from ?
Python
Suppose a class has a method that modifies it 's internals.Should that method call save on itself before returning or should the save be left to the caller to explicitly save after the modifying method has been called ? Example : Explicitly calling save : or allowing method to call save : I 'm working with django , but...
class Bar ( models.Model ) : def set_foo ( self , foo ) : self.foo = foobar = Bar ( ) bar.set_foo ( `` foobar '' ) bar.save ( ) class Bar ( models.Model ) : def set_foo ( self , foo ) : self.foo = foo self.save ( ) bar = Bar ( ) bar.set_foo ( `` foobar '' )
Should a modifying class method save itself or be explicity called after the method is called ?
Python
I 'm trying to create a signed file using OpenSSL and Python , and I 'm not receiving any error mesage , but the proccess is not working properly and I ca n't find the reason.Below is my step-by-step to sign the file and check the signature : First I create the crt in command lineopenssl req -nodes -x509 -sha256 -newke...
import os.pathfrom Crypto.PublicKey import RSAfrom Crypto.Signature import PKCS1_v1_5from Crypto.Hash import SHA256from base64 import b64encode , b64decodedef __init__ ( self ) : folder = os.path.dirname ( os.path.realpath ( __file__ ) ) file_path = os.path.join ( folder , '../static/cert.key ' ) self.key = open ( file...
Problems to verify a file signed with python
Python
I 'd like to wrap df.groupby ( pd.TimeGrouper ( freq='M ' ) ) .sum ( ) in a function so that I can assign sum ( ) , mean ( ) or count ( ) as arguments in that function . I 've asked a similar question earlier here , but I do n't think I can use the same technique in this particular case.Here is a snippet with reproduci...
# Importsimport pandas as pdimport numpy as np # Dataframe with 1 or zero # 100 rows and 4 columns # Indexed by datesnp.random.seed ( 12345678 ) df = pd.DataFrame ( np.random.randint ( 0,2 , size= ( 100 , 4 ) ) , columns=list ( 'ABCD ' ) ) datelist = pd.date_range ( pd.datetime ( 2017 , 1 , 1 ) .strftime ( ' % Y- % m- ...
Pandas : How to assign sum ( ) or mean ( ) to df.groupby inside a function ?
Python
lets say I have two arraysI need to divide the arrays element-wise , thus using numpy.My issue is the `` secure division '' implemented.when doing : I get the output : My problem with this is that I need it to return the element that is not 0 when it divides by 0 , making the ideal output : Is there any workaround to d...
x = [ 1,2,3 ] y = [ 0,1,0 ] np.divide ( x , y ) .tolist ( ) [ 0.0 , 2.0 , 0.0 ] [ 1.0 , 2.0 , 3.0 ] def mydiv ( x , y ) : if y == 0 : return xelse : return x / y
Numpy division by 0 workaround
Python
I have a web application which uses Google 's Datastore , and has been running out of memory after enough requests.I have narrowed this down to a Datastore query . A minimum PoC is provided below , a slightly longer version which includes memory measuring is on Github.Profiling the process RSS shows approximately 1 MiB...
from google.cloud import datastorefrom google.oauth2 import service_accountdef test_datastore ( entity_type : str ) - > list : creds = service_account.Credentials.from_service_account_file ( `` /path/to/creds '' ) client = datastore.Client ( credentials=creds , project= '' my-project '' ) query = client.query ( kind=en...
How should I investigate a memory leak when using Google Cloud Datastore Python libraries ?
Python
I tested two different ways to reverse a list in python.Interestingly , the 2nd method that inserts the value to the first element is pretty much slower than the first one . Why is this ? In terms of operation , inserting an element to the head does n't seem that expensive .
import timeitvalue = [ i for i in range ( 100 ) ] def rev1 ( ) : v = [ ] for i in value : v.append ( i ) v.reverse ( ) def rev2 ( ) : v = [ ] for i in value : v.insert ( 0 , i ) print timeit.timeit ( rev1 ) print timeit.timeit ( rev2 ) 20.485130071673.5116429329
Why l.insert ( 0 , i ) is slower than l.append ( i ) in python ?
Python
I install py3-pandas as following , Then I try to import pandas , it 's not avaialbleSo it turns out pandas are installed in the different python directoryHow do I make py3-pandas to use the python version which is already installed in the system ?
FROM alpine : latest RUN echo `` http : //dl-8.alpinelinux.org/alpine/edge/testing '' > > /etc/apk/repositories RUN echo `` http : //dl-8.alpinelinux.org/alpine/edge/community '' > > /etc/apk/repositories RUN apk add -- update \ python3 \ python3-dev \ py3-numpy py3-pandas py3-scipy py3-numpy-dev bash-5.0 # python3Pyth...
alpine docker : installing pandas / numpy
Python
So litheor ( 2 ) is True and 2 in sieve ( 100 ) is True , so the if clause in the list comprehension is False . But why is 2 still in the output of the list comprehension ?
> > > [ l for l in range ( 2,100 ) if litheor ( l ) ! =l in sieve ( 100 ) ] [ 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43 , 47 , 53 , 59 , 61 , 67 , 71 , 73 , 79 , 83 , 89 , 97 ] > > > 2 in sieve ( 100 ) True > > > litheor ( 2 ) True
Python : Something went wrong somewhere in the list comprehension ?
Python
I 've written a script in Python to get only the name visible in my profile in SO . The thing is I would like to log in that site using requests module and once I 'm logged in I wish to get the profile name using Selenium . The bottom line is -- when I get the profile URL , I would like that URL to be reused by Seleniu...
import requestsfrom bs4 import BeautifulSoupurl = `` https : //stackoverflow.com/users/login ? ssrc=head & returnurl=https % 3a % 2f % 2fstackoverflow.com % 2f '' req = requests.get ( url ) sauce = BeautifulSoup ( req.text , '' lxml '' ) fkey = sauce.select_one ( `` [ name='fkey ' ] '' ) [ 'value ' ] payload = { 'fkey ...
Ca n't fetch the profile name using Selenium after logging in using requests
Python
I found a similar class definition as below in a Python code base . It seems there is no similar examples in the official documents . Very hard to find similar thing by Google and searching in the forum . May anyone help me to understand the principle in Python behind this ?
class a : passclass b : passcondition = Trueclass c ( a if condition == True else b ) : pass
Python class definition based on a condition
Python
I want to retrieve the value of the var modelCode . I made a regex function like this , but it does n't work at all . I 've posted the structure of the page below.Can somebody help me , please ? Structure of the page : }
regex2 = re.compile ( r ' '' var modelCode '' \s* : \s* ( .+ ? \ } ) ' , re.DOTALL ) source_json3 = response.xpath ( `` //script [ contains ( . , 'if ( pageTrackName == 'product detail ' || pageTrackName == 'generic product details ' ) ' ) ] /text ( ) '' ) .re_first ( regex2 ) source_json3 = re.sub ( r'// [ ^\n ] + ' ,...
scrapy - How to retrieve a variable value using regex
Python
I 'd like to create a `` class property '' that is declared in an abstract base class , and then overridden in a concrete implementation class , while keeping the lovely assertion that the implementation must override the abstract base class ' class property.Although I took a look at this question my naive attempt to r...
> > > import abc > > > class ClassProperty ( abc.abstractproperty ) : ... def __get__ ( self , cls , owner ) : ... return self.fget.__get__ ( None , owner ) ( ) ... > > > class Base ( object ) : ... __metaclass__ = abc.ABCMeta ... @ ClassProperty ... def foo ( cls ) : ... raise NotImplementedError ... > > > class Impl ...
How can I combine abc.abstractproperty with a classmethod to make an `` abstract class property '' ?
Python
I read Storm ORM 's tutorial at https : //storm.canonical.com/Tutorial , and I stumbled upon the following piece of code : I 'm not sure that the second argument of the find method will be evaluated to True/False . I think it will be interpreted as a lambda . If that is true , how can I achieve the same effect in my fu...
store.find ( Person , Person.name == u '' Mary Margaret '' ) .set ( name=u '' Mary Maggie '' )
what python feature is illustrated in this code ?
Python
I have been trying to find a way to continue my for loop to the previous element . Its hard to explain . Just two be clear , here is an example : - On executing this , when the loop reaches to ' c ' , it sees that bar is equal to ' c ' , it replaces that ' c ' in the list , continues to the next element & does n't prin...
foo = [ `` a '' , `` b '' , `` c '' , `` d '' ] for bar in foo : if bar == `` c '' : foo [ foo.index ( bar ) ] = `` abc '' continue print ( bar )
'continue ' the 'for ' loop to the previous element
Python
I have the following objects and relations defined . This is actually quite a simple case , and I am providing all those fields just to show why I believe inhalation and injection anesthesia should be defined by two different classes.I would , however , like to define the anesthetic attribute of the Operation class in ...
class InhalationAnesthesia ( Base ) : __tablename__ = `` inhalation_anesthesias '' id = Column ( Integer , primary_key=True ) anesthetic = Column ( String ) concentration = Column ( Float ) concentration_unit = Column ( String ) duration = Column ( Float ) duration_unit = Column ( String ) class TwoStepInjectionAnesthe...
multiple/split class associations in sqlalchemy
Python
Suppose I have a matrix that is 100000 x 100I wish to go through this matrix , and if each row contains entirely either 1 or 0 I wish to change a state variable to that value . If the state is not changed , I wish to set the entire row the value of state . The initial value of state is 0 . Naively in a for loop this ca...
import numpy as npmat = np.random.randint ( 2 , size= ( 100000,100 ) ) state = 0for row in mat : if set ( row ) == { 1 } : state = 1 elif set ( row ) == { 0 } : state = 0 else : row [ : ] = state array ( [ [ 0 , 1 , 0 ] , [ 0 , 0 , 1 ] , [ 1 , 1 , 1 ] , [ 0 , 0 , 1 ] , [ 0 , 0 , 1 ] ] ) array ( [ [ 0 , 0 , 0 ] , [ 0 , ...
How to vectorize a loop through a matrix numpy
Python
I 'm looking for efficient alternate ways to compute cosine angle between 2D vectors . Your insights on this problem will be of much help.Problem Statement : vectors is a 2D array where vectors are stored . The shape of the vectors array is ( N , 2 ) where N is the number of vectors . vectors [ : , 0 ] has x-component ...
vectors = np.array ( [ [ 1 , 3 ] , [ 2 , 4 ] , [ 3 , 5 ] ] ) vec_x = vectors [ : , 0 ] vec_y = vectors [ : , 1 ] a1 = np.ones ( [ vec_x.shape [ 0 ] , vec_x.shape [ 0 ] ] ) * vec_xa2 = np.ones ( [ vec_x.shape [ 0 ] , vec_x.shape [ 0 ] ] ) * vec_ya1b1 = a1 * a1.Ta2b2 = a2 * a2.Tmask = np.triu_indices ( a1b1.shape [ 0 ] ,...
Fastest way to compute angle between 2D vectors
Python
I have a simple code named main.py that generates a folder and a file within it : If this script run in a folder , then the structure should be like : I use a setup.py file to pack the code up , where I assigned an entry point named foo . The setup.py looks like : I packed the code with the structure below : And I inst...
import osdef main ( ) : path = os.path.join ( os.path.dirname ( __file__ ) , 'folder ' ) if not os.path.isdir ( path ) : os.mkdir ( path ) with open ( os.path.join ( path , 'file.txt ' ) , ' w+ ' ) as f : f.write ( 'something ' ) if __name__ == '__main__ ' : main ( ) .├── main.py└── folder └── file.txt from setuptools ...
Setuptools : How to make sure file generated by packed code be deleted by pip
Python
If a template is missing deep inside the rendering of a django template , I get a exception like below.After searching very long I found the bogus part : form.template_name was empty in my context.How can I find the relevant template name without searching for hours ? I am missing a traceback like for normal python cod...
{ % include form.template_name % } /home/foo_fm_d/bin/python /usr/local/pycharm-community-4.5/helpers/pycharm/utrunner.py /home/foo_fm_d/src/foo-time/foo_time/tests/unit/views/user/test_preview_of_next_days.py : :EditTestCase : :test_preview_of_next_days trueTesting started at 09:26 ... ErrorTraceback ( most recent cal...
Better errors message if template is missing
Python
I have to detect whether a file is a valid mp3 file . So far , I have found two solutions , including : this solution from Peter Carrollusing try-catch expression : Both solutions above work , but may have some drawbacks , the 1st solution seems too complicated while the 2nd solution is too slow ( in seconds depending ...
try : _ = librosa.get_duration ( filename=mp3_file_path ) return Trueexcept : return False
Best way to verify an mp3 file with python
Python
How do I merge a list of lists ? intoEven better if I can add a value on the beginning and end of each item before merging the lists , like html tags.i.e. , the end result would be :
[ [ ' A ' , ' B ' , ' C ' ] , [ 'D ' , ' E ' , ' F ' ] , [ ' G ' , ' H ' , ' I ' ] ] [ ' A ' , ' B ' , ' C ' , 'D ' , ' E ' , ' F ' , ' G ' , ' H ' , ' I ' ] [ ' < tr > A < /tr > ' , ' < tr > B < /tr > ' , ' < tr > C < /tr > ' , ' < tr > D < /tr > ' , ' < tr > E < /tr > ' , ' < tr > F < /tr > ' , ' < tr > G < /tr > ' ,...
Merging a list of lists
Python
Not sure if title is correct terminology.If you have to compare the characters in 2 strings ( A , B ) and count the number of matches of chars in B against A : is faster on % timeit thanI understand that the first one will create a list of bool , and then sum the values of 1.The second one is a generator . I 'm not cle...
sum ( [ ch in A for ch in B ] ) sum ( ch in A for ch in B )
Why is summing list comprehension faster than generator expression ?
Python
I have a somewhat bizarre metaclass question . I 'm using a meta class to dynamically create a 'sibling ' class that inherits from another superclass and assign it as an attribute on the original class . Below is a minimal setup : Something seems to be going wrong above with the creation of the 'sibling ' class but I '...
class Meta ( type ) : def __new__ ( cls , name , parents , dct ) : sdct = dct.copy ( ) dct [ 'sibling ' ] = type ( name+'Sibling ' , ( Mom , ) , sdct ) return super ( ) .__new__ ( cls , name , ( Dad , ) , dct ) class Mom : def __init__ ( self ) : self.x = 3class Dad : def __init__ ( self ) : self.x = 4class Child ( met...
python metaclass inheritance issue
Python
I have just started learning python and I have stumbled across a particularitypython version : Python 2.7.2 ( default , Jul 20 2011 , 02:32:18 ) [ GCC 4.2.1 ( LLVM , Emscripten 1.5 , Empythoned ) ] on linux2on : http : //repl.it/languages/PythonWorking with the interpreter assigning : Ok floating point precision is not...
pi = 3.141 // 3 places decimal precision # typing pi & pressing return puts 3.141 type ( pi ) = > < type 'float ' > pi = 3.1415 type ( pi ) = > < type 'float ' > # pi puts 3.1415000000000002 pi2 = 3.1415100000000002 pi == pi2 # pi was assigned 3.1415 = > True print ( pi2 ) 3.14151 # Where 's my precision ?
Float random ( ? ! ) precision quirk
Python
having been looking for solution for this problem for a while but ca n't seem to find anything . For example , I have an numpy array of what I would like to achieve is the generate another array to indicate the elements between a pair of numbers , let 's say between 2 and -2 here . So I want to get an array like this N...
[ 0 , 0 , 2 , 3 , 2 , 4 , 3 , 4 , 0 , 0 , -2 , -1 , -4 , -2 , -1 , -3 , -4 , 0 , 2 , 3 , -2 , -1 , 0 ] [ 0 , 0 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 0 , 0 ]
numpy array set ones between two values , fast
Python
I have a Django project and I wanted to generate some objects ( from the models ) What I 'm trying to get at : Standalone Python Script to create bunch of objects and/or filter , delete.after importing the model with from apps.base.models import MyModeland setting up the configuration as the previous StackOverflow Ques...
import osos.environ.setdefault ( `` DJANGO_SETTINGS_MODULE '' , `` myProject.settings '' ) import djangodjango.setup ( ) from apps.base.models import MyModel
Django 2.0 Access Models ( CREATE/REMOVE/FILTER ) Standalone [ without manage.py shell ]
Python
There are some URLs which are handled by my Pyramid application . When an unauthenticated user tries to open any URL then the user is redirected to login form : But for some urls ( routes ) I have to return not the login form , but a 401 Unauthorized status code with WWW-Authenticate header . How I can setup my routes ...
def forbidden ( request ) : if request.user.keyname == 'guest ' : return HTTPFound ( location=request.route_url ( 'auth.login ' , ) ) request.response.status = 403 return dict ( subtitle=u '' Access denied '' ) config.add_view ( forbidden , context=HTTPForbidden , renderer='auth/forbidden.mako ' )
Different login views in Pyramid
Python
Why is the size of sets in Python noticeably larger than that of lists with same elements ? output :
a = set ( range ( 10000 ) ) b = list ( range ( 10000 ) ) print ( 'set size = ' , a.__sizeof__ ( ) ) print ( 'list size = ' , b.__sizeof__ ( ) ) set size = 524488list size = 90088
Why are sets bigger than lists in python ?
Python
I have this code : The output is a list of 45 tuples.I would like to divide 45 tuples into 9 groups of 5 tuples , each of which are unique items . For example like so : So each list contains tuples with items from 1 to 10 without repetition .
from itertools import groupbyfrom itertools import combinationsteams = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] combo = list ( combinations ( teams , 2 ) ) [ ( 1 , 2 ) , ( 1 , 3 ) , ( 1 , 4 ) , ( 1 , 5 ) , ( 1 , 6 ) , ( 1 , 7 ) , ( 1 , 8 ) , ( 1 , 9 ) , ( 1 , 10 ) , ( 2 , 3 ) , ( 2 , 4 ) , ( 2 , 5 ) , ( 2 , 6 ) , ( 2...
Groups of unique pairs where members appear once per group
Python
I am running a python script on a remote machine , which runs fine , but soon after starting I get the warning : I did n't worry about this warning as it was n't stopping my code.I then tried to submit the same code using Slurm workload manager , using the command : When I do this , the code does n't work , and I get t...
QStandardPaths : XDG_RUNTIME_DIR not set , defaulting to '/tmp/runtime-myusername ' sbatch -- wrap= '' python mycode.py '' -N 1 -- cpus-per-task=8 -o mycode.o Traceback ( most recent call last ) : File `` mycode.py '' , line 99 , in < module > fig=plt.figure ( figsize= ( 20 , 12 ) , dpi = 100 , facecolor= ' w ' , edgec...
Error only when submitting python job in Slurm
Python
I am trying to fit at TensorForestEstimator model with numerical floating-point data representing 7 features and 7 labels . That is , the shape of both features and labels is ( 484876 , 7 ) . I set num_classes=7 and num_features=7 in ForestHParamsappropriately . The format of the data is as follows : When calling fit (...
f1 f2 f3 f4 f5 f6 f7 l1 l2 l3 l4 l5 l6 l739000.0 120.0 65.0 1000.0 25.0 0.69 3.94 39000.0 39959.0 42099.0 46153.0 49969.0 54127.0 55911.032000.0 185.0 65.0 1000.0 75.0 0.46 2.19 32000.0 37813.0 43074.0 48528.0 54273.0 60885.0 63810.0 30000.0 185.0 65.0 1000.0 25.0 0.41 1.80 30000.0 32481.0 35409.0 39145.0 42750.0 46678...
TensorFlow crashes when fitting TensorForestEstimator
Python
I have seen here and here on how to return every nth row ; but my problem is different . A separate column in the file provides specifics about which nth element to return ; which are different depending on the group . Here is a sample of the dataset where the Nth column provides the rows to return . That is , for Id g...
Id TagNo Ntha A-A-3 3a A-A-1 3a A-A-5 3a A-A-2 3a AX-45 3a AX-33 3b B-B-5 4b B-B-4 4b B-B-3 4b BX-B2 4 Id TagNo Nth a A-A-3 3 a A-A-2 3 b B-B-5 4
Take every nth row from a file with groups and n is a given in a column
Python
Is there a way to add multiple items to a list in a list comprehension per iteration ? For example : output : [ [ 1,2,3 ] , ' a ' , [ 1,2,3 ] , ' b ' , [ 1,2,3 ] , ' c ' , [ 1,2,3 ] , 'd ' ]
y = [ ' a ' , ' b ' , ' c ' , 'd ' ] x = [ 1,2,3 ] return [ x , a for a in y ]
list comprehension question
Python
I have an issue with Recurrentshop and Keras . I am trying to use Concatenate and multidimensional tensors in a Recurrent Model , and I get dimension issue regardless of how I arrange the Input , shape and batch_shape.Minimal code : ErrorCode : Please help .
from keras.layers import *from keras.models import *from recurrentshop import *from keras.layers import Concatenateinput_shape= ( 128,128,3 ) x_t = Input ( shape= ( 128,128,3 , ) ) h_tm1 = Input ( shape= ( 128,128,3 , ) ) h_t1 = Concatenate ( ) ( [ x_t , h_tm1 ] ) last = Conv2D ( 3 , kernel_size= ( 3,3 ) , strides= ( 1...
Recurrentshop and Keras : multi-dimensional RNN results in a dimensions mismatch error
Python
I have two HUGE Pandas dataframes with location based values , and I need to update df1 [ 'count ' ] with the number of records from df2 which are less than 1000m from each point in df1 . Here 's an example of my data , imported into PandasIn reality , df1 has ~10 million rows , and df2 has ~1 millionI created a workin...
df1 = lat long valA count 0 123.456 986.54 1 0 1 223.456 886.54 2 0 2 323.456 786.54 3 0 3 423.456 686.54 2 0 4 523.456 586.54 1 0df2 = lat long valB 0 123.456 986.54 1 1 223.456 886.54 2 2 323.456 786.54 3 3 423.456 686.54 2 4 523.456 586.54 1 import pandas as pdimport geopy.distance as gpdfile1 = ' C : \\path\\file1....
Improved efficiency versus iterating over two large Pandas Dataframes
Python
I have this list : I need to then shuffle or randomize the list : And then I need to go through and find any adjacent 1 's and move them so that they are separated by at least one 0 . For example I need the result to look like this : I am not sure of what the most efficient way to go about searching for adjacent 1 's a...
row = [ 1 , 1 , 1 , 1 , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] shuffle ( row ) row = [ 0 , 0 , 1 , 0 , 1 , 0 , 0 , 0 , 1 , 0 , 0 , 1 , 0 , 0 , 0 , 1 , 0 , 1 , 0 , 0 ] row = [ 1 , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] rowlist = set ( list ( permutations ( row ) ) ) rowschemes = [ ( 0 , 0 ) + x for...
How to check for adjacency in list , then fix adjacency in python
Python
TL ; DR I 'm looking for help to implement the marble diagram below . The intention is to sort the non-sorted values to the extent possible without waiting time between scan executions.I 'm not asking for a full implementation . Any guidance will be welcome.I have an asynchronous slow ( forced for testing purpose ) sca...
thread_1_scheduler = ThreadPoolScheduler ( 1 ) thread = ExternalDummyService ( ) external_obs = thread.subject.publish ( ) external_obs \ .flat_map ( lambda msg : Observable.just ( msg ) .subscribe_on ( thread_1_scheduler ) ) \ .scan ( seed=State ( 0 , None ) , accumulator=slow_scan_msg ) \ .subscribe ( log , print , l...
RxPy : Sort hot observable between ( slow ) scan executions
Python
I have a model called Appointment which has the columns datetime which is a DateTime field and duration which is an Integer field and represents duration in minutes . Now I want to check if func.now ( ) is between the datetime of the appointment and the sum of the datetime and durationI am currently to try to do it thi...
current_appointment = Appointment.query.filter ( Appointment.datetime.between ( func.now ( ) , func.timestampadd ( 'MINUTES ' , Appointment.duration , func.now ( ) ) ) ) .limit ( 1 ) .one_or_none ( )
Sqlalchemy get row in timeslot
Python
This may be a simple question , but I 'm having trouble making a unique search for it . I have a class that defines a static dictionary , then attempts to define a subset of that dictionary , also statically.So , as a toy example : This produces NameError : global name 'first_d ' is not definedHow should I be making th...
class example ( object ) : first_d = { 1:1,2:2,3:3,4:4 } second_d = dict ( ( k , first_d [ k ] ) for k in ( 2,3 ) ) class example2 ( object ) : first = 1 second = first + 1
Reference class variable in a comprehension of another class variable
Python
I am creating random Toeplitz matrices to estimate the probability that they are invertible . My current code isCan this be sped up ? I would like to increase the value 50000 to get more accuracy but it is too slow to do so currently.Profiling using only for n in xrange ( 10,14 ) shows
import randomfrom scipy.linalg import toeplitzimport numpy as npfor n in xrange ( 1,25 ) : rankzero = 0 for repeats in xrange ( 50000 ) : column = [ random.choice ( [ 0,1 ] ) for x in xrange ( n ) ] row = [ column [ 0 ] ] + [ random.choice ( [ 0,1 ] ) for x in xrange ( n-1 ) ] matrix = toeplitz ( column , row ) if ( np...
Speed up random matrix computation
Python
Answering this question I faced an interesting situation 2 similar code snippets performed quite differently . I 'm asking here just to understand the reason for that and to improve my intuition for such cases.I 'll adapt code snippets for Python 2.7 ( In Python 3 the performance differences are the same ) .Output : Th...
from collections import OrderedDictfrom operator import itemgetterfrom itertools import izipitems = OrderedDict ( [ ( ' a ' , 10 ) , ( ' b ' , 9 ) , ( ' c ' , 4 ) , ( 'd ' , 7 ) , ( ' e ' , 3 ) , ( ' f ' , 0 ) , ( ' g ' , -5 ) , ( ' h ' , 9 ) ] ) def f1 ( ) : return min ( items , key=items.get ) def f2 ( ) : return min...
Understanding performance difference
Python
Is there any way to compare two dates without calling strptime each time in python ? I 'm sure given my problem there 's no other way , but want to make sure I 've checked all options . I 'm going through a very large log file , each line has a date which I need to compare to see if that date is within the range of two...
Fri Sep 2 15:12:43 2016 output2.file 63518075 function calls ( 63517618 primitive calls ) in 171.409 seconds Ordered by : cumulative time List reduced from 571 to 10 due to restriction < 10 > ncalls tottime percall cumtime percall filename : lineno ( function ) 1 0.003 0.003 171.410 171.410 script.py:3 ( < module > ) 1...
alternative to strptime for comparing dates ?
Python
I am trying to click the tabs on the webpage as seen below . Unfortunately , it only seems to click some of the tabs despite correct correct xpath in inspect Chrome . I can only assume it ’ s not clicking all the tabs because the full xpath is not being used . However..I have tried changing the xpath : //div [ @ class=...
clickMe = wait ( driver , 10 ) .until ( EC.element_to_be_clickable ( ( By.XPATH , ' ( //div [ @ class= '' KambiBC-collapsible-container KambiBC-mod-event-group-container '' ] ) [ % s ] ' % str ( index + 1 ) ) ) ) # KambiBC-contentWrapper__bottom > div > div > div > div > div.KambiBC-quick-browse-container.KambiBC-quick...
Not clicking all tabs and not looping once issues
Python
I have a pandas DataFrame with a secondary y axis and I need a bar plot with the legend in front of the bars . Currently , one set of bars is in front of the legend . If possible , I would also like to place the legend in the lower-left corner . Any ideas appreciated ! I have attempted to set the legend=false and add a...
import pandas as pdimport matplotlib.pyplot as pltdf_y = pd.DataFrame ( [ [ 'jade',12,800 ] , [ 'lime',12,801 ] , [ 'leaf',12,802 ] , [ 'puke',12,800 ] ] , columns= [ 'Territory ' , 'Cuisines ' , 'Restaurants ' ] ) df_y.set_index ( 'Territory ' , inplace=True ) plt.figure ( ) ax=df_y.plot ( kind='bar ' , secondary_y= [...
Put the legend of pandas bar plot with secondary y axis in front of bars
Python
I have the following 4 dictionaries in a MongoDB collection called favoriteColors : I 'm trying to create an ORDERED list of color values matching a different ordered list.For example , if I have the list [ `` Johnny '' , `` Steve '' , `` Ben '' , `` Johnny '' ] the new list will [ `` green '' , `` blue '' , `` red '' ...
{ `` name '' : `` Johnny '' , `` color '' : `` green '' } { `` name '' : `` Steve '' , `` color '' : `` blue '' } , { `` name '' : `` Ben '' , `` color '' : `` red '' } , { `` name '' : `` Timmy '' , `` color '' : `` cyan '' } name_list = [ `` Steve '' , `` Steve '' , `` Ben '' , `` Ben '' , `` Johnny '' ] color_list =...
Iterating over a dictionary to create a list
Python
I do understand how setattr ( ) works in python , but my question is when i try to dynamically set an attribute and give it an unbound function as a value , so the attribute is a callable , the attribute ends up taking the name of the unbound function when i call attr.__name__ instead of the name of the attribute . Her...
class Filter : def __init__ ( self , column= [ 'poi_id ' , 'tp.event ' ] , access= [ 'con ' , 'don ' ] ) : self.column = column self.access = access self.accessor_column = dict ( zip ( self.access , self.column ) ) self.set_conditions ( ) def condition ( self , name ) : # i want to be able to get the name of the dynami...
Python setattr ( ) to function takes initial function name
Python
What does the * mean in the following code ( found in the pprint library ) ? If it was *args then it would be an arbitrary number of positional parameters . The parameter values would be in the tuple called args . The first 4 parameters could be assigned either by name or by position , the parameter compact could only ...
def pformat ( object , indent=1 , width=80 , depth=None , * , compact=False ) : `` '' '' Format a Python object into a pretty-printed representation . '' '' '' return PrettyPrinter ( indent=indent , width=width , depth=depth , compact=compact ) .pformat ( object )
What does a star * alone mean in a function declaration ?
Python
I am scripting GDB with Python 2.7.I am simply stepping instructions with gdb.execute ( `` stepi '' ) . If the debugged program is idling and waiting for user interaction , gdb.execute ( `` stepi '' ) does n't return . If there is such a situation , I want to stop the debugging session without terminating gdb.To do so ...
from ctypes import c_ulonglong , c_boolfrom os import killfrom threading import Threadfrom time import sleepimport signal # We need mutable primitives in order to update them in the threadit = c_ulonglong ( 0 ) # Instructions counterprogram_exited = c_bool ( False ) t = Thread ( target=check_for_idle , args= ( pid , it...
gdb.execute blocks all the threads in python scripts
Python
I have setup TwiMl on eroku in Python.When I call user A from user B , user A did n't get call and VOIP also , while user B is got bot message like `` thanks for calling '' .When I try to placeCall to user B from PostMan , user B gets call and also got bot message like `` thanks for calling '' .PostMan URL : https : //...
Flask==0.10.1Jinja2==2.7.3MarkupSafe==0.23Werkzeug==0.9.6httplib2==0.9itsdangerous==0.24six==1 . *twiliowsgiref==0.1.2 import osfrom flask import Flask , requestfrom twilio.jwt.access_token import AccessTokenfrom twilio.jwt.access_token.grants import VoiceGrantfrom twilio.rest import Clientimport twilio.twimlACCOUNT_SI...
twilio App to App calling is not working
Python
( Data sample and attempts at the end of the question ) With a dataframe such as this : How can I find what percentage of each type [ A , B , C , D ] that belongs to each area [ North , South , East , West ] ? Desired output : My best attempt so far is : Which returns : And I guess I can build on that by calculating su...
Type Class Area Decision0 A 1 North Yes1 B 1 North Yes2 C 2 South No3 A 3 South No4 B 3 South No5 C 1 South No6 A 2 North Yes7 B 3 South Yes8 B 1 North No9 C 1 East No10 C 2 West Yes North South East WestA 0.66 0.33 0 0B 0.5 0.5 0 0C 0 0.5 0.25 0.25 df_attempt1= df.groupby ( [ 'Area ' , 'Type ' ] ) [ 'Type ' ] .aggrega...
Pandas : How to find percentage of group members type per subgroup ?
Python
I am new to programming and to Python . Not sure how to proceed to achieve this ( explained below ) problem , hence the question.I have n number of lists , each containing 1 or more items . I want to have a new list with all possible combinations , which uses one item from each list once , and always.Example : Result w...
list_1 = [ ' 1 ' , ' 2 ' , ' 3 ' ] list_2 = [ ' 2 ' , ' 5 ' , ' 7 ' ] list_3 = [ ' 9 ' , ' 9 ' , ' 8 ' ]
Python combination generation
Python
Suppose I have the following list foo that I would like to sort : To inform the sort , I have the following dictionary of `` dependencies '' , where if a value is in a list for a key , that value must sort higher than the key in list foo : For example , looking at list foo , we see the value 63 at index 0 . But , check...
foo = [ 63,64,65 ] bar = { 63 : [ 64 , 65 ] , 64 : [ 65 ] }
sorting python list based on `` dependencies '' from dictionary
Python
I 'm trying to parse various pages on the web using lxml module , like : But it seems like I have to switch this lxml.html to lxml.html.html5parser in the case of html5 pages.http : //lxml.de/html5parser.htmlSo how can I determine if a page is html5-based ? Do I have to check the DOCTYPE char by char before parse it ? ...
def dom ( self ) : return lxml.html.fromstring ( self.content ) import lxml.htmlfrom lxml.html import html5parserdef dom ( self ) : content = self.content if self._is_html5 ( ) : elm = html5parser.fromstring ( content ) content = lxml.html.tostring ( elm , method='html ' ) return lxml.html.fromstring ( content ) def _i...
How do I check if a page is html5-based in python ?
Python
IssueLet 's say I have a function in python that returns a dict with some objects.At some point I notice that it would make sense to rename the key 'some string ' as it is misleading and not well describing what is actually stored with this key . However , if I were to just change the key , people who use this bit of c...
class MyObj : passdef my_func ( ) : o = MyObj ( ) return { 'some string ' : o , 'additional info ' : 'some other text ' } from warnings import warnclass MyDict ( dict ) : def __getitem__ ( self , key ) : if key == 'some string ' : warn ( 'Please use the new key : ` some object ` instead of ` some string ` ' ) return su...
How to make a dict key deprecated ?
Python
I am attempting to pass a shared secret to child processes . In a Linux environment this works . In a Windows environment the child does not receive the shared secret . The three files below are a simple example of what I 'm trying to do : main.pymodule1.pymodule2.pyIn an Ubuntu 14.04 environment , on Python 3.5 , I re...
import multiprocessingimport module1import module2if __name__ == `` __main__ '' : module1.init ( ) process = multiprocessing.Process ( target=module2.start ) process.start ( ) process.join ( ) import ctypesimport multiprocessingx = Nonedef init ( ) : global x x = multiprocessing.Value ( ctypes.c_wchar_p , `` asdf '' ) ...
Multiprocessing output differs between Linux and Windows - Why ?
Python
Is there an algorithm to find ALL factorizations of an integer , preferably in Python/Java but any feedback is welcome.I have an algorithm to calculate the prime factors . For instance [ 2,2,5 ] are the prime factors of 20.I also have an algorithm to compute all factors ( prime and non-prime ) of an algorithm . For ins...
def prime_factorization ( n ) : primfac = [ ] d = 2 while d*d < = n : while ( n % d ) == 0 : primfac.append ( d ) n /= d d += 1 if n > 1 : primfac.append ( n ) return primfac def factors ( n ) : a , r = 1 , [ 1 ] while a * a < n : a += 1 if n % a : continue b , f = 1 , [ ] while n % a == 0 : n //= a b *= a f += [ i * b...
Algorithm to find ALL factorizations of an integer
Python
Problem : The input is a ( i , j ) -matrix M. The desired output is a ( i^n , j^n ) matrix K , where n is the number of products taken . The verbose way to get the desired output is as followsGenerate all arrays of n row permutations I ( total of i**n n-arrays ) Generate all arrays of n column permutations J ( total of...
import numpy as npimport itertoolsm=np.array ( [ [ 1,2,3 ] , [ 4,5,6 ] ] ) def f ( m ) : labels_i = [ list ( p ) for p in itertools.product ( range ( np.shape ( m ) [ 0 ] ) , repeat=3 ) ] labels_j = [ list ( p ) for p in itertools.product ( range ( np.shape ( m ) [ 1 ] ) , repeat=3 ) ] out = np.zeros ( [ len ( labels_i...
Numpy/Python : Efficient matrix as multiplication of cartesian product of input matrix
Python
I have very simple task . After migration and adding new field ( repeated and composite property ) to existing NDB Entity ( ~100K entities ) I need to setup default value for it.I tried that code first : But it fails with such errors : The task runs on separate task queue so it have at least 10 mins to execute but seem...
q = dm.E.query ( ancestor=dm.E.root_key ) for user in q.iter ( batch_size=500 ) : user.field1 = [ dm.E2 ( ) ] user.put ( ) 2015-04-25 20:41:44.792 /**** 500 599830ms 0kb AppEngine-Google ; ( +http : //code.google.com/appengine ) module=default version=1-17-0W 2015-04-25 20:32:46.675 suspended generator run_to_queue ( q...
Update for big count of NDB Entities fails
Python
The actual problem I wish to solve is , given a set of N unit vectors and another set of M vectors calculate for each of the unit vectors the average of the absolute value of the dot product of it with every one of the M vectors . Essentially this is calculating the outer product of the two matrices and summing and ave...
N = 7M = 5 # Create the unit vectors , just so we have some examples , # this is not meant to be elegantphi = np.random.rand ( N ) *2*np.pictheta = np.random.rand ( N ) *2 - 1stheta = np.sqrt ( 1-ctheta**2 ) nhat = np.array ( [ stheta*np.cos ( phi ) , stheta*np.sin ( phi ) , ctheta ] ) .T # Create the other vectorsm = ...
Non-trivial sums of outer products without temporaries in numpy
Python
I 've tried running the following code in IDLE : There is no result : But when I run it in the command line , i get this : Can someone explain the difference in what I did ?
import sysdir ( sys ) > > > > > > dir ( sys ) [ '__displayhook__ ' , '__doc__ ' , '__excepthook__ ' , '__name__ ' , '__package__ ' , '__stderr__ ' , '__stdin__ ' , '__stdout__ ' , '_clear_type_cache ' , '_current_frames ' , '_getframe ' , '_mercurial ' , 'api_version ' , 'argv ' , 'builtin_module_names ' , 'byteorder '...
dir ( ) function in commandline vs IDLE
Python
Having a Matrix M of size m , n over integers , what would be a good algorithm to transform it such that the sum of all elements is maximal ? The only operations allowed are multiplying by -1 column-wise or row-wise . There can be executed as many such operations as required.Rough , overall idea : What I have thought a...
import numpy as npM = np.matrix ( [ [ 2,2,2,2 ] , [ 2,2 , -2,2 ] , [ 2,2,2,2 ] , [ 2,2,2,1 ] , ] ) def invert_at ( M , n , m ) : M [ n , : ] *= -1 M [ : ,m ] *= -1 invert_at ( M , 1 , 2 ) # startinvert_at ( M , 2 , 2 ) invert_at ( M , 3 , 2 ) invert_at ( M , 3 , 3 ) # end [ [ 2 2 -2 -2 ] [ -2 -2 -2 2 ] [ -2 -2 2 2 ] [ ...
Make the sum of integers in a matrix maximal by multiplying rows and columns by -1
Python
I converted a JSON into DataFrame and ended up with a column 'Structure_value ' having below values as list of dictionary/dictionaries : Since it is an object so I guess it ended up in this format.I need to split it into below four columns : Structure_value_room_1Structure_value_length_1Structure_value_room_2Structure_...
Structure_value [ { 'Room ' : 6 , 'Length ' : 7 } , { 'Room ' : 6 , 'Length ' : 7 } ] [ { 'Room ' : 6 , 'Length ' : 22 } ] [ { 'Room ' : 6 , 'Length ' : 8 } , { 'Room ' : 6 , 'Length ' : 9 } ] Structure_value_room_1 Structure_value_length_1 Structure_value_room_2 \0 6 7 6.0 1 6 22 NaN 2 6 8 6.0 Structure_value_length_2...
How to convert nested json structure to dataframe