lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | I have 3 buckets 1.commonfolder 2.jsonfolder 3.csvfolder.Common folder will be having both json and csv filesneed to copy all csv files to csvfolderneed to copy all json files to json folderCode is below to get all the files from commonfolder How to copy after thatneed to create a new function copyjson , copycsv to do ... | import boto3s3 = boto3.client ( 's3 ' ) def lambda_handler ( event , context ) : # List all the bucket names response = s3.list_buckets ( ) for bucket in response [ 'Buckets ' ] : print ( bucket ) print ( f ' { bucket [ `` Name '' ] } ' ) # Get the files of particular bucket if bucket [ `` Name '' ] == 'tests3json ' : ... | How to copy from one bucket to another bucket in s3 of certain suffix |
Python | Let 's say you have a big ( python ) software project called Ninja . There are several parts of the project like a server and a client , but also a common infrastructure library , which contains common classes and tools . Naturally I would create a package structure like this : ninja.core , ninja.server and ninja.clien... | eclipse_workspace| > -Ninja_core| || > -ninja| || > -core| > -Ninja_client| || > -ninja| || > -client ... # __init__.py of ninjaimport ninja_core as core # or this : from ninja_core import core # or this : import ninja_core.core | How can python libraries of different projects be in the same package ? |
Python | I have a Pandas DataFrame with categorical data written by humans . Let 's say this : I want to normalize these values by stripping spaces and uppercasing them . This works great : The issue I 'm having is that I also have a few nan values , and I effectively want those to remain as nans after this transformation . But... | > > > df = pd.DataFrame ( { 'name ' : [ `` A '' , `` A '' , `` A `` , `` b '' , `` B '' ] } ) name0 A1 A2 A3 b4 B > > > df.apply ( lambda x : x [ 'name ' ] .upper ( ) .strip ( ) , axis=1 ) 0 A1 A2 A3 B4 B > > > df2 = pd.DataFrame ( { 'name ' : [ `` A '' , `` A '' , `` A `` , `` b '' , `` B '' , np.nan ] } ) > > > df2.a... | Applying string functions to elements that can be NaN |
Python | I have dataframeand i need to getIf I try it unions all strings . How should I do to get desirable ? | ID url date active_seconds111 vk.com 12.01.2016 5111 facebook.com 12.01.2016 4111 facebook.com 12.01.2016 3111 twitter.com 12.01.2016 12222 vk.com 12.01.2016 8222 twitter.com 12.01.2016 34111 facebook.com 12.01.2016 5 ID url date active_seconds111 vk.com 12.01.2016 5111 facebook.com 12.01.2016 7111 twitter.com 12.01.20... | Pandas : union duplicate strings |
Python | I got a list of strings from an REST API . I know from the documentation that the item at index 0 and 2 are integers and item at 1 and 3 are floats.To do any sort of computation with the data I need to cast it to the proper type . While it 's possible to cast the values each time they 're used I rather prefer to cast t... | rest_response = [ '23 ' , ' 1.45 ' , ' 1 ' , ' 1.54 ' ] first_int = int ( rest_response [ 0 ] ) first_float = float ( rest_response [ 1 ] ) second_int = int ( rest_response [ 2 ] ) second_float = float ( rest_response [ 3 ] ) first_int , first_float , second_int , second_float = float_response | Is there an easy and beautiful way to cast the items in a list to different types ? |
Python | I had to rewrite a python script from python2 to python 3 to solve the encoding problems I had the easiest way . I had to move from mysqldb to pymysql which seemed to use same syntax . I accessed the pymysql 's github [ 1 ] site and following examples I noticed that when query result was one element it returned a JSON ... | # Connect to the databaseconnection = pymysql.connect ( host='localhost ' , user='user ' , passwd='passwd ' , db='db ' , charset='utf8mb4 ' , cursorclass=pymysql.cursors.DictCursor ) | Why do JSON queries return object if there is one element , list if more than one ? |
Python | According to the Python3 Regex documentation : Causes the resulting RE to match from m to n repetitions of the preceding RE , attempting to match as few repetitions as possible . This is the non-greedy version of the previous qualifier . For example , on the 6-character string 'aaaaaa ' , a { 3,5 } will match 5 ' a ' c... | { m , n } ? import reregex = re.compile ( ' ( abc|d|abcde ) { 1,2 } ? ( e|f ) ' ) regex.match ( 'abcdef ' ) | Does { m , n } ? regex actually minimize repetitions or does it minimize number of characters matched ? |
Python | I 've just started programming , and I 'm solving Project Euler problems with Python for practice . ( This is problem # 2 , finding the sum of the even fibonacci numbers within 4 million . ) My problem appears in the loop at the bottom , where I 'm trying to locate the odd numbers in the list , and delete them.del fibl... | # euler2def fibonacciList ( limit ) : `` 'generates a list of fib numbers up to N '' ' mylist = [ ] a , b = 1,2 while True : if a < = limit : mylist.append ( a ) a , b = b , a+b else : break return mylistfiblist = fibonacciList ( 4000000 ) for i in fiblist : if i % 2 ! = 0 : # if not even , delete from list print i del... | Iterative deletion from list ( Python 2 ) |
Python | Why this slicing example does n't give the same results as standard lists ? It works like if it first evaluates an [ :2 ] = bn [ :2 ] and then bn [ :2 ] = an [ :2 ] .Output : If I do it like this - everything works : | import numpy as npl1 = [ 1 , 2 , 3 ] l2 = [ 4 , 5 , 6 ] a = list ( l1 ) b = list ( l2 ) an = np.array ( a ) bn = np.array ( b ) print ( a , b ) a [ :2 ] , b [ :2 ] = b [ :2 ] , a [ :2 ] print ( a , b ) print ( an , bn ) an [ :2 ] , bn [ :2 ] = bn [ :2 ] , an [ :2 ] print ( an , bn ) -- -- -- -- -- -- -- -- -- -- [ 1 , ... | Why this slicing example does n't work in NumPy the same way it works with standard lists ? |
Python | Let 's say I have this variable list_1 which is a list of dictionaries.Each dictionary has a nested dictionary called `` group '' in which it has some information including `` name '' .What I 'm trying to do is to sum the scores of each unique group name.So I am looking for an output similar to : Total Scores in ( Cera... | list_1 = [ { `` title '' : `` Painting '' , `` score '' : 8 , `` group '' : { `` name '' : `` Ceramics '' , `` id '' : 391 } } , { `` title '' : `` Exam 1 '' , `` score '' : 10 , `` group '' : { `` name '' : `` Math '' , `` id '' : 554 } } , { `` title '' : `` Clay Model '' , `` score '' : 10 , `` group '' : { `` name ... | Trying to find sums of unique values within a nested dictionary . ( See example ! ) |
Python | Suppose we have this simple pandas.DataFrame : I would like to create a new column , say modified_value , that applies a function N times to the value column , N being the quantity column.Suppose that function is new_value = round ( value/2 , 1 ) , the expected result would be : What would be an elegant/vectorized way ... | import pandas as pddf = pd.DataFrame ( columns= [ 'quantity ' , 'value ' ] , data= [ [ 1 , 12.5 ] , [ 3 , 18.0 ] ] ) > > > print ( df ) quantity value0 1 12.51 3 18.0 quantity value modified_value0 1 12.5 6.2 # applied 1 time1 3 9.0 1.1 # applied 3 times , 9.0 - > 4.5 - > 2.2 - > 1.1 | Applying/Composing a function N times to a pandas column , N being different for each row |
Python | I built and installed my custom Django app following the official tutorial https : //docs.djangoproject.com/en/1.8/intro/reusable-apps/The installation seems successful.Where can I find the source code of all my custom classes and methods ? I tried to search it through my system but did n't find them . Is the code comp... | $ pip install -- user ../horizon2fa-0.1.tar.gzProcessing /opt/stack/horizon2fa-0.1.tar.gz Requirement already satisfied ( use -- upgrade to upgrade ) : horizon2fa==0.1 from file : ///opt/stack/horizon2fa-0.1.tar.gz in /opt/stack/.local/lib/python2.7/site-packagesBuilding wheels for collected packages : horizon2fa Runni... | Where is my custom Django app code ? |
Python | I have a dataframe with around around 9k rows and 57 cols , this is 'df'.I need to have a new dataframe : 'df_final ' - for each row of 'df ' i have to replicate each row ' x ' times and increase the day in each row one by one , also ' x ' times . While i can do this for a couple of iterations , when i do it for the fu... | df.shapeoutput : ( 9454 , 57 ) df_int = df [ 0:0 ] df_final = df_int [ 0:0 ] range_df = len ( df ) for x in range ( 0,2 ) : df_int = df.iloc [ 0+x : x+1 ] if abs ( df_int.iat [ -1,3 ] ) > 0 : df_int = pd.concat ( [ df_int ] *abs ( df_int.iat [ -1,3 ] ) , ignore_index=True ) for i in range ( 1 , abs ( df_int.iat [ -1,3 ... | pandas dataframe create a new dataframe by duplicating n times rows of the previous dataframe and change date |
Python | In Python , say I have two sets A and B , along with multiple references to both sets.Is there a way to merge the two sets A and B such that all references to both sets will refer to the newly merged set ? If possible , what will be the runtime ? Thank youEDIT : Some people have been asking why I wanted to do this , an... | A = { 1,3 } B = { 2,4 } aRef1 = AaRef2 = AbRef1 = BbRef2 = BMergeSets ( A , B ) # Now , whenever I use any of ( A , B , aRef1 , aRef2 , bRef1 , bRef2 ) # they refer to the same set which will be { 1,2,3,4 } | Is it possible to merge two sets such that all references to both sets will refer to the new ? |
Python | Is there a way to add personalized methods and attributes to Pandas CategoricalDtype ? Should I use a class inheritance or something like ExtensionDtype ? For example : Is there a solution to add methods and attributes to vehicle_dtype in order to do things like this ? Thank you for your help . | vehicles = [ `` Plane '' , `` Rocket '' , `` Car '' , `` Truck '' ] vehicle_dtype = CategoricalDtype ( categories=vehicles ) s = pd.Series ( [ `` Plane '' , `` Plane '' , `` Car '' ] ) s = s.astype ( vehicle_dtype ) s.cat.is_flying [ True , True , False ] | Add personalized methods and attributes to CategoricalDtype |
Python | Forgive me if I 'm being ignorant of the obvious here , but what would happen if you save a call to super in a variable and use it later.Here is a part of a class definition to show you what I mean.This came up when I was implementing this CaselessDict class and almost every method had super in it . | class CaselessDict ( dict ) : def __init__ ( self , *args , **kwargs ) : self.super = super ( CaselessDict , self ) # save super self.update ( *args , **kwargs ) def __getitem__ ( self , key ) : key = self.parsekey ( key ) return self.super.__getitem__ ( key ) # use saved super | What happens if you save a call to super in a variable for future use ? |
Python | Never seen anything like this . Simple while loop : Last 3 printed values : Looks right to me . Now , I change t_step to 0.01 : Last 3 printed values : Question : Why it does n't go for the final loop when time = t_end =100.0 ? What is the alternative solution ? | t_end = 100.0t_step= 0.1time = 0while time < =t_end : time+=t_step print time ... 99.9100.0100.1 t_end = 100.0t_step= 0.01time = 0while time < =t_end : time+=t_step print time ... 99.9899.99100.0 | Python while loop inconstancy |
Python | I have a list of items that I would like to sort on multiple criterion.Given input list : Criterions : Hm > AwI > R > H > EThe output should be : I know this function needs to be passed onto the built-in sorted ( ) but any ideas how to actually write it ? | cols = [ 'Aw H ' , 'Hm I1 ' , 'Aw I2 ' , 'Hm R ' , 'Aw R ' , 'Aw I1 ' , 'Aw E ' , 'Hm I2 ' , 'Hm H ' , 'Hm E ' , ] cols = [ 'Hm I1 ' , 'Aw I1 ' , 'Hm I2 ' , 'Aw I2 ' , 'Hm R ' , 'Aw R ' , 'Hm H ' , 'Aw H ' , 'Hm E ' , 'Aw E ' ] | Advanced custom sort |
Python | I 'm trying to print out sentences from a dataframe that contains words with one character no matter where it is beginning of the sentence middle or end of it , the challenge is my code works perfectly for English script but when I change the scrips say to Arabic it prints wrong output all sentences instead of the want... | tdata = pd.read_csv ( fileinput , nrows=0 ) .columns [ 0 ] skip = int ( tdata.count ( ' ' ) == 0 ) tdata = pd.read_csv ( fileinput , names= [ 'sentences ' ] , skiprows=skip ) df = tdata [ dftdata'sentences ' ] .str.contains ( r'\b\w { 1 } \b ' ) ] print ( df ) a sample set -- -- -- -- -- -- -- -- -- -- -- -- -- -- - # ... | How to look for sentences having single characters using Python and Pandas |
Python | I have a system where there is a many to one relationship with a number a model ( say 1 a - > many b ) and that many model has a one to one relationship with another model ( say 1 b - > 1 c ) . Drawn like so : I 'm determined to create a method in that collects all the c 's that correspond to a.Given an model system wi... | / -- - b1 -- - c1 /a -- -- b2 -- - c2 \ \ -- - b3 -- - c3 from django.db import modelsclass Person ( models.Model ) : `` '' '' The ' a ' from my above example `` '' '' def find_important_treats ( self ) : return ( pet.treat for pet in self.pets ) class Pet ( models.Model ) : `` '' '' The ' b ' from my above example `` ... | Django can not determine queryset for chaining one-to-many with one-to-one relationship |
Python | I am trying to setup a simple flask server : But I Get an error : What am I doing wrong ? | import envkeyimport pysherfrom flask import Flask # from predictor import PythonPredictorapp = Flask ( __name__ ) pusher = pysher.Pusher ( envkey.get ( 'PUSHER_KEY ' ) ) def my_func ( *args , **kwargs ) : print ( `` processing Args : '' , args ) print ( `` processing Kwargs : '' , kwargs ) # We ca n't subscribe until w... | How can I set up a Pusher server with Flask ? |
Python | In python 2 , the built in function map seems to call the __len__ when length is overwritten . Is that correct - if so , why are we computing the length of the iterable to map ? Iterables do n't need to have length overwritten ( e.g . ) , and the map function works even when length is not pre-defined by the iterable.Ma... | class Iterable : def __iter__ ( self ) : self.iterable = [ 1,2,3,4,5 ] .__iter__ ( ) return self def next ( self ) : return self.iterable.next ( ) # def __len__ ( self ) : # self.iterable = None # return 5def foo ( x ) : return xprint ( [ foo ( x ) for x in Iterable ( ) ] ) print ( map ( foo , Iterable ( ) ) ) /* Do a ... | Python 2 , map not equivalent to list comprehension in simple case ; length dependent |
Python | I am trying to click the button labled `` Pickup '' at the following link : https : //firehouse.alohaorderonline.com/StartOrder.aspx ? SelectMenuType=Retail & SelectMenu=1000560 & SelectSite=01291My code is below but does nothing until it fails with the error element not interactableThe code appears to locate an elemen... | pickupurl = 'https : //firehouse.alohaorderonline.com/StartOrder.aspx ? SelectMenuType=Retail & SelectMenu=1000560 & SelectSite=1291'driver = webdriver.Chrome ( 'd : \\chromedriver\\chromedriver.exe ' ) driver.implicitly_wait ( 80 ) driver.get ( pickupurl ) button = driver.find_elements_by_xpath ( '//* [ @ id= '' ctl00... | Issue clicking Javascript button with python/Selenium |
Python | Are there exists any examples of Django widgets which can be useful for ManyToManyFields with 'through ' attributes ? For example , i have these models ( got the source from django documentation ) : Obvisously , standart ModelMultipleChoiceField wo n't work here . I need to populate 'date_joined ' , and 'invite_reason ... | from django.db import models class Person ( models.Model ) : name = models.CharField ( max_length=128 ) def __str__ ( self ) : # __unicode__ on Python 2 return self.name class Group ( models.Model ) : name = models.CharField ( max_length=128 ) members = models.ManyToManyField ( Person , through='Membership ' ) def __st... | Django M2MFields 'through ' widgets |
Python | In a dataframe with around 40+ columns I am trying to change dtype for first 27 columns from float to int by using iloc : However , it 's not working . I 'm not getting any error , but dtype is not changing as well . It still remains float.Now the strangest part : If I first change dtype for only 1st column ( like belo... | df1.iloc [ : ,0:27 ] =df1.iloc [ : ,0:27 ] .astype ( 'int ' ) df1.iloc [ : ,0 ] =df1.iloc [ : ,0 ] .astype ( 'int ' ) df1.iloc [ : ,0:27 ] =df1.iloc [ : ,0:27 ] .astype ( 'int ' ) | I need to change the type of few columns in a pandas dataframe . Ca n't do so using iloc |
Python | Does the Python standard library have a function that returns the value at index 0 ? In other words : I need to use this in a higher-order function like map ( ) . I ask because I believe it 's clearer to use a reusable function rather than define a custom one - for example : I also ask because Haskell does have such a ... | zeroth = lambda x : x [ 0 ] pairs = [ ( 0,1 ) , ( 5,3 ) , ... ] xcoords = map ( funclib.zeroth , pairs ) # Reusablevs.xcoords = map ( lambda p : p [ 0 ] , pairs ) # Customxcoords = [ 0 , 5 , ... ] # ( or iterable ) head : : [ a ] - > ahead ( x : xs ) = xhead xs = xs ! ! 0xcoords = ( map head ) pairs | Python function that returns the value at index 0 ? |
Python | Why are not these two statements equivalents ? Python 3.5.3 ( default , Jan 19 2017 , 14:11:04 ) | > > math.pow ( -2,2 ) 4.0 > > -2 ** 2-4 | Why is -2**2 == -4 but math.pow ( -2 , 2 ) == 4.0 ? |
Python | As the title suggests I have a question regarding changing objects in Sets such that they become exactly the same ( in the eyes of the set ) . Just curious.I ask this question with regard to Python , but if it is generalizable feel free to do that.If I have understood correctly in Python the Set iterable will determine... | hash ( a ) == hash ( b ) | What happens when objects in a Set are altered to match each other ? |
Python | Consider the following example that uses __subclasscheck__ for a custom exception type : Now when raising an exception of this type , the __subclasscheck__ method gets invoked ; i.e . raise MyError ( ) results in : Here the first line of the output shows that __subclasscheck__ got invoked to check whether MyError is a ... | class MyMeta ( type ) : def __subclasscheck__ ( self , subclass ) : print ( f'__subclasscheck__ ( { self ! r } , { subclass ! r } ) ' ) class MyError ( Exception , metaclass=MyMeta ) : pass __subclasscheck__ ( < class '__main__.MyError ' > , < class '__main__.MyError ' > ) Traceback ( most recent call last ) : File `` ... | Why does raising an exception invoke __subclasscheck__ ? |
Python | Regarding coding style : I often use the former when the following blocks , or the last block is a large chunk of code . It seems to help readability.I generally use the latter when the various blocks have a common concept running through them ( as in the case above ) . The common indentation helps to communicate their... | def size ( number ) : if number < 100 : return Small ( ) if number < 1000 : return Medium ( ) return Big ( ) def size1 ( number ) : if number < 100 : return Small ( ) elif number < 1000 : return Medium ( ) else : return Big ( ) | Should I use elif if I have already returned from the function in a previous block ? |
Python | Note : Since asking this question , I discovered later on that python -m pip install -e . will install the extension to cmod with .venv/lib/python3.8/site-packages/hello-c-extension.egg-link pointing to the project in the current directory . I 've also switched to a src layout in later commits and have found https : //... | $ tree hello-c-extension/hello-c-extension/├── LICENSE├── Makefile├── README.md├── cmod│ ├── __init__.py│ ├── _cmodule.cc│ └── pymod.py├── setup.py└── tests ├── __init__.py └── test_cext.py cd hello-c-extensionpython -m venv .venvsource ./.venv/bin/activatepython -m pip install -U pip wheel setuptoolspython setup.py bu... | Can not import C++ extension if in the package root directory |
Python | I hava a pandas dataset called tf which has a column containing blank space seperated keywords titled `` Keywords '' : As an input I want to provide a set of strings to filter the rows by these keywords . I thought about using a list : I found out that I can filter rows if I make the list a string with the entries sepe... | Name ... Keywords0 Jonas 0 ... Archie Betty1 Jonas 1 ... Archie2 Jonas 2 ... Chris Betty Archie3 Jonas 3 ... Betty Chris4 Jonas 4 ... Daisy5 Jonas 5 ... NaN6 Jonas 5 ... Chris Archie list = [ `` Chris '' , `` Betty '' ] Name ... Keywords0 Jonas 0 ... Archie Betty2 Jonas 2 ... Chris Betty Archie3 Jonas 3 ... Betty Chris... | How can I find specified string matching filter patterns with Pandas |
Python | So I have roughly 40,000 rows of people and their complaints . I am attempting to sort them into their respective columns for analysis , and for other analysts at my company who use other tools can use this data . DataFrame Example : Desired Output : Things I 've tried / where I 'm at : So I 've been able to at least s... | df = pd.DataFrame ( { `` person '' : [ 1 , 2 , 3 ] , `` problems '' : [ `` body : knee hurts ( bad-pain ) , toes hurt ( BIG/MIDDLE ) ; mind : stressed , tired '' , `` soul : missing ; mind : ca n't think ; body : feels great ( lifts weights ) , overweight ( always bulking ) , missing a finger '' , `` none '' ] } ) df ╔... | Break up a list of strings in a pandas dataframe column into new columns based on first word of each sentence |
Python | I am working with a custom number type which is best thought of as YearQuarter , ( i.e . 20141 , 20142 , 20143 , 20144 , 20151 , 20152 , ... ) , or as I label it , quarter_code , q_code for short . Its incrementing function would be something like : I want to warn or raise exceptions for numbers which do n't conform to... | def code_sum ( q_code , n ) : q_code_year , q_code_quarter = q_code // 10 , q_code % 10 n_year , n_quarter = ( n // 4 ) , ( n % 4 - 1 ) quarters = q_code_quarter + n_quarter years = q_code_year + n_year + quarters // 4 return years * 10 + quarters % 4 + 1 # code_sum ( 20141 , 1 ) = 20142 , code_sum ( 20144 , 1 ) = 2015... | Python : using a custom number class or type |
Python | I am able to retrieve the list of files with similar names . What I am trying to do is retrieve the newest file in order to be manipulated . With glob , I am able to retrieve all of the files , but not the specific one.Here is my sample code : Here is the result when I print it : What I want is just PermissionsOnSystem... | permissionCurrentDate = '\n'.join ( glob.iglob ( os.path.join ( `` PermissionsOnSystems* '' ) ) ) PermissionsOnSystems2.txtPermissionsOnSystems20170313-144036.txt | Python glob -- get newest file from list |
Python | How do I efficiently move identical elements from a sorted numpy array into subarrays ? from here : to here : | import numpy as np a=np.array ( [ 0,0,1,1,1,3,5,5,5 ] ) a2=array ( [ [ 0 , 0 ] , [ 1 , 1 , 1 ] , [ 3 ] , [ 5 , 5 , 5 ] ] , dtype=object ) | how to move identical elements in numpy array into subarrays |
Python | Suppose I have two lists : How would you sort this most efficiently , such that : list b is sorted with respect to a . Unique elements in b should be placed at the end of the sorted list . Unique elements in a can be ignored.example output : Sorry , it 's a simple question . My attempt is stuck at the point of taking t... | a = [ '30 ' , '10 ' , '90 ' , '1111 ' , '17 ' ] b = [ '60 ' , '1201 ' , '30 ' , '17 ' , '900 ' ] c = [ '30 ' , '17 ' , '60 ' , '1201 ' , '900 ' ] intersection = sorted ( set ( a ) & set ( b ) , key = a.index ) | Sort a list by presence of items in another list |
Python | What 's the best way to do this ? | d1 = { 'apples ' : 2 , 'oranges':5 } d2 = { 'apples ' : 1 , 'bananas ' : 3 } result_dict = { 'apples ' : 1.5 , 'oranges ' : 5 , 'bananas ' : 3 } | What 's the most pythonic way to merge 2 dictionaries , but make the values the average values ? |
Python | How does Python 's super ( ) work with multiple inheritance ? I was looking at the above question/answers and made myself really confused Fourth ( ) third second thats it Fourth ( ) second thats it Could someone explain to me what 's happening behind the scene in regards to why the top prints `` third '' and the bottom... | 53 class First ( object ) : 54 def __init__ ( self ) : 55 print `` first '' 56 57 class Second ( First ) : 58 def __init__ ( self ) : 59 super ( Second , self ) .__init__ ( ) 60 print `` second '' 61 62 class Third ( First ) : 63 def __init__ ( self ) : 64 print `` third '' 65 66 class Fourth ( Second , Third ) : 67 de... | How to use super to initialize all the parents when using multiple inheritance |
Python | I am trying to make a program that will pick a random number , and run a corresponding command to that number . I put multiple commands in a list as seen belowIs there any way to run a command this way ? ( I am using python 3.5 ) | list = [ cmd1 ( ) , cmd2 ( ) , cmd3 ( ) , cmd4 ( ) ] x = randint ( 0 , len ( list-1 ) ) list [ x ] | Is it possible to run a command that is in a list ? |
Python | Why this cython function : returns 1 , for foo ( 1 ) ? I compiled similar code in C , and did n't observe both operands ( a , b ) had been promoted to unsigned int . | cimport numpy as npcimport cythondef foo ( np.uint32_t b ) : cdef np.int32_t a = 0 if a-b < 0 : return 0 else : return 1 | Strange type promotion in arithmetic operation |
Python | I am trying to figure out how to simplify this piece of code . The logic for every if condition is basically the same so I want to get rid of the duplicate ifs : I hope this can be done in 3-4 lines instead of my 18 lines . | if `` video_codec '' in profile : self.video_codec = profile [ `` video_codec '' ] if `` resolution_width '' in profile : self.resolution_width = profile [ `` resolution_width '' ] if `` resolution_height '' in profile : self.resolution_height = profile [ `` resolution_height '' ] if `` ratio '' in profile : self.ratio... | How to simplify this mass of similar ifs |
Python | When using an optional import , i.e . the package is only imported inside a function as I want it to be an optional dependency of my package , is there a way to type hint the return type of the function as one of the classes belonging to this optional dependency ? To give a simple example with pandas as an optional dep... | def my_func ( ) - > pd.DataFrame : import pandas as pd return pd.DataFrame ( ) df = my_func ( ) def my_func ( ) - > 'pd.DataFrame ' : import pandas as pd return pd.DataFrame ( ) df = my_func ( ) | How to type hint with an optional import ? |
Python | I 'm wondering how to sum up 10 rows of a data frame from any point.I tried using rolling ( 10 , window =1 ) .sum ( ) but the very first row should sum up the 10 rows below . Similar issue with cumsum ( ) So if my data frame is just the A column , id like it to output B.It would be similar to doing this operation in ex... | A B0 10 5501 20 6502 30 7503 40 8504 50 9505 60 10506 70 11507 80 12508 90 13509 100 145010 110 etc11 120 etc12 130 etc13 140 14 150 15 160 16 170 17 180 18 190 | Summing up previous 10 rows of a dataframe |
Python | It has been a long time when I asked this question and still did n't get an answers . I am trying to add infinite scroll down with Django but it is not working fine with the following code . I just paginating post by 10 and then its just showing me loading icon .it is not working when i am scrolling down . Can you guys... | class PostListView ( ListView ) : model = Post context_object_name = 'post_list ' paginate_by = 10 def get_queryset ( self ) : return Post.objects.filter ( create_date__lte=timezone.now ( ) ) .order_by ( '-create_date ' ) { % extends 'base.html ' % } { % block content % } < div class= '' container '' > < div class= '' ... | Infinite scroll bar is not working with django |
Python | To see how repr ( x ) works for float in CPython , I checked the source code for float_repr : This calls PyOS_double_to_string with format code ' r ' which seems to be translated to format code ' g ' with precision set to 17 : So I 'd expect repr ( x ) and f ' { x : .17g } ' to return the same representation . However ... | buf = PyOS_double_to_string ( PyFloat_AS_DOUBLE ( v ) , ' r ' , 0 , Py_DTSF_ADD_DOT_0 , NULL ) ; precision = 17 ; format_code = ' g ' ; > > > repr ( 1.1 ) ' 1.1 ' > > > f ' { 1.1 : .17g } '' 1.1000000000000001 ' > > > > > > repr ( 1.225 ) ' 1.225 ' > > > f ' { 1.225 : .17g } '' 1.2250000000000001 ' | Why does float.__repr__ return a different representation compared to the equivalent formatting option ? |
Python | I am trying to obtain the spectrum of periodic signals using the fft function . Then plot the magnitude and phase of the transform . Magnitude plots are OK , but phase plots are completely unexpected . For example I used the functions Sin³ ( t ) and Cos³ ( t ) . The code I have used is : The plots obtained are : i ) Fo... | import matplotlib.pyplot as pltimport numpy.fft as nfimport mathimport numpy as nppi = math.piN=512 # Sin³ ( x ) t=np.linspace ( -4*pi,4*pi , N+1 ) ; t=t [ : -1 ] y= ( np.sin ( t ) ) **3Y=nf.fftshift ( nf.fft ( y ) ) /Nw=np.linspace ( -64,64 , N+1 ) ; w=w [ : -1 ] plt.figure ( `` 0 '' ) plt.subplot ( 2,1,1 ) plt.plot (... | numpy.fft.fft ( ) implementation in Python |
Python | I have a ( very ugly ) txt output from an SQL query which is performed by external system that I ca n't change . Here is the output example : As you can see , the FruitName column and the Owner column may consists of few words and there 's no fixed pattern in how many words could be in these columns . If I use line.spl... | FruitName Owner OwnerPhone============= ================= ============Red Apple Sr Lorem Ipsum 123123Yellow Banana Ms Dolor sir Amet 456456 [ 'Red ' , 'Apple ' , 'Sr ' , 'Lorem ' , 'Ipsum ' , '123123 ' ] [ 'Yellow ' , 'Banana ' , 'Ms ' , 'Dolor ' , 'sir ' , 'Amet ' , '456456 ' ] [ 'Red Apple ' , 'Sr Lorem Ipsum ' , '12... | Split lines with multiple words in Python |
Python | Let 's say I have 2 dictionaries in Python , like this : Instead I could do it like this : Accessing it could be done with d [ ( i , j ) ] [ 0 ] and d [ ( i , j ) ] [ 1 ] .What I would like to ask is this : Does the second option need less memory than the first ? If yes , is it half the memory ? I need to use very larg... | d1 = { } d2 = { } d1 [ ( i , j ) ] = 10d2 [ ( i , j ) ] = 20 d = { } d [ ( i , j ) ] = ( 10 , 20 ) | Python memory usage of using two dictionaries vs one |
Python | I have two files in the same directory , and there are no __init__.py files anywhere : one file imports the other : The import succeeds even when run from a completely different location : I 'm runningand my PYTHONPATH and PYTHONHOME variables are not setHow does a1.py find a2 ? | c : \work\test > tree.| -- a| ` -- a| | -- a1.py| ` -- a2.py ` -- b c : \work\test > type a\a\a1.pyprint 'a1-start'import a2print 'a1-end ' c : \work\test > type a\a\a2.pyprint 'a2 ' c : \work\test\b > python ..\a\a\a1.pya1-starta2a1-end c : \work\test > python -VPython 2.7.3 c : \work\test > echo % PYTHONPATH % % PYTH... | How does this Python import work ? |
Python | I want to concatenate vertically a lot of images . I used skimage to read images then in each iteration io read image and vconcat concatenate the new image on the old image vertically.The result of my code did n't concatenate the images , just combine the images . Any ideas how to make each image in each iteration conc... | data= [ ] if nSpectogram < 3765 : for k in range ( 0,21 ) : path=io.imread ( ' E : \\wavelet\\spectrograms\\paz05\\'+'spec_'+isPreictal+ ' _'+str ( nSpectogram+1 ) + ' _'+str ( k+1 ) +'.png ' ) im_v_array=np.array ( im_v ) data.append ( path ) res=np.concatenate ( data ) plt.imshow ( res , cmap='inferno ' , aspect='aut... | How to concatenate 1000 images vertically using for loop in python ? |
Python | I wanted to merge two datasets on their key value and got strange results . I made a simple version to reproduce that problem.I got this output : I thought this was strange , so I decided to try this one : And got the result I expected : If there is no zero then the join is messed up , but if there is zero everything w... | df = pd.DataFrame ( { 'key ' : [ 1 , 2 , 3 ] } ) other = pd.DataFrame ( { 'key ' : [ 1 , 2 , 3 ] } ) df.join ( other , on='key ' , lsuffix='_caller ' ) key_caller key0 1 2.01 2 3.02 3 NaN df = pd.DataFrame ( { 'key ' : [ i for i in range ( 3 ) ] } ) other = pd.DataFrame ( { 'key ' : [ i for i in range ( 3 ) ] } ) df.jo... | Is this a bug or do I not understand something ? |
Python | Lets say I have a list of numbers : but the list contains a little too much data , and I want to convey the spread . I want to print 10 of those numbers . With 1 being the highest number and 10 being the lowest number , how could I sort the list and print a range of 10 numbers to represent the spread from highest to lo... | some_numbers = [ 16.0 , 16.01 , 24.53 , 22.99 , 22.72 , 22.71 , 22.2 , 21.36 , 21.34 , 21.0 , 22.67 , 22.62 , 15.89 , 23.54 , 27.0 , 21.35 , 26.99 , 25.46 , 22.54 , 22.53 , 17.99 , 22.13 , 17.97 , 17.96 , 17.95 , 22.4 , 22.32 , 22.25 , 22.19 , 22.16 , 20.68 , 21.74 , 15.38 , 11.13 , 15.82 , 22.33 , 22.31 , 22.23 , 22.1... | How to get an average 'spread ' from a list of numbers ? |
Python | I 'm new to python and using PyDev with Eclipse I noticed excruciatingly slow startup time whenever I try to execute the code I 'm working on . I narrowed this down to libraries import . For example if I run the following codeIt will benchmark time for PyDev as : while with command line execution it will be : Can anybo... | import timeitstartTime = timeit.default_timer ( ) import numpy as npprint ( `` loaded numpy : `` , timeit.default_timer ( ) - startTime ) import pandas as pdprint ( `` loaded pandas : `` , timeit.default_timer ( ) - startTime ) from pandas import ExcelWriterprint ( `` loaded sub-pandas 1 : `` , timeit.default_timer ( )... | PyDev import times are 10x slower than using command line |
Python | Trying to get re.split to work correctly.Input = `` a1 a2 a3 , a4 , a5 '' | expecting output = [ 'a1 ' , 'a2 ' , 'a3 ' , 'a4 ' , 'a5 ' ] s = re.split ( ' , |\s ' , `` a1 a2 a3 , a4 , a5 '' ) getting output = [ 'a1 ' , 'a2 ' , 'a3 ' , ' ' , 'a4 ' , 'a5 ' ] | Python re.split on `` , '' or `` `` |
Python | I wrote this python code to give the Harmonic Series of a certain value n both recursively and iteratively . Here is the functions : Then , when I run the code 10 times for each , I get the following times : The code is supposed to find H_rec ( 100000000 ) and H ( 100000000 ) , which are fairly big numbers . I do n't u... | def H ( n ) : if ( n < = 0 ) : raise ValueError ( `` n must be bigger than 0 . '' ) if ( n == 1 ) : return 1 else : return sum ( [ 1/x for x in range ( 1 , n+1 ) ] ) def H_rec ( n ) : if ( n < = 0 ) : raise ValueError ( `` n must be bigger than 0 . '' ) if ( n == 1 ) : return 1 else : return 1/n + H ( n-1 ) RECURSIVE T... | simpler recursive code runs slower than iterative version of the same thing |
Python | Made a request on the above Wikipedia page . Specifically I need to scrape `` results matrix '' from https : //en.wikipedia.org/wiki/2017 % E2 % 80 % 9318_La_Liga # ResultsDoing pprint.pprint ( selectedSeasonPage.text ) and jumping to source code of matrix , it can be seen it 's incomplete.Snippet of HTML returned by r... | selectedSeasonPage = requests.get ( 'https : //en.wikipedia.org/wiki/2017–18_La_Liga ' , features='html5lib ' ) < table class= '' wikitable plainrowheaders '' style= '' text-align : center ; font-size:100 % ; '' > .. < th scope= '' row '' style= '' text-align : right ; '' > < a href= '' /wiki/Deportivo_Alav % C3 % A9s ... | Python requests.get ( ) returns broken source code instead of expected source code ? |
Python | I am trying to find an efficient way to search three or more consecutive duplicates and replace them for only one in a Python list.What seems to be the problem here ? Is there a more efficient way ? | list_before = [ 1 , 1 , 1 , 2 , 3 , 4 , 5 , 5 , 5 , 6 , 6 , 7 , 7 , 7 , 8 , 8 , 8 , 8 , 8 ] # expectedlist_after = [ 1 , 2 , 3 , 4 , 5 , 6 , 6 , 7 , 8 ] def replace ( list_to_replace ) : for idx , val in enumerate ( list_to_replace ) : if idx + 3 < len ( list_to_replace ) : if val == list_to_replace [ idx+1 ] == list_t... | Python find duplicates which occur more than 3 times |
Python | I have some very inefficient code I 'd like to make more general/efficient . I am trying to create strings from a set of lists . Here is what I currently have : Now I want to create strings that have every combination in my combination list . This is the inefficient part . I 'd like it so that I do n't have to hardwire... | # contains categoriesnumind = [ ( 'Length ' , ) , ( 'Fungus ' , ) ] # contains values that pertain to the categoriesrecords = [ ( 'Length ' , 'Long ' ) , ( 'Length ' , 'Med ' ) , ( 'Fungus ' , 'Yes ' ) , ( 'Fungus ' , 'No ' ) ] # contains every combination of values between the 2 categories . # for example , ( Long , Y... | Efficient way to create strings from a list |
Python | The string/list is e.g . 'foobar ' . I need to break this up in all possible combinations where the number of groups is n , e.g . 3.This would give me e.g.etcWhat is the best algorithm to create all the possible combinations ? | [ 'foo ' , 'ba ' , ' r ' ] [ ' f ' , 'ooba ' , ' r ' ] [ 'fo ' , 'oo ' , 'bar ' ] [ ' f ' , ' o ' , 'obar ' ] | Create possible combinations of specific size |
Python | So , I 'm playing around with packaging a python script I 've written , and it has a submodule , let 's call it submodule . The folder structure looks like this : Now , after many pip install . and pip install -e . calls , I have the situation where submodule can be imported globally . No matter where on my system , th... | cool_script/ setup.py cool_script.py submodule/ __init__.py implementation.py $ python3 [ ... ] > > > import submodule > > > submodule.__file__'/home/me/fake/path/cool_script/submodule/__init__.py ' $ ls /usr/local/lib/python3.4/dist-packages | ack cool $ ls /usr/local/lib/python3.4/dist-packages | ack submodule $ $ ec... | Python can import a module that is n't installed |
Python | I believe that readability and the KISS principle are the most important things in programming . That 's why I use Python : ) And here is exact situation , which I encounter very often : Say , I have a nice and clean script , which is a wrapper for database handling : Which is used like this : At some point , I want to... | import database_schema as schemaloader = schema.Loader ( `` sqlite : ///var/database.db '' ) session = loader.sessiondef addUser ( name , full_name , password ) : user = schema.User ( name , full_name , password ) session.add ( user ) session.commit ( ) def listUsers ( ) : all_users = session.query ( schema.User ) .all... | Transition from small scripts to bigger apps is not easy |
Python | I have a lot of HTML text , likeSometimes HTML tags , such as < sub > , < /sub > are missing their < brackets . This can lead to difficulties later in the code . Now , my question is : How can I detect those missing brackets intelligently and repair them ? The correct text would be : Of course , I could hardcode all po... | text = 'Hello , how < sub > are < /sub > you ? There is a < sub > small error < /sub in this text here and another one < sub > here /sub > . ' text = 'Hello , how < sub > are < /sub > you ? There is a < sub > small error < /sub > in this text here and another one < sub > here < /sub > . ' text = re.sub ( r ' < /sub ' ,... | Repair HTML Tag Brackets using Python |
Python | I 'm writing a simple linked list implementation as follows : This code runs fine without the __len__ method . Deleting those three lines and running the code above outputs : However , if the __len__ method is present , then the results are : Note the presence of first in the output . print_list ( ) is executed once , ... | class Node ( object ) : def __init__ ( self , value ) : self.value = value self._next = None def __iter__ ( self ) : here = self while here : yield here here = here._next def __len__ ( self ) : print ( `` Calling __len__ on : { } '' .format ( self ) ) return sum ( 1 for _ in self ) def append_to_tail ( self , value ) :... | Why is __len__ ( ) called implicitly on a custom iterator |
Python | Sorry this is my first time asking a question , my formatting may be wrong . I am unsure about the syntax for calling functions from a class without creating an instance of the class . For the code : How come I am able to call And have the console print out the value 10 , but if I were to call Then I get the error : An... | class A_Class : var = 10 def __init__ ( self ) : self.num = 12 def print_12 ( self ) : return 12 print ( A_Class.var ) print ( A_Class.num ) AttributeError : type object 'A_Class ' has no attribute 'num ' print ( A_Class.print_12 ) < function A_Class.print_12 at 0x039966F0 > | Syntax confusion during calling of functions from python classes |
Python | I am in the process of learning list comprehensions and stumbled into a type of problem that I can not find resources to adequately understand.The problem stems from the following question : We have an Array [ 1,2,3,8,9 ] and want to create an expression that would return each odd number twice , while even numbers are ... | OtherNumList = [ 1 , 2 , 3 , 8 , 9 ] OtherNumList2 = [ ] for i in OtherNumList : if i % 2==1 : OtherNumList2.append ( i ) OtherNumList2.append ( i ) else : OtherNumList2.append ( i ) print ( OtherNumList2 ) | List Comprehension Append Odds Twice Evens Once |
Python | We 're applying Black code style to a django project.In all the tutorials / examples I find ( such as in django cookiecutter and this blog ) , I keep seeing django 's migrations files excluded from the linter.But to my mind , these are still python files . Sure , django may not autogenerate them to meet the Black spec ... | # Generated by Django 2.2.3 on 2019-10-28 09:45from django.db import migrations , modelsclass Migration ( migrations.Migration ) : dependencies = [ ( 'api ' , '0009_figures_notes_tables ' ) , ] operations = [ migrations.AlterField ( model_name='project ' , name='processed_kmz_sha ' , field=models.CharField ( max_length... | Why are migrations files often excluded from code formatting ? |
Python | if I run this code it will return 13I know that the interpreter applied name mangling so the variable __x became _test__xbut this is the same as the global variable.i tried to use self._test__x but it did not workHow to access the __x variable declared in __init __.py but not the global variable ? | # global variable_test__x=13class test : def __init__ ( self , x ) : self.__x=x def rex ( self ) : return __xd = test ( 5 ) print ( d.rex ( ) ) | python name mangling and global variables |
Python | Suppose I have the following dataframe : Then I want to add another column such that it will display the number of zero valued column that occur contiguously from the right.The new column would be : | C1 C2 C3 C4 0 1 2 3 0 1 4 0 0 0 2 0 0 0 3 3 0 3 0 0 Cnew 0 1 1 3 2 0 3 2 | How do I calculate the number of consecutive columns with zero values from the right until the first non zero element occurs |
Python | I am trying to realize this piece of high-order function in python using C++ : Here are the three versions I created : The outputs are : Only add1_v1 matches what I want . Can anyone explain the reason for me ? | def add1 ( x ) : def helper ( ) : nonlocal x x += 1 return x return helper # include < iostream > # include < functional > using namespace std ; function < int ( void ) > add1_v1 ( int x ) { function < int ( void ) > g = [ & x ] ( ) { return ++x ; } ; return g ; } auto add1_v2 ( int x ) { function < int ( void ) > g = ... | Different results obtained by using generic lambdas and automatic return type feature in C++14 |
Python | Class objects have a __bases__ ( and a __base__ ) attribute : Sadly , these attributes are n't accessible in the class body , which would be very convenient for accessing parent class attributes without having to hard-code the name : Is there a reason why __bases__ and __base__ ca n't be accessed in the class body ? ( ... | > > > class Foo ( object ) : ... pass ... > > > Foo.__bases__ ( < class 'object ' > , ) class Foo : cls_attr = 3class Bar ( Foo ) : cls_attr = __base__.cls_attr + 2 # throws NameError : name '__base__ ' is not defined | Why is n't __bases__ accessible in the class body ? |
Python | I noticed many times that the import mod statement can be placed tightly before a call mod.something ( ) . Though I noticed that usually developers put the import statement at the beginning of the source file . Is there a good reason for this ? I often use only a few functions from some module in particular place . It ... | # middle of the source fileimport modmod.something ( ) | Place of the import statement |
Python | I have the following three strings ( they exist independently but are displayed here together for convenience ) : I 'm looking to populate a dict with some values based on the reversed ( bottom to top ) order of the strings . Specifically , for each string , I 'm extracting the IP address as an index of sorts , and the... | from mx2.x.org ( mx2.x.org . [ 198.186.238.144 ] ) by mx.google.com with ESMTPS id g34si6312040qgg.122.2015.04.22.14.49.15 ( version=TLSv1 cipher=ECDHE-RSA-RC4-SHA bits=128/128 ) ; Wed , 22 Apr 2015 14:49:16 -0700 ( PDT ) from HQPAMAIL08.x.org ( 10.64.17.33 ) by HQPAMAIL13.x.x.org ( 10.34.25.11 ) with Microsoft SMTP Se... | Can I trust the order of a dict to remain the same each time it is iterated over ? |
Python | I was wondering which of the following examples is more accepted within the Python community:1.2.Or maybe something else ? Please advise . | return any ( host [ 0 ] .endswith ( bot_hosts ) for bot_hosts in bot_hosts ) if any ( host [ 0 ] .endswith ( bot_hosts ) for bot_hosts in bot_hosts ) : return Trueelse : return False | Is returning a calculated boolean pythonic or I should use traditional if/else ? |
Python | I have been doing the conversions manually , but is there a way to use bins or ranges with sklearn 's labelencoder : desired output -- > [ 2,1,1,2,2 ] Or you could imagine using age ranges , distances , etc . Is there a way to do this ? | le = LabelEncoder ( ) A = [ `` paris '' , `` memphis '' ] B = [ `` tokyo '' , `` amsterdam '' ] le.fit ( [ A , B ] ) print ( le.transform ( [ `` tokyo '' , `` memphis '' , `` paris '' , '' tokyo '' , `` amsterdam '' ] ) ) | Python sklearn 's labelencoder with categorical bins |
Python | I 'm trying to make an Evaluator for my model . Until now every other components are fine but When I try this config : to make this evaluator : I get this : I thought it was my config , but I do n't get what is wrong with this.I 'm using this data set Kaggle - BBC News Classification.I 've followed this notebook : TFX ... | eval_config = tfma.EvalConfig ( model_specs= [ tfma.ModelSpec ( label_key='Category ' ) , ] , metrics_specs=tfma.metrics.default_multi_class_classification_specs ( ) , slicing_specs= [ tfma.SlicingSpec ( ) , tfma.SlicingSpec ( feature_keys= [ 'Category ' ] ) ] ) model_resolver = ResolverNode ( instance_name='latest_ble... | TFX IndexError on Evaluator component |
Python | I have this DataFramewhich looks like thisI want thisreplaced all values with the maximum value . we choose the maximum value from both val1 and val2if i do this i will get the maximum from only val1 | lst = [ [ 'AAA',15 , 'BBB',20 ] , [ 'BBB',16 , 'AAA',12 ] , [ 'BBB',22 , 'CCC',15 ] , [ 'CCC',11 , 'AAA',31 ] , [ 'DDD',25 , 'EEE',35 ] ] df = pd.DataFrame ( lst , columns = [ 'name1 ' , 'val1 ' , 'name2 ' , 'val2 ' ] ) name1 val1 name2 val20 AAA 15 BBB 201 BBB 16 AAA 122 BBB 22 CCC 153 CCC 11 AAA 314 DDD 25 EEE 35 nam... | Groupby names replace values with there max value in all columns pandas |
Python | I have two large NumPy arrays each with shape of ( 519990 , ) that look something like this : As you can see the first array is always in ascending and a positive number . I would like to group everything within the Letters to Order to turn out looking like this : The code I have to do this is : My problem is this proc... | Order = array ( [ 0 , 0 , 0 , 5 , 6 , 10 , 14 , 14 , 14 , 23 , 23 , 39 ] ) Letters = array ( [ A , B , C , D , E , F , G , H , I , J , K , L ] ) { 0 : [ A , B , C ] , 5 : [ D ] , 6 : [ E ] , 10 : [ F ] , 14 : [ G , H , I ] , 23 : [ J , K ] , 39 : [ L ] } df = pd.DataFrame ( ) df [ 'order ' ] = Orderdf [ 'letters ' ] = ... | Grouping two NumPy arrays to a dict of lists |
Python | I do an experiment about how much memory each of Python array types spends , which is list , tuple , set , dict , np.array . Then i got the following result . ( x axis is the length of array , y axis is the memory size . ) I found that the amount of memory a Python set spends increases in steps ( also dict ) , while th... | def get_size ( obj , seen = None ) : size = sys.getsizeof ( obj ) if seen is None : seen = set ( ) obj_id = id ( obj ) if obj_id in seen : return 0 seen.add ( obj_id ) if isinstance ( obj , dict ) : size += sum ( [ get_size ( v , seen ) for v in obj.values ( ) ] ) size += sum ( [ get_size ( k , seen ) for k in obj.keys... | The amount of memory a Python set spends increases in steps |
Python | Details : Currently I am writing within a project based on Magento Cloud test cases with Python-Selenium . So far everything is fine . Currently I only have one problem , which I ca n't explain anymore . Actually it 's only about the verification of a text . Or the verification of a block title within a profile page . ... | selenium.common.exceptions.StaleElementReferenceException : Message : stale element reference : element is not attached to the page document ( Session info : chrome=78.0.3904.108 ) # Verify My Account driver.get ( `` https : my-url.de '' ) try : self.assertEqual ( `` Account Information '' , driver.find_element_by_xpat... | Python Selenium : Block-Title is not properly verified . ( Magento Cloud ) |
Python | In the manual is says : in general , __lt__ ( ) and __eq__ ( ) are sufficient , if you want the conventional meanings of the comparison operatorsBut I see the error : when I run this test : I am surprised that when IntVar ( ) is on the right , __int__ ( ) is not being called . What am I doing wrong ? Adding __gt__ ( ) ... | > assert 2 < threeE TypeError : unorderable types : int ( ) < IntVar ( ) from unittest import TestCaseclass IntVar ( object ) : def __init__ ( self , value=None ) : if value is not None : value = int ( value ) self.value = value def __int__ ( self ) : return self.value def __lt__ ( self , other ) : return self.value < ... | Minimum Methods for Ordering with Duck Typing in Python 3.1 |
Python | I am trying to translate a pipeline of manipulations on a dataframe in R over to its Python equivalent . A basic example of the pipeline is as follows , incorporating a few mutate and filter calls : I can replicate this in pandas without too much trouble but find that it involves some nested lambda calls when using ass... | library ( tidyverse ) calc_circle_area < - function ( diam ) pi / 4 * diam^2calc_cylinder_vol < - function ( area , length ) area * lengthraw_data < - tibble ( cylinder_name=c ( ' a ' , ' b ' , ' c ' ) , length=c ( 3 , 5 , 9 ) , diam=c ( 1 , 2 , 4 ) ) new_table < - raw_data % > % mutate ( area = calc_circle_area ( diam... | How to avoid excessive lambda functions in pandas DataFrame assign and apply method chains |
Python | ( This question was asked here , but the answer was Linux-specific ; I 'm running on FreeBSD and NetBSD systems which ( EDIT : ordinarily ) do not have /proc . ) Python seems to dumb down argv [ 0 ] , so you do n't get what was passed in to the process , as a C program would . To be fair , sh and bash and Perl are no b... | the C child program gets it right : arbitrary-arg0 arbitrary-arg1the python2 program dumbs it down : [ './something2.py ' , 'arbitrary-arg1 ' ] the python3 program dumbs it down : [ './something3.py ' , 'arbitrary-arg1 ' ] the sh script dumbs it down : ./shscript.sh arbitrary-arg1the bash script dumbs it down : ./bashs... | python : obtaining the OS 's argv [ 0 ] , not sys.argv [ 0 ] |
Python | A script in Python did n't work , and I reduced the problem to what follows.In PostgreSQL 9.1 I tried : And in Python 2.7.3 : Why is ' ' not lower than ' ! ' in PostgreSQL ? What is happening ? | SELECT ' P 0 ' < ' P ! ' f > > > ' P 0 ' < ' P ! 'True | ' P 0 ' < ' P ! ' in python and postgresql |
Python | I have a project that I built for it a Class in C ( python c-api ) which I extended more in the python project . The project 's purpose is to provide a test framework for a C library . The test is mainly executed for each pull request of the C library.The project needs to download form a Nexus server the relevant build... | from utils.my_custom_py import MyCustomExtendedfrom importlib.util import find_specfrom importlib import reloadfrom os import system , statimport weakrefimport sysdef setup ( ) : if system ( './setup.py clean build install ' ) > 0 : raise SystemError ( `` Failed to setup python c-api extention class '' ) def main ( ) :... | Python3 reload project that use python c-api |
Python | When you call vpa ( from Octave 's symbolic package ) for the first time , Octave produces some text on screen before outputting the actual result . For example : Note that the actual output ( variable x ) is the string ' 1.0*I ' , as expected . The rest is not part of the function output , but rather text produced dir... | > > x = pretty ( vpa ( 'sqrt ( -1 ) ' ) ) OctSymPy v2.2.4 : this is free software without warranty , see source.Initializing communication with SymPy using a popen2 ( ) pipe.Detected Windows : using `` winwrapy.bat '' to workaround Octave bug # 43036Some output from the Python subprocess ( pid 6680 ) might appear next.... | Avoid unwanted text from Octave 's symbolic package |
Python | Consider the following code , why do n't I need to pass x to Y ? Thank you to the top answers , they really helped me see what was the problem , namely misunderstanding regarding variable scope . I wish I could choose both as correct answer as they are enlightening in their own way . | class X : def __init__ ( self ) : self.a = 1 self.b = 2 self.c = 3class Y : def A ( self ) : print ( x.a , x.b , x.c ) x = X ( ) y = Y ( ) y.A ( ) | Python : Regarding variable scope . Why do n't I need to pass x to Y ? |
Python | Python seems to be automatically converting strings ( not just input ) into raw strings . Can somebody explain what is happening here ? The question marked as a duplicate for this one seems to be useful , but then I do not understand whydoes not get two backslashes when called , and does when repr ( ) is called on it . | Python 3.7.1 ( v3.7.1:260ec2c36a , Oct 20 2018 , 14:57:15 ) [ MSC v.1915 64 bit ( AMD64 ) ] on win32Type `` help '' , `` copyright '' , `` credits '' or `` license '' for more information. > > > s = '\stest ' > > > s'\\stest ' # looks like a raw string > > > print ( s ) \stest > > > s = '\ntest ' > > > s'\ntest ' # thi... | Python automatically converting some strings to raw strings ? |
Python | Why is b read-only while a is not ? This is not mentioned in the documentation . | > > > a = np.where ( np.ones ( 5 ) ) [ 0 ] > > > aarray ( [ 0 , 1 , 2 , 3 , 4 ] ) > > > a.flags [ 'WRITEABLE ' ] True > > > b = np.where ( np.ones ( ( 5,2 ) ) ) [ 0 ] > > > barray ( [ 0 , 0 , 1 , 1 , 2 , 2 , 3 , 3 , 4 , 4 ] ) > > > b.flags [ 'WRITEABLE ' ] False | Why is np.where 's result read-only for multi-dimensional arrays ? |
Python | I want to find all possible combination of the following list : I know it looks a straightforward task and it can be achieved by something like the following code : but what I want is actually a way to give each element of the list data two possibilities ( ' a ' or '-a ' ) .An example of the combinations can be [ ' a '... | data = [ ' a ' , ' b ' , ' c ' , 'd ' ] comb = [ c for i in range ( 1 , len ( data ) +1 ) for c in combinations ( data , i ) ] | all combination of a complicated list |
Python | I have a simple series data looks like : My goal is to reshape it to the horizontal format , one row for each id with its correlated issues and saved in excel , looks likeI am new to Python and not sure how can I achieve it using Python ? Thanks . | id 100241 Issue 1100241 Issue 2100241 Issue 3100242 Issue 1100242 Issue 2100242 Issue 3 id 100241 Issue 1 Issue 2 Issue 3100242 Issue 1 Issue 2 Issue 3 | Reshape vertical series to horizontal in Python |
Python | I 'm trying to get my Python version using Go : This returns empty slices : Any idea what I 'm doing wrong ? | import ( `` log '' `` os/exec '' `` strings '' ) func verifyPythonVersion ( ) { _ , err : = exec.LookPath ( `` python '' ) if err ! = nil { log.Fatalf ( `` No python version located '' ) } out , err : = exec.Command ( `` python '' , `` -- version '' ) .Output ( ) log.Print ( out ) if err ! = nil { log.Fatalf ( `` Error... | Getting Python version using Go |
Python | I have code below to add the data into elastic searchRequirementHow to update the documentHere Dr. Messi , Dr. Christiano has to update the index and Dr. Bernard M. Aaron should not update as it is already present in the index | from elasticsearch import Elasticsearches = Elasticsearch ( ) es.cluster.health ( ) r = [ { 'Name ' : 'Dr . Christopher DeSimone ' , 'Specialised and Location ' : 'Health ' } , { 'Name ' : 'Dr . Tajwar Aamir ( Aamir ) ' , 'Specialised and Location ' : 'Health ' } , { 'Name ' : 'Dr . Bernard M. Aaron ' , 'Specialised an... | How to update the elastic search document with python ? |
Python | I have trained a ML model , and stored it into a Pickle file.In my new script , I am reading new 'real world data ' , on which I want to do a prediction.However , I am struggling . I have a column ( containing string values ) , like : Now comes the issue . I received a new ( unique ) value , and now I can not make pred... | Sex Male Female # This is just as example , in real it is having much more unique values df = pd.read_csv ( 'dataset_that_i_want_to_predict.csv ' ) model = pickle.load ( open ( `` model_trained.sav '' , 'rb ' ) ) # I have an 'example_df ' containing just 1 row of training data ( this is exactly what the model needs ) e... | Can we make the ML model ( pickle file ) more robust , by accepting ( or ignoring ) new features ? |
Python | Here 's the input : And here 's expected output : I 've tried this : But of course it 's not right solution - regex have to match ( \d+ ) 1. but not PRub . 1 1..What should I do to make it work ? | 7 . Data 1 1 . STR1 STR2 3 . 12345 4 . 0876 9 . NO 2 1 . STR 2 . STRT STR 3 . 9909090 5 . YES 6 . NO 7 . YES 8 . NO 9 . YES 10 . 5000 XX 11 . 1000 ZŁ 12 . NO PRub . 1 1 . 1000 XX 2 . NO 3 1 . STRT 2 . STRT 3 . 63110300291 5 . YES 6 . NO 7 . NO 8 . NO 9 . YES 10 . 5000 XX 11 . 1000 ZŁ 12 . NO PRub . 1 1 . 1000 XX 2 . NO... | How to construct regex for this text |
Python | I have dictionary of dictionaries like this.I need to get key of the item that has highest value of c + h.I know you can get key of item with highest value in case like this : Is it possible to use the max function in my case ? | d = { ' a ' : { ' c ' : 1 , ' h ' : 2 } , ' b ' : { ' c ' : 3 , ' h ' : 5 } , ' c ' : { ' c ' : 2 , ' h ' : 1 } , 'd ' : { ' c ' : 4 , ' h ' : 1 } } d = { ' a ' : 1 , ' b ' : 2 , ' c ' : 3 } max ( d , key = d.get ) # ' c ' | Find key of object with maximum property value |
Python | I have an abstract base class in python which defines an abstract method . I want to decorate it with a timer function such that every class extending and implementing this base class is timed and does n't need to be manually annotated . Here 's what I have The error i get is as followI think understand the error pytho... | import functoolsimport timeimport abcclass Test ( metaclass=abc.ABCMeta ) : @ classmethod def __subclasshook__ ( cls , subclass ) : return ( hasattr ( subclass , 'apply ' ) and callable ( subclass.apply ) ) @ abc.abstractmethod def apply ( self , a : str ) - > str : raise NotImplementedError def timer ( func ) : @ func... | Decorators on Python AbstractMethods |
Python | It 's entirely possible that this question is a duplicate , but I do n't know what this concept is called so I do n't even know how to search for it.I 'm new to Python and trying to understand this function from a Caffe example : I figured the parameters stride=1 , pad=1 , etc in the conv_relu function definition are d... | def conv_relu ( bottom , ks , nout , stride=1 , pad=0 , group=1 ) : conv = L.Convolution ( bottom , kernel_size=ks , stride=stride , num_output=nout , pad=pad , group=group ) return conv , L.ReLU ( conv , in_place=True ) | Name of and reason for Python function parameters of type ` name=value ` |
Python | Python allows you to assign a pre-defined function to a class as an attribute , such asHowever , if we try do saywe get the get the following errorPython seems to be viewing this as a object method and providing the implied 'self ' argument . Fair enough , it seems I 've just learned that assigning a function as an att... | def fish_slap ( fish ) : # do somethingclass dance ( object ) : dance_move=fish_slap d=dance ( ) d.dance_move ( `` Halibut '' ) TypeError : fish_slap ( ) takes exactly 1 arguement ( 2 given ) def RMSE ( predicted , observed ) : `` Root mean squared error '' return sp.sqrt ( sp.mean ( ( predicted-observed ) **2 ) ) some... | Assigning functions as attributes of an object , then calling without the implied 'self ' arguement ? |
Python | I 'm trying to implement a recursive merge sort algorithm with only functions that return nothing but I am having difficulty getting it to work . It seems as though it is breaking down the lists and sorting them correctly but is not carrying over those sorted lists into the next recursive call . | def merge ( list1 , list2 ) : result = [ ] i = 0 j = 0 k = 0 while i < len ( list1 ) and j < len ( list2 ) : if list1 [ i ] < list2 [ j ] : result.append ( list1 [ i ] ) i+=1 else : result.append ( list2 [ j ] ) j+=1 k+=1 while i < len ( list1 ) : result.append ( list1 [ i ] ) i+=1 k+=1 while j < len ( list2 ) : result... | Python Recursive Merge Sort Not Working |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.