lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Python
I have a pandas dataframe as follows : I wanted to query this df for the longest streak ( none order_number is skipped ) and last streak ( since last order_number ) . The ideal result is as follows : I 'd appreciate any insights on this .
user_id product_id order_number1 1 11 1 21 1 31 2 11 2 52 1 12 1 32 1 42 1 53 1 13 1 23 1 6 user_id product_id longest_streak last_streak1 1 3 31 2 0 02 1 3 33 1 2 0
Pandas - Check if Numbers in Column are in row
Python
I need to select half of a dataframe using the groupby , where the size of each group is unknown and may vary across groups . For example : The size of groups from groupyby ( 'participant_id ' ) are 10 , 7 , 9 for participant_id 13 , 14 , 15 respectively . What I need is to take only the FIRST half ( or floor ( N/2 ) )...
index summary participant_id0 130599 17.0 131 130601 18.0 132 130603 16.0 133 130605 15.0 134 130607 15.0 135 130609 16.0 136 130611 17.0 137 130613 15.0 138 130615 17.0 139 130617 17.0 1310 86789 12.0 1411 86791 8.0 1412 86793 21.0 1413 86795 19.0 1414 86797 20.0 1415 86799 9.0 1416 86801 10.0 1420 107370 1.0 1521 107...
Find half of each group with Pandas GroupBy
Python
I 'm using AudioLazy Library for the extraction of some audio features.The lpc function ( Linear Predictive Coding ) receives a block in the time domain , and returns the whitening LPC filter ( ZFilter ) filt is a ZFilter as : The plot function , return an image : I would like extract the numerical values ( in dB ) fro...
filt = lpc ( intensity , order=16 ) # Analysis filtergain = 1e-2 # Gain just for alignment with DFT ( gain / filt ) .plot ( min_freq=0 , max_freq=3.141592653589793/4 ) ; 1 - 2.47585 * z^-1 + 2.68746 * z^-2 - 1.71373 * z^-3 + 0.383238 * z^-4 + 0.451183 * z^-5 - 0.480446 * z^-6 + 0.304557 * z^-7 + 0.0277818 * z^-8 - 0.28...
Extract numerical values from zfilter object in python in AudioLazy library
Python
Below is a big section of my code and basically if you scroll down to the execute_subscripts ( ) function you can see I 've got two scripts running via execfile which work beautifully , they show prints , they save traceback errors to an error file.I 'm trying to turn the second script into one that does n't wait for i...
from datetime import date , timedeltafrom sched import schedulerfrom time import time , sleep , strftimeimport randomimport tracebackimport subprocesss = scheduler ( time , sleep ) random.seed ( ) def periodically ( runtime , intsmall , intlarge , function ) : # # Get current time currenttime = strftime ( ' % H : % M :...
Custom Scheduler to have sequential + semi-sequential scripts with timeouts/kill switches ?
Python
See updated input and output data at Edit-1.What I am trying to accomplish is turninginto a python data structure such as I 've looked at many different wiki markup languages , markdown , restructured text , etc but they are all extremely complicated for me to understand how it works since they must cover a large amoun...
+ 1 + 1.1 + 1.1.1 - 1.1.1.1 - 1.1.1.2 + 1.2 - 1.2.1 - 1.2.2 - 1.3+ 2- 3 [ { ' 1 ' : [ { ' 1.1 ' : { ' 1.1.1 ' : [ ' 1.1.1.1 ' , ' 1.1.1.2 ' ] } , ' 1.2 ' : [ ' 1.2.1 ' , ' 1.2.2 ' ] } , ' 1.3 ' ] , ' 2 ' : { } } , [ ' 3 ' , ] ] * 1 * 1.1 * 1.2 - Note for 1.2* 2* 3- Note for root [ { 'title ' : ' 1 ' , 'children ' : [ {...
How can I parse marked up text for further processing ?
Python
Below the performance difference between Slice and manual reverse operation . If this is the case , What is the reason for that ?
timeit.timeit ( `` a [ : :-1 ] '' , '' a= [ 1,2,3,4,5,6 ] '' , number=100 ) 6.054327968740836e-05timeit.timeit ( `` [ a [ i ] for i in range ( len ( a ) -1 , -1 , -1 ) ] '' , '' a= [ 1,2,3,4,5,6 ] '' , number=100 ) 0.0003132152330920235
Why manual string reverse is worse than slice reverse in Python 2.7 ? What is the algorithm being used in Slice ?
Python
I have the following dataframe : All I want is shown below : Thanks in advance !
A B C A 1 3 0 B 3 2 5 C 0 5 4 my_list = [ ( ' A ' , ' A',1 ) , ( ' A ' , ' B',3 ) , ( ' A ' , ' C',0 ) , ( ' B ' , ' B',2 ) , ( ' B ' , ' C',5 ) , ( ' C ' , ' C',4 ) ]
Create a list including row name , column name and the value from dataframe
Python
I am trying to scrape content of the zillow website . Ex- https : //www.zillow.com/homedetails/689-Luis-Munoz-Marin-Blvd-APT-508-Jersey-City-NJ-07310/108625724_zpid/The problem is I ca n't scrape contents of the price and tax history.I thought that they are javascript elements loading when the page loads and hence trie...
phistory = soup.find ( `` div '' , { `` id '' : `` hdp-price-history '' } ) print phistory < div class= '' loading yui3-widget yui3-async-block yui3-complaintstable yui3-hdppricehistory yui3-hdppricehistory-content '' id= '' hdp-price-history '' > div class= '' zsg-content-section zsg-loading-spinner_lg '' > < /div > <...
Ca n't scrape some elements off of zillow website
Python
I want to get JS file names from the input content which contains jquery as a substring by RE.This is my code : Step 1 : Extract JS file from the content.Step 2 : Get JS file which have sub string as jqueryCan I do above Step 2 in the Step 1 means RE Pattern to get result ?
> > > data = `` '' '' < script type= '' text/javascript '' src= '' js/jquery-1.9.1.min.js '' / > ... < script type= '' text/javascript '' src= '' js/jquery-migrate-1.2.1.min.js '' / > ... < script type= '' text/javascript '' src= '' js/jquery-ui.min.js '' / > ... < script type= '' text/javascript '' src= '' js/abc_bsub...
Extracting specific src attributes from script tags
Python
How would I go about breaking the following line ? The PEP8 guideline does n't make it very clear to me .
confirmation_message = _ ( 'ORDER_CREATED : % ( PROPERTY_1 ) s - % ( PROPERTY_2 ) s - % ( PROPERTY_3 ) s - % ( PROPERTY_4 ) s ' ) % { 'PROPERTY_1 ' : order.lorem , 'PROPERTY_2 ' : order.ipsum , 'PROPERTY_4 ' : order.dolor , 'PROPERTY_5 ' : order.sit }
How to correctly break a long line in Python ?
Python
Got this exercise on a python exam.Trying to return a deep o copy of a list like this : l1 should contain [ 0,1,2 ] not [ 1,1,2 ] The exercise specified to implement it by using a metaclass.From what i know , the '= ' in python is a statement and not an operator and it ca n't be overriden . Any idea on how to return a ...
l = list ( ) l = [ 0,1,2 ] l1 = ll [ 0 ] = 1 class deep ( type ) : def __new__ ( meta , classname , bases , classDict ) : return type.__new__ ( meta , classname , bases , classDict ) def __init__ ( cls , name , bases , dct ) : super ( deep , cls ) .__init__ ( name , bases , dct ) def __call__ ( cls , *args , **kwds ) :...
Python deepcopy of list on assignment
Python
I was writing a tic-tac-toe game and using an Enum to represent the three outcomes -- lose , draw , and win . I thought it would be better style than using the strings ( `` lose '' , `` win '' , `` draw '' ) to indicate these values . But using enums gave me a significant performance hit.Here 's a minimal example , whe...
import enumimport timeitclass Result ( enum.Enum ) : lose = -1 draw = 0 win = 1 > > > timeit.timeit ( 'Result.lose ' , 'from __main__ import Result ' ) 1.705788521998329 > > > timeit.timeit ( ' '' lose '' ' , 'from __main__ import Result ' ) 0.024598151998361573 k = 12 > > > timeit.timeit ( ' k ' , 'from __main__ impor...
How to use Python 3.4 's enums without significant slowdown ?
Python
I have a list of numbers , sayI 'd like to compute the difference between 2 and 2 items , ( that is , for the above dataI want to compute 45-34,33-20,16-13 and 12-3 , what 's the python way of doing that ? Also , more generally , how should I apply a function to 2 and 2 of these elements , that is , I want to call myfu...
data = [ 45,34,33,20,16,13,12,3 ]
Perform an action over 2 and 2 elements in a list
Python
When reading fixed-width files using the read_fwf function in pandas ( 0.18.1 ) with Python ( 3.4.3 ) , it is possible to specify a comment character using the comment argument . I expected that all lines beginning with the comment character would be ignored . However , if you do not specify the first column in the fil...
import io , sysimport pandas as pdsys.version # ' 3.4.3 ( v3.4.3:9b73f1c3e601 , Feb 24 2015 , 22:43:06 ) [ MSC v.1600 32 bit ( Intel ) ] 'pd.__version__ # ' 0.18.1 ' # Two input files , first line is comment , second line is data. # Second file has a column ( with the letter A ) # that I do n't want at start of data.st...
read_fwf in pandas in Python does not use comment character if colspecs argument does not include first column
Python
I have a simple PyGObject application : I am trying to freeze it using cx_freeze on Linux using following setup.py script : And I am running it like this : python3 setup_pygobject.py buildWhen I try to run the frozen application , I get the following error message : I am probably missing a bunch of libraries in the dir...
from gi.repository import Gtkclass Window ( Gtk.Window ) : def __init__ ( self , *args , **kwargs ) : super ( ) .__init__ ( *args , **kwargs ) self.set_border_width ( 5 ) self.button = Gtk.Button ( 'Test ' ) self.box = Gtk.Box ( ) self.box.pack_start ( self.button , True , True , 0 ) self.add ( self.box ) self.connect ...
cx_freeze PyGObject application on Linux
Python
I am trying to find a vectorized approach of finding the first position in an array where the values did not get higher than the maximum of n previous numbers . I thought about using the find_peaks method of scipy.signal to find a local maximum . I think it does exactly that if you define the distance to let 's say 10 ...
arr1 = np.array ( [ 1. , 0.73381293 , 0.75649351 , 0.77693474 , 0.77884614 , 0.81055903 , 0.81402439 , 0.78798586 , 0.78839588 , 0.82967961 , 0.8448 , 0.83276451 , 0.82539684 , 0.81762916 , 0.82722515 , 0.82101804 , 0.82871127 , 0.82825041 , 0.82086957 , 0.8347826 , 0.82666665 , 0.82352942 , 0.81270903 , 0.81191224 , 0...
find_peaks does not identify a peak at the start of the array
Python
BackgroundI have a game with a HUD I based on this exampleI have a pyglet application with two gluOrtho2D views . One which is mapped 1/1 to the screen , which acts as my HUD . One which is mapped to the game world , so it scales.ProblemWhen a player in the game world is rendered in a certain location , I want to displ...
from pyglet import clock , window , fontfrom pyglet.gl import * class Camera ( object ) : def __init__ ( self , win ) : self.win = win def project_world ( self ) : glMatrixMode ( GL_PROJECTION ) glLoadIdentity ( ) gluOrtho2D ( -500 , 1000 , -500 , 500 ) def project_hud ( self ) : glMatrixMode ( GL_PROJECTION ) glLoadId...
Pyglet HUD text location / scaling
Python
Suppose I have a scipy.sparse.csr_matrix representing the values belowI want to calculate the cumulative sum of non-zero values in-place , which would change the array to : The actual values are not 1 , 2 , 3 , ... The number of non-zero values in each row are unlikely to be the same.How to do this fast ? Current progr...
[ [ 0 0 1 2 0 3 0 4 ] [ 1 0 0 2 0 3 4 0 ] ] [ [ 0 0 1 3 0 6 0 10 ] [ 1 0 0 3 0 6 10 0 ] ] import scipy.sparseimport numpy as np # sparse dataa = scipy.sparse.csr_matrix ( [ [ 0,0,1,2,0,3,0,4 ] , [ 1,0,0,2,0,3,4,0 ] ] , dtype=int ) # methodindptr = a.indptrdata = a.datafor i in range ( a.shape [ 0 ] ) : st = indptr [ i ...
Scipy Sparse Cumsum
Python
For sake of simplicity I 've defined a class that is not subclassed from ndarray ( for many reasons I find it very complicated ) , but has an __array__ ( ) method that returns a nd.array of a given fixed shape . Let 's call this class Foo.In my script I also generate large lists of Foo instances , and I want to convert...
numpy.array ( map ( lambda x : numpy.array ( x ) , [ foo_1 , ... , foo_n ] ) ) numpy.array ( [ foo_1 , ... , foo_n ] )
numpy - transform a list of objects into an array without subclassing ndarray
Python
This is my first time asking a question.I 'm working with a large CSV dataset ( it contains over 15 million rows and is over 1.5 GB in size ) .I 'm loading the extracts into Pandas dataframes running in Jupyter Notebooks to derive an algorithm based on the dataset . I group the data by MAC address , which results in 1+...
pandas.core.groupby.DataFrameGroupBy.filter pandas.core.groupby.DataFrameGroupBy.filter import pandas as pddef import_data ( _file , _columns ) : df = pd.read_csv ( _file , low_memory = False ) df [ _columns ] = df [ _columns ] .apply ( pd.to_numeric , errors='coerce ' ) df = df.sort_values ( by= [ 'mac ' , 'time ' ] )...
How do I improve the performance of pandas GroupBy filter operation ?
Python
I have Python from Microsoft package in VS Code.When I run some Python Code , I have errors : Python on my laptop in C : \Users\abukreev\Documents\Python367\ . But pydev await it in C : \Users\abukreev\AppData\Roaming\Python\Python36\site-packages How can I change the pydev settings ?
pydev debugger : Unable to find real location for : threading.pypydev debugger : Unable to find real location for : C : \Users\abukreev\AppData\Roaming\Python\Python36\site-packagespydev debugger : Unable to find real location for : < frozen importlib._bootstrap > pydev debugger : Unable to find real location for : gen...
Wrong paths in pydev debugger :
Python
I have a problem understanding what is happening with the outcome of the following pieces of code : The output is : Another piece of code is : The output is : The question is : What is happening here in each print ( ) statement ? Can anyone explain why the print ( ) statement get the string from the different namespace...
my_str = `` outside func '' def func ( ) : my_str = `` inside func '' class C ( ) : print ( my_str ) print ( ( lambda : my_str ) ( ) ) my_str = `` inside C '' print ( my_str ) outside funcinside funcinside C my_str = `` not in class '' class C : my_str = `` in the class '' print ( [ my_str for i in ( 1,2 ) ] ) print ( ...
Python class and global vs local variables
Python
I have a python script : It 's so easy to achieve multiple return values in python.And now I want to achieve the same result in C # . I tried several ways , like return int [ ] or KeyValuePair . But both ways looked not elegant . I wonder a exciting solution . thanks a lot .
def f ( ) : a = None b = None return ( a , b ) a , b = f ( )
How to achieve multiple return values in C # like python style
Python
From what I understand , when calling pickle.dumps on an object , it will call the object 's __getstate__ method ( if it has one ) to determine what to pickle.If I create a class such as : I get this result : I can do the same thing , replacing 'dict ' with 'list ' : But if I use 'set ' , something different happens : ...
class DictClass ( dict ) : def __getstate__ ( self ) : print `` pickling '' return self > > > pickle.dumps ( DictClass ( ) ) pickling'ccopy_reg\n_reconstructor\np0 ... ' class ListClass ( list ) : def __getstate__ ( self ) : print `` pickling '' return self > > > pickle.dumps ( ListClass ( ) ) pickling'ccopy_reg\n_reco...
__getstate__ method not being called when pickling a subclass of set
Python
My question is different than the title implies ( I do n't know how to summarize the question so I 'm having a hard time googling ) . I do not want a Union type . Union [ A , B ] says that the type can be either of type A , or of type B. I need to the opposite . I want it to mean that it is both type A and B , which is...
from typing import Unionclass A ( object ) : def a ( self ) : return Trueclass B ( object ) : def b ( self ) : return Trueclass C ( A , B ) : passdef foo ( d : Union [ A , B ] ) - > bool : # need something other than Union ! print ( d.a ( ) and d.b ( ) ) > > > foo ( A ( ) ) Traceback ( most recent call last ) : File ``...
Type hinting values that are multiple types ?
Python
I am working on Project Euler problem 5 and am using the following : Is there a Python function with which I can combine factorization and factors like this function does ? For example , if factors= [ 2 , 3 , 5 ] and factorization= [ 2 , 2 , 3 ] , the combined list should be [ 2 , 2 , 3 , 5 ] .
def findLCM ( k ) : start=time.time ( ) primes= [ 2,3,5,7,11,13,17,19,23 ] factors= [ ] for factor in range ( 2 , k ) : if factor in primes : factors.append ( factor ) else : factorization= [ ] while factor ! =1 : for prime in primes : lastFactor=prime if factor % prime==0 : factor/=prime factorization.append ( lastFac...
Combine Two LIsts in Unique Way in Python
Python
If I set shade_lowest = False , the colorbar still contains the lowest level ( purple-ish ) . Is there any generic way to remove it entirely ?
import seaborn as snsimport numpy as npimport matplotlib.pyplot as plta = np.random.normal ( 0 , 1 , 100 ) b = np.random.normal ( 0 , 1 , 100 ) fig , ax = plt.subplots ( ) sns.kdeplot ( a , b , shade = True , shade_lowest = False , cmap = `` viridis '' , cbar = True , n_levels = 4 , ax = ax ) plt.show ( )
Remove lowest color from colorbar in Seaborn/Matplotlib
Python
I am using python langauge to send & receive messages using Azure bus service queue.I am getting `` The lock supplied is invalid.Either the lock expired , or the message has already been removed from the queue '' when deleting message from queue using below code . sbs.delete_queue_message ( 'taskqueue',5 , 'ef4e2189-bf...
from azure.servicebus.control_client import ServiceBusService , Message , Topic , Rule , DEFAULT_RULE_NAMEkey_name = ' # # # # # # # # # # # # # # # ' # SharedAccessKeyName from Azure portalkey_value = ' # # # # # # # # # # # # # # # # # # # # ' # SharedAccessKey from Azure portalservice_namespace = ' # # # # # # # # #...
Why am I getting `` The lock supplied is invalid . '' error when I am trying to delete queue message using LockTocken
Python
I ran the following Python code , which creates a Pandas DataFrame with two Series ( a and b ) , and then attempts to create two new Series ( c and d ) : My understanding is that if a Pandas Series is part of a DataFrame , and the Series name does not have any spaces ( and does not collide with an existing attribute or...
import pandas as pddf = pd.DataFrame ( { ' a ' : [ 1 , 2 , 3 ] , ' b ' : [ 4 , 5 , 6 ] } ) df [ ' c ' ] = df.a + df.bdf.d = df.a + df.b > > > df a b c0 1 4 51 2 5 72 3 6 9 > > > df.d0 51 72 9dtype : int64 > > > type ( df.d ) pandas.core.series.Series
Creating a Pandas Series with a period in the name
Python
I have a Dataframe with a column of an array with a fixed amount of integers.How can I add to the df a column that contains the number of trailing zeroes in the array ? I would like to avoid using a UDF for better performance.For example , an input df : And a wanted output :
> > > df.show ( ) + -- -- -- -- -- -- +| A|+ -- -- -- -- -- -- +| [ 1,0,1,0,0 ] || [ 2,3,4,5,6 ] || [ 0,0,0,0,0 ] || [ 1,2,3,4,0 ] |+ -- -- -- -- -- -- + > > > trailing_zeroes ( df ) .show ( ) + -- -- -- -- -- -- + -- -- -- -- -- -- -- -- -+| A| trailingZeroes|+ -- -- -- -- -- -- + -- -- -- -- -- -- -- -- -+| [ 1,0,1,0...
How to count the trailing zeroes in an array column in a PySpark dataframe without a UDF
Python
Assume I have a Resnet34 pretained model in MXNet and I want to add to it the premade ROIPooling Layer included in the API : https : //mxnet.incubator.apache.org/api/python/ndarray/ndarray.html # mxnet.ndarray.ROIPoolingIf the code for initializing Resnet is the following , how can I add ROIPooling at the last layer of...
batch_size = 40num_classes = 11init_lr = 0.001step_epochs = [ 2 ] train_iter , val_iter , num_samples = get_iterators ( batch_size , num_classes ) resnet34 = vision.resnet34_v2 ( pretrained=True , ctx=ctx ) net = vision.resnet34_v2 ( classes=num_classes ) class ROIPOOLING ( gluon.HybridBlock ) : def __init__ ( self ) :...
Using ROIPooling layer with a pretrained ResNet34 model in MxNet-Gluon
Python
I 'm new to using Turtle graphics in Python 3 , and I 'm at a loss on what to do . One of my problems is that I have no idea where to begin with creating a function that will draw a marker inside of a grid cell based on a data set called 'path ' containing 3 variables . The grid map itself is 7x7 and there 's 5 markers...
grid_cell_size = 100 # pxnum_squares = 7 # this for creating the 7x7 grid map # for clarification : path = [ 'Start ' , location , marker_value ] path = [ [ 'Start ' , 'Centre ' , 4 ] , [ 'North ' , 2 , 3 ] , [ 'East ' , 2 , 2 ] , [ 'South ' , 4 , 1 ] , [ 'West ' , 2 , 0 ] ] path_var_3 = [ [ 'Start ' , 'Bottom left ' ,...
Python Turtle how to draw a marker inside a cell in a 7x7 grid
Python
I have train a CNN model using Keras and store the weights . When I am trying to load them back to the same model I am receiving the following error : ValueError : You are trying to load a weight file containing 2 layers into a model with 1 layers.I figure out that this is a common error . However , the proposed remedi...
def build_model ( self ) : model = Sequential ( ) # pdb.set_trace ( ) model.add ( Dense ( 128 * 7 * 7 , activation= '' relu '' , input_shape= ( None , self.latent_dim ) ) ) model.add ( Reshape ( ( 7 , 7 , 128 ) ) ) model.add ( UpSampling2D ( ) ) model.add ( Conv2D ( 128 , kernel_size=4 , padding= '' same '' ) ) model.a...
Keras you are trying to load a weight file containing 2 layers into a model with 1 layers
Python
I have followed the TensorFlow MNIST Estimator tutorial and I have trained my MNIST model.It seems to work fine , but if I visualize it on Tensorboard I see something weird : the input shape that the model requires is 100 x 784.Here is a screenshot : as you can see in the right box , expected input size is 100x784.I th...
input_layer = tf.reshape ( features [ `` x '' ] , [ -1 , 28 , 28 , 1 ] , name= '' input_layer '' ) with tf.gfile.GFile ( `` /path/to/my/frozen/model.pb '' , `` rb '' ) as f : graph_def = tf.GraphDef ( ) graph_def.ParseFromString ( f.read ( ) ) with tf.Graph ( ) .as_default ( ) as graph : tf.import_graph_def ( graph_def...
Tensorflow MNIST Estimator : batch size affects the graph expected input ?
Python
Our business ' pricing is dependent on multiple parameters , and now we want to introduce another possible M2M parameter to the existing setup in Django.For this , we have an existing table for pricing , which has a unique_together constraint on all fields except the price_field . Apologies for the generic / letter-bas...
class PricingTable ( models.Model ) : a = models.ForeignKey ( A , on_delete=models.CASCADE ) price = MoneyField ( ) b = ArrayField ( models.CharField ( choices=CHOICES ) ) c = models.ForeignKey ( C , on_delete=models.CASCADE ) class Meta : ordering = ( `` a '' , ) unique_together = ( `` a '' , `` b '' , `` c '' ) def v...
Unique together involving multiple foreign keys & a many to many field
Python
I 've a dictionary with a ( x , y ) key , where ( x , y ) means the same as ( y , x ) , How should I do this ? I can do : Is there a better way of doing this , so d.get ( ( 2,1 ) ) would match the key ( 1,2 ) directly ? ideally i 'd want to insert e.g . ( 2,1 ) and not have it be distinct from the ( 1,2 ) key as well .
> > > d = { ( 1,2 ) : `` foo '' } > > > i = d.get ( 2,1 ) > > > if i is None : ... i = d.get ( ( 1,2 ) ) ... > > > i'foo '
Look up a tuple in a python dictionary matching ( x , y ) or ( y , x )
Python
This is probably a noob question . For any dictionary 'd ' in python is this always True : Are the keys and values returned in the same corresponding order ?
dict ( zip ( d.keys ( ) , d.values ( ) ) ) == d
Key-value consistency in python dictionaries
Python
I have a dataframe like so : I would like phone_number_1_clean to be as populated as possible . This will require shifting either phone_number_2_clean or phone_number_3_clean to phone_number_1_clean and vice versa meaning getting phone_number_2_clean as populated as possible if phone_number_1_clean is populated etc . T...
phone_number_1_clean phone_number_2_clean phone_number_3_clean NaN NaN 8546987 8316589 8751369 NaN 4569874 NaN 2645981 phone_number_1_clean phone_number_2_clean phone_number_3_clean 8546987 NaN NaN 8316589 8751369 NaN 4569874 2645981 NaN
Pandas : shifting columns depending on if NaN or not
Python
I use the brokenaxes package ( https : //github.com/bendichter/brokenaxes ) to break the y-axis ( // ) . Now I want a second Y-axis , which should also be broken ( // ) just like the first one.How do I do this in the following example ? ( Here in this example I used ax.twinx , because I could n't get it to work with th...
import numpy as npimport matplotlib.pyplot as pltfrom brokenaxes import brokenaxesfig , ax = plt.subplots ( ) plt.gca ( ) .axes.get_yaxis ( ) .set_visible ( False ) bax = brokenaxes ( ylims= ( ( 0 , 1.1 ) , ( 60 , 80 ) ) , hspace=.05 ) x = np.linspace ( 0 , 1 , 100 ) bax.plot ( x , 5 * np.sin ( 10 * x ) + 70 ) bax.plot...
Matplotlib with brokenaxes package second Y-Axis
Python
I have a huge list of integers in Python ( 1000000+ elements ) , but I will illustrate what I need with an example for the sake of simplicity . Let 's suppose I have this list : Now I 'd like to get all the combinations ( size 3 ) of that list , so I use itertools.But my problem is that this will return the combination...
A = [ 1,2,3,4,100 ] combinations = itertools.combinations ( A,3 ) ( 1,2,3 ) ( 1,2,4 ) ( 1,2,100 ) ( 1,3,4 )
Sort combinations by sum of its elements in Python
Python
I am following the book and am pretty sure I copied the code verbatim . When I copy the Contact Us page on the publisher website ( nostarch.com/ContactUs ) and run it through the program , it outputs all the phone numbers but no email addresses.I made sure the code was copied correctly . I thought it may be an issue wi...
import pyperclip , re # email regexemailRegex = re.compile ( r '' ' ( [ a-zA-Z0-9._ % +- ] + # username @ # at symbol [ a-zA-Z0-9.- ] + # domain name ( \ . [ a-zA-Z ] { 2-4 } ) # dot-something ) ' '' , re.VERBOSE ) # find matches in clipboard texttext = str ( pyperclip.paste ( ) ) matches = [ ] for groups in phoneRegex...
Automate the Boring Stuff Chapter 7 : Regular Expressions - phone number and email extractor only extracting phone numbers
Python
I have two models in my application , Transaction and Person , with a many-to-many relationship . There are persons included in each Transaction . For each person , there is also a amount connected to each Transaction the Person is connected to . Therefor I need to model a many-to-many relationship with relation data ....
class TransactionPerson ( db.Model ) : # References transaction = db.ReferenceProperty ( Transaction , required=True ) person = db.ReferenceProperty ( Person , required=True ) # Values amount = db.FloatProperty ( required=True ) class Transaction ( db.Model ) : persons = ListProperty ( db.Key ) persons_amount = ListPro...
Modelling many-to-many with relation data in Google App Engine
Python
I am currently doing this : Is there a more pythonic way to express this if statement ?
if x in a and y in a and z in a and q in a and r in a and s in a : print b
Test if all values are in an iterable in a pythonic way
Python
On my Python 2.7.9 on x64 I see the following behavior : Unless there 's some deeper rationale I 'm missing this violates least surprise . When I got the ValueError on `` 10 '' * ( 2**29 ) I figured it was just a limitation on very long strings , but then `` 0 '' * ( 2**33 ) worked . What 's going on ? Can anyone justi...
> > > float ( `` 10 '' * ( 2**28 ) ) inf > > > float ( `` 10 '' * ( 2**29 ) ) Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > ValueError : could not convert string to float : 1010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101...
Why does Python 's float raise ValueError for some very long inputs ?
Python
I have data set like the following ( this is an example , it actually has 66k rows ) : I 'd like to fill all the missing combinations ( how many bananas are there in Houses 3-7 ? , how many peppers are there elsewhere than House-5 ? ) with 0.I know that R has this function integrated : http : //rpackages.ianhowson.com/...
Type Food Loc Num0 Fruit Banana House-1 151 Fruit Banana House-2 42 Fruit Apple House-2 63 Fruit Apple House-3 84 Vegetable Broccoli House-3 85 Vegetable Lettuce House-4 126 Vegetable Peppers House-5 37 Vegetable Corn House-4 48 Seasoning Olive Oil House-6 29 Seasoning Vinegar House-7 2 for key , grp in fruit.groupby (...
Fill a list/pandas.dataframe with all the missing data combinations ( like complete ( ) in R )
Python
I had namedtuple variable which represents version of application ( its number and type ) . But i want and some restriction to values : My solution for now is primitive class with no methods : Is it pythonic ? Is it overkill ?
Version = namedtuple ( `` Version '' , [ `` app_type '' , `` number '' ] ) version = Version ( `` desktop '' ) # i want only `` desktop '' and `` web '' are valid app typesversion = Version ( `` deskpop '' ) # i want to protect from such mistakes class Version : def __init__ ( self , app_type , number ) : assert app_ty...
How to validate namedtuple values ?
Python
An oft-asked question is whether there is an equivalent to static variables inside functions in Python . There are many answers , such as creating wrapper classes , using nested functions , decorators , etc.One of the most elegant solutions I found was this , which I have slightly modified : Example : static.pyoutputIs...
def foo ( ) : # see if foo.counter already exists try : test = foo.counter # if not , initialize it to whatever except AttributeError : foo.counter = 0 # do stuff with foo.counter ... .. ... .. def foo ( x ) : # see if foo.counter already exists try : test = foo.counter # if not , initialize it to whatever except Attri...
Is this Python `` static variable '' hack ok to use ?
Python
I am attempting to solve multiple linear systems using python and scipy using threads . I am an absolute beginner when it comes to python threads . I have attached code which distils what I 'm trying to accomplish . This code works but the execution time actually increases as one increases totalThreads . My guess is th...
def Worker ( threadnum , totalThreads ) : for i in range ( threadnum , N , totalThreads ) : x [ : ,i ] = sparse.linalg.spsolve ( A , b [ : ,i ] ) threads = [ ] for threadnum in range ( totalThreads ) : t = threading.Thread ( target=Worker , args= ( threadnum , totalThreads ) ) threads.append ( t ) t.start ( ) for threa...
Python : Solving Multiple Linear Systems using Threads
Python
I did an experiment in which I tried to find the time it takes to search a python list . I have a list arr with random integers . arr_s has the same elements only sorted.Now I create a random array of integers find which has elements that I want to search in arr and arr_s.Now I understand that I have not used any speci...
arr = np.random.randint ( low = 0 , high = 1000 , size = 500 ) arr_s = sorted ( arr ) > > > % % timeit ... : find = np.random.randint ( 0 , 1000 , 600 ) ... : for i in find : ... : if i in arr : ... : continue [ OUT ] :100 loops , best of 3 : 2.18 ms per loop > > > % % timeit ... : find = np.random.randint ( 0 , 1000 ,...
Why search in sorted list in python takes longer ?
Python
I 'm inheriting a product from someone who used Django and I have absolutely no idea how to use it.What I 'm trying to accomplish is to serve up different scripts in my base.html file , something like this : The file structure is as follows : Inside the settings folder , there looks to be 3 files : Inside development.p...
< ! -- if development -- > < script src= '' { % static `` js/main.js '' % } > < /script > < ! -- end -- > < ! -- if production -- > < script src= '' { % static `` production/js/main.min.js '' % } > < /script > < ! -- end -- > app_name|__ pages|__ settings|__ static|__ templates|__ etc base.py : shared settingsdevelopme...
Django Templates Development vs. Production
Python
I 've developed a set of audio streaming server , all of them are using Twisted , and they are in Python , of course . They work , but a problem keeps troubling me , when I found some bugs there in the running server , or I want add something into the server , I need to stop them and start . Unlike HTTP servers , it 's...
Broadcasting rev.123 is running ... .Startup Broadcasting rev.124 ... .Broadcasting rev.124 is stand byHand over connections from instance of rev.123 to instance of rev.124Stop Broadcasting rev . 123 instance
How to build Twisted servers which are able to do hot code swap in Python ?
Python
I have a few classes that need to do the following : When the constructor is called , if an equal object ( aka an object with the same id ) already exists , return that object . Otherwise , create a new instance.Basically , To achieve this , I 've written a class decorator like so : This does what I want , but : How ca...
> > > cls ( id=1 ) is cls ( id=1 ) True class Singleton ( object ) : def __init__ ( self , cls ) : self.__dict__.update ( { 'instances ' : { } , 'cls ' : cls } ) def __call__ ( self , id , *args , **kwargs ) : try : return self.instances [ id ] except KeyError : instance= self.cls ( id , *args , **kwargs ) self.instanc...
Make isinstance ( obj , cls ) work with a decorated class
Python
Django 1.7 has introduced a new way for handling application configuration that is independent of models.py . However the method for using the new AppConfig requires this line : Unfortunately , this will break in Django 1.6 as there is no apps module.Is it possible to have an app be compatible with 1.6 and 1.7 using co...
from django.apps import AppConfig
Is there a recommended approach for handling AppConfig when designing an app for Django 1.6 and 1.7 ?
Python
Problem summary : I am currently trying to migrate existing tests from pure python to robot framework in order to benefit from the nice reporting features . These system tests have to be re-run using multiple parameter sets consisting of many parameters . That 's why I already have a python generator yielding dictionar...
*** Settings ***Test Template Check Result With Args*** Keywords ***Check Result With Args [ Arguments ] $ { par1 } ... $ { par2 } ... $ { par3 } Set par par1 $ { par1 } Set par par2 $ { par2 } Set par par3 $ { par3 } Evaluation Check result*** Test Cases *** par1 par2 par3description000 0 0 0description001 0 0 1descri...
Is there an elegant way for calling robot framework tests with automatically generated arguments ?
Python
I 've often been frustrated by the lack of flexibility in Python 's iterable unpacking.Take the following example : Works fine . a contains 0 and b contains 1 , just as expected . Now let 's try this : Now , we get a ValueError : Not ideal , when the desired result was 0 in a , and None in b.There are a number of hacks...
a , b = range ( 2 ) a , b = range ( 1 ) ValueError : not enough values to unpack ( expected 2 , got 1 ) a , *b = function_with_variable_number_of_return_values ( ) b = b [ 0 ] if b else None
Default values for iterable unpacking
Python
I have a list of numbers : And a list of conditions : I want to check if a number in ' a ' meets one of the conditions in ' b ' and if yes , put these numbers in list ' c'In above case : I created this code what seems to do what I want : However my list ' a ' can be very big.Is there not an easier and faster way to obt...
a = [ 3 , 6 , 20 , 24 , 36 , 92 , 130 ] b = [ `` 2 '' , `` 5 '' , `` 20 '' , `` range ( 50,100 ) '' , `` > 120 '' ] c = [ 20 , 92 , 130 ] c = [ ] for x in a : for y in b : if `` range '' in y : rangelist = list ( eval ( y ) ) if x in rangelist : c.append ( x ) elif `` > '' in y or `` < `` in y : if eval ( str ( x ) + y...
How to check if elements in list ' a ' meet conditions in list ' b ' ?
Python
We use py2app extensively at our facility to produce self contained .app packages for easy internal deployment without dependency issues . Something I noticed recently , and have no idea how it began , is that when building an .app , py2app started including the .git directory of our main library.commonLib , for instan...
commonLib/ |- .git/ # because commonLib is a git repo |- __init__.py |- database/ |- __init__.py |- utility/ |- __init__.py # ... etc from setuptools import setupfrom myApp import VERSIONappname = 'MyApp'APP = [ 'myApp.py ' ] DATA_FILES = [ ] OPTIONS = { 'includes ' : 'atexit , sip , PyQt4.QtCore , PyQt4.QtGui ' , 'str...
py2app picking up .git subdir of a package during build
Python
I have 2 , 2D NumPy arrays consisting of ~300,000 ( x , y ) pairs each . Given the ith ( x , y ) pair in array A , I need to find the corresponding jth ( x , y ) pair in array B such that ( [ xi - xj ] 2 + [ yi - yj ] 2 ) ½ , the distance between the two ( x , y ) pairs , is minimized.What I 'm currently doing is argmi...
thickness = [ ] for i in range ( len ( A ) ) : xi = A [ i ] [ 0 ] yi = A [ i ] [ 1 ] idx = ( np.sqrt ( np.power ( B [ : , 0 ] - xi , 2 ) + np.power ( B [ : , 1 ] - yi , 2 ) ) ) .argmin ( ) thickness.append ( [ ( xi + B [ idx ] [ 0 ] ) / 2 , ( yi + B [ idx ] [ 1 ] ) / 2 , A [ i ] [ 2 ] + B [ idx ] [ 2 ] ] )
How to pair ( x , y ) pairs using numpy
Python
My understanding is that pythonanywhere supports a headless Firefox browser but you needAnd so you can connect usingAnd I connect just fine . However , after I start using the driver withI get this error after just a little while For what it 's worth , this code works perfectly fine on my local machine . Also , I am a ...
from pyvirtualdisplay import Display with Display ( ) : while True : try : driver = webdriver.Firefox ( ) break except : time.sleep ( 3 ) with Display ( ) : while True : try : driver = webdriver.Firefox ( ) break except : time.sleep ( 3 ) wb=load_workbook ( r'/home/hoozits728/mutual_fund_tracker/Mutual_Fund_Tracker.xls...
Getting selenium to work on pythonanywhere
Python
I partially understood ( which is dangerous ) the reason that i is same for all functions because Python ’ s closures are late binding.The output is [ 6 , 6 , 6 , 6 ] ( not [ 0 , 2 , 4 , 6 ] as I was expecting ) .I see that it works fine with a generator , my expected output is coming in below version.Any simple explan...
def multipliers ( ) : return [ lambda x : i * x for i in range ( 4 ) ] print [ m ( 2 ) for m in multipliers ( ) ] def multipliers ( ) : return ( lambda x : i * x for i in range ( 4 ) ) print [ m ( 2 ) for m in multipliers ( ) ]
Python closures with generator
Python
This code is currently executing about 50 SQL queries : I need to cut down the number of used queries to the minimum to speed up things and do not cause server load.Basically , I have three models : Category , Author , Book . The Author belong to the Category ( not books ) and I need to get a list of all categories wit...
c = Category.objects.all ( ) categories_w_rand_books = [ ] for category in c : r = Book.objects.filter ( author__category=category ) .order_by ( ' ? ' ) [ :5 ] categories_w_rand_books.append ( ( category , r ) )
How can I cut down the number of queries ?
Python
I am very new to Python/Django and programming in general . With the limited tools in my programming bag , I have written three views functions for after a user registers : it allows the user to add information and upload a thumbnail before activating his account.I have posted the code that I have written so far so tha...
# in model.pychoices = ( [ ( x , str ( x ) ) for x in range ( 1970,2015 ) ] ) choices.reverse ( ) class UserProfile ( models.Model ) : `` '' '' Fields are user , network , location , graduation , headline , and position . user is a ForeignKey , unique = True ( OneToOne ) . network is a ForeignKey . loation , graduation...
Improving Python/django view code
Python
I 'm trying to use the Dedupe package to merge a small messy data to a canonical table . Since the canonical table is very large ( 122 million rows ) , I ca n't load it all into memory.The current approach that I 'm using based off this takes an entire day on test data : a 300k row table of messy data stored in a dict ...
blocked_pairs = block_data ( messy_data , canonical_db_cursor , gazetteer ) clustered_dupes = gazetteer.matchBlocks ( blocked_pairs , 0 ) def block_data ( messy_data , c , gazetteer ) : block_groups = itertools.groupby ( gazetteer.blocker ( messy_data.viewitems ( ) ) , lambda x : x [ 1 ] ) for ( record_id , block_keys ...
How do I link records to a large table efficiently using python Dedupe ?
Python
I am stuck at this particular example from dive into pythonExample 4.18 . When the and−or Trick FailsSince a is an empty string , which Python considers false in a boolean context , 1 and `` evalutes to `` , andthen `` or 'second ' evalutes to 'second ' . Oops ! That 's not what you wanted.The and−or trick , bool and a...
> > > > a = `` '' > > > > b = `` second '' > > > 1 and a or b > > > > 'second '
Dive into python and-or fail
Python
This particular code I wrote in another question recently , and I 'm not sure it 's optimal . I could n't find a less-indented way of doing this though . Is there ? I keep hearing that nesting too much is bad , but this seems to be necessary . It 's currently four indentations deep .
def msg_generator ( self ) : `` ' Provides messages until bot dies `` ' while self.alive : for msg in self.irc.recv ( self.buffer ) .split ( ( '\r\n ' ) .encode ( ) ) : if len ( msg ) > 3 : try : yield Message ( msg.decode ( ) ) except Exception as e : self.log ( ' % s % s\n ' % ( except_str , str ( e ) ) )
My code nests too deep . Is there a better way ?
Python
I use various continuous distributions from scipy.stats ( e.g . norm ) . So if I want to find P ( Z < 0.5 ) I would do : Is there a tool ( scipy.stats or statsmodels or else ) that I can use to describe a discrete distribution and then calculate CDF/CMF etc on it ? I can write the code myself but I was wondering if som...
from scipy.stats import normnorm ( 0 , 1 ) .cdf ( 0.5 ) # Z~N ( 0,1 )
Python scipy - specify custom discrete distribution
Python
I 'm writing a Mercurial extension in Python and need to call the `` Pull '' command using the Mercurial API , but I want to suppress its output using the -- quiet flag.In Hg terms , I want to execute the following code , but from within my extension : Given the Mercurial API documentation , I thought it would be as si...
hg pull -- quiet commands.pull ( ui , repo , quiet=True )
Using the -- quiet tag when extending Mercurial
Python
I was wondering whether there is a trick to ( easily ) incorporate some python code into a moinmoin page , perhaps by adding some action . The idea is that something likeis displayed on the page asQuick and dirty is ok , safety is not a concern , I would like to have this for a stand-alone , `` desktop-mode '' installa...
< < < for j in [ 1,3,5 ] : print ( i ) > > > 135
Is there a way to incorporate python code into moinmoin pages ?
Python
I was trying to get Gmail inbox event as a push notification for my application using Google Pub/Sub refering official documentation . Although I declare labelIds as [ 'INBOX ' ] , Gmail API sends notifications for all events ( i.e . INBOX , SENT , IMPORTANT & etc ) . My python Code looks as below , How can I get it no...
credentials = get_credentials ( ) http = credentials.authorize ( httplib2.Http ( ) service = discovery.build ( 'gmail ' , 'v1 ' , http=http ) request = { 'labelIds ' : [ 'INBOX ' ] , 'topicName ' : 'projects/myproject/topics/getNotification ' } service.users ( ) .watch ( userId='me ' , body=request ) .execute ( )
Can not filter Gmail API push notifications
Python
After reading the Apple documentation for Executing Mach-O files it says : The two-level namespace feature of OS X v10.1 and later adds the module name as part of the symbol name of the symbols defined within it . This approach ensures a module ’ s symbol names don ’ t conflict with the names used in other modules.So i...
# include < { ... } /include/python2.7/Python.h > int main ( int argc , const char * argv [ ] ) { auto* py3 = dlopen ( `` ... /python36 '' , RTLD_GLOBAL | RTLD_NOW ) ; if ( py3 == nullptr ) return 0 ; auto* py2 = dlopen ( `` ... /python27 '' , RTLD_GLOBAL | RTLD_NOW ) ; if ( py2 == nullptr ) return 0 ; auto* init = ( (...
RTLD_GLOBAL and Two Level Namespaces on macOS
Python
I 'm very confused with python 's eval ( ) : I tried eval ( ' '' \x27 '' ' ) == eval ( ' '' \\x27 '' ' ) and it evaluates to True . Can somebody explain why this is the case ? Both expressions evaluate to `` ' '' . I understand why eval ( ' '' \x27 '' ' ) does ( the string evaluated has a single character , which is an...
s = `` \x27 '' t = `` \\x27 ''
Why is eval ( ' '' \x27 '' ' ) == eval ( ' '' \\x27 '' ' ) ?
Python
Let 's suppose I have 2 classes in different scenario.Scenario 1Scenario 2Now when will variable temp will be treated as a class variable and instance variable . I am confused because in both the scenarios I am able to access the value of variable temp using both.Object.Temp ( behaving as instance variable ) ClassName....
class MyClass ( ) : temp = 5 class MyClass ( ) : temp = 5 def myfunc ( self ) : print self.temp
Understanding instance and class variable python
Python
I have a Django model ( called BiomSearchJob ) which is currently live and I want to add a new many-to-many relation to make the system more customizable for the user . Previously , users can submit a job without specifying a set of TaxonomyLevelChoices but to add more features to the system , users should now be able ...
class TaxonomyLevelChoice ( models.Model ) : taxon_level = models.CharField ( verbose_name= '' Taxonomy Chart Level '' , max_length=60 ) taxon_level_proper_name = models.CharField ( max_length=60 ) def __unicode__ ( self ) : return self.taxon_level_proper_nameclass BiomSearchJob ( models.Model ) : ... # The new many-to...
Retroactively set new ManyToManyField default values to existing model
Python
A few days ago someone said to me that recursion would be better then iteration and should , if possible , always be used . So , I dove into recursion and tried writing a simple program to get the factorial of a number . This is the recursion : and although this works fine , it gets a RuntimeError : maximum recursion d...
def fact ( n ) : if n == 1 : return 1 return n * fact ( n - 1 ) def fact ( n ) : a = 1 for x in range ( 0 , n , 1 ) : a = a * ( n - x ) return a
Is recursion worse than iteration ?
Python
Based on the answer to this question I was trying to use the line_profiler with a cythonized function.On the abovementioned question , the accepted answer gives us an example on how to use it with jupyter notebook.However , when I try to build the pyx file using disutils it does n't work.We I plainly try to run the scr...
kernprof -l -v script.py undeclared name not builtin : profile
Can not use line_profiler with Cython
Python
I have two classes : a parent class and a container class . The parent class instance has matching container class instance as a weak reference.There is a problem while deep copying the parent instance , the weakref is still linking to the original instance . Here is a minimal example : The second assertion fails.I sus...
import weakreffrom copy import deepcopyclass Container : def __init__ ( self , parent ) : self.parent = weakref.ref ( parent ) class Parent : def __init__ ( self ) : self.container = Container ( self ) if __name__ == '__main__ ' : parent1 = Parent ( ) assert ( parent1 is parent1.container.parent ( ) ) parent2 = deepcop...
Creating a deepcopy of class instance with nested weakref to it
Python
I have written the following code : When I invoke this as it gets into an infinite loop and gives this output : I was expecting it to print numbers 1-10 . I am not able to understand why it does n't . Can someone please tell me why this happens.I 'm using python2.7 .
def incr_num ( x , y ) : while x < = y : print x incr_num ( x+1 , y ) incr_num ( 1 , 10 ) 12345678910101010101010 ( number 10 keeps repeating )
Seemingly straightforward recursive function ends in infinite loop
Python
Is there a way to perform keyword searching of module and function docstrings from the interpreter ? Often , when I want to do something in Python , I know there 's a module that does what I want , but I do n't know what it 's called . I would like a way of searching for `` the name of the function or module that does ...
urllib.urlopen : Create a file-like object for the specified URL to read from.urllib2.urlopen : ... ...
Python docstring search - similar to MATLAB ` lookup ` or Linux ` apropos `
Python
The code is from the guide of pyqueryMy question is this in the 3rd line is an unbound variable and is never defined in current environment , but the above code still works.How can it work ? Why it does n't complain NameError : name 'this ' is not defined ? It seems that something happens at https : //bitbucket.org/ola...
from pyquery import PyQueryd = PyQuery ( ' < p class= '' hello '' > Hi < /p > < p > Bye < /p > ' ) d ( ' p ' ) .filter ( lambda i : PyQuery ( this ) .text ( ) == 'Hi ' )
Why can this unbound variable work in Python ( pyquery ) ?
Python
I 'm investigating solutions of storing and querying a historical record of event occurrences for a large number of items.This is the simplified scenario : I 'm getting a daily log of 200 000 streetlamps ( labeled sl1 to sl200000 ) which shows if the lamp was operational on the day or not . It does not matter for how l...
class Streetlamp ( object ) : `` '' '' Class for streetlamp record '' '' '' def __init__ ( self , **args ) : self.location = args [ 'location ' ] self.power = args [ 'power ' ] self.inservice = ? ? ? sl1000_up = dict ( '2010 ' : '11100000000000 ... ' , '2011 ' : '11111100100 ... ' )
Algorithm in Python to store and search daily occurrence for thousands of numbered events ?
Python
How can I get the total amount of contributors of a GitHub repository ? The API makes it quite difficult because of the pagination.This is what I tried so far using Python :
contributors = `` https : //api.github.com/repos/JetBrains/kotlin-web-site/contributors '' x = requests.get ( contributors ) y = json.loads ( x.text ) len ( y ) # maximum 30 because of pagination
How to get the total amount of contributors to a GitHub repository ?
Python
The following short Python script takes three command-line arguments : a passphrase , an input path , and an output path . Then it uses the passphrase to decrypt the contents of the input path , and puts the decrypted content in the output path.This decryption works fine , as long as the correct passphrase is provided ...
from gpg import Contextimport syspp = sys.argv [ 1 ] # passphraseenc = sys.argv [ 2 ] # input file ( assumed to be encrypted ) dec = sys.argv [ 3 ] # output filewith open ( enc , 'rb ' ) as reader , open ( dec , 'wb ' ) as writer , Context ( ) as ctx : try : ctx.decrypt ( reader , sink=writer , passphrase=pp ) except E...
How to prevent passphrase-caching from within a gpgme-based Python script ?
Python
In R , I can add elements to a list easily : How do I do this in rpy2 ? I am using rpy2 2.1.9 . I tried the following but it does n't work
mylist = list ( ) mylist [ [ 1 ] ] = c ( 1,2 ) mylist [ [ 2 ] ] = c ( 2,3 ) mylist [ [ length ( mylist ) +1 ] ] = c ( 3,4 ) import rpy2.robjects as robjectsa = robjects.r ( 'list ( ) ' ) b = robjects.IntVector ( [ 1,2 ] ) a [ 0 ] = bIndexError : Index out of range.a [ 1 ] = bIndexError : Index out of range.aa = a.__add...
Adding an element ( vector ) to a list in rpy2
Python
I asked this question a few weeks ago . Today I have actually written and released a standard Django application , i.e . a fully-functional relational DB-backed ( and consequently fully-functional Django admin ) enabled by Google CloudSQL . The only time I had to deviate from doing things the standard Django way was to...
libraries : - name : django version : `` 1.3 ''
Django on GoogleAppEngine : performance howto
Python
I 'm trying to test an UpdateView that adds a message to the redirected success page . It seems my issue comes from messages because of pytest returns : django.contrib.messages.api.MessageFailure : You can not add messages without installing django.contrib.messages.middleware.MessageMiddlewareMy test code is : I precis...
def test_authenticated_staff ( self , rf ) : langues = LanguageCatalog.objects.create ( lang_src='wz ' , lang_dest='en ' , percent= ' 4 ' ) req = rf.get ( reverse ( `` dashboard.staff : lang-update '' , kwargs= { 'pk ' : langues.pk } ) ) data = { 'lang_src ' : 'it ' , 'lang_dest ' : 'en ' , 'percent ' : '34 ' } req = r...
Django messages middleware issue while testing post request
Python
I have a list of tuples , each of which contains between 1 to 5 elements . I 'd like to unpack these tuples into five values but that wo n't work for tuples of less than five elements : It 's ok to set non-existing values to None . Basically , I 'm looking for a better ( denser ) way if this function : ( This questions...
> > > t = ( 1,2 ) # or ( 1 ) or ( 1,2,3 ) or ... > > > a , b , c , d , e = ( t ) Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > ValueError : need more than 2 values to unpack def unpack ( t ) : if len ( t ) == 1 : return t [ 0 ] , None , None , None , None if len ( t ) == 2 : return...
How to unpack a tuple into more values than the tuple has ?
Python
It is possible to 'fill ' an array in Python like so : I wanted to use this sample principle to quickly create a list of similar objects : But it appears these objects are linked with one another : Given that Python does not have a clone ( ) method ( it was the first thing I looked for ) , how would I create unique obj...
> [ 0 ] * 10 [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] > a = [ { 'key ' : 'value ' } ] * 3 > a [ { 'key ' : 'value ' } , { 'key ' : 'value ' } , { 'key ' : 'value ' } ] > a [ 0 ] [ 'key ' ] = 'another value ' > a [ { 'key ' : 'another value ' } , { 'key ' : 'another value ' } , { 'key ' : 'another value ' } ]
Make List of Unique Objects in Python
Python
I have found lots of Scrapy tutorials ( such as this good tutorial ) that all need the steps listed below . The result is a project , with lots of files ( project.cfg + some .py files + a specific folder structure ) .How to make the steps ( listed below ) work as a self-contained python file that can be run with python...
from scrapy.item import Item , Field class MyItem ( Item ) : title = Field ( ) link = Field ( ) ... from scrapy.spider import BaseSpiderfrom scrapy.selector import HtmlXPathSelectorclass MySpider ( BaseSpider ) : name = `` myproject '' allowed_domains = [ `` example.com '' ] start_urls = [ `` http : //www.example.com '...
A web crawler in a self-contained python file
Python
Python supports chained comparisons : 1 < 2 < 3 translates to ( 1 < 2 ) and ( 2 < 3 ) .I am trying to make an SQL query using SQLAlchemy which looks like this : The results I got were not as expected . I 've turned the engine 's echo=True keyword , and indeed - the generated SQL query only included one of the two compa...
results = session.query ( Couple ) .filter ( 10 < Couple.NumOfResults < 20 ) .all ( )
Chained comparisons in SQLAlchemy
Python
I have a dataframe like this : I 'm trying to know the number of trips that each individual makes , so I would like to create a new column so the new table would probably look like this : Are there any possible solutions ? I would really appreciate if someone can help with it ! Thanks in advance !
IndividualID Trip1 Trip2 Trip3 Trip4 Trip5 Trip6 Trip7 Trip8 Trip9200100001 23 1 2 4 4 1 5 5 5200100002 21 1 12 3 1 55 7 7200100003 12 3 3 6 3 200100004 4 200100005 6 5 3 9 3 5 6 200100005 23 4 4 2 4 3 6 5 IndividualID Trip1 Trip2 Trip3 Trip4 Trip5 Trip6 Trip7 Trip8 Trip9 Chains200100001 23 1 2 4 4 1 5 5 5 9200100002 2...
How to count the number of columns with a value on each row in python ?
Python
How can I configure Django logging to support different DSNs for different loggers ? Something like this : settings.pyviews.py
LOGGING = { .. 'handlers ' : { 'sentry1 ' : { 'level ' : 'ERROR ' , 'class ' : 'raven.contrib.django.handlers.SentryHandler ' , 'dsn ' : ' < DSN1 > ' , } , 'sentry2 ' : { 'level ' : 'ERROR ' , 'class ' : 'raven.contrib.django.handlers.SentryHandler ' , 'dsn ' : ' < DSN2 > ' , } , } , 'loggers ' : { 'sentry1 ' : { 'hand...
Django/Raven/Sentry : different loggers for different DSNs
Python
Can you filter a list comprehension based on the result of the transformation in the comprehension ? For example , suppose you want to strip each string in a list , and remove strings that are just whitespace . I could easily do the following : But that iterates over the list twice . Alternatively you could do the foll...
filter ( None , [ x.strip ( ) for x in str_list ] ) [ x.strip ( ) for x in str_list if x.strip ( ) ] for x in str_list : x = x.strip ( ) if x : yield x
Python List Comprehension : Using `` if '' Statement on Result of the Comprehension
Python
I was wondering how to highlight diagonal elements of pandas dataframe using df.style method.I found this official link where they discuss how to highlight maximum value , but I am having difficulty creating function to highlight the diagonal elements.Here is an example : This gives following output : I am wanting a ye...
import numpy as npimport pandas as pddf = pd.DataFrame ( { ' a ' : [ 1,2,3,4 ] , ' b ' : [ 1,3,5,7 ] , ' c ' : [ 1,4,7,10 ] , 'd ' : [ 1,5,9,11 ] } ) def highlight_max ( s ) : `` ' highlight the maximum in a Series yellow. `` ' is_max = s == s.max ( ) return [ 'background-color : yellow ' if v else `` for v in is_max ]...
Pandas style : How to highlight diagonal elements
Python
You can sort a list of lists by length as follows : I ca n't figure out how to keep track of the indicies to then match up the contents of sorted_lists with the original list names l1 , l2 and l3.This gets close , but I 'm not sure how the solution can be implemented when sorting by length .
l1 = [ 1,2,3 ] l2 = [ 1,2,3 ] l3 = [ 1,2 ] lists = [ l1 , l2 , l3 ] sorted_lists = sorted ( lists , key=len ) print sorted_lists # [ [ 1,2 ] , [ 1,2,3 ] , [ 1,2,3 ] ]
Keeping track of original indicies when sorting a list of lists by length
Python
I accidentally found that in python , an operation of the formCan be equivalently expressed asFurthermore , after trying timeit with a few different sized inputs , this weird way to join seems to be more than twice as fast . Why should the join method be slower ? Is replacing the empty string like this a safe/well-defi...
string1.join ( string2 ) string2.replace ( `` , string1 ) [ len ( string1 ) : -len ( string1 ) ]
Replacing the empty strings in a string
Python
So , I have a list of groupsand I need to shuffle a flattened version of this listso that elements of the same group would end at some distance from each other . E. g. [ a , c , b , d , f , e ] and not [ a , c , b , d , e , f ] , because d and e are in the same group.I do n't care if the distance is just one element or...
[ [ ' a ' , ' b ' ] , [ ' c ' , 'd ' , ' e ' ] , [ ' f ' ] ] [ a , b , c , d , e , f ]
Specific shuffling list in Python
Python
EDIT : This video by Franchois Chollet says that Layer + training eval methods = ModelIn keras documentation it says that models are made up of layers . However in this section it shows that a model can be made up of models.So , what is the effective difference between Model and layers ? Is it just for code readability...
from keras.layers import Conv2D , MaxPooling2D , Input , Dense , Flattenfrom keras.models import Model # First , define the vision modulesdigit_input = Input ( shape= ( 27 , 27 , 1 ) ) x = Conv2D ( 64 , ( 3 , 3 ) ) ( digit_input ) x = Conv2D ( 64 , ( 3 , 3 ) ) ( x ) x = MaxPooling2D ( ( 2 , 2 ) ) ( x ) out = Flatten ( ...
Keras : What is the difference between model and layers ?
Python
I have a trivial WSGI app running on pesto , mod_wsgi and Apache : On my test machine , I get about 100kb/s of throughput , meaning the request takes about 12 seconds to complete . Downloading static files from the same Apache instance gives me about 20MB/s . Why is there such a huge difference , and how can I speed up...
def viewData ( request ) : return Response ( `` aaaaaaaaaa '' * 120000 ) # return 1,2MB of data
Low Apache/mod_wsgi throughput
Python
In Python 3.6 , the new Variable Annotations were introduced in the language . But , when a type does not exist , the two different things can happen : Why is the non-existing type handling behavior different ? Would not it potentially cause one to overlook the undefined types in the functions ? NotesTried with both Py...
> > > def test ( ) : ... a : something = 0 ... > > > test ( ) > > > > > > a : something = 0Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > NameError : name 'something ' is not defined
Variable type annotation NameError inconsistency
Python
Say I want to install pyodbc . It ca n't be build on some Windows machines but there 's an alternative - pypyodbc which is pure python implementation of pyobdc.Is there a way to specify install_requires= [ `` pyobdc '' ] for setuptools.setup with falling back to pypyodbc if the former package was n't installed ? UPD : ...
import sysfrom setuptools import setupif sys.platform.startswith ( `` win '' ) : pyodbc = `` pypyodbc > =1.2.0 '' else : pyodbc = `` pyodbc > =3.0.7 '' ... setup ( ... install_requires= [ pyobdc ] )
Alternative dependencies ( fall back ) in setup.py