lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Python
I 'd like to add a new keyword to Python and @ EliBendersky 's wonderful answer explains how to do this by changing the code and re-distributing the Python compiler.Is it possible to introduce a new keyword without changing the compiler code ? Perhaps introduce it through a library ? Edit : For example , I 'd like to a...
`` You ca n't take the sky from me '' matches '.+sky.+ '
Add new statements to Python without customizing the compiler
Python
I have a Box2D world with circles representing pedestrians and squares representing buildings , I have an algorithm which finds the nearest building and then it will turn at the edge but I have a problem that it will turn when it is exactly in the middle between the buildings , so the algorithm kind of works but not th...
def pedestrian_walk ( pedestrian , buildings ) : # # Find the building nearest to the pedestrian list_of_distances = [ ] for building in buildings : list_of_distances.append ( np.sqrt ( ( pedestrian.body.position [ 0 ] - building.footprint.position [ 0 ] ) **2 + ( pedestrian.body.position [ 1 ] - building.footprint.pos...
A circle changes its direction when exactly between two squares
Python
I 'm writing a script to make backups of various different files . What I 'd like to do is store meta information about the backup . Currently I 'm using the file name , so for example : Where c represents the file creation datetime , and d represents `` data time '' which represents what the cool_file actually contain...
backups/cool_file_bkp_c20120119_104955_d20120102
Is there a standard way , across operating systems , of adding `` tags '' to files
Python
I am trying to plot three graphs ( day , month , year ) and give the user the option to pick which graph they want to see with a dropdown menu . When I do it for ( day , month ) it works perfectly ( with month showing as the default graph ) , but when I add ( year ) , then ( day , month ) do n't show up ( in this scena...
# Plot Daytemp_day = pd.DataFrame ( df.day.value_counts ( ) ) temp_day.reset_index ( inplace=True ) temp_day.columns = [ 'day ' , 'tweet_count ' ] temp_day.sort_values ( by= [ 'day ' ] , inplace=True ) temp_day.reset_index ( inplace=True , drop=True ) trace_day = go.Scatter ( x=temp_day.day.values , y=temp_day.tweet_co...
Plotly : Dropdown menu wo n't show plots
Python
I have a list that looks likeHow can I convert this list of list into a text file that looks likeIt seemed straightforward but none of the solution on the web seemed concise and elucidating enough for dummies like me to understand.Thank you !
[ [ `` a '' , '' b '' , '' c '' , '' d '' ] , [ `` e '' , '' f '' , '' g '' , '' h '' ] , [ `` i '' , '' j '' , '' k '' , '' l '' ] ] a b c de f g hi j k l
writing list of list into a COLUMNED .txt file via python
Python
I am working on an online project by Udacity . I am using vagrant configured by them , to run the server containing the Database . Unfortunately when I tried to give the code persistence , the server returns an error everytime . I am new to python so please forgive any obvious mistakes.Here is the error : And this is t...
Serving HTTP on port 8000 ... Traceback ( most recent call last ) : File `` /usr/lib/python2.7/wsgiref/handlers.py '' , line 85 , in run self.result = application ( self.environ , self.start_response ) File `` forum.py '' , line 95 , in Dispatcher return DISPATCH [ page ] ( env , resp ) File `` forum.py '' , line 68 , ...
Pyscopg DB - Error Adding Persistence to code
Python
When I want to define my business logic , I 'm struggling finding the right way to do this , because I often both need a property AND a custom queryset to get the same info . In the end , the logic is duplicated.Let me explain ... First , after defining my class , I naturally start writing a simple property for data I ...
class PickupTimeSlot ( models.Model ) : @ property def nb_bookings ( self ) - > int : `` '' '' How many times this time slot is booked ? `` '' '' return self.order_set.validated ( ) .count ( ) class PickupTimeSlotQuerySet ( query.QuerySet ) : def add_nb_bookings_data ( self ) : return self.annotate ( db_nb_bookings=Cou...
Django : Duplicated logic between properties and queryset annotations
Python
I want to create a list which is the combination of incoming + outgoing . E.g incoming [ 0 ] [ 0 ] should be added to outgoing [ 0 ] [ 0 ] , incoming [ 0 ] [ 1 ] should be added to outgoing [ 0 ] [ 1 ] and so on . A list called joint will be produced and have the exact same structure as incoming and outgoing ( e.g a li...
outgoing= [ [ 27 , 42 , 66 , 85 , 65 , 64 , 68 , 68 , 77 , 58 ] , [ 24 , 39 , 58 , 79 , 60 , 62 , 67 , 62 , 55 , 35 ] , [ 3 , 3 , 8 , 6 , 5 , 2 , 1 , 6 , 22 , 23 ] , [ 3 , 3 , 8 , 6 , 5 , 2 , 1 , 6 , 22 , 23 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , ] incoming= [ [ 459 , 469 , 549 , 740 , 695 , 629 , 780 , 571 , ...
Python - List comprehension with 2 for loops & a ADD AND operand
Python
Working with PRAW , in my main thread I 've created a Reddit instance : Which works fine.As the code grows , I 've created various modules ( .py files ) which the main .py file where main is imports them into.There are times where these other modules need to access the above instance instead of creating a new one that ...
import prawreddit = praw.Reddit ( client_id='my client id ' , client_secret='my client secret ' , user_agent='my user agent ' )
Python : retain instance
Python
I have minute-by-minute stock data from 2017 to 2019.I want to keep only data after 9:16 for each daytherefore I want to convert any data between 9:00 to 9:16 as value of 9:16ie : value of 09:16 should beopen : value of 1st data from 9:00 - 9:16 , here 116.00high : highest value from 9:00 - 9:16 , here 117.00low : lowe...
open high low closedate 2017-01-02 09:08:00 116.00 116.00 116.00 116.002017-01-02 09:16:00 116.10 117.80 117.00 113.002017-01-02 09:17:00 115.50 116.20 115.50 116.202017-01-02 09:18:00 116.05 116.35 116.00 116.002017-01-02 09:19:00 116.00 116.00 115.60 115.75 ... ... ... ... ... 2029-12-29 15:56:00 259.35 259.35 259.35...
pandas combine stock data if it falls between specific time only in dataframe
Python
I am writing a custom loss function that requires calculating ratios of predicted values per group . As a simplified example , here is what my Data and model code looks like : What I need help with is the custom_loss function . As you can see , it is currently written as if the inputs are Pandas DataFrames . However , ...
def main ( ) : df = pd.DataFrame ( columns= [ `` feature_1 '' , `` feature_2 '' , `` condition_1 '' , `` condition_2 '' , `` label '' ] , data= [ [ 5 , 10 , `` a '' , `` 1 '' , 0 ] , [ 30 , 20 , `` a '' , `` 1 '' , 1 ] , [ 50 , 40 , `` a '' , `` 1 '' , 0 ] , [ 15 , 20 , `` a '' , `` 2 '' , 0 ] , [ 25 , 30 , `` b '' , `...
Keras custom loss function per tensor group
Python
In a Traversal pyramid app , how does one handle a resource w/ a __name__ that matches a view 's name ? If I wanted to get to the view callable `` view '' for a Resource , I 'd use a URL path like : /foo/bar/view . It traverses the resource_tree as so : ... and because it ca n't traverse past Bar & 'view ' is left over...
RootFactory ( request ) = > RootFactoryRootFactory [ 'foo ' ] = > FooFoo [ 'bar ' ] = > BarBar [ 'view ' ] = > KeyError @ view_config ( name='view ' ) def view ( context , request ) : return Response ( context.__name__ ) # path : /foo/viewRootFactory ( request ) = > RootFactoryRootFactory [ 'foo ' ] = > Foo # ideally s...
Pyramid Traversal __name__ matching a view name
Python
I am using a recurrent neural network to make hourly wind predictions based on previous wind data . I am trying to shift my data 1 hour back using the .shift to generate this . My DateFrame looks like [ this ] [ 1 ] My code is : The error message I am getting from this is :
import numpy as npimport pandas as pd from pandas import DataFrame wind_p = [ 0 , 0.03454225 , 0.02062136 , 0.00186715 , 0.01517354 , 0.0129046 , 0.02231125 , 0.01492537 , 0.09646542 , 0.28444476 ] Speed = [ 0 , 2.25226244 , 1.44078451 , 0.99174488 , 0.71179491 , 0.92824542 , 1.67776948 , 2.96399534 , 5.06257161 , 7.06...
KeyError when shifting column data back 1
Python
I am reading Learn You Some Erlang for Great Good ! and found out interesting puzzle . I decided to implement it in Python in a most functional way.Please see my code : But I hit into problem , I do n't know how to keep state of current location . Result is : [ 8 , 27 , 95 , 40 ] . Could you please help to fix my code ...
def open_file ( ) : file_source = open ( 'resource/path.txt ' , ' r ' ) # contains 50\n 10\n 30\n 5\n 90\n 20\n 40\n 2\n 25\n 10\n 8\n 0\n return file_sourcedef get_path_tuple ( file_source , pathList= [ ] ) : try : node = int ( next ( file_source ) ) , int ( next ( file_source ) ) , int ( next ( file_source ) ) pathLi...
Functional solution for short path algorithm in Python
Python
I have a list of lines Lines= ( [ ( ' B ' , ' C ' ) , ( 'D ' , ' A ' ) , ( 'D ' , ' C ' ) , ( ' A ' , ' B ' ) , ( 'D ' , ' B ' ) ] ) and geometry = ( ' B ' , ' C ' , 'D ' ) is a list of points that set up the triangle ( B , C , D ) . I want to check whether geometry can be set up from list of lines in Lines . How can I...
> > Lines= ( [ ( ' B ' , ' C ' ) , ( 'D ' , ' A ' ) , ( 'D ' , ' C ' ) , ( ' A ' , ' B ' ) , ( 'D ' , ' B ' ) , ] ) > > geometry1 = ( ' B ' , ' C ' , 'D ' ) > > check_geometry ( Lines , geometry1 ) True > > geometry2 = ( ' A ' , ' B ' , ' E ' ) > > check_geometry ( Lines , geometry2 ) False import itertoolsdef check_ge...
Checking that the geometry for a triangle is contained in a list of lines
Python
So this page about memoization got me curious . I ran my own benchmarks.1 ) Mutable default dictionary : Out:2 ) Same idea , but following the principle “ Easier to ask forgiveness than permission ” : Out : My questionsWhy is 2 ) so slow compared to 1 ) ? EditAs @ kevin suggest in the comments , I got the decorator com...
% % timeitdef fibo ( n , dic= { } ) : if n not in dic : if n in ( 0,1 ) : dic [ n ] = 1 else : dic [ n ] = fibo ( n-1 ) +fibo ( n-2 ) return dic [ n ] fibo ( 30 ) 100000 loops , best of 3 : 18.3 µs per loop In [ 21 ] : % % timeitdef fibo ( n , dic= { } ) : try : return dic [ n ] except : if n in ( 0,1 ) : dic [ n ] = 1...
Why is one memoization strategy slower than the other ?
Python
I am trying to make an spatial operation using sqlalchemy and geoalchemy2 on Python 3.5 . I have a table with points as a geom attribute . I have already read the table and follow the documentation instructions : This correctly returns me the name of the columns of my table . Now , I want to create a spatial subset of ...
metadata = MetaData ( ) table = Table ( 'table ' , metadata , autoload=True , schema = `` schema '' , autoload_with=engine ) print ( table.columns ) # Create session for queriesSession = sessionmaker ( bind=engine ) session = Session ( ) # SELECT * FROM table : q = session.query ( table ) .filter ( table.c.geom.ST_Inte...
Error spatially subsetting and PostGIS database
Python
Given a csv with the contents of something like : How can I print this out in python so that it would look like this : Do I have to create the table manually with + 's - 's and | 's taking into account respective column 's longest strings or is there a built-in method for this ? I did search for python tables , but not...
Colour , Red , Black , BlueTaste , Good , Bad , DisgustingSmell , Pleasant , Deceptive , Intolerable + -- -- -- -+ -- -- -- -- -- -+ -- -- -- -- -- -+|Colour |Taste | Smell |+ -- -- -- -+ -- -- -- -- -- -+ -- -- -- -- -- -+| Red |Good | Pleasant || Black | Bad | Deceptive || Blue | Disgusting|Intolerable|+ -- -- -- -+ ...
Table creation with csv data
Python
I have two arrays ( x1 and x2 ) of equal length that have overlapping ranges of values.I need to find a value q such that l1-l2 is minimized , andI need this to be reasonably high-performance since the arrays can be large . A solution using native numpy routines would be preferred .
l1 = x1 [ np.where ( x1 > q ) ] .shape [ 0 ] l2 = x2 [ np.where ( x2 < q ) ] .shape [ 0 ]
Find Value that Partitions two Numpy Arrays Equally
Python
I am working on an Agent class in Python 2.7.11 that uses a Markov Decision Process ( MDP ) to search for an optimal policy π in a GridWorld . I am implementing a basic value iteration for 100 iterations of all GridWorld states using the following Bellman Equation : T ( s , a , s ' ) is the probability function of succ...
# Returns all states in the GridWorlddef getStates ( ) # Returns all legal actions the agent can take given the current statedef getPossibleActions ( state ) # Returns all possible successor states to transition to from the current state # given an action , and the probability of reaching each with that actiondef getTr...
Why is shallow copy needed for my values dictionary to correctly update ?
Python
I 'm having an issue managing imports with a big software repo that we have . For sake of clarity , let 's pretend the repo looks something like this : Now our __init__.py files are setup so that we can do something like thisIn this example repo/utils/__init__.py would haveThis structure has worked out well for us from...
repo/ __init__.py utils/ __init__.py math.py readers.py ... ... from repo.utils import IniReader from .readers import IniReader , DatReader from repo.utils import IniReaderif __name__ == '__main__ ' : r = IniReader ( 'blah.ini ' ) print ( r.fields ) import numpy as npimport scipyimport tensorflowfrom .math import trans...
structuring a large python repository , to not import everything
Python
I 'm new to Python and initializing parameters for a X number of model runs . I need to create every possible combination from N dictionaries , each dictionary having nested data.I know that I need to use itertools.product somehow , but I 'm stuck on how to navigate the dictionaries . Maybe I should n't even be using d...
{ `` chisel '' : [ { `` type '' : `` chisel '' } , { `` depth '' : [ 152 , 178 , 203 ] } , { `` residue incorporation '' : [ 0.4 , 0.5 , 0.6 , 0.7 , 0.8 , 0.9 , 1.0 ] } , { `` timing '' : [ `` 10-nov '' , `` 10-apr '' ] } , ] , `` disc '' : [ { `` type '' : `` disc '' } , { `` depth '' : [ 127 , 152 , 178 , 203 ] } , {...
Every product/combination of nested dictionaries saved to DataFrame
Python
Using Python , is there any way to store a reference to a reference , so that I can change what that reference refers to in another context ? For example , suppose I have the following class : I would like to create something analogous to the following : Such that the following codeWould result in f.standalone equal to...
class Foo : def __init__ ( self ) : self.standalone = 3 self.lst = [ 4 , 5 , 6 ] class Reassigner : def __init__ ( self , target ) : self.target = target def reassign ( self , value ) : # not sure what to do here , but reassigns the reference given by target to value f = Foo ( ) rStandalone = Reassigner ( f.standalone ...
Storing a reference to a reference in Python ?
Python
I 'm not sure if this is an opinionated question or if it is me misunderstanding what 'implicit ' and 'explicit ' really means in the context of Python.I 'm trying to follow the Zen of Python rule , but I 'm curious to know if this applies in this situation or if I am over-thinking it ? Appreciate any guidance I can ge...
a = [ ] # my understanding is that this is implicitif not a : print ( `` list is empty '' ) # my understanding is that this is explicitif len ( a ) == 0 : print ( `` list is empty '' )
Zen of Python 'Explicit is better than implicit '
Python
Greetings.I searched for a long time , and found many related questions with no answer for me . Despite mine seems to be a simple beginner doubt.We have a ( I guess ) typical class definition : You get the idea . A lot of attributes . I need all of them.The question is : **Is there a shortcut to save all those `` self....
class Town : def __init__ ( self , Name , Ruler = `` Spanish Inquisition '' ) : self.Name = Name self.Population = 0 self.LocationX = 0 self.LocationY = 0 self.Religion = `` Jedi '' self.Ruler = Ruler self.Products = [ `` Redstone '' , `` Azaleas '' ] with self : Name = Name Population = 0 ...
How to not put self . when initializing every attribute in a Python class ?
Python
I 'd like to do : which is easy enough to do ( see code below ) for any x and any y except in the case that x is a str.Is there any way ( e.g . adding a special method or raising a specific error ) to cause old style string formatting to fail ( similarly to how 1 % doSomthing fails with a TypeError ) and revert to the ...
x % doSomething % y class BinaryMessage ( object ) : def __init__ ( self , fn ) : self._fn = fn def __rmod__ ( self , LHS ) : return BinaryMessagePartial ( self._fn , LHS ) class BinaryMessagePartial ( object ) : def __init__ ( self , fn , LHS ) : self._fn = fn self._LHS = LHS def __mod__ ( self , RHS ) : return self._...
Is it possible to overwrite str 's % behaviour using __rmod__ ?
Python
I am trying to combine the lists below to display a date in the format 'dd/hh : mm'.the lists are as follows : So combining the lists would look something likeand so on . I tried using a for loop ( below ) for this , but each time was unsurprisingly met withI know I ca n't combine int and str in this loop but am not su...
dd = [ 23 , 23 , 24 , 24 , 24 , 24 , 25 , 25 , 25 , 25 , 25 , 26 , 26 , 26 , 26 , 26 , 27 , 27 , 27 , 27 , 27 , 27 , 27 , 27 ] hh = [ 21 , 23 , 7 , 9 , 16 , 19 , 2 , 5 , 12 , 15 , 22 , 1 , 8 , 11 , 18 , 21 , 2 , 8 , 12 , 12 , 13 , 13 , 18 , 22 ] mm = [ 18 , 39 , 3 , 42 , 52 , 43 , 46 , 41 , 42 , 35 , 41 , 27 , 37 , 30 ...
Combining strings and ints to create a date string results in TypeError
Python
As a part of some unit testing code that I 'm writing , I wrote the following function . The purpose of which is to determine if ' a ' could be rounded to ' b ' , regardless of how accurate ' a ' or ' b ' are . Here 's some output from the function : As far as I can tell , it works . However , I 'm scared of relying on...
def couldRoundTo ( a , b ) : `` '' '' Can you round a to some number of digits , such that it equals b ? '' '' '' roundEnd = len ( str ( b ) ) if a == b : return True for x in range ( 0 , roundEnd ) : if round ( a , x ) == b : return True return False > > > couldRoundTo ( 3.934567892987 , 3.9 ) True > > > couldRoundTo ...
Python : a could be rounded to b in the general case
Python
I 've been writing a simple program in python that encodes a string into a number using Gödel 's encoding . Here 's a quick overview : you take the first letter of the string , find its position in the alphabet ( a - > 1 , b - > 2 , ... , z - > 26 ) and raise the first prime number ( 2 ) to this power . The you take th...
import string , mathalphabet = list ( string.ascii_lowercase ) def primes ( n ) : `` Returns a list of primes up to n. '' primes = [ 2 , 3 ] i = 5 while i < n : l = math.ceil ( math.sqrt ( i ) ) k = math.ceil ( math.sqrt ( i+2 ) ) for p in primes [ : l ] : if i % p == 0 : break else : primes.append ( i ) for p in prime...
Checking divisibility for ( sort of ) big numbers in python
Python
Here is my code.And the output is I have no idea why there is this 4.Pardon me if i made some noobish mistake , as i ca n't seem to figure it out .
# Prime numbers between 0-100for i in range ( 2,100 ) : flg=0 for j in range ( 2 , int ( i/2 ) ) : if i % j==0 : flg=1 break if flg ! =1 : print ( i ) 234 < -57111317192329313741434753596167717379838997
There is a 4 in my prime number list generated in Python
Python
Very simple question : Specifically in Python ( since Python actually has `` strongly recommended '' style guidelines specified in PEP 8 , but really this applies to any language ) , should a function with an if clause that always returns have the alternative code in an else clause or not ? In other words , func_style_...
def func_style_one ( ) : if some_conditional_function ( ) : do_something ( ) return something ( ) else : do_something_else ( ) return something_else ( ) def func_style_two ( ) : if some_conditional_function ( ) : do_something ( ) return something ( ) do_something_else ( ) return something_else ( )
Preferred Python ( or any language , really ) style : Should else be used when if returns ?
Python
I have a regex that looks for numbers in a file.I put results in a list The problem is that it prints each results on a new line for every single number it finds . it aslo ignore the list I 've created.What I want to do is to have all the numbers into one list.I used join ( ) but it does n't works.code : output :
def readfile ( ) : regex = re.compile ( '\d+ ' ) for num in regex.findall ( open ( '/path/to/file ' ) .read ( ) ) : lst = [ num ] jn = `` .join ( lst ) print ( jn ) 12234764
joining output from regex search
Python
I get the following result when testing the performance of struct.pack : Why is the slowest run 578 times slower ? Is pack doing some internal caching , or is this the result of some sort of CPU-level caching , or something else ?
In [ 3 ] : % timeit pack ( 'dddd ' , 1.0 , 1.0 , 1.0 , 1.0 ) The slowest run took 578.59 times longer than the fastest . This couldmean that an intermediate result is being cached 1000000 loops , best of 3 : 197 ns per loop
Why does struct.pack have such high variability in performance ?
Python
I convert [ int , bool , float ] to [ 'int ' , 'bool ' , 'float ' ] using many lines of command.How to accomplish such a task in an elegant manner ?
Numbers = [ int , bool , float ] > > > [ i for i in Numbers ] [ < class 'int ' > , < class 'bool ' > , < class 'float ' > ] > > > foo = [ str ( i ) for i in Numbers ] > > > foo [ `` < class 'int ' > '' , `` < class 'bool ' > '' , `` < class 'float ' > '' ] > > > bar = [ i.replace ( ' < class ' , '' ) for i in foo ] > >...
Is it possible to convert [ int , bool , float ] to [ 'int ' , 'bool ' , 'float ' ] with one single line command ?
Python
Is it possible to nest yield from statements ? The simple form is obvious : Which produces : But what if I have nested generators ? This produces : Why does it produce None if I used yield from ( even though it is nested ) ? I know I can do something like : Which produces the same output leaving out the None ( which is...
def try_yield1 ( ) : x = range ( 3 ) yield from x 012 def try_yield_nested ( ) : x = [ range ( 3 ) for _ in range ( 4 ) ] yield from ( ( yield from y ) for y in x ) 012None # why ? 012None # ... 012None # ... from itertools import chaindef try_yield_nested_alternative ( ) : x = [ range ( 3 ) for _ in range ( 4 ) ] yiel...
Why does nesting `` yield from '' statements ( generator delegation ) produce terminating ` None ` value ?
Python
Assume we define a function and then end it with : Another option is to end a function with a print : Question : May I end function with a return statement , get it via function ( ) or not ? I mean I do n't care whether function saves the result or not . However the function can have several different results , i.e I n...
def function ( ) : # ... return result # To see the result , we need to type : print ( function ( ) ) def function ( ) : # ... print ( result ) # no need of print at the call anymore sofunction ( )
What 's the best between return the result and print it at the end of the function ?
Python
why this one worksand prints out : while thisdoes not
def fun ( a , b , c , d ) : print ( ' a : ' , a , ' b : ' , b , ' c : ' , c , 'd : ' , d ) fun ( 3 , 7 , d=10 , * ( 23 , ) ) a : 3 b : 7 c : 23 d : 10 fun ( 3 , 7 , c=10 , * ( 23 , ) ) Traceback ( most recent call last ) : File `` /home/lookash/PycharmProjects/PythonLearning/learning.py '' , line 10 , in < module > fun...
Python - value unpacking order in method parameters
Python
If expression is False , does [ on_true ] still get evaluated ? Reason I ask is because I have a django ORM query as the [ on_true ] and will write this another way if it evaluates every time this line is run .
[ on_true ] if [ expression ] else [ on_false ]
Python ternary order of operations
Python
I trained LSTM classification model , but got weird results ( 0 accuracy ) . Here is my dataset with preprocessing steps : and here is my model with resuslts : Why do I get 0 accuracy ?
import pandas as pdfrom sklearn.model_selection import train_test_splitimport tensorflow as tffrom tensorflow import kerasimport numpy as npurl = 'https : //raw.githubusercontent.com/MislavSag/trademl/master/trademl/modeling/random_forest/X_TEST.csv'X_TEST = pd.read_csv ( url , sep= ' , ' ) url = 'https : //raw.githubu...
0 accuracy with LSTM
Python
Possible Duplicate : Is there any difference between “ foo is None ” and “ foo == None ” ? Quite a simple question really.Whats the difference between : andexcuse my ignorance
if a.b is 'something ' : if a.b == 'something ' :
difference between 'is ' and '== '
Python
I just ran the following code in Python to take all of the certain emails out of an IMAP folder . The extraction part works fine and the BeautifulSoup part works okay , but the output has a lot of '\r ' and '\n ' within . I tried to remove these with REGEX sub function but it 's not working ... not even giving an error...
mail.list ( ) # Lists all labels in GMailmail.select ( 'INBOX/Personal ' ) # Connected to inbox.resp , items = mail.search ( None , ' ( SEEN ) ' ) items = items [ 0 ] .split ( ) # getting the mails id for emailid in items : # getting the mail content resp , data = mail.fetch ( emailid , ' ( UID BODY [ TEXT ] ) ' ) text...
beautiful soup regex
Python
I was learning the itertools module and I am trying to make an iterator to return each element from the iterables provided as input.with one more rider that if say the lists are not of the same length then next ( it ) should return elements from the longer list when the shorter one runs out.Attempt at solutionWhich kin...
Agruments Resultsp , q , … p0 , q0 , … plast , qlast import itertoolsl1= [ 1,2,3,4,5,6 ] l2= [ ' a ' , ' b ' , ' c ' , 'd ' ] l= [ ] for x , y in itertools.zip_longest ( l1 , l2 ) : l.extend ( [ x , y ] ) it=iter ( x for x in l if x is not None ) print ( list ( it ) ) [ 1 , ' a ' , 2 , ' b ' , 3 , ' c ' , 4 , 'd ' , 5 ...
Create iterator to return elements from each iterable one by one
Python
I 'm working on the Rosalind problem Mortal Fibonacci Rabbits and the website keeps telling me my answer is wrong when I use my algorithm written JavaScript . When I use the same algorithm in Python I get a different ( and correct ) answer.The inconsistency only happens when the result gets large . For example fibd ( 9...
function fibd ( n , m ) { // Create an array of length m and set all elements to 0 var rp = new Array ( m ) ; rp = rp.map ( function ( e ) { return 0 ; } ) ; rp [ 0 ] = 1 ; for ( var i = 1 ; i < n ; i++ ) { // prepend the sum of all elements from 1 to the end of the array rp.splice ( 0 , 0 , rp.reduce ( function ( e , ...
Javascript is giving a different answer to same algorithm in Python
Python
I have two DataFrames containing the same columns ; an id , a date and a str : I would like to join these two datasets on the id and date columns , and create a resulting column that is the concatenation of str : I guess I can make an inner join and then concatenate the strings , but is there an easier way to achieve t...
df1 = pd.DataFrame ( { 'id ' : [ ' 1 ' , ' 2 ' , ' 3 ' , ' 4 ' , '10 ' ] , 'date ' : [ ' 4 ' , ' 5 ' , ' 6 ' , ' 7 ' , ' 8 ' ] , 'str ' : [ ' a ' , ' b ' , ' c ' , 'd ' , ' e ' ] } ) df2 = pd.DataFrame ( { 'id ' : [ ' 1 ' , ' 2 ' , ' 3 ' , ' 4 ' , '12 ' ] , 'date ' : [ ' 4 ' , ' 5 ' , ' 6 ' , ' 7 ' , ' 8 ' ] , 'str ' :...
Concatenate strings based on inner join
Python
Initialising the Foo object does run the method func ( ) , but the value of self.a gets set to None anyway . How can I get the following code to work ? The output is :
# ! /usr/bin/env pythonclass Foo ( object ) : def __init__ ( self , num ) : self.a = self.func ( num ) print self.a def func ( self , num ) : self.a = range ( num ) print self.a def __str__ ( self ) : return str ( self.a ) def main ( ) : f = Foo ( 20 ) print fif __name__ == `` __main__ '' : main ( ) [ 0 , 1 , 2 , 3 , 4...
Ca n't set class attributes in python using a method
Python
I though that a += b is just a shortcut for a = a + b . It seems it is not quite . Here 's an example : But this works as expected : Now , I understand that when I do b = a , b references the same list as a does , and if I do some operations on b , they automatically `` apply '' to a ( since they both point to the same...
> > > a = [ 1 , 2 , 3 ] > > > b = a > > > b += [ 4 , 5 , 6 ] > > > b [ 1 , 2 , 3 , 4 , 5 , 6 ] > > > a # is also changed [ 1 , 2 , 3 , 4 , 5 , 6 ] > > > a = [ 1 , 2 , 3 ] > > > b = a > > > b = b + [ 4 , 5 , 6 ] > > > b [ 1 , 2 , 3 , 4 , 5 , 6 ] > > > a # not changed [ 1 , 2 , 3 ]
Python 's += operator and lists
Python
I thought the print statement just called the .write ( ) method on the sys.stdout ( by default ) object.but having written a subclass like this : It seems to work if I create a logfile object and call the write method , but when trying to change the sys.stdout object to an instance of the logfile it appears as though p...
import timeclass logfile ( file ) : def __init__ ( self , *args , **kwargs ) : file.__init__ ( self , *args , **kwargs ) def write ( self , logstr ) : if logstr [ -1 ] ! = '\n ' : logstr += '\n ' super ( logfile , self ) .write ( time.strftime ( ' % D- % T ' ) + str ( logstr ) ) # ! /usr/bin/pythonfrom myfile import lo...
pythons 'print ' statement does n't call the .write ( ) method ?
Python
ProblemI came across this code in Object Oriented Programming by Dusty Phillips ( simplified for brevity ) and I unsure about a specific part of this definition.QuestionsSince the method resolution order is ( __main__.C , __main__.A , __main__.B , object ) , could class B be defined in the following way instead ? Is n'...
class A : def __init__ ( self , a , **kwargs ) : super ( ) .__init__ ( **kwargs ) self.a = aclass B : def __init__ ( self , b , **kwargs ) : super ( ) .__init__ ( **kwargs ) self.b = bclass C ( A , B ) : def __init__ ( self , c , **kwargs ) : super ( ) .__init__ ( **kwargs ) self.c = c class B : def __init__ ( self , b...
Multiple Inheritance with kwargs
Python
This question pertains to ( at least ) CPython 2.7.2 and 3.2.2.Suppose we define Class and obj as follows.Short versionWhy does the following code output False for each print ( ) ? ( That 's for Python 2 ; for Python 3 , omit the print ( ) for Class.m and add similar print ( ) s for obj.__eq__ , obj.__ge__ , obj.__gt__...
class Class ( object ) : def m ( self ) : pass @ property def p ( self ) : return None @ staticmethod def s ( ) : passobj = Class ( ) print ( Class.__dict__ is Class.__dict__ ) print ( Class.__subclasshook__ is Class.__subclasshook__ ) print ( Class.m is Class.m ) print ( obj.__delattr__ is obj.__delattr__ ) print ( ob...
Why do some expressions that reference ` x.y ` change ` id ( x.y ) ` ?
Python
I have a pandas.DatetimeIndex for an interval [ '2018-01-01 ' , '2018-01-04 ' ) ( start included , end excluded ) and freq=1D : How can I obtain the correct open end='2018-01-04 ' attribute again ? I need it for a DB query with timestamp ranges.There is no index.endindex [ -1 ] returns '2018-01-03'index [ -1 ] + index....
> > > index = pd.DatetimeIndex ( start='2018-01-01 ' , end='2018-01-04 ' , freq='1D ' , closed='left ' ) DatetimeIndex ( [ '2018-01-01 ' , '2018-01-02 ' , '2018-01-03 ' ] , dtype='datetime64 [ ns ] ' , freq='D ' )
Can pandas.DatetimeIndex remember whether it is closed ?
Python
I found some questions asking about TypeError : 'tuple ' object does not support item assignment on SO , but still , I 'm confused about this : Consider the code snippet : My questions are : tuples are immutable , but 1 successfully changed its value.Why ? ( I know I dont really understand python immutability.. ) If 1 ...
> > > a = ( [ ] , [ ] ) > > > a [ 0 ] .append ( 1 ) # 1 > > > a ( [ 1 ] , [ ] ) > > > a [ 0 ] += [ 2 ] Traceback ( most recent call last ) : File `` < pyshell # 5 > '' , line 1 , in < module > a [ 0 ] += [ 2 ] TypeError : 'tuple ' object does not support item assignment # 2 > > > a ( [ 1 , 2 ] , [ ] ) # 3 > > >
python tuple , can someone explain this behavior ?
Python
I 'm making a very basic command line utility using python , and I 'm trying to set it up such that the user has the ability to interrupt any running operation during execution with Ctrl+C , and exit the program by sending an EOF with Ctrl+Z . However , I 've been fighting with this frustrating issue for the last day w...
import timedef parse ( inp ) : time.sleep ( 1 ) print ( inp ) if inp == ' e ' : return 'exit'while True : try : user_in = input ( `` > `` ) .strip ( ) except ( KeyboardInterrupt , Exception ) as e : print ( e.__class__.__name__ ) continue if not user_in : continue try : if parse ( user_in ) == 'exit ' : break except Ke...
Ctrl+C sends EOFError once after cancelling process
Python
I have a list `` records '' like thisI want to remove records that are `` duplicates '' , where equality is defined by a list of logical conditions . Each element in the list is an OR condition , and all elements are ANDed together . For example : means that two records are considered equal if their name AND ( their pr...
data = [ { 'id':1 , 'name ' : ' A ' , 'price ' : 10 , 'url ' : 'foo ' } , { 'id':2 , 'name ' : ' A ' , 'price ' : 20 , 'url ' : 'bar ' } , { 'id':3 , 'name ' : ' A ' , 'price ' : 30 , 'url ' : 'baz ' } , { 'id':4 , 'name ' : ' A ' , 'price ' : 10 , 'url ' : 'baz ' } , { 'id':5 , 'name ' : ' A ' , 'price ' : 20 , 'url '...
Comparing dictionaries based on a combination of keys
Python
I have a some nested loops ( three total ) where I 'm trying to use numpy.einsum to speed up the calculations , but I 'm struggling to get the notation correct . I managed to get rid of one loop , but I ca n't figure out the other two . Here 's what I 've got so far : While this was much faster than the original , this...
import numpy as npimport timedef myfunc ( r , q , f ) : nr = r.shape [ 0 ] nq = q.shape [ 0 ] y = np.zeros ( nq ) for ri in range ( nr ) : for qi in range ( nq ) : y [ qi ] += np.einsum ( ' i , i ' , f [ ri , qi ] *f [ : ,qi ] , np.sinc ( q [ qi ] *r [ ri , : ] /np.pi ) ) return yr = np.random.random ( size= ( 1000,100...
removing loops with numpy.einsum
Python
As per the subject line , is there a standard Python 2.7 library call that I can use like this : The catch is that I want all three forms of output : the returncode and the entire ( and separate ) content from both stdout and stderr . I expected to find something like this in the subprocess module , but the closest I c...
( returncode , stdout , stderr ) = invoke_subprocess ( args , stdin ) def method ( args , input ) : from subprocess import Popen , PIPE p = Popen ( args , stdin=PIPE , stdout=PIPE , stderr=PIPE ) out , err = p.communicate ( input ) return ( p.poll ( ) , out , err )
Is there a Python subprocess-like call that takes a stdin input string and returns stderr , stdout , and return code ?
Python
I am using neurolab in python to create a neural-netowork . I create a newff network and am using the default train_bfgs training function . My problem is a lot of times , the training just ends way before either the epochs run out or even the error target is reached . I looked around and found a post on neurolabs gith...
trainingComplete = Falsewhile not trainingComplete : error = net.train ( trainingData , TS , epochs=50 , show=10 , goal=0.001 ) if len ( error ) < 0.8*epochs : if len ( error ) > 0 and min ( error ) < 0.01 : trainingComplete = True else : net.reset ( ) continue else : trainingComplete = True
Neurolab retrain the network
Python
I maintain a project that has a function definition similar to this : While debugging the code I discovered that a .1 key appeared in locals ( ) , with the value ( b1 , b2 ) . A quick check revealed that a function definition like the following : will have a .0 key in locals ( ) with the value ( a1 , a2 ) . I was surpr...
def f ( a , ( b1 , b2 ) , c ) : print locals ( ) def f ( ( a1 , a2 ) ) : print locals ( )
Does the inaccessible ` .0 ` variable in ` locals ( ) ` affect memory or performance ?
Python
These two questions concern using import inside a function vs. at the top of a module . I do not need to be convinced to put my imports at the top , there are good reasons to do that . However , to better understand the technical issues I would like to ask a followup.Can you get the best of both worlds performance-wise...
import sysdef get_version ( ) : return sys.version def get_version ( ) : import sys return sys.version def _get_version ( ) : import sys def nested ( ) : return sys.version global get_version get_version = nested return nested ( ) get_version = _get_version
Can you optimize imports in functions using closures ?
Python
I am looking at making iterable objects and am wondering which of these two options would be the more pythonic/better way , is there no difference or have I got wrong idea about using yield ? To me using yield seems cleaner and apparently it is faster than using __next__ ( ) but i 'm not sure.Using yield :
class iterable_class ( ) : def __init__ ( self , n ) : self.i = 0 self.n = n def __iter__ ( self ) : return self def __next__ ( self ) : if self.i < self.n : i = self.i self.i += 1 return i else : raise StopIteration ( ) class iterable_class_with_generator ( ) : def __init__ ( self , n ) : self.i = 0 self.n = n def __i...
Iterable using yield or __next__ ( )
Python
Is it possible ? Obviously x [ 1 : -1 ] .sort ( ) does n't work because the slice is a copy . Current workaround : Can I somehow get a view on a python list ?
> > > x = [ 4 , 3 , 1 , 2 , 5 ] > > > s = slice ( 1 , -1 ) > > > x [ s ] = sorted ( x [ s ] ) > > > x [ 4 , 1 , 2 , 3 , 5 ]
In-place sort of sublist
Python
To train a neural network , I modified a code I found on YouTube . It looks as follows : Now , I tried to train a neural network using this code , train sample size is 105.000 ( image files which contain 8 characters out of 37 possibilities , A-Z , 0-9 and blank space ) .I used a relatively small batch size ( 32 , I th...
def data_generator ( samples , batch_size , shuffle_data = True , resize=224 ) : num_samples = len ( samples ) while True : random.shuffle ( samples ) for offset in range ( 0 , num_samples , batch_size ) : batch_samples = samples [ offset : offset + batch_size ] X_train = [ ] y_train = [ ] for batch_sample in batch_sam...
How to get Data Generator more efficient ?
Python
With respect to these models : I want to create a view that displays forms for all of the current projects . This is easy using a modelformset_factory . But how can I also add an additional form to each of these project form instances so that an Update to the project ( foreign key ) can be made ? Ideally the user makes...
class Projects ( models.Model ) : projectDescription = models.CharField ( max_length=50 , blank=True , null = True , ) status = models.IntegerField ( choices = Status_CHOICES , default = 4 ) projectOwner = models.ForeignKey ( staff , on_delete=models.CASCADE , blank=True , null = True , ) class Updates ( models.Model )...
how to add a different model form to modelformset_factory
Python
I 'm a little curious why the following code raises a NameError.At the normal interpreter level , we can find foo in bar.func_globals or bar.func_closure if in a function . I guess I 'm wondering why namespace [ 'bar ' ] does n't put foo in func_closure ...
> > > s = `` '' '' ... foo = [ 1,2,3 ] ... def bar ( ) : ... return foo [ 1 ] ... `` '' '' > > > namespace = { } > > > exec ( s , { '__builtins__ ' : None } , namespace ) > > > print namespace { 'foo ' : [ 1 , 2 , 3 ] , 'bar ' : < function bar at 0x7f79871bd0c8 > } > > > namespace [ 'bar ' ] ( )
exec does n't pick up variables from closure
Python
I have a api with a before hook . I want to patch it to my custom_function.Any idea how do I do it ? I have already patch falcon.before to my custom_falcon_before.second print is False.My API model is as below
class TestModel ( MyTestCase ) : def falcon_before ( self , model_exists ) : return model_exists def model_exists ( self , req , resp , resource , params , require_exists ) : pass @ patch ( `` app.views.expect_model_existence '' , side_effect=model_exists ) @ patch ( `` falcon.before '' , side_effect=falcon_before ) de...
Patching Falcon hook
Python
I have a DataFrame that looks like such : I want to create a DataFrame with roughly 1440 columns labled as timestamps , where the respective daily value is the return over the prior minute : My issue is that this is a very large DataFrame ( several GB ) , and I need to do this operation multiple times . Time and memory...
closingDate Time Last0 1997-09-09 2018-12-13 00:00:00 10001 1997-09-09 2018-12-13 00:01:00 1002 2 1997-09-09 2018-12-13 00:02:00 1001 3 1997-09-09 2018-12-13 00:03:00 1005 closingDate 00:00:00 00:01:00 00:02:000 1997-09-09 2018-12-13 -0.08 0.02 -0.001 ... 1 1997-09-10 2018-12-13 ...
pandas - efficiently computing minutely returns as columns on intraday data
Python
In google appengine NDB there are queries like this : How come the Account.userid > = 40 expression is not expanded at call time to true or false before passed as an argument ? How is the filter expression passed to the query ? Is it done with operator overloading ?
query = Account.query ( Account.userid > = 40 )
Why is this python expression parameter is not expanded at call time ?
Python
I have a ( really big ) pandas Dataframe df : I have another pandas Dataframe freq : I wan na count the pair of values in freq when they occur in df : I 'm using this code , but it takes too long : Is there a faster way to do that ? Please note : I have to use freq because not all combinations ( as for instance 20 and ...
country age genderBrazil 10 FUSA 20 F Brazil 10 FUSA 20 MBrazil 10 MUSA 20 M age gender counting 10 F 0 10 M 0 20 F 0 age gender counting 10 F 2 10 M 1 20 F 1 for row in df.itertuples ( index=False ) : freq.loc [ np.all ( freq [ 'age ' , 'gender ' ] ==row [ 2:3 ] , axis=1 ) , 'counting ' ] += 1
How to count the occurrence of values in one pandas Dataframe if the values to count are in another ( in a faster way ) ?
Python
Is there a faster , more pythonic way of doing this ? What isgenerating this warning UserWarning : Boolean Series key will bereindexed to match DataFrame index . `` DataFrame index . `` , UserWarningand should I be concerned with it ? I have a csv file with 3 columns : org , month , person.Which I 've read into a panda...
| org | month | person || -- - | -- -- -- -- -- | -- -- -- || 1 | 2014-01-01 | 100 || 1 | 2014-01-01 | 200 || 1 | 2014-01-02 | 200 || 2 | 2014-01-01 | 300 | data = pd.read_csv ( 'data_base.csv ' , names= [ 'month ' , 'org ' , 'person ' ] , skiprows=1 ) org : 1 , month : 2014-01-01 , count ( intersection ( ( 100 , 200 )...
How should I structure and access a table of data so that I can compare subsets easily in Python 3.5 ?
Python
Suppose that I have the following observations of integers : I know that this can be used as an input to make a density plot : but suppose that what I have is a counts table : which is cheaper to store than the full observed_scores Series ( I have LOTS of observations ) .I know it 's possible to plot the histogram usin...
df = pd.DataFrame ( { 'observed_scores ' : [ 100 , 100 , 90 , 85 , 100 , ... ] } ) df [ 'observed_scores ' ] .plot.density ( ) df = pd.DataFrame ( { 'observed_scores ' : [ 100 , 95 , 90 , 85 , ... ] , 'counts ' : [ 1534 , 1399 , 3421 , 8764 , ... } )
how to convert a dataframe of counts to a probability density function
Python
I came across a different type of problem while scraping a webpage using python . When an image is clicked , new information concerning its ' flavor comes up under the image . My goal is to parse all the flavors connected to each image . My script can parse the flavors of currently active image but breaks after clickin...
from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECdriver = webdriver.Chrome ( ) driver.get ( `` https : //www.optigura.com/uk/product/gold-standard-100-whey/ '' ) wait = WebDrive...
How can I activate each item and parse their information ?
Python
I 'm no novice when creating cross-platform runtimes of my python desktop apps . I create various tools for my undergraduates using mostly pyinstaller , cxfreeze , sometimes fbs , and sometimes briefcase . Anyone who does this one a regular basis knows that there are lots of quirks and adjustments needed to target Linu...
/home/nogard/Desktop/cppyytest/target/MyApp/cppyy_backend/loader.py:113 : UserWarning : No precompiled header available ( [ Errno 2 ] No such file or directory : '/home/nogard/Desktop/cppyytest/target/MyApp/cppyy_backend ' ) ; this may impact performance.Traceback ( most recent call last ) : File `` main.py '' , line 5...
Is there *any* solution to packaging a python app that uses cppyy ?
Python
I have that Code example : As you can see , both clients are mostly identical and shall contain the same name ( so that everyone knows what to expect ) . Now I want to be DRY and write bird_async ( bird ) . Because every extension in bird shall be used in bird_async as well . This is possible , but my coworker says , i...
from time import sleepimport asyncioclass bird : def __init__ ( self , sleeptime=1 ) : self.var = sleeptime def wait_meep ( self ) : sleep ( self.var ) print ( `` Meep '' ) def do_sth ( self ) : print ( `` Dop Dop Do do ... '' ) class bird_async : def __init__ ( self , sleeptime=1 ) : self.var = sleeptime async def wai...
Stay SOLID and DRY with coroutines and functions as methods in python
Python
I 'm trying to figure out how to add a security layer to my Dask Cluster deployed using helm on GKE on GCP , that would force a user to input the certificate and key files into the Security Object , as explained in this documentation [ 1 ] . Unfortunately , I get a timeout error from the scheduler pod crashing . Upon i...
Traceback ( most recent call last ) : File `` /opt/conda/bin/dask-scheduler '' , line 10 , in < module > sys.exit ( go ( ) ) File `` /opt/conda/lib/python3.7/site-packages/distributed/cli/dask_scheduler.py '' , line 226 , in go main ( ) File `` /opt/conda/lib/python3.7/site-packages/click/core.py '' , line 764 , in __c...
Dask : How to Add Security ( TLS/SSL ) to Dask Cluster ?
Python
I have a dataframe like this : I want the result to be like this : As you see the name of the column has been replaced if there is 1 in that column . and all has been put in another array.I have looked at this post link but it did not help me as the name has changed staticly.Thanks : )
ADR WD EF INF SSI DI0 1.0 NaN NaN NaN NaN NaN1 NaN NaN 1 1 NaN NaN2 NaN NaN NaN NaN 1 NaN3 NaN 1 1 1 NaN NaN4 NaN 1.0 NaN NaN NaN NaN [ [ `` ADR '' ] , [ `` EF '' , '' INF '' ] , [ `` SSI '' ] , [ `` WD '' , '' EF '' , '' INF '' ] , [ `` WD '' ] ]
how to put column name into data frame cell with specific conditions in pandas
Python
I am trying to understand how the fft and ifft functions work in python . I made a simple example of an imaginary odd function to compute the inverse Fourier transform in the hopes of getting a real odd function ( as should be the case ) . Below is my code : Clearly , the function sampled by v is an odd imaginary funct...
v = np.array ( [ -1 , -2,0,2,1 ] ) * 1jt = [ -2 , -1,0,1,2 ] V = ifft ( fftshift ( v ) )
Python Inverse Fourier Transform of Imaginary Odd Function
Python
I have the following table . Some values are NaNs . Let 's assume that columns are highly correlated . Taking row 0 and row 5 I say that value in col2 will be 4.0 . Same situation for row 1 and row 4 . But in case of row 6 , there is no perfectly matching sample so I should take most similar row - in this case , row 0 ...
example = pd.DataFrame ( { `` col1 '' : [ 3 , 2 , 8 , 4 , 2 , 3 , np.nan ] , `` col2 '' : [ 4 , 3 , 6 , np.nan , 3 , np.nan , 5 ] , `` col3 '' : [ 7 , 8 , 9 , np.nan , np.nan , 7 , 7 ] , `` col4 '' : [ 7 , 8 , 9 , np.nan , np.nan , 7 , 6 ] } ) col1 col2 col3 col40 3.0 4.0 7.0 7.01 2.0 3.0 8.0 8.02 8.0 6.0 9.0 9.03 4.0 ...
Filling missing values with values from most similar row
Python
I 'm trying to perform an action after the update of member properties on @ @ personal-information , but the event is not being fired . On configure.zcml I 've put the following : I 've already tried to use ipdb to check if propertiesUpdated of subscribers.py is being executed , but it 's not.I 've checked the https : ...
< subscriber for= '' Products.PluggableAuthService.interfaces.events.IPropertiesUpdatedEvent '' handler= '' .subscribers.propertiesUpdated '' / >
Plone memberdata update : PropertiesUpdatedEvent not triggered
Python
I 'm writing a small function to check if all elements in a list are less than or equal to a limit . This is just for practice , and should be done without using any loops.Been on this for a while but I can not find any substituting code to replace the for loop.This code works perfectly fine as it is - however , I am t...
def small_enough ( a , limit ) : return all ( x < = limit for x in a ) small_enough ( [ 66 , 101 ] , 200 )
Condition statement without loops
Python
I have a difficult issue regarding rows in a PySpark DataFrame which contains a series of json strings.The issue revolves around that each row might contain a different schema from another , so when I want to transform said rows into a subscriptable datatype in PySpark , I need to have a `` unified '' schema.For exampl...
import pandas as pdjson_1 = ' { `` a '' : 10 , `` b '' : 100 } 'json_2 = ' { `` a '' : 20 , `` c '' : 2000 } 'json_3 = ' { `` c '' : 300 , `` b '' : `` 3000 '' , `` d '' : 100.0 , `` f '' : { `` some_other '' : { `` A '' : 10 } , `` maybe_this '' : 10 } } 'df = spark.createDataFrame ( pd.DataFrame ( { ' A ' : [ 1 , 2 ,...
Unify schema across multiple rows of json strings in Spark Dataframe
Python
In my main file ( root level ) , I have : And I also have an __init__.py that has : I have a directory structure that looks like : But I get an error : I also tried : but get the same error.What am I doing wrong ?
from deepspeech2_utils import reduce_tensor , check_loss from submodules.deepspeech2 import utils as deepspeech2_utils main.py__init__.py-submodules -deepspeech2 -utils.py from deepspeech2_utils import reduce_tensor , check_lossImportError : No module named deepspeech2_utils from submodules.deepspeech2.utils import red...
How do I import something from a nested child directory with Python ?
Python
Running : Results in : Same statement but opposite results . Why ?
a = 257b = 257print id ( a ) == id ( b )
When the Python interpreter deals with a .py file , is it different from dealing with a single statement ?
Python
I have a dictionary : ( Note : My dictionary is n't actually numbers to strings ) I am passing this dictionary into a function that calls for it . I use the dictionary often for different functions . However , on occasion I want to send in big_dict with an extra key : item pair such that the dictionary I want to send i...
big_dict = { 1 : '' 1 '' , 2 : '' 2 '' , ... 1000 : '' 1000 '' } big_dict [ 1001 ] = '' 1001 '' big_dict [ 1001 ] = '' 1001 '' function_that_uses_dict ( big_dict ) del big_dict [ 1001 ] function_that_uses_string ( myString + 'what I want to add on ' )
How to pass in a dictionary with additional elements in python ?
Python
I am attempting to unit test some Python 3 code that imports a module . Unfortunately , the way the module is written , simply importing it has unpleasant side effects , which are not important for the tests . I 'm trying to use unitest.mock.patch to get around it , but not having much luck.Here is the structure of an ...
.└── work ├── __init__.py ├── test_work.py ├── work.py └── work_caller.py import osdef work_on ( ) : path = os.getcwd ( ) print ( f '' Working on { path } '' ) return pathdef unpleasant_side_effect ( ) : print ( `` I am an unpleasant side effect of importing this module '' ) # Note that this is called simply by importi...
Avoiding running top-level module code in unit test
Python
I have this chunk of code and I want to write it as SQL . Does anyone know how would equivalent SQL code look like ? UPDATE : I am looking for SQL standard dialect.Here is a dataset example ( partial first 10 rows ) :
lags = range ( 1 , 5 ) df = df.assign ( ** { ' { } { } '.format ( 'lag ' , t ) : df.groupby ( 'article_id ' ) .num_views.shift ( t ) for t in lags } ) article_id section time num_views comments0 abc111b A 00:00 15 01 abc111b A 01:00 36 02 abc111b A 02:00 36 03 bbbddd222hf A 03:00 41 04 bbbddd222hf B 04:00 44 05 nnn678w...
SQL equivalent for Pandas 's [ df.groupby ( ... ) [ 'col_name ' ] .shift ( 1 ) ]
Python
Suppose I have an array : And I want a dict ( or JSON ) : Is there any good way or some library for this task ? In this example the array is just 4-column , but my original array is more complicated ( 7-column ) .Currently I implement this naively : And defaultdict way : But I think neither is smart .
[ [ ' a ' , 10 , 1 , 0.1 ] , [ ' a ' , 10 , 2 , 0.2 ] , [ ' a ' , 20 , 2 , 0.3 ] , [ ' b ' , 10 , 1 , 0.4 ] , [ ' b ' , 20 , 2 , 0.5 ] ] { ' a ' : { 10 : { 1 : 0.1 , 2 : 0.2 } , 20 : { 2 : 0.3 } } ' b ' : { 10 : { 1 : 0.4 } , 20 : { 2 : 0.5 } } } import pandas as pddf = pd.DataFrame ( array ) grouped1 = df.groupby ( 'c...
Convert redundant array to dict ( or JSON ) ?
Python
What is the best way to override python any 3rd party package single file ? Suppose . I have a package called foo . Foo contains file tar.py which have an import line.tar.pyhow do I replace that single line importi want to change this line outside virtualenv in python project
from xyz import abc # some code # from from xyz import abc # to from xyz.xy import abc
Python override 3rd party package single file
Python
The goal to create a new column ( filt_col ) where record from numeric column ( raw_col ) are removed with the following logic ; if rate of change between two adjacent rows is less than threshold remove the latter.It works but is very inefficient in terms of running time.Any hints on how I could optimise it ?
def filter_data ( df , raw_col , threshold , filt_col ) : df [ 'pct ' ] = None df [ filt_col ] = None df [ filt_col ] [ 0 ] = df [ raw_col ] [ 0 ] max_val = df [ raw_col ] [ 0 ] for i in range ( 1 , len ( df ) ) : df [ 'pct ' ] [ i ] = ( df [ raw_col ] [ i ] - max_val ) *1.0 / max_val if abs ( df [ 'pct ' ] [ i ] ) < t...
Optimise filtering function for runtime in pandas
Python
I am connecting to a SQL Server database using SQLAlchemy ( with the pymssql driver ) .which results in : As per PEP 249 ( cursor 's .description attribute ) : The first two items ( name and type_code ) are mandatory , the other five are optional and are set to None if no meaningful values can be provided.I am assuming...
import sqlalchemyconn_string = f'mssql+pymssql : // { uid } : { pwd } @ { instance } / ? database= { db } ; charset=utf8'sql = 'SELECT * FROM FAKETABLE ; 'engine = sqlalchemy.create_engine ( conn_string ) connection = engine.connect ( ) result = connection.execute ( sql ) result.cursor.description ( ( 'col_1 ' , 1 , No...
SQLAlchemy accessing column types from query results
Python
I will use the followig code as reference for my question : I will conditionally test cases where : a is defined and b may or may not be defineda is False and b is not defined , or a is True and b is definedI would use if a or b : for the first case and if a and b : for the second one . Per my tests above it works , bu...
> > > a = 10 > > > if a or b : ... print ( a ) ... 10 > > > if False and b : ... print ( a ) ... > > > if a and b : ... print ( a ) ... Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > NameError : name ' b ' is not defined
Python : can I assume that conditions are tested from left to right and stop when met ?
Python
I 'm writing an program where im using two main functions however those both functions uses same inner functions . I 'm wondering how I should write them in most pythonic way ? My point is to hide those helpers somewhere inside and to dont repeat helper functions.The only reasonable solution which i can figure out is d...
def main_function1 ( ) : helper1 ( ) helper2 ( ) # dowork1def main_function2 ( ) helper1 ( ) helper2 ( ) # dowork2def helper1 ( ) # workhelp1def helper2 ( ) # workhelp2 Strictly speaking , private methods are accessible outside their class , just not easily accessible . Nothing in Python is truly private [ ... ] class ...
Most pythonic way to declare inner functions
Python
Let 's say I have a pandas df like so : What 's a good fast way to add a column like so : I.e . adding an increasing index for each unique value ? I know I could use df.unique ( ) , then use a dict and enumerate to create a lookup , and then apply that dictionary lookup to create the column . But I feel like there shou...
Index A B0 foo 31 foo 22 foo 53 bar 34 bar 45 baz 5 Index A B Aidx0 foo 3 01 foo 2 02 foo 5 03 bar 3 14 bar 4 15 baz 5 2
A pythonic and uFunc-y way to turn pandas column into `` increasing '' index ?
Python
I tried to log calls to random ( ) by putting a wrapper around it to print stuff . Surprisingly I noticed that I started getting different random values . I have created a small example to demonstrate the behavior : Script main.py : Output of python3.7.5 main.py ( same as python 3.6.9 ) So as you see the state of the R...
import randomdef not_wrapped ( seed ) : `` '' '' not wrapped `` '' '' gen = random.Random ( ) gen.seed ( seed ) # def wrappy ( func ) : # return lambda : func ( ) # gen.random = wrappy ( gen.random ) gen.randint ( 1 , 1 ) return gen.getstate ( ) def wrapped ( seed ) : `` '' '' wrapped `` '' '' gen = random.Random ( ) g...
Why does wrapping the random method of random.Random seem to affect the RNG ?
Python
let 's say I have an msi `` foo.msi '' If I want to pass an option like Is it possible ? If so how can I do this ? I am using cx_freeze to create msi
foo.msi < option >
How to create a msi by using cx_freeze which will accept command line input
Python
In an expression likeI 'd like to swap a and b to retrieve b + 2*a. I triedbut neither works ; the result is 3*a in both cases as b , for some reason , gets replaced first.Any hints ?
import sympya = sympy.Symbol ( ' a ' ) b = sympy.Symbol ( ' b ' ) x = a + 2*b y = x.subs ( [ ( a , b ) , ( b , a ) ] ) y = x.subs ( { a : b , b : a } )
SymPy : Swap two variables
Python
Similar questions may have been asked a couple of times before , but none of them seem to have my case/scenario or it does not work.I am trying to multithread a for loop as showed in an example . This for loop will do a function as it loops through an array . I would like to multithread it.Example : This should loop th...
array = [ `` a '' , `` b '' , `` c '' , `` d '' , `` e '' ] def dosomething ( var ) : # dosomething this is just an example as my actual code is not relevant to this questionfor arrayval in array : dosomething ( arrayval )
How to multi-thread with `` for '' loop ?
Python
I 'm confused about this scope behavior : This gives the output : But I would have expected that func_wrapper would always be the correct function . I know that the scope of func_wrapper is to the whole function but I redefine it in every loop iteration and the last instance got saved away in the attrib . I also tried ...
class Bar : def __init__ ( self ) : for fn in [ `` open '' , '' openW '' , '' remove '' , '' mkdir '' , '' exists '' , '' isdir '' , '' listdir '' ] : print `` register '' , fn def func_wrapper ( filename ) : print `` called func wrapper '' , fn , filename setattr ( self , fn , func_wrapper ) bar = Bar ( ) bar.open ( `...
strange Python function scope behavior
Python
I am trying to plot a simple chart with Bokeh but it fails to display anything when the x values are text based : I am wondering if this is a bug . Version : 0.13.0After applying the suggested fix it works :
x= [ '- ' , 'AF ' , 'AS ' , 'EU ' , 'NA ' , 'OC ' , 'SA ' ] y= [ 8 , 7621750 , 33785311 , 31486697 , 38006434 , 7312002 , 7284879 ] p = figure ( plot_width=480 , plot_height=300 , title='test ' ) p.vbar ( x=x , width=0.5 , bottom=0 , top=y , color= '' navy '' , alpha=0.5 ) p.toolbar.logo = Nonep.toolbar_location = None...
Is there a way to use text based X values with Bokeh ?
Python
I am new to python and I am stuck with a problem . What I 'm trying to do that I have a string containing a conversation between two people : I want to create 2 lists from the string using dylankid and senpai as names : and here is where I am struggling , inside list dylankid I want to place all the words that come aft...
str = `` dylankid : *random words* senpai : *random words* dylankid : *random words* senpai : *random words* '' dylankid = [ ] senpai = [ ] dylankid = [ `` random words '' , `` random words '' , `` random words '' ] senpai = [ `` random words '' , `` random words '' , `` random words '' ]
Slicing a String after certain key words are mentioned into a list
Python
Why does n't numpy throw an error when you do something likeSuch addition is not clearly defined in linear algebra , and it just took me several hours to track down a bug that boiled down to this
np.ones ( ( 5,5 ) ) + np.ones ( 5 )
Why does numpy let you add different size arrays ?
Python
Short version : I 'm trying to efficiently create an array like x : I 've tried simple for looping and it takes too long for the real usecase.Long version : ( extends short version ) I 've got a 400k rows long dataframe , which I need to partition into arrays of a next n elements from the element currently iterated ove...
input = [ 0 , 1 , 2 , 3 , 4 , 5 , 6 ] x = [ [ 0,1,2 ] , [ 1,2,3 ] , [ 2,3,4 ] , [ 3,4,5 ] , [ 4,5,6 ] ] class ModelInputParsing ( object ) : def __init__ ( self , data ) : self.parsed_dataframe = data.fillna ( 0 ) def process_data ( self , lb=50 ) : self.X , self.Y = [ ] , [ ] for i in range ( len ( self.parsed_datafra...
Efficiently create arrays from a next n elements from an array