lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | The title to this may be confusing , but basically I want to be able to do the following : Expected behavior would be that it would open up a python terminal session , then open up xkcd comic 353 , print 'this is so meta ' to the command line , and finally exit the python command line.Basically , I want to be able to o... | import subprocesssubprocess.call ( [ `` python '' ] ) subprocess.call ( [ `` import '' , `` antigravity '' ] ) subprocess.check_call ( [ `` print '' , '' \ '' This is so meta\ '' `` ] ) subprocess.call ( [ `` exit ( ) '' ] ) | Input python commands on the python command line |
Python | I tried to stress my server a little , and something weird happened . I 'm using mod_wsgi , with basic script plugged in : I tried to stress it a little with simple `` hit it all I can '' : And weird thing happened - wget thrown at me reports about error 500 on server.when I checked out apache logs , this is what I fou... | import socketdef application ( environ , start_response ) : status = '200 OK ' output = 'Hello World ! ' response_headers = [ ( 'Content-type ' , 'text/plain ' ) , ( 'Content-Length ' , str ( len ( output ) ) ) ] start_response ( status , response_headers ) return [ output ] # ! /bin/zshfor i in { 1..50 } dowget http :... | mod_wsgi fails under pressure |
Python | My script loops through each line of an input file and performs some actions using the string in each line . Since the tasks performed on each line are independent of each other , I decided to separate the task into threads so that the script does n't have to wait for the task to complete to continue with the loop . Th... | def myFunction ( line , param ) : # Doing something with line and param # Sends multiple HTTP requests and parse the response and produce outputs # Returns nothingparam = arg [ 1 ] with open ( targets , `` r '' ) as listfile : for line in listfile : print ( `` Starting a thread for : `` , line ) t=threading.Thread ( ta... | What is the safest way to queue multiple threads originating in a loop ? |
Python | I have a Python pandas DataFrame in which each element is a float or NaN . For each row , I will need to find the column which holds the nth number of the row . That is , I need to get the column holding the nth element of the row that is not NaN . I know that the nth such column always exists.So if n was 4 and a panda... | 10 20 30 40 50 60 70 80 90 100 ' A ' 4.5 5.5 2.5 NaN NaN 2.9 NaN NaN 1.1 1.8 ' B ' 4.7 4.1 NaN NaN NaN 2.0 1.2 NaN NaN NaN ' C ' NaN NaN NaN NaN NaN 1.9 9.2 NaN 4.4 2.1 'D ' 1.1 2.2 3.5 3.4 4.5 NaN NaN NaN 1.9 5.5 ' A ' 60 ' B ' 70 ' C ' 100 'D ' 40 import pandas as pdimport mathn = some arbitrary intfor row in myDF.in... | For each row , what is the fastest way to find the column holding nth element that is not NaN ? |
Python | I 've got a problem with removing \n in my program here is the code tried using .rstrip and other variants but it does nothing for my , this is the result i getthe problem is when i call children [ `` Patricia '' ] i get [ ] , because it recognizes only children [ `` Patricia\n '' ] | with open ( filename ) as f : for line in f.readlines ( ) : parent , child = line.split ( `` , '' ) parent.strip ( ) child.strip ( ) children [ child ] .append ( parent ) { 'Patricia\n ' : [ 'Mary ' ] , 'Lisa\n ' : [ 'Mary ' ] } | removing \n in dictionary |
Python | a follow-up question on this question : i ran the code below on python 3.5 and python 3.6 - with very different results : as stated in the previous question this raises TypeError : type object got multiple values for keyword argument ' b'on python 3.6. but on python 3.5 i get the exception : KeyError : 0moreover if i d... | class Container : KEYS = ( ' a ' , ' b ' , ' c ' ) def __init__ ( self , a=None , b=None , c=None ) : self.a = a self.b = b self.c = c def keys ( self ) : return Container.KEYS def __getitem__ ( self , key ) : if key not in Container.KEYS : raise KeyError ( key ) return getattr ( self , key ) def __str__ ( self ) : # p... | In-place custom object unpacking different behavior with __getitem__ python 3.5 vs python 3.6 |
Python | I receive next warning using SciPy fmin_bfgs ( ) optimization in the NeuralNetwork . Everything should be clear and simple , following Backpropagation algorithm.1 Feed Forward training examples.2 Calculate Error term for each Unit.3 Accumulate gradient ( for the first example , I 'm skipping regularization term ) .I ju... | Starting Loss : 7.26524579601Check gradient : 2.02493576268Warning : Desired error not necessarily achieved due to precision loss . Current function value : 5.741300 Iterations : 3 Function evaluations : 104 Gradient evaluations : 92Trained Loss : 5.74130012926 def feed_forward ( x , theta1 , theta2 ) : hidden_dot = np... | SciPy optimization Warning in the Neural Network |
Python | I 'm playing with django ( I 'm a quite new beginner ) and while surfing the web I read it could be possible to keep our internal camelCase naming conventions inside the mySQL database and also for the models ' name inside models.pyWell , after some days I can conclude it 's better to leave things as they were designed... | class City ( models.Model ) : id = models.AutoField ( db_column='ID ' , primary_key=True ) name = models.CharField ( db_column='Name ' , max_length=35 ) countrycode = models.ForeignKey ( Country , db_column='CountryCode ' ) district = models.CharField ( db_column='District ' , max_length=20 ) population = models.Intege... | Django migration with `` -- fake-initial '' is not working if AddField referes to `` same '' column |
Python | Hi i have written regex to check where ther string have the char like - or . or / or : or AM or PM or space .The follworig regex work for that but i want to make case fail if the string contain the char other than AMP .import reOutput : Edited : Validate ( { 'Date ' : '12122010 ' } ) Date 12122010 False ( Expecting Fal... | Datere = re.compile ( `` [ -./\ : ? AMP ] + '' ) FD = { 'Date ' : lambda date : bool ( re.search ( Datere , date ) ) , } def Validate ( date ) : for k , v in date.iteritems ( ) : print k , v print FD.get ( k ) ( v ) Validate ( { 'Date ' : '12/12/2010 ' } ) Date 12/12/2010TrueValidate ( { 'Date ' : '12/12/2010 12:30 AM ... | Regex to check date |
Python | Retrieving the order of key-word arguments passed via **kwargs would be extremely useful in the particular project I am working on . It is about making a kind of n-d numpy array with meaningful dimensions ( right now called dimarray ) , particularly useful for geophysical data handling.For now say we have : What works ... | import numpy as npfrom dimarray import Dimarray # the handy class I am programmingdef make_data ( nlat , nlon ) : `` '' '' generate some example data `` '' '' values = np.random.randn ( nlat , nlon ) lon = np.linspace ( -180,180 , nlon ) lat = np.linspace ( -90,90 , nlat ) return lon , lat , values > > > lon , lat , va... | How to retrieve the original order of key-word arguments passed to a function call ? |
Python | I feel like I want an `` Everything '' keyword in Python that would have the following properties : Any boolean test of the form x in Everything would always return True , regardless of x.Any attempt to iterate it , such as for x in Everything would raise an exceptionMy motivation is that I would like to have an option... | def check_allowed ( x , whitelist=None ) : if whitelist is None or x in whitelist : print ( `` x is ok '' ) else : print ( `` x is not ok '' ) def check_allowed ( x , whitelist=Everything ) : if x in whitelist : print ( `` x is ok '' ) else : print ( `` x is not ok '' ) | A Python `` Everything '' keyword that always returns True for membership tests |
Python | I find myself often wanting to structure my exception classes like this : I have only seen this pattern used in Django ( DoesNotExist ) and it makes so much sense . Is there anything I 'm missing , why most people seem to favor top-level Exceptions ? editI would use these classes for versatile granularity , e.g : | # legends.pyclass Error ( Exception ) : passclass Rick ( object ) : class Error ( Error ) : pass class GaveYouUp ( Error ) : pass class LetYouDown ( Error ) : passclass Michael ( object ) : class Error ( Error ) : pass class BlamedItOnTheSunshine ( Error ) : pass class BlamedItOnTheMoonlight ( Error ) : pass import leg... | Are python Exceptions as class attributes a bad thing ? |
Python | I am working on fitting statistical models to distributions using matplotlib 's hist function . For example my code fits an exponential distribution using the following code : Which runs fine , but when I modify it to do the same thing for a uniform distribution between a & b , The code crashes , with ValueError : The ... | try : def expDist ( x , a , x0 ) : return a* ( exp ( - ( x/x0 ) ) /x0 ) self.n , self.bins , patches = plt.hist ( self.getDataSet ( ) , self.getDatasetSize ( ) /10 , normed=1 , facecolor='blue ' , alpha = 0.55 ) popt , pcov = curve_fit ( expDist , self.bins [ : -1 ] , self.n , p0= [ 1 , mean ] ) print `` Fitted gaussia... | What specific requirements does the function passed to scipy.optimize.curve_fit need to fulfill in order to run ? |
Python | I have created a form widget that is automatically adding a add new record section at the top of the form , which i do not want to be there . can someone tell me how to disable this ? I just want to display the variables not the add form.forms.pyadmin.pychange_view.htmlpage that is loaded : | class TemplateVariablesWidget ( forms.Widget ) : template_name = 'sites/config_variables.html ' def render ( self , name , value , attrs=None ) : sc_vars = ConfigVariables.objects.filter ( type='Showroom ' ) wc_vars = ConfigVariables.objects.filter ( type='Major Site ' ) context = { 'SConfigVariables ' : sc_vars , 'WCo... | Django - Remove add new record from form widget > |
Python | such asI want to know , when does python combine the constant string as the CONST.If possible , please tell me which source code about this at cpython ( whatever 2.x , 3.x ) . | In [ 9 ] : dis.disassemble ( compile ( `` s = '123 ' + '456 ' '' , `` < execfile > '' , `` exec '' ) ) 1 0 LOAD_CONST 3 ( '123456 ' ) 3 STORE_NAME 0 ( s ) 6 LOAD_CONST 2 ( None ) 9 RETURN_VALUE | When does python compile the constant string letters , to combine the strings into a single constant string ? |
Python | I want to define constraint specification language based on Python . For example : Here IntVar is a class describing a variable that can assume any integer value , and Constraint is a class to represent constraints . To implement this I can just overload operator < by defining method __lt__ for class IntVar.Suppose now... | x = IntVar ( ) c = Constraint ( x < 19 ) c.solve ( ) c = Constraint ( x > 10 and x < 19 ) c = Constraint ( `` x < 19 '' ) c = Constraint ( lambda : x < 19 ) | Defining new semantics for expressions in Python |
Python | Could n't really find it , but probably it 's me not knowing how to search properly : ( Just wanted to find out what the name is for : type of construct ? | [ x for x in some_list ] | What is the name for [ x for x in some_list ] type of construct in python ? |
Python | I understand that one way to work with the digits of a number in Python is to convert the number to a string , and then use string methods to slice the resulting `` number '' into groups of `` digits '' . For example , assuming I have a function prime that tests primality , I can confirm that an integer n is both a lef... | all ( prime ( int ( str ( n ) [ : -i ] ) ) and prime ( int ( str ( n ) [ i : ] ) ) for i in range ( 1 , len ( str ( n ) ) ) ) | Is using ` str ` the correct idiom for working with digits in Python |
Python | I am trying to use Mutagen for changing ID3 ( version 2.3 ) cover art for a bunch of MP3 files in the following way : However , the file ( or at least the APIC tag ) remains unchanged , as checked by reading the tag back . In the system file explorer , the file does show an updated Date modified , however . How can I g... | from mutagen.mp3 import MP3from mutagen.id3 import APICfile = MP3 ( filename ) with open ( 'Label.jpg ' , 'rb ' ) as albumart : file.tags [ 'APIC ' ] = APIC ( encoding=3 , mime='image/jpeg ' , type=3 , desc=u'Cover ' , data=albumart.read ( ) ) file.save ( v2_version=3 ) | Mutagen 's save ( ) does not set or change cover art for MP3 files |
Python | Consider the following list of day-of-week-hour pairs in 24H format : and two time points , e.g . : Start : End : Say we need to know how many hours there are between these two datetimes ( either rounding up or down ) for each of the day-of-week-hour pairs specified above.How can I approach this problem in Python ? I e... | { 'Mon ' : [ 9,23 ] , 'Thu ' : [ 12 , 13 , 14 ] , 'Tue ' : [ 11 , 12 , 14 ] , 'Wed ' : [ 11 , 12 , 13 , 14 ] 'Fri ' : [ 13 ] , 'Sat ' : [ ] , 'Sun ' : [ ] , } datetime.datetime ( 2015 , 7 , 22 , 17 , 58 , 54 , 746784 ) datetime.datetime ( 2015 , 8 , 30 , 10 , 22 , 36 , 363912 ) | Counting day-of-week-hour pairs between two dates |
Python | I started learning how to use theano with lasagne , and started with the mnist example . Now , I want to try my own example : I have a train.csv file , in which every row starts with 0 or 1 which represents the correct answer , followed by 773 0s and 1s which represent the input . I did n't understand how can I turn th... | ... with gzip.open ( filename , 'rb ' ) as f : data = pickle_load ( f , encoding='latin-1 ' ) # The MNIST dataset we have here consists of six numpy arrays : # Inputs and targets for the training set , validation set and test set.X_train , y_train = data [ 0 ] X_val , y_val = data [ 1 ] X_test , y_test = data [ 2 ] ...... | numpy array from csv file for lasagne |
Python | I 'd like to add a polynomial curve to a scatter plot that is rendered using a callback.Following is my callback function which returns the scatter plot.Resulting plot : I am able to add a polyfit line using sklearn.preprocessing.Is there a way to do this in plotly ? | @ app.callback ( Output ( 'price-graph ' , 'figure ' ) , [ Input ( 'select ' , 'value ' ) ] ) def update_price ( sub ) : if sub : fig1 = go.Figure ( data= [ go.Scatter ( x=dff [ 'Count ' ] , y=dff [ 'Rent ' ] , mode='markers ' ) ] , layout=go.Layout ( title= '' , xaxis=dict ( tickfont=dict ( family='Rockwell ' , color=... | Plotly : How to add polynomial fit line to plotly go.scatter figure using a DASH callback ? |
Python | Lets assume I have a ( text ) file with the following structure ( name , score ) : And so on . My aim is to sum the scores for every name and order them from highest score to lowest score . So in this case , I want the following output : In advance I do not know what names will be in the file.I was wondering if there i... | a 0 a 1 b 0 c 0 d 3 b 2 d 3 b 2 a 1 c 0 | Efficiently processing data in text file |
Python | In the python idle : But when I put the code in a script and run it , I will get a different result : Why did this happen ? I know that is compares the id of two objects , so why the ids of two objects are same/unique in python script/idle ? I also found that , if I use a small int , for example 1 , instead of 1.1 , th... | > > > a=1.1 > > > b=1.1 > > > a is bFalse $ cat t.pya=1.1b=1.1print a is b $ python t.pyTrue | Different behavior in python script and python idle ? |
Python | I want to run tests with multiple builds of a product running them once . Here is example of the code : The first iteration works well , but on the start of the second one an error appears : What is happening ? What result runner calls ? And why does it fail ? Any ideas how to solve the problem ? | import unittestsuite = unittest.TestLoader ( ) .discover ( `` ./tests '' ) runner = unittest.TextTestRunner ( ) for build in [ build1 , build2 ] : get_the_build ( build ) runner.run ( suite ) Traceback ( most recent call last ) : File `` D : /Path/to/my/folder/run_tests.py '' , line 9 , in < module > runner.run ( suite... | How to run the same TestSuite multiple times unittest texttestrunner |
Python | I was looking into how Python represents string after PEP 393 and I am not understanding the difference between PyASCIIObject and PyCompactUnicodeObject.My understanding is that strings are represented with the following structures : Correct me if I am wrong , but my understanding is that PyASCIIObject is used for stri... | typedef struct { PyObject_HEAD Py_ssize_t length ; /* Number of code points in the string */ Py_hash_t hash ; /* Hash value ; -1 if not set */ struct { unsigned int interned:2 ; unsigned int kind:3 ; unsigned int compact:1 ; unsigned int ascii:1 ; unsigned int ready:1 ; unsigned int :24 ; } state ; wchar_t *wstr ; /* w... | Python > = 3.3 Internal String Representation |
Python | Using Spacy , I extract aspect-opinion pairs from a text , based on the grammar rules that I defined . Rules are based on POS tags and dependency tags , which is obtained by token.pos_ and token.dep_ . Below is an example of one of the grammar rules . If I pass the sentence Japan is cool , it returns [ ( 'Japan ' , 'co... | import spacynlp = spacy.load ( `` en_core_web_lg-2.2.5 '' ) review_body = `` Air France is cool . `` doc=nlp ( review_body ) rule3_pairs = [ ] for token in doc : children = token.children A = `` 999999 '' M = `` 999999 '' add_neg_pfx = False for child in children : if ( child.dep_ == `` nsubj '' and not child.is_stop )... | Named Entity Recognition in aspect-opinion extraction using dependency rule matching |
Python | I am trying to implement a NaN-safe shuffling procedure in Cython that can shuffle along several axis of a multidimensional matrix of arbitrary dimension.In the simple case of a 1D matrix , one can simply shuffle over all indices with non-NaN values using the Fisher–Yates algorithm : I would like to extend this algorit... | def shuffle1D ( np.ndarray [ double , ndim=1 ] x ) : cdef np.ndarray [ long , ndim=1 ] idx = np.where ( ~np.isnan ( x ) ) [ 0 ] cdef unsigned int i , j , n , m randint = np.random.randint for i in xrange ( len ( idx ) -1 , 0 , -1 ) : j = randint ( i+1 ) n , m = idx [ i ] , idx [ j ] x [ n ] , x [ m ] = x [ m ] , x [ n ... | In-place shuffling of multidimensional arrays |
Python | I am trying to create f-distributed random numbers with given degree of freedoms d1 and d2 , and plot both a histogram with f-distributed random numbers , and plot an idealised f-distribution curve , but when I give small values to df 's , the histogram does not show up . I am new at statistics and matplotlib , and I c... | def distF ( request , distribution_id ) : dist = get_object_or_404 ( Distribution , pk=distribution_id ) dfd = dist.var4 dfn = dist.var2 x = np.random.f ( dfn , dfd , size = dist.var3 ) num_bins = 50 fig , ax = plt.subplots ( ) print ( x ) # the histogram of the data n , bins , patches = ax.hist ( x , num_bins , normed... | Histogram does not show up in f-distribution plot |
Python | When reading the book 'Effective Python ' by Brett Slatkin I noticed that the author suggested that sometimes building a list using a generator function and calling list on the resulting iterator could lead to cleaner , more readable code.So an example : Where a user could callorand get the same result.The suggestion w... | num_list = range ( 100 ) def num_squared_iterator ( nums ) : for i in nums : yield i**2def get_num_squared_list ( nums ) : l = [ ] for i in nums : l.append ( i**2 ) return l l = list ( num_squared_iterator ( num_list ) ) l = get_num_squared_list ( nums ) | Is it efficient to build a list with a generator function |
Python | In python : | > > > a = b or { } | What is the official name of this construct ? |
Python | I have an autobahn Websocket Server with the typical onX functions in it 's protocol . My problem is that I ca n't find a way to exit onX , while keep doing the various stuff that I wanted to do when the specific message arrived . More specifically in my onMessage function , I sometimes perform an HTTP request to an AP... | @ asyncio.coroutinedef send ( command , userPath , token ) : websocket = yield from websockets.connect ( 'wss : //127.0.0.1:7000 ' , ssl=ssl.SSLContext ( protocol=ssl.PROTOCOL_TLSv1_2 ) ) data = json.dumps ( { `` api_command '' : '' session '' , '' body '' : command , '' headers '' : { ' X-User-Path ' : userPath , ' X-... | Autobahn , leave onMessage block |
Python | I have : and then I get an error : If I set the two sizes to be the same , then the error goes away . But I 'm wondering if my input_size is some large number , say 15 , and I want to reduce the number of hidden features to 5 , why should n't that work ? | def __init__ ( self , feature_dim=15 , hidden_size=5 , num_layers=2 ) : super ( BaselineModel , self ) .__init__ ( ) self.num_layers = num_layers self.hidden_size = hidden_size self.lstm = nn.LSTM ( input_size=feature_dim , hidden_size=hidden_size , num_layers=num_layers ) RuntimeError : The size of tensor a ( 5 ) must... | With a PyTorch LSTM , can I have a different hidden_size than input_size ? |
Python | I have a buffer object in C++ that inherits from std : :vector < char > . I want to convert this buffer into a Python string so that I can send it out over the network via Twisted 's protocol.transport.write.Two ways I thought of doing this are ( 1 ) making a string and filling it char by char : and ( 2 ) making a char... | def scpychar ( buf , n ) : s = `` for i in xrange ( 0 , n ) : s += buf [ i ] return s def scpyarr ( buf , n ) : a = array.array ( ' c ' , ' 0'*n ) for i in xrange ( 0 , n ) : a [ i ] = buf [ i ] return a.tostring ( ) | Python buffer copy speed - why is array slower than string ? |
Python | I am aware that regular queryset or the iterator queryset methods evaluates and returns the entire data-set in one shot .for instance , take this : QuestionIn both methods all the rows are fetched in a single-go.Is there any way in djago that the queryset rows can be fetched one by one from database.Why this weird Requ... | my_objects = MyObject.objects.all ( ) for rows in my_objects : # Way 1for rows in my_objects.iterator ( ) : # Way 2 | Fetching queryset data one by one |
Python | After encountering some probable memory leaks in a long running multi threaded script I found out about maxtasksperchild , which can be used in a Multi process pool like this : Is something similar possible for the Threadpool ( multiprocessing.pool.ThreadPool ) ? | import multiprocessingwith multiprocessing.Pool ( processes=32 , maxtasksperchild=x ) as pool : pool.imap ( function , stuff ) | Is it possible to set maxtasksperchild for a threadpool ? |
Python | My project looks like this : The contents of the .py files are shown below : main.pyc/run_project.pyc/z/the_module.pyc/z/y/the_module_module.pyc/z/y/the_support_function.pyGitHub repo to make replication easier : running-pycharm-project-at-cmdThe problem : in Pycharm load up the project with running-pycharm-project-at-... | running-pycharm-project-at-cmd - main.py - c - run_project.py - z - __init__.py - the_module.py - y - __init__.py - template.md - the_module_module.py - the_support_function.py from c.run_project import runprint ( 'running main.py ... ' ) run ( ) from c.z.the_module import the_module_function , the_module_write_functio... | How do I replicate the way PyCharm is running my Python 3.4 project at the command line ? |
Python | I have made a small script in Python to solve various Gym environments with policy gradients.What should be passed backwards to calculate the gradients ? I am using gradient ascent but I could switch it to descent . Some people have defined the reward function as totalReward*log ( probabilities ) . Would that make the ... | import gym , osimport numpy as np # create environmentenv = gym.make ( 'Cartpole-v0 ' ) env.reset ( ) s_size = len ( env.reset ( ) ) a_size = 2 # import my neural network codeos.chdir ( r ' C : \ -- -\ -- -\ -- -\Python Code ' ) import RLPolicypolicy = RLPolicy.NeuralNetwork ( [ s_size , a_size ] , learning_rate=0.0000... | What Loss Or Reward Is Backpropagated In Policy Gradients For Reinforcement Learning ? |
Python | Simple repro : This question has an effective duplicate , but the duplicate was not answered , and I dug a bit more into the CPython source as a learning exercise . Warning : i went into the weeds . I 'm really hoping I can get help from a captain who knows those waters . I tried to be as explicit as possible in tracin... | class VocalDescriptor ( object ) : def __get__ ( self , obj , objtype ) : print ( '__get__ , obj= { } , objtype= { } '.format ( obj , objtype ) ) def __set__ ( self , obj , val ) : print ( '__set__ ' ) class B ( object ) : v = VocalDescriptor ( ) B.v # prints `` __get__ , obj=None , objtype= < class '__main__.B ' > '' ... | Why does setting a descriptor on a class overwrite the descriptor ? |
Python | With SQLAlchemy , I 'm finding that sometimes I mis-type a name of an attribute which is mapped to a column , which results in rather difficult to catch errors : Is there a way to configure the mapped class so assigning to anything which is not mapped to an SQLAlchemy column would raise an exception ? | class Thing ( Base ) : foo = Column ( String ) thing = Thing ( ) thing.bar = `` Hello '' # a typo , I actually meant thing.fooassert thing.bar == `` Hello '' # works here , as thing.bar is a transient attribute created by the assignment abovesession.add ( thing ) session.commit ( ) # thing.bar is not saved in the datab... | How do I raise an exception when assigning to an attribute which is NOT mapped to an SQLAlchemy column ? |
Python | I am running to of the following programs . Importantly , imagine that there is mymodule.py file in the directory where both these programs are located.The first : The second : The first snippet raises ImportError as expected ( after all , the directory where mymodule is located is not in path ) . The second snippet , ... | exec ( `` 'import sysimport osos.chdir ( '/ ' ) sys.path = [ ] import mymodule '' ' , { } ) import mymoduleexec ( `` 'import sysimport osos.chdir ( '/ ' ) sys.path = [ ] import mymodule '' ' , { } ) | Difference between exec behavior when module is imported or not |
Python | I was looking at the source code for the built-in argparse._AppendAction , which implements the `` append '' action , and puzzled over the way it is implemented : To break it down : _ensure_value is like dict.setdefault for attributes . That is , if namespace has an attribute with the name self.dest then it is returned... | def __call__ ( self , parser , namespace , values , option_string=None ) : items = _copy.copy ( _ensure_value ( namespace , self.dest , [ ] ) ) items.append ( values ) setattr ( namespace , self.dest , items ) def __call__ ( self , parser , namespace , values , option_string=None ) : items = _ensure_value ( namespace ,... | Please explain reasoning behind code snippet from argparse module |
Python | Reading the Django docs , it advices to make a custom creation method for a model named Foo by defining it as create_foo in the manager : My question is that why is the previous one preferred to simply overriding the base class 's create method : Imo it seems that only overriding create will prevent anyone from acciden... | class BookManager ( models.Manager ) : def create_book ( self , title ) : book = self.create ( title=title ) # do something with the book return bookclass Book ( models.Model ) : title = models.CharField ( max_length=100 ) objects = BookManager ( ) book = Book.objects.create_book ( `` Pride and Prejudice '' ) class Boo... | Why define create_foo ( ) in a Django models.Manager instead of overriding create ( ) ? |
Python | I 'm trying to use the __defaults__ attribute of a function object to get default values for arguments . It works for this case : but for this it does n't : Why does test.__defaults__ contain None ? How can I get the default value for the parameter in this case ? | > > > def test ( x , y=1 ) : pass ... > > > test.__defaults__ ( 1 , ) > > > def test ( *args , y=1 ) : pass ... > > > test.__defaults__ > > > | How can I access the default value for a keyword argument in Python ? |
Python | I have created a simple custom MultiValueField and MultiWidget for the purpose of entering a date of birth but allowing separate entry of the day , month and year . The rationale is that the app is for entry of historical data , so one or more of these fields could be unknown . There is also a checkbox that displays 'u... | class CustomDateWidget ( forms.MultiWidget ) : `` '' '' Custom MultiWidget to allow saving different date values . '' '' '' template_name = 'myapp/widgets/custom_date_widget.html ' def __init__ ( self , attrs=None ) : _widgets = ( forms.NumberInput ( attrs= ( { 'placeholder ' : 'DD ' } ) ) , forms.NumberInput ( attrs= ... | Django Custom MultiWidget Retaining Old Values |
Python | Using the snippet below , I have added tab completion to the python interpreter.However , I have encountered a weird behaviour where after hitting TAB , the interpreter would give duplicates as such:108 possibilities ! min 2 , max 4 duplicates.Furthermore , if I subclass dict the total number of possibilities increases... | import readlineimport rlcompleterif 'libedit ' in readline.__doc__ : readline.parse_and_bind ( `` bind ^I rl_complete '' ) else : readline.parse_and_bind ( `` tab : complete '' ) Python 2.7.3 ( v2.7.3:70274d53c1dd , Apr 9 2012 , 20:52:43 ) [ GCC 4.2.1 ( Apple Inc. build 5666 ) ( dot 3 ) ] on darwinType `` help '' , `` ... | Duplicate output on Python tab completion ( OsX 10.8 ) |
Python | Using MySQL , I am trying to have a table with a composite key of multiple fields.The issue is that some of the fields are large ( 255 - 1024 length ) , if I try to run the migration , I will get : Instead of increasing the DB 's key length ( or changing some other DB / table settings ) , I found out that I can just li... | django.db.utils.OperationalError : ( 1071 , 'Specified key was too long ; max key length is 767 bytes ' ) ALTER TABLE < table > ADD UNIQUE KEY ` < table > _composite_key ` ( ` col1 ` , ` col2 ` ( 75 ) , ` col3 ` , ` col4 ` , ` col5 ` ( 150 ) ) ; | Django - limit key size on unique_together columns |
Python | I have a array of identifiers that have been grouped into threes . For each group , I would like to randomly assign them to one of three sets and to have those assignments stored in another array . So , for a given array of grouped identifiers ( I presort them ) : A possible output would beUltimately , I would like to ... | groupings = array ( [ 1,1,1,2,2,2,3,3,3 ] ) assignments = array ( [ 0,1,2,1,0,2,2,0,1 ] ) assignment = numpy.zeros ( ( 12,10 ) , dtype=int ) for i in range ( 0,12,3 ) : for j in range ( 10 ) : assignment [ i : i+3 , j ] = numpy.random.permutation ( 3 ) | Permutations over subarray in python |
Python | I used shap to determine the feature importance for multiple regression with correlated features . shap offers a chart to get the shap values . Is there also a statistic available ? I am interested in the exact shap values . I read the Github repository and the documentation but I found nothing regarding this topic . | import numpy as npimport pandas as pd from sklearn.linear_model import LinearRegressionfrom sklearn.datasets import load_bostonimport shapboston = load_boston ( ) regr = pd.DataFrame ( boston.data ) regr.columns = boston.feature_namesregr [ 'MEDV ' ] = boston.targetX = regr.drop ( 'MEDV ' , axis = 1 ) Y = regr [ 'MEDV ... | Shap statistics |
Python | if the customer sign in and he has permission to see the data that the admin has given to him , he will see the data after he sign in , but if the admin does n't give him permission , this message will appear You are not authorized to view this pagein my case no matter what the permission given the admin this message a... | from .decorators import unathenticated_user , allowed_users , staff_onlyfrom django.contrib.auth.models import Group @ login_required ( login_url='loginpage ' ) @ staff_onlydef adminpage ( request ) : return render ( request , 'Homepage/adminsite.html ' ) def loginpage ( request ) : if request.method == 'POST ' : usern... | Django Group permission how to print it in template |
Python | The docs say that : Each class keeps a list of weak references to its immediate subclasses . This method returns a list of all those references still alive . But how does each class obtain a list of weak references to its subclasses in the first place ? In other words , when I createhow does A find out that B just subc... | class B ( A ) : pass | How is __subclasses__ method implemented in CPython ? |
Python | I 'm getting desperate because I ca n't seem to find a solution for what I thought would be used by everyone out there.I want to test a simple login with selenium and pytest with a live_server url . According to pytest-django doc , a simple fixture called live_server should do the trick ( https : //pytest-django.readth... | def test_selenium ( self , live_server , create_staff_user_in_db ) : browser = webdriver.Remote ( command_executor='http : //selenium:4444/wd/hub ' , desired_capabilities=DesiredCapabilities.CHROME , ) browser.get ( live_server.url ) @ pytest.fixturedef test_server ( ) - > LiveServer : addr = socket.gethostbyname ( soc... | Selenium login test does n't accept pytest fixtures for login or refuses to connect |
Python | I have a Python package that only runs on Python 2 . It has the following classifiers in its setup.py : However , if I create a virtualenv with Python 3 , pip happily installs this package.How do I prevent the package being installed ? Should my setup.py throw an error based on sys.version_info ? Can I stop pip even do... | setup ( # ... classifiers= [ 'Programming Language : : Python ' , 'Programming Language : : Python : : 2 ' , 'Programming Language : : Python : : 2 : : Only ' , ] ) | How do I mark a Python package as Python 2 only ? |
Python | Set-upI 'm using PyDrive 2.0 to connect to the Google Drive API.The working directory /Users/mypath/access_google_drive contains the client_secrets.json , which looks like , where I replaced the real client_id and client_secret with xxx.IssueWhen the browser ( Safari 14.0 ) shows Gdrive api link wants to access your Go... | def connect_google_drive_api ( ) : import os # use Gdrive API to access Google Drive os.chdir ( '/Users/my/fol/ders/access_google_drive ' ) from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive gauth = GoogleAuth ( ) gauth.LocalWebserverAuth ( ) # client_secrets.json need to be in the same directory... | PyDrive 2.0 – AuthenticationError : No code found in redirect |
Python | I want a code that deletes all instances of any number that has been repeated from a list.E.g . : I have tried to remove the duplicated elements in the list already ( by using the `` unique '' function ) , but it leaves a single instance of the element in the list nevertheless ! I went through a lot of StackOverflow ar... | Inputlist = [ 2 , 3 , 6 , 6 , 8 , 9 , 12 , 12 , 14 ] Outputlist = [ 2,3,8,9,14 ] seen = set ( ) uniq = [ ] for x in Outputlist : if x not in seen : uniq.append ( x ) seen.add ( x ) seen | How to delete all instances of a repeated number in a list ? |
Python | I 've been working on some Python code to be able to get links to social media accounts from government websites , for a research into ease with which municipalities can be contacted . I 've managed to adapt some code to work in 2.7 , which prints all links to facebook , twitter , linkedin and google+ present on a give... | import cookielibimport mechanizebase_url = `` http : //www.amsterdam.nl '' br = mechanize.Browser ( ) cj = cookielib.LWPCookieJar ( ) br.set_cookiejar ( cj ) br.set_handle_robots ( False ) br.set_handle_equiv ( False ) br.set_handle_redirect ( True ) br.set_handle_refresh ( mechanize._http.HTTPRefreshProcessor ( ) , ma... | Using multiple web pages in a web scraper |
Python | I would like to handle a NameError exception by injecting the desired missing variable into the frame and then continue the execution from last attempted instruction.The following pseudo-code should illustrate my needs.Read the whole unittest on repl.it NotesAs pointed out by ivan_pozdeev in his answer , this is known ... | def function ( ) : return missing_vartry : print function ( ) except NameError : frame = inspect.trace ( ) [ -1 ] [ 0 ] # inject missing variable frame.f_globals [ `` missing_var '' ] = ... # continue frame execution from last attempted instruction exec frame.f_code from frame.f_lasti | How to continue a frame execution from last attempted instruction after handling an exception ? |
Python | Consider a sequence of coin tosses : 1 , 0 , 0 , 1 , 0 , 1 where tail = 0 and head = 1.The desired output is the sequence : 0 , 1 , 2 , 0 , 1 , 0Each element of the output sequence counts the number of tails since the last head.I have tried a naive method : Question : Is there a better method ? | def timer ( seq ) : if seq [ 0 ] == 1 : time = [ 0 ] if seq [ 0 ] == 0 : time = [ 1 ] for x in seq [ 1 : ] : if x == 0 : time.append ( time [ -1 ] + 1 ) if x == 1 : time.append ( 0 ) return time | Count number of tails since the last head |
Python | I have login history data from User A for a day . My requirement is that at any point in time the User A can have only one valid login . As in the samples below , the user may have attempted to login successfully multiple times , while his first session was still active . So , any logins that happened during the valid ... | start_time end_time0 00:12:38 01:00:021 00:55:14 01:00:022 01:00:02 01:32:403 01:00:02 01:08:404 01:41:22 03:56:235 18:58:26 19:16:496 20:12:37 20:52:497 20:55:16 22:02:508 22:21:24 22:48:509 23:11:30 00:00:00 start_time end_time isDup0 00:12:38 01:00:02 01 00:55:14 01:00:02 12 01:00:02 01:32:40 03 01:00:02 01:08:40 14... | Compare current row value to previous row values |
Python | This question is spurred from the answers and discussions of this question . The following snippet shows the crux of the question : The questions I have are the following : Why was it decided that the bool value of NotImplemented should be True ? It feels unpythonic.Is there a good reason I am unaware of ? The document... | > > > bool ( NotImplemented ) True > > > class A : ... def something ( self ) : ... return NotImplemented ... > > > a = A ( ) > > > a.something ( ) NotImplemented > > > if a.something ( ) : ... print ( `` this is unintuitive '' ) ... this is unintuitive | Why is NotImplemented truthy in Python 3 ? |
Python | I have the following Pandas dataframe : and the following dict : I would now like to map all the entries in the lists in my dataframe using the dictionary . The result should be the following : How can this be done most efficiently ? | 1 [ `` Apple '' , `` Banana '' ] 2 [ `` Kiwi '' ] 3 None4 [ `` Apple '' ] 5 [ `` Banana '' , `` Kiwi '' ] { 1 : [ `` Apple '' , `` Banana '' ] ,2 : [ `` Kiwi '' ] } 1 [ 1 ] 2 [ 2 ] 3 None4 [ 1 ] 5 [ 1 , 2 ] | Convert elements of list in pandas series using a dict |
Python | I am working with an ORM that accepts classes as input and I need to be able to feed it some dynamically generated classes . Currently , I am doing something like this contrived example : While this works fine , it feels off by a bit : for example , both classes print as < class '__main__.Cls ' > on the repl . While th... | def make_cls ( _param ) : def Cls ( object ) : param = _param return ClsA , B = map ( make_cls , [ ' A ' , ' B ' ] ) print A ( ) .fooprint B ( ) .foo | What is the least-bad way to create Python classes at runtime ? |
Python | How to terminate loop.run_in_executor with ProcessPoolExecutor gracefully ? Shortly after starting the program , SIGINT ( ctrl + c ) is sent.With max_workers equal or lesser than the the number of tasks everything works . But if max_workers is greater , the output of the above code is as follows : I would like to catch... | def blocking_task ( ) : sleep ( 3 ) async def main ( ) : exe = concurrent.futures.ProcessPoolExecutor ( max_workers=4 ) loop = asyncio.get_event_loop ( ) tasks = [ loop.run_in_executor ( exe , blocking_task ) for i in range ( 3 ) ] await asyncio.gather ( *tasks ) if __name__ == `` __main__ '' : try : asyncio.run ( main... | How to terminate loop.run_in_executor with ProcessPoolExecutor gracefully ? |
Python | I need to find the intersection of a GeoDataFrame with itself through geopandas in QGIS . The code works perfectly in the Anaconda environment but it fails in the QGIS python.Shapefile is available at below link : https : //drive.google.com/file/d/1DQqg7Cf6AokyadkmOE8Y6k41tqDMXdmS/view ? usp=drivesdk Below is the code ... | df1 = gpd.GeoDataFrame.from_file ( `` C : \\QGIS_ShapeFile1\\qgis\\laneGroup.shp '' ) intersection_gdf = overlay ( df1 , df1 , how='intersection ' ) An error has occurred while executing Python code : AttributeError : 'NoneType ' object has no attribute 'intersection ' Traceback ( most recent call last ) : File '' C : ... | geopandas overlay ( ) function not working in QGIS |
Python | I have a codebase where I 'm cleaning up some messy decisions by the previous developer . Frequently , he has done something like : ... This , of course , pollutes the name space and makes it difficult to tell where an attribute in the module is originally from.Is there any way to have Python analyze and fix this for m... | from scipy import *from numpy import * | Reversing from module import * |
Python | I 'm working on a Python project where a previous developer placed a large portion of the code in the base __init__.py file . I would like to be able to move code out of the file to a new file in a subdirectory.So importing the spam module would use the code in foobar/eggs.py.I would like to keep 100 % compatibility be... | spam/ __init__.py foobar/ __init__.py eggs.py | Moving code out of __init__.py but keeping backwards compatibility |
Python | I want to make forward forecasting for monthly times series of air pollution data such as what would be 3~6 months ahead of estimation on air pollution index . I tried scikit-learn models for forecasting and fitting data to the model works fine . But what I wanted to do is making a forward period estimate such as what ... | import pandas as pdfrom sklearn.preprocessing StandardScalerfrom sklearn.metrics import accuracy_scorefrom sklearn.linear_model import BayesianRidgeurl = `` https : //gist.githubusercontent.com/jerry-shad/36912907ba8660e11cd27be0d3e30639/raw/424f0891dc46d96cd5f867f3d2697777ac984f68/pollution.csv '' df = pd.read_csv ( u... | any workaround to do forward forecasting for estimating time series in python ? |
Python | Possible Duplicate : Do python 's variable length arguments ( *args ) expand a generator at function call time ? Let 's say you have a function like this : And you call it like that : Will the elements be called lazily or will the generator run through all the possibly millions of elements before the function can be ex... | def give_me_many ( *elements ) : # do something ... generator_expr = ( ... for ... in ... ) give_me_many ( *generator_expr ) | Are *parameters calls lazy ? |
Python | Given this file : http : //mtarchive.geol.iastate.edu/2019/02/18/mrms/ncep/GaugeCorr_QPE_01H/GaugeCorr_QPE_01H_00.00_20190218-150000.grib2.gz… I get different output depending on the software I use.andboth output : However : outputs -3 for all 24,500,000 records.I get the same result if I parse the file using Python + ... | wgrib2 2019021815.grib2 -csv wgrib2.csv cdo outputtab , date , time , lat , lon , value 2019021815.grib2 > cdo.txt -3 ( undefined ) : 8,869,250 records0 : 14,848,865 recordsOther values : 781,885 records___________________________________Total : 24,500,000 records gdal_translate.exe -of xyz 2019021815.grib2 gdal.csv | Possible bug in GDAL ? |
Python | Trying to find an efficient way to extract all instances of items in an array out of another.For exampleArray 1 is an array of items that need to be extracted out of array 2 . Thus , array 2 should be modified to [ `` 456 '' , `` 789 '' ] I know how to do this , but no in an efficient manner . | array1 = [ `` abc '' , `` def '' , `` ghi '' , `` jkl '' ] array2 = [ `` abc '' , `` ghi '' , `` 456 '' , `` 789 '' ] | Using arrays with other arrays in Python |
Python | I need to sum all the numbers in the list . If 0 occurs start subtracting , until another 0 , start adding . For example : This is what I 've tried : | [ 1 , 2 , 0 , 3 , 0 , 4 ] - > 1 + 2 - 3 + 4 = 4 [ 0 , 2 , 1 , 0 , 1 , 0 , 2 ] - > -2 - 1 + 1 - 2 = -4 [ 1 , 2 ] - > 1 + 2 = 3 [ 4 , 0 , 2 , 3 ] = 4 - 2 - 3 = -1 sss = 0for num in numbers : if 0 == num : sss = -num else : sss += numreturn sss | Sum numbers in a list but change their sign after zero is encountered |
Python | I just started learning Python and I 'm confused about this example : If to was initialized once , would n't to not be None the 2nd time it 's called ? I know the code above works but ca n't wrap my head around this `` initialized once '' description . | def append_to ( element , to=None ) : if to is None : to = [ ] to.append ( element ) return to | Python default params confusion |
Python | Does unit test library for python ( especially 3.x , I do n't really care about 2.x ) has decorator to be accessed only by root user ? I have this testing function.blabla function can only be executed by root . I want root user only decorator so normal user will skip this test : Does such decorator exist ? We have @ su... | def test_blabla_as_root ( ) : self.assertEqual ( blabla ( ) , 1 ) @ support.root_onlydef test_blabla_as_root ( ) : self.assertEqual ( blabla ( ) , 1 ) | Unit test for only root user in python |
Python | Sorry for the badly explained title . I am trying to parallelise a part of my code and got stuck on a dot product . I am looking for an efficient way of doing what the code below does , I 'm sure there is a simple linear algebra solution but I 'm very stuck : | puy = np.arange ( 8 ) .reshape ( 2,4 ) puy2 = np.arange ( 12 ) .reshape ( 3,4 ) print puy , '\n'print puy2.Tzz = np.zeros ( [ 4,2,3 ] ) for i in range ( 4 ) : zz [ i , : , : ] = np.dot ( np.array ( [ puy [ : ,i ] ] ) .T , np.array ( [ puy2.T [ i , : ] ] ) ) | Numpy Dot Product of two 2-d arrays in numpy to get 3-d array |
Python | I try to create a kivy widget from Scatter , which is freely zoomable , but once the mouse button is lifted falls back to the closest zoom level . It works , but it does not update the zoom until the next click . I think I need to bind some event here , but I 'm pretty new to kivy and can not figure it out . Here is my... | from kivy.app import Appfrom kivy.uix.label import Labelfrom kivy.uix.scatter import Scatterfrom kivy.graphics.transformation import MatrixZOOM_LEVELS = [ 0.25 , 0.5 , 1 , 2 , 4 ] class PPMap ( Scatter ) : def __init__ ( self , **kwargs ) : super ( PPMap , self ) .__init__ ( **kwargs ) self.bind ( on_touch_up=self.adju... | Modified kivy scatter widget does not update transformation |
Python | Code : Here , I try to replace all the occurrences of 'abc ' with 'XXX ' . Is there a shorter way to do this ? | > > > mylist = [ 'abc ' , 'def ' , 'ghi ' ] > > > mylist [ 'abc ' , 'def ' , 'ghi ' ] > > > for i , v in enumerate ( mylist ) : ... if v=='abc ' : ... mylist [ i ] = 'XXX ' ... > > > mylist [ 'XXX ' , 'def ' , 'ghi ' ] > > > | Replacing particular elements in a list |
Python | Is it possible to merge strings that start with ' ( ' and end with ' ) ' and then reinsert it into the same list or a new list ? My desired output poke_list = [ ... 'Charizard ( Mega Charizard X ) ' , '78 ' , '130 ' , ... ] | poke_list = [ ... 'Charizard ' , ' ( Mega ' , 'Charizard ' , ' X ) ' , '78 ' , '130 ' , ... ] # 1000+ values | How to join strings between parentheses in a list of strings |
Python | An error is raised when I try to set the value of an argument of a class who inherits from str . The error occurs only when I try to access the argument with myClass ( arg = 'test ' ) . The error is : The issue is shown in this exemple : Only the last line raises the error . The previous line works well.The problem is ... | TypeError : 'arg ' is an invalid keyword argument for this function class A ( str ) : def __init__ ( self , arg ) : passA ( `` test '' ) # Works wellA ( arg = `` test '' ) # Fails class A ( str ) : def __new__ ( cls , *args , **kwargs ) : return str.__new__ ( cls ) def __init__ ( self , arg01 ) : print ( arg01 ) A ( ar... | Set the value of an argument in a class who inherits from int or float or str |
Python | I want to search a list of strings ( having from 2k upto 10k strings in the list ) in thousands of text files ( there may be as many as 100k text files each having size ranging from 1 KB to 100 MB ) saved in a folder and output a csv file for the matched text filenames.I have developed a code that does the required job... | # -*- coding : utf-8 -*-import pandas as pdimport osdef match ( searchterm ) : global result filenameText = `` matchrateText = `` for i , content in enumerate ( TextContent ) : matchrate = search ( searchterm , content ) if matchrate : filenameText += str ( listoftxtfiles [ i ] ) + '' ; '' matchrateText += str ( matchr... | How to make searching a string in text files quicker |
Python | My project structure seems to be correct . File script1.py imports script2.py using 'import script2'.I can run code without errors with following commands : Unfortunately , when I try to execute tests using pytest or python -m pytest I get error that there 's no module named script2 ( full message below ) . I installed... | setup.pymypackage/ __init__.py __main__.py main.py script1.py # import script2 script2.pytests/ test_script2.py python mypackagepython mypackage/main.py ( venv ) lecho : ~/pytest-imports-demo $ pytest================================================= test session starts ==================================================... | ModuleNotFoundError for import within the same package while using pytest |
Python | Haskell : Python : It should output the next two values of the list , e.g . 5.0 , 3.4But it outputs 5.0 twice , why ? | average x y = ( x + y ) / 2sqrt ' : : ( Ord a , Fractional a ) = > a - > Int - > asqrt ' 0 _ = 0.0sqrt ' 1 _ = 1.0sqrt ' s approximations = ( infsqr ' s ) ! ! approximationsinfsqr ' n = unfoldr acc 1 where acc guess | guess < 0 = Nothing | otherwise = Just ( newguess ' , newguess ' ) where newguess ' = average guess ( ... | Why does n't this Haskell I translated to Python work properly ? |
Python | I have a directed tree , and I would like to get its size . I have no information about its depth or distribution of nodes . There are two major obstacles:1 ) The tree is very large ( ~billions of nodes ) 2 ) Edge traversal is expensive.Are there statistical methods I can use to get an estimate of its size ( number of ... | amounts = [ ] def estimateHelper ( node ) : amounts [ node.depth ] .push ( len ( node.children ) ) for each child in small random sample of node.children : estimateHelper ( child ) def estimate ( root ) : estimateHelper ( root ) reach = 0 for ( j = len ( amounts ) - 1 ; j > = 0 ; -- j ) : avgChildrenPerNodeAtThisLevel ... | Statistic estimation of total nodes in a tree where edge traversal is expensive |
Python | I have the following example dataframe : which creates this dataframe : I am trying to `` unmelt '' though not exactly the source and test columns into new dataframe Columns such that it will look like this : It 's my understanding that pivot and melt will do the entire DisplayLabel column and not just some of the valu... | df = pd.DataFrame ( data = { 'RecordID ' : [ 1,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5 ] , 'DisplayLabel ' : [ 'Source ' , 'Test ' , 'Value 1 ' , 'Value 2 ' , 'Value3 ' , 'Source ' , 'Test ' , 'Value 1 ' , 'Value 2 ' , 'Source ' , 'Test ' , 'Value 1 ' , 'Value 2 ' , 'Source ' , 'Test ' , 'Value 1 ' , 'Value 2 ' , 'Sour... | Unmelt only part of a column from pandas dataframe |
Python | I 'm creating several classes to use them as state flags ( this is more of an exercise , though I 'm going to use them in a real project ) , just like we use None in Python , i.e.NoneType has several special properties , most importantly it 's a singleton , that is there ca n't be more than one NoneType instance during... | ... some_var is None ... class FlagMetaClass ( type ) : def __setattr__ ( self , *args , **kwargs ) : raise TypeError ( `` { } class is immutable '' .format ( self ) ) def __delattr__ ( self , *args , **kwargs ) : self.__setattr__ ( ) def __repr__ ( self ) : return self.__name__class BaseFlag ( object ) : __metaclass__... | Mimic Python 's NoneType |
Python | In a program that I 'm writing , I wanted to make a ConfigParser that 's read only so that it can safely be used globally . I did n't realize this , but apparently the SafeConfigParser is an old-style class , thus I had to subclass it like this : If I did n't use object as a mixin , the call to SafeConfigParser 's __in... | class ConstParser ( SafeConfigParser , object ) : `` '' '' This is a implementation of the SafeConfigParser that ca n't write any values . This is to ensure that it can only be filled once and wo n't get messy with multiple modules writing to it . '' '' '' def __init__ ( self , files , defaults= { } ) : super ( ConstPa... | Is it safe to make an old-style class into a new-style class using Multiple Inheritance ? |
Python | I have made a multiplayer Pong game with TCP , UDP and pygame.the modules i 'm using are : pygame , os , logging , threading , random , yaml ( PyYAML ) and socketWhen running the game from the commandline with python2.7 it works well , but the compiled version with py2app gives me a error which is : I have googled arou... | TypeError : Error when calling the metaclass bases function ( ) argument 1 must be code , not str class Entity ( pygame.Surface ) : def __init__ ( self , x , y , w , h , color= ( 255 , 255 , 255 ) ) : pygame.Surface.__init__ ( self , ( w , h ) ) from setuptools import setup APP = [ 'src/client.py ' ] OPTIONS = { 'argv_... | Game runs well from source , but not from py2app |
Python | I need to write XML files using lxml and Python.However , I ca n't figure out whether to use a class to do this or a function . The point being , this is the first time I am developing a proper software and deciding where and why to use a class still seems mysterious.I will illustrate my point.For example , consider th... | from lxml import etreeroot = etree.Element ( 'document ' ) def createSubElement ( text , tagText = `` '' ) : etree.SubElement ( root , text ) # How do I do this : element.text = tagTextcreateSubElement ( 'firstChild ' ) createSubElement ( 'SecondChild ' ) < document > < firstChild/ > < SecondChild/ > < /document > | Confused as to use a class or a function : Writing XML files using lxml and Python |
Python | I 'm trying to write a binary translator - with a string as an input and its binary representation as output.And I 'm having some difficulties , I wrote in variable the translation for each letter , but they are variables , not strings , so I want to take an input from that matches with the name of the variable and pri... | a = `` 01000001 '' b = `` 01000010 '' c = `` 01000011 '' d = `` 01000100 '' # all the way to zword = input ( `` enter here : `` ) print ( word ) | Text to Binary in Python |
Python | I have an irregularly spaced ( with respect to time frequency ) pandas data frame . I can successfully up-sample the data frame to a daily frequency using the resample command , however my problem is that the resampling ends at the last ( pre-resampled ) data observation . I would like the resampling to span all the wa... | dataOut [ 1 ] : Var 1 Var 2 Var 3 Var 4Dates 2017-09-20 16.0 1.328125 1.375 0.1359762017-12-13 16.0 1.343750 1.375 0.0853912018-03-21 15.0 2.191667 2.125 0.2749462018-06-13 15.0 2.241667 2.375 0.2084522018-09-26 16.0 4.312500 2.375 0.1118032018-12-19 17.0 4.279412 2.375 0.0830262019-03-20 17.0 3.507353 2.375 0.179358 d... | How to resample irregular time series to daily frequency and have it span to today ? |
Python | I have a script that can re-write a Python module so that all occurrences of func ( a ) are transfored to func2 ( a is None ) . I now want to support also func ( a , msg ) becoming func2 ( a is None , msg ) , but I ca n't find the pattern that will do this . This following shows my attempt : For each func found in the ... | from lib2to3 import refactor , fixer_basefrom textwrap import dedentPATTERN_ONE_ARG = `` '' '' power < 'func ' trailer < ' ( ' arglist < obj1=any > ' ) ' > > '' '' '' PATTERN_ONE_OR_TWO_ARGS = `` '' '' power < 'func ' trailer < ' ( ' arglist < obj1=any [ ' , ' obj2=any ] > ' ) ' > > '' '' '' class TestFixer ( fixer_bas... | pattern to match 1-or-2-arg function call for lib2to3 |
Python | I have this neural network that I 've trained seen bellow , it works , or at least appears to work , but the problem is with the training . I 'm trying to train it to act as an OR gate , but it never seems to get there , the output tends to looks like this : I have this loss graph : Its strange it appears to be trainin... | prior to training : [ [ 0.50181624 ] [ 0.50183743 ] [ 0.50180414 ] [ 0.50182533 ] ] post training : [ [ 0.69641759 ] [ 0.754652 ] [ 0.75447178 ] [ 0.79431198 ] ] expected output : [ [ 0 ] [ 1 ] [ 1 ] [ 1 ] ] import sysimport mathimport numpy as npimport matplotlib.pyplot as pltfrom itertools import productclass NeuralN... | Neural network backprop not fully training |
Python | I am trying to merge several DataFrames based on a common column . This will be done in a loop and the original DataFrame may not have all of the columns so an outer merge will be necessary . However when I do this over several different DataFrames columns duplicate with suffix _x and _y . I am looking for one DataFram... | df1=pd.DataFrame ( { 'Company Name ' : [ ' A ' , ' B ' , ' C ' , 'D ' ] , 'Data1 ' : [ 1,34,23,66 ] , 'Data2 ' : [ 13,54,5354,443 ] } ) Company Name Data1 Data20 A 1 131 B 34 542 C 23 53543 D 66 443 pd.DataFrame ( { 'Company Name ' : [ ' A ' , ' B ' ] , 'Address ' : [ 'str1 ' , 'str2 ' ] , 'Phone ' : [ 'str1a ' , 'str2... | Merge DataFrames in Python without duplicating columns |
Python | I 'm writing a simple string parser which allows regexp-like quantifiers . An input string might look like this : My parser function translates this string to a list of tuples : Now , the tricky bit is that I need a list of all valid combinations that are specified by the quantification . The combinations all have to h... | s = `` x y { 1,2 } z '' list_of_tuples = [ ( `` x '' , 1 , 1 ) , ( `` y '' , 1 , 2 ) , ( `` z '' , 1 , 1 ) ] [ [ `` x '' , `` y '' , None , `` z '' ] , [ `` x '' , `` y '' , `` y '' , `` z '' ] ] import itertoolsdef permute_input ( lot ) : outer = [ ] # is there something that replaces these nested loops ? for val , st... | More elegant way to implement regexp-like quantifiers |
Python | Say I have a decorator which causes the function to print out any exceptions and return None , if an exception happens , instead of failing . Assuming this is a good idea , what 's the preferred naming style ? a ) b ) That is : should it a ) be a command ( the decorator tells the function to do something different ) , ... | @ ignore_exceptionsdef foobar ( a , b , c ) : raise ValueError ( `` This function always fails ... '' ) @ ignores_exceptionsdef foobar ( a , b , c ) : raise ValueError ( `` This function always fails ... '' ) | python : should decorator names be actions or descriptions ? |
Python | I am trying to extract all slices of length 4 along 0th axis of a 2-dim tensor . So far I can do it mixing pure Python with tensorflow.What would be an efficient way of doing that without using pure Python ? Note that the `` test '' array is actually supposed to be a tensor , thus its shape is n't known before I execut... | r = test.shape [ 0 ] # test should be a tensorn = 4a_list = list ( range ( r ) ) the_list = np.array ( [ a_list [ slice ( i , i+n ) ] for i in range ( r - n+1 ) ] ) test_stacked = tf.stack ( tf.gather ( test , the_list ) ) array = np.array ( [ [ 0 , 1 ] , [ 1 , 2 ] , [ 2 , 3 ] , [ 3 , 4 ] , [ 4 , 5 ] , [ 5 , 6 ] ] ) ar... | How to efficiently extract all slices of given length using tensorflow |
Python | I 'm storing contacts between different elements . I want to eliminate elements of certain type and store new contacts of elements which were interconnected by the eliminated element.Problem backgroundImagine this problem . You have a water molecule which is in contact with other molecules ( if the contact is a hydroge... | A B | | H H . . O / \ H H . . C D id|atom|amino1 | O | HOH2 | N | ARG < - atom A from image3 | S | CYS < - B 4 | O | SER < - C5 | N | ARG < - D donor_id|acceptor_id|directness1 4 D1 5 D2 1 D3 1 D donor_id|acceptor_id|directness3 4 W < - B-C3 5 W < - B-D2 4 W < - A-C2 5 W < - A-D2 3 X < - A-B ( These last two rows are e... | Refining data stored in SQLite - how to join several contacts ? |
Python | I have a custom environment in keras-rl with the following configurations in the constructorAs you can see , my agent will perform 3 actions , depending on the action , a different reward will be calculated in the function step ( ) below : The problem is the fact that , if I print the actions at every episode , they ar... | def __init__ ( self , data ) : # Declare the episode as the first episode self.episode=1 # Initialize data self.data=data # Declare low and high as vectors with -inf values self.low = numpy.array ( [ -numpy.inf ] ) self.high = numpy.array ( [ +numpy.inf ] ) self.observation_space = spaces.Box ( self.low , self.high , d... | Define action values in keras-rl |
Python | QNetworkAccessManager can do requests asynchronously , and time.sleep ( secs ) can suspend the execution for the given number of seconds . I was confused by the code below . Is t2 here always greater than 10 seconds ? Without using time.sleep ( secs ) in the code here , the finished slot getWebPageSRC was called in fix... | de myMethod ( self ) : ... reply.finished.connect ( self.getWebPageSRC ) self.t=time.clock ( ) time.sleep ( 10 ) def getWebPageSRC ( self ) : t2=time.clock ( ) -self.t print ( t2 ) | can time.sleep ( secs ) suspend QNetworkAccessManager does request asynchronously ? |
Python | I need to get a calculation of some data so , in annotate I put some maths logic with other field but whenever there is 0 it is throwing an error . I need to handle that error in annotate . My code looks like this : In total_billable , there is total_billable_leads variable which may have Zero ( 0 ) then on a division ... | total_amount = Invoice.objects.filter ( client_account__account_UID=account_UID , created_at__range= ( from_date , to_date ) ) .aggregate ( Sum ( 'total_amount ' ) ) [ 'total_amount__sum ' ] total_billable_leads = CampaignContact.objects.filter ( campaign=campaigns , billable=True , billable_item__created_at__range= ( ... | Throwing ZeroDivisionError |
Python | Here is what I am looking at : I know that int in Python is growable ( can get bigger that 24 bytes ) objects that live on the heap , and I see why that object can be quite large , but is n't a list just a collections of such objects ? Apparently it is not , what is going on here ? | In [ 1 ] : import sysIn [ 2 ] : sys.getsizeof ( 45 ) Out [ 2 ] : 24In [ 3 ] : sys.getsizeof ( [ ] ) Out [ 3 ] : 72In [ 4 ] : sys.getsizeof ( range ( 1000 ) ) Out [ 4 ] : 8072 | Why is single int 24 bytes , but in list it tends to 8 bytes |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.