lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | I am using pytorch-1.5 to do some gan test . My code is very simple gan code which just fit the sin ( x ) function : But when i runing it got this error : Is there something wrong with my code ? | import torchimport torch.nn as nnimport numpy as npimport matplotlib.pyplot as plt # Hyper ParametersBATCH_SIZE = 64LR_G = 0.0001LR_D = 0.0001 N_IDEAS = 5 ART_COMPONENTS = 15 PAINT_POINTS = np.vstack ( [ np.linspace ( -1 , 1 , ART_COMPONENTS ) for _ in range ( BATCH_SIZE ) ] ) def artist_works ( ) : # painting from the... | RuntimeError : one of the variables needed for gradient computation has been modified by an inplace operation ? |
Python | Scenario : On a checkerboard of size MxN , there are red and green pieces.Each square on the board may contain any number of pieces , of any color . ( We can have 5 pieces - 3 green and 2 red in the same square , or for e.g . green green , or red red , or whatever number ) I 'm looking for an axis-aligned rectangle on ... | +-+-+-+-+-+-+ 3 | | | |o|x|o| +-+-+-+-+-+-+ 2 |o| |x| | |o| +-+-+-+-+-+-+ 1 |o| |o| |o|x| +-+-+-+-+-+-+ 0 | |o| |x| |x| +-+-+-+-+-+-+ 0 1 2 3 4 5 | Board game : Find maximum green points with restricted red points |
Python | There are some URLs with [ ] in it likeBut when I try scraping this URL with Scrapy , it makes Request to this URLHow can I force scrapy to not to urlenccode my URLs ? | http : //www.website.com/CN.html ? value_ids [ ] =33 & value_ids [ ] =5007 http : //www.website.com/CN.html ? value_ids % 5B % 5D=33 & value_ids % 5B % 5D=5007 | Force Python Scrapy not to encode URL |
Python | I am currently trying to get a hold of the TF2.0 api , but as I compared the GradientTape to a regular keras.Model.fit I noticed : It ran slower ( probably due to the Eager Execution ) It converged much slower ( and I am not sure why ) .Here is the training loop I used with the GradientTape : And here is the Keras.Mode... | + -- -- -- -- + -- -- -- -- -- -- -- + -- -- -- -- -- -- -- + -- -- -- -- -- -- -- -- -- +| Epoch | GradientTape | GradientTape | keras.Model.fit || | | shuffling | |+ -- -- -- -- + -- -- -- -- -- -- -- + -- -- -- -- -- -- -- + -- -- -- -- -- -- -- -- -- +| 1 | 0.905 | 0.918 | 0.8793 |+ -- -- -- -- + -- -- -- -- -- -- ... | GradienTape convergence much slower than Keras.model.fit |
Python | I am working with Selenium 3.4.0 with Python 3.6.1 . I have written a script following the Python documentation through unittest module which is a built-in Python based on Java ’ s JUnit using geckodriver 0.16.1 and Mozilla Firefox 57.0 on Windows 8 Pro machine , 64 bit OS , x-64 processor . In my test method test_sear... | def test_search_in_python_org ( self ) : driver = self.driver driver.get ( `` http : //www.python.org '' ) self.assertIn ( `` Python '' , driver.title ) elem = driver.find_element_by_name ( `` q '' ) elem.send_keys ( `` pycon '' ) elem.send_keys ( Keys.RETURN ) assert `` No results found . '' not in driver.page_source | Selenium3.4.0-Python3.6.1 : In Selenium-Python binding using unittest how do I decide when to use self.assertIn or assert |
Python | A string is given as an input ( e.g . `` What is your name ? '' ) . The input always contains a question which I want to extract . But the problem that I am trying to solve is that the input is always with unneeded input.So the input could be ( but not limited to ) the following:1- `` eo000 ATATAT EG\n\nWhat is your na... | def extractQuestion ( input ) : index_end_q = input.find ( ' ? ' , 1 ) index_first_letter_of_q = 0 # TODO question = '\n ' . join ( input [ index_first_letter_of_q : index_end_q ] ) | How to slice a string input at a certain unknown index |
Python | Having some arbitrary string such as Can I somehow find repetitive sub-strings delimited by spaces ( EDIT ) ? In this case it would be 'hello ' , ' I am ' and 'string'.I have been wondering about this for some time but I still can not find any real solution . I also have read some articles concerning this topic and hit... | hello hello hello I am I am I am your string string string string of strings ( hello ) { 3 } ( I am ) { 3 } your ( string ) { 4 } of strings | Finding repetitive substrings |
Python | Here is my entire program : which results in : Process finished with exit code -1073741819 ( 0xC0000005 ) In the first place I imported Quandl , but then I received : ModuleNotFoundError : No module named 'Quandl'and then I googled it and read a suggestion to change the name to quandl.I have installed the package in th... | import quandlprint ( `` Hello World '' ) ; | 'import quandl ' produces 'Process finished with exit code -1073741819 ( 0xC0000005 ) ' |
Python | ProblemI need to construct a 2D grid using a set of candidate positions ( values in X and Y ) . However , there may be false positive candidates that should be filtered out , as well as false negatives ( where the position needs to be created for the expected position given the surrounding positions ' values ) . The ro... | grid_size = ( 4 , 4 ) expected_distance = 105 X = np.array ( [ 61.43283582 , 61.56626506 , 62.5026738 , 65.4028777 , 167.03030303 , 167.93965517 , 170.82191781 , 171.37974684 , 272.02884615 , 272.91089109 , 274.1031746 , 274.22891566 , 378.81553398 , 379.39534884 , 380.68181818 , 382.67164179 ] ) Y = np.array ( [ 55.14... | Constructing a 2D grid from potentially incomplete list of candidates |
Python | We have implemented a twisted web api.To handle auth we have used a decorator that we wrap some routes with.The requires_auth wrapper is implemented as follows.The issue is if there are multiple routes with this decorator , then a call toany of them results in the latest route to be decorated being called.This is obvio... | @ requires_auth ( roles= [ Roles.Admin ] ) def get_secret_stuff ( request ) : return 42 def requires_auth ( roles ) : def wrap ( f ) : def wrapped_f ( request , *args , **kwargs ) : # If the user is authenticated then ... return f ( request , *args , **kwargs ) return wrapped_f return wrap def requires_auth ( roles ) :... | Python decorator internally calls wrong function |
Python | I know how to delete every 4th element in a numpy array : Now I want to know if there is a simple command that can delete every nth ( e.g 4 ) times 3 values.A basic example : input : [ 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 ... . ] Would lead to : output : [ 1,2,3,7,8,9,13,14,15,19,20 , ... . ] I was hoping... | frame = np.delete ( frame , np.arange ( 4 , frame.size,4 ) ) | Delete a series of elements every nth time in numpy array |
Python | I 'm working with datasets from two different webpages , but for the same individual - the data sets are legal info on . Some of the data is available on the first page , so I initialize a Defendant object with the proper info , and set the attributes that I do n't currently have the data for to null . This is the clas... | class Defendant ( object ) : `` '' '' holds data for each individual defendant '' '' '' def __init__ ( self , full_name , first_name , last_name , type_of_appeal , county , case_number , date_of_filing , race , sex , dc_number , hair_color , eye_color , height , weight , birth_date , initial_receipt_date , current_faci... | More Pythonic way of adding attributes to class ? |
Python | Suppose I want to write a generic class using mypy , but the type argument for the class is itself a generic type . For example : When I try to call mypy in the definition above I get an error : I tried adding constraints to the T TypeVar 's definition but failed to make this work . Is it possible to do this ? | from typing import TypeVar , Generic , CallableA = TypeVar ( `` A '' ) B = TypeVar ( `` B '' ) T = TypeVar ( `` T '' ) class FunctorInstance ( Generic [ T ] ) : def __init__ ( self , map : Callable [ [ Callable [ [ A ] , B ] , T [ A ] ] , T [ B ] ] ) : self._map = map def map ( self , x : T [ A ] , f : Callable [ [ A ]... | How to use Generic ( higher-kinded ) type variables in python 's type hinting system ? |
Python | I perform the cross product of contiguous segments of a trajectory ( xy coordinates ) using the following script : func1 is particularly slow because of the inner loop so I rewrote the cross-product myself ( func2 ) which is orders of magnitude faster.Is it possible to use the numpy einsum function to make the same cal... | In [ 129 ] : def func1 ( xy , s ) : size = xy.shape [ 0 ] -2*s out = np.zeros ( size ) for i in range ( size ) : p1 , p2 = xy [ i ] , xy [ i+s ] # segment 1 p3 , p4 = xy [ i+s ] , xy [ i+2*s ] # segment 2 out [ i ] = np.cross ( p1-p2 , p4-p3 ) return outdef func2 ( xy , s ) : size = xy.shape [ 0 ] -2*s p1 = xy [ 0 : si... | Can numpy einsum ( ) perform a cross-product between segments of a trajectory |
Python | In Python 2.7 and 3 , the following works : but this gives an error : It seems like there is an upper limit on the number of repetitions allowed . Is this part of the regular expression specification , or a Python-specific limitation ? If Python-specific , is the actual number documented somewhere , and does it vary be... | > > > re.search ( r '' a { 1,9999 } '' , 'aaa ' ) < _sre.SRE_Match object at 0x1f5d100 > > > > re.search ( r '' a { 1,99999 } '' , 'aaa ' ) Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > File `` /usr/lib/python2.7/re.py '' , line 142 , in search return _compile ( pattern , flags ) .... | What 's the maximum number of repetitions allowed in a Python regex ? |
Python | In C++ , I often use the following pattern : But in python I have to repeat call twice : How to avoid duplication of getNextElementPlease ? | while ( int i = getNextElementPlease ( ) ) { printf ( `` % d\n '' , i ) ; } i = getNextElementPlease ( ) while ( i ) : print ( i ) i = getNextElementPlease ( ) | How to use while ( i = getNext ( ) ) pattern in python |
Python | Recently I had an issue where a signal I was using from flask-security was not behaving as expected in python 3.3 . In looking at the source code for flask-security I noticed that the signal I was importing from a module in the flask-security package was also imported in __init__.py . By importing the signal from the t... | from flask.ext.security import user_registeredfrom flask.ext.security.signals import user_registered as user_reg_siguser_registered==user_reg_sig from flask_security.signals import user_registered as user_reg_sigfrom flask_security import user_registereduser_registered==user_reg_sig from flask_security.signals import u... | Difference between python 2.7 and 3.3+ when importing in __init__.py and module from same directory |
Python | In the TensorFlow Functional API guide , there 's an example shown where multiple models are created using the same graph of layers . ( https : //www.tensorflow.org/beta/guide/keras/functional # using_the_same_graph_of_layers_to_define_multiple_models ) Is it possible to save and load these two models while still shari... | encoder_input = keras.Input ( shape= ( 28 , 28 , 1 ) , name='img ' ) x = layers.Conv2D ( 16 , 3 , activation='relu ' ) ( encoder_input ) x = layers.Conv2D ( 32 , 3 , activation='relu ' ) ( x ) x = layers.MaxPooling2D ( 3 ) ( x ) x = layers.Conv2D ( 32 , 3 , activation='relu ' ) ( x ) x = layers.Conv2D ( 16 , 3 , activa... | Saving and loading multiple models with the same graph in TensorFlow Functional API |
Python | I have this pandas DataFrame : I want to get the frequency of the 'yes ' and 'no ' in the class columns per row and have a new data frame which looks like : I looked at this question , but I do n't want the sum but the counts.Any ideas ? | df = pd.DataFrame ( data= [ [ 'yes ' , 'no ' , np.nan ] , [ 'no ' , 'yes ' , 'no ' ] , [ np.nan , 'yes ' , 'yes ' ] , [ 'no ' , 'no ' , 'no ' ] ] , index=pd.Index ( [ 'xyz_1 ' , 'xyz_2 ' , 'xyz_3 ' , 'xyz_4 ' ] , name='ID ' ) , columns= [ 'class1 ' , 'class2 ' , 'class3 ' ] ) print ( df ) Out : ID class1 class2 class3x... | How to get the frequency of a specific value in each row of pandas dataframe |
Python | I 'm kind of new to Haskell and tried making a scrabble solver . It takes in the letters you currently have , finds all permutations of them and filters out those that are dictionary words . The code 's pretty simple : However it 's incredibly slow , compared to a very similar implementation I have with Python . Is the... | import Data.Listmain = do dict < - readFile `` words '' letters < - getLine let dictWords = words dict let perms = permutations letters print [ x | x < - perms , x ` elem ` dictWords ] from itertools import permutationsletters = raw_input ( `` please enter your letters ( without spaces ) : `` ) d = open ( 'words ' ) di... | Why is this Haskell code so slow ? |
Python | The following code defines a sequence of names that are mapped to numbers . It is designed to take a number and retrieve a specific name . The class operates by ensuring the name exists in its cache , and then returns the name by indexing into its cache . The question in this : how can the name be calculated based on t... | class NumberToName : def __generate_name ( ) : def generate_tail ( length ) : if length > 0 : for char in NumberToName.CHARS : for extension in generate_tail ( length - 1 ) : yield char + extension else : yield `` for length in itertools.count ( ) : for char in NumberToName.FIRST : for extension in generate_tail ( leng... | Is there a faster way of converting a number to a name ? |
Python | I 'm trying to wrap for python this simple C++ code using SWIG : and here the relative header : As SWIG input file I 'm using : Now , my makefile ( which is running fine ) is : as I was able to put together from different sources relative to the problem online . Now , once I try to import in python my library as done w... | # include `` hello.h '' int helloW ( ) { std : :cout < < `` Hello , World ! '' ; return 0 ; } # include < iostream > int helloW ( ) ; // decl /* file : pyhello.i *//* name of module to use*/ % module pyhello % { # include `` hello.h '' % } % include `` hello.h '' ; all : swig -c++ -python -Wall pyhello.i gcc -c -fpic p... | Wrapping C++ code for python using SWIG . Ca n't use cout command |
Python | In pdb/ipdb debugging , the useful interact command gives me a fully featured interactive Python console.However , this appears to always be the `` standard '' Python console , even if I use ipdb to begin with . Is there a way to configure ipdb such that interact will give me the IPython console , rather than the stand... | In [ 24 ] : 1/0 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -ZeroDivisionError Traceback ( most recent call last ) < ipython-input-24-05c9758a9c21 > in < module > ( ) -- -- > 1 1/0ZeroDivisionError : division by zeroIn [ 25 ] : % debug > < ipython-input... | Make 'interact ' use IPython console , rather than standard Python one ? |
Python | With the following script : I get the following output : However , if I make a slight modification and wrap time.gmtime : then I get the following error : Obviously it 's trying to call Foo.func as if it was an instance method and passing self as the first argument.Two questions : Both time.gmtime and tmp are functions... | import timeclass Foo ( object ) : func = time.gmtime def go ( self ) : return self.func ( 0.0 ) print time.strftime ( ' % Y ' , Foo ( ) .go ( ) ) 1970 import timedef tmp ( stamp ) : return time.gmtime ( stamp ) class Foo ( object ) : func = tmp def go ( self ) : return self.func ( 0.0 ) print time.strftime ( ' % Y ' , ... | calling a function saved in a class attribute : different behavior with built-in function vs. normal function |
Python | I 'm trying to execute a few python scripts in order to manipulate some images on my website . The external program/tool is written in python and is called PHATCH . I 'm under Windows and using WAMP as my web server.Executing only just one script seems to work well , but I need to execute 4 scripts at the same time ( t... | system ( `` C : \\python\\python.exe C : \\phatch\\phatch.py script1.phatch '' ) ; system ( `` C : \\python\\python.exe C : \\phatch\\phatch.py script2.phatch '' ) ; system ( `` C : \\python\\python.exe C : \\phatch\\phatch.py script3.phatch '' ) ; system ( `` C : \\python\\python.exe C : \\phatch\\phatch.py script4.ph... | Executing several Python scripts at same time causes PHP/Apache to hang |
Python | Write a simple program that reads a line from the keyboard and outputs the same line whereevery word is reversed . A word is defined as a continuous sequence of alphanumeric charactersor hyphen ( ‘ - ’ ) . For instance , if the input is “ Can you help me ! ” the output should be “ naC uoy pleh em ! ” I just tryed with ... | print '' Enter the string : '' str1=raw_input ( ) print ( ' '.join ( ( str1 [ : :-1 ] ) .split ( ' ' ) [ : :-2 ] ) ) | String reverse in Python |
Python | From my understanding , should never match . Actually , php 's preg_replace even refuses to compile this and so does ruby 's gsub . The python re module seems to have a different opinion though : Result : Can anyone provide a reasonable explanation for this behavior ? UpdateThis behavior appears to be a limitation in t... | ( . ) ( ? < ! \1 ) import retest = 'xAAAAAyBBBBz'print ( re.sub ( r ' ( . ) ( ? < ! \1 ) ' , r ' ( \g < 0 > ) ' , test ) ) ( x ) AAAA ( A ) ( y ) BBB ( B ) ( z ) import regextest = 'xAAAAAyBBBBz'print ( regex.sub ( r ' ( . ) ( ? < ! \1 ) ' , r ' ( \g < 0 > ) ' , test ) ) # # xAAAAAyBBBBzprint ( regex.sub ( r ' ( . ) ( ... | Impossible lookbehind with a backreference |
Python | My soft is written in C++ and called by python scripts ( through Swig ) .When the python function uuid.uuid1 ( ) is called in the scripts , the seed used by std : :rand ( ) of C++ seems lost . It 's a problem beacause I have to be able to relaunch my soft with exactly the same behaviour in the C++ code ( it 's not a ma... | # ifndef __INCLUDE__TESTRAND_H__ # define __INCLUDE__TESTRAND_H__void initialize ( unsigned long int seed ) ; unsigned long int get_number ( ) ; # endif # include `` testrand.h '' # include < cstdlib > void initialize ( unsigned long int seed ) { std : :srand ( seed ) ; } unsigned long int get_number ( ) { return std :... | Conflict between uuid.uuid ( ) from Python and std : :rand ( ) from C++ |
Python | Is there a way to get all overriden functions of a subclass in Python ? Example : Here , I would like to get a list [ `` a2 '' ] for an object of class B ( or for the class object itself ) since class B overrides only a single method , namely a2 . | class A : def a1 ( self ) : pass def a2 ( self ) : passclass B ( A ) : def a2 ( self ) : pass def b1 ( self ) : pass | Get overridden functions of subclass |
Python | Im solving some problems on Project Euler and had to generate 2 million primes to solve a problem . My implementation of the Sieve of Eratosthenes turned out to be EXTREMELY slow but I do n't quite know why . Could someone please explain the major problems with this implementation . I thought it was so pretty , and the... | def generatePrimes ( upperBound ) : numbers = range ( 2 , upperBound+1 ) primes = [ ] while numbers : prime = numbers [ 0 ] primes.append ( prime ) numbers = filter ( ( lambda x : x % prime ) , numbers ) return primes def generatePrimes ( upperBound ) : numbers = range ( 2 , upperBound+1 ) for i in xrange ( len ( numbe... | Why is my Sieve of Eratosthenes so slow ? |
Python | Why `` \ '' and `` / '' are mixed ? os.getcwd ( ) emits backslash string.On the other hand , QFileDialog emits forward slash string.Why ? ExamplePlease execute this sample code.Result ( on my occasion ) from os.getcwd ( ) : J : \from QFileDialog : C : /Users/******/setup.py | from PySide import QtGuifrom PySide import QtCoreimport sysimport osclass DirectoryPrinter ( QtGui.QWidget ) : def __init__ ( self , parent=None ) : super ( DirectoryPrinter , self ) .__init__ ( parent=None ) self.filedialog_pushbutton = QtGui.QPushButton ( `` filedialog '' , self ) self.connect ( self.filedialog_pushb... | Why does QFileDialog use slash instead of backslash ? |
Python | What is the best way of doing this in Python ? I actually tried Google first , but as far as I can see the only solution would be to use while . | for ( v = n / 2 - 1 ; v > = 0 ; v -- ) | For-loops in Python |
Python | Consider the array aWhat is a vectorized way to get the cumulative argmax ? Here is a non-vectorized way to do it . Notice that as the window expands , argmax applies to the growing window . | np.random.seed ( [ 3,1415 ] ) a = np.random.randint ( 0 , 10 , ( 10 , 2 ) ) aarray ( [ [ 0 , 2 ] , [ 7 , 3 ] , [ 8 , 7 ] , [ 0 , 6 ] , [ 8 , 6 ] , [ 0 , 2 ] , [ 0 , 4 ] , [ 9 , 7 ] , [ 3 , 2 ] , [ 4 , 3 ] ] ) array ( [ [ 0 , 0 ] , < -- both start off as max position [ 1 , 1 ] , < -- 7 > 0 so 1st col = 1 , 3 > 2 2nd col... | cumulative argmax of a numpy array |
Python | I was expecting to be able to do something like : or maybe : My current solution , which seems to work fine isBut it looks somewhat hacky . Is there a more `` correct '' way ? I do n't need a deep copy . | a = SimpleNamespace ( x='test ' ) b = a.copy ( ) b = SimpleNamespace ( a ) b = SimpleNamespace ( **a.__dict__ ) | How to `` correctly '' copy a types.SimpleNamespace object ? |
Python | I have a set of modules that I 've written in C++ and exported to Python using pybind11 . All of these modules should be able to be used independently , but they use a common set of custom types that are defined in a utility library.In each module there is code something like what 's below . The Color.hpp header define... | # include < pybind11/pybind11.h > # include < pybind11/stl.h > # include < string > # include `` Color.hpp '' std : :vector < Color > buncha_colors ( int n , std : :string & color ) { std : :vector < Color > out ; for ( ; n -- > 0 ; ) { out.push_back ( Color ( color ) ) ; } return out ; } PYBIND11_MODULE ( pb11_example... | Splitting up pybind11 modules and issues with automatic type conversion |
Python | Relating to this answer , is there a fast way to compute medians over an array that has groups with an unequal number of elements ? E.g . : And then I want to compute the difference between the number and the median per group ( e.g . median of group 0 is 1.025 so the first result is 1.00 - 1.025 = -0.025 ) . So for the... | data = [ 1.00 , 1.05 , 1.30 , 1.20 , 1.06 , 1.54 , 1.33 , 1.87 , 1.67 , ... ] index = [ 0 , 0 , 1 , 1 , 1 , 1 , 2 , 3 , 3 , ... ] result = [ -0.025 , 0.025 , 0.05 , -0.05 , -0.19 , 0.29 , 0.00 , 0.10 , -0.10 , ... ] import numpy as npnp.random.seed ( 0 ) rows = 10000cols = 500ngroup = 100 # Create random data and group... | Fast alternative for numpy.median.reduceat |
Python | I try to do a SELECT ... WHERE id IN ( 1,2,3 ) efficiently using Sqlalchemy with Postges.If I do a simple select : Sqlalchemy runs this query : When the array gets longer this is not efficient . Also this does not work with baked queries.Knowing that Postgres supports tuples as parameters , I tried to put in my Array/T... | s.query ( Model ) .filter ( Model.id.in_ ( [ 1,2,3 ] ) ) .all ( ) SELECT model.id AS model_id FROM model WHERE model.id IN ( % ( id_1 ) s , % ( id_2 ) s , % ( id_3 ) s ) { 'id_1 ' : 1 , 'id_2 ' : 2 , 'id_3 ' : 3 } s.query ( Model ) .filter ( Model.id.in_ ( bindparam ( 'my_tuple ' ) ) ) .params ( my_tuple= ( 1,2,3 ) ) .... | Executing WHERE IN using bindparameters in Sqlalchemy/Postgres |
Python | Consider this simple setup : As you can see , the indexes are the same , just in a different order . Now , consider a simple logical comparison using the equality ( == ) operator : This throws a ValueError , most likely because the indexes do not match . On the other hand , calling the equivalent eq operator works : OT... | x = pd.Series ( [ 1 , 2 , 3 ] , index=list ( 'abc ' ) ) y = pd.Series ( [ 2 , 3 , 3 ] , index=list ( 'bca ' ) ) xa 1b 2c 3dtype : int64yb 2c 3a 3dtype : int64 x == y -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -ValueError Traceback ( most recent call la... | Why is n't pandas logical operator aligning on the index like it should ? |
Python | I have two matrix ( same row and column ) : one with float values , which are grouped by indices in the other matrix . As a result , I want a dictionary or a list with the sums of the elements for each index.Indices always start at 0.I found this solution , but I 'm searching for a faster one.I 'm working with matrix w... | A = np.array ( [ [ 0.52,0.25 , -0.45,0.13 ] , [ -0.14 , -0.41,0.31 , -0.41 ] ] ) B = np.array ( [ [ 1,3,1,2 ] , [ 3,0,2,2 ] ] ) RESULT = { 0 : -0.41 , 1 : 0.07 , 2 : 0.03 , 3 : 0.11 } import numpy as npdef matrix_sum_by_indices ( indices , matrix ) : a = np.hstack ( indices ) b = np.hstack ( matrix ) sidx = a.argsort (... | Sum matrix elements group by indices in Python |
Python | There are a couple of ways to construct a dictionary in python , for example : andWhen you benchmark theseyou see that the first method is almost 3x slower than the second . Why is this ? | keyvals = [ ( 'foo ' , 1 ) , ( 'bar ' , 'bar ' ) , ( 'baz ' , 100 ) ] dict ( keyvals ) dkwargs = { 'foo ' : 1 , 'bar ' : 'bar ' , 'baz ' : 100 } dict ( **dkwargs ) In [ 0 ] : % timeit dict ( keyvals ) 667 ns ± 38 ns per loop ( mean ± std . dev . of 7 runs , 1000000 loops each ) In [ 1 ] : % timeit dict ( **dkwargs ) 22... | Why is python dict creation from list of tuples 3x slower than from kwargs |
Python | I am stuck on how to apply the custom function to calculate the p-value for two groups obtained from pandas groupby.vocabularyproblem setupQuestionNow I want to add two more columns to get the p-value between test and control group.But in my groupby I can only operate on one series at a time and I am not sure how to us... | test = 0 == > testtest = 1 == > control import numpy as npimport pandas as pdimport scipy.stats as ssnp.random.seed ( 100 ) N = 15df = pd.DataFrame ( { 'country ' : np.random.choice ( [ ' A ' , ' B ' , ' C ' ] , N ) , 'test ' : np.random.choice ( [ 0,1 ] , N ) , 'conversion ' : np.random.choice ( [ 0,1 ] , N ) , 'sex '... | How to get the p-value between two groups after groupby in pandas ? |
Python | The following simple four-line code produces a memory leak in my Python 2.6.6 / NumPy 1.7.0 / MKL 10.3.6 setup : With each operation , the used memory grows by the size of a 10x10 matrix . However , there is no such behaviour when I use a NumPy 1.4.1/ATLAS setup . I have read about MKL not necessarily freeing memory au... | import numpy as npt = np.random.rand ( 10,10 ) while True : t = t / np.trace ( t ) numpy 1.7.0lapack_opt_info : libraries = [ 'mkl_rt ' , 'pthread ' ] library_dirs = [ ' $ MKLPATH/lib/intel64 ' ] define_macros = [ ( 'SCIPY_MKL_H ' , None ) ] include_dirs = [ ' $ MKLPATH/include ' ] blas_opt_info : libraries = [ 'mkl_rt... | How to avoid this four-line memory leak with NumPy+MKL ? |
Python | Consider the following functions : They should be equivalent . But there 's a performance difference : The version without the else is 10 % slower . This is pretty significant . Why ? | def fact1 ( n ) : if n < 2 : return 1 else : return n * fact1 ( n-1 ) def fact2 ( n ) : if n < 2 : return 1 return n * fact2 ( n-1 ) > > > T ( lambda : fact1 ( 1 ) ) .repeat ( number=10000000 ) [ 2.5754408836364746 , 2.5710129737854004 , 2.5678811073303223 ] > > > T ( lambda : fact2 ( 1 ) ) .repeat ( number=10000000 ) ... | Why does removing the else slow down my code ? |
Python | I have a list of strings as follows : and I 'm trying to find an effective way to create two time objects ( I suppose this is the only way to keep track of a range of time , which I will later combine with a date object ) . It is clear to humans what we mean we say 11:00-1:00AM , but wondering what 's an effective way ... | 4:00-5:00PM11:00-2:00PM12:00-1:00PM11:00-1:00AM datetime.time ( 23 , 0 ) datetime.time ( 1 , 0 ) | Python : Effective way to convert ambiguous hours into time object ? |
Python | Let 's say I have a list of 16 numbers . With these 16 numbers I can create different 4x4 matrices . I 'd like to find all 4x4 matrices where each element in the list is used once , and where the sum of each row and each colum is equal to 264.First I find all combination of elements within the list that sum up to 264re... | numbers = [ 11 , 16 , 18 , 19 , 61 , 66 , 68 , 69 , 81 , 86 , 88 , 89 , 91 , 96 , 98 , 99 ] candidates = [ ] result = [ x for x in itertools.combinations ( numbers , 4 ) if sum ( x ) == 264 ] for i in range ( 0 , len ( result ) ) : candidates.append ( list ( itertools.permutations ( result [ i ] ) ) ) test = [ ] for i ... | Given a list of numbers , find all matrices such that each column and row sum up to 264 |
Python | I was wondering why many functions - especially in numpy - utilize tuples as function parameters ? e.g . : What could possibly be the use for that ? Why not simply have something such as the following , since clearly the first parameters will always denote the size of the array ? Is it because there might be additional... | a = numpy.ones ( ( 10 , 5 ) ) a = numpy.ones ( 10 , 5 ) a = numpy.ones ( 10 , 5 , dtype=numpy.int ) | Why tuple convention in function parameters ? |
Python | Currently , I 'm trying to scrape 10-K submission text files on sec.gov.Here 's an example text file : https : //www.sec.gov/Archives/edgar/data/320193/000119312515356351/0001193125-15-356351.txtThe text document contains things like HTML tags , CSS styles , and JavaScript . Ideally , I 'd like to scrape only the conte... | import requestsimport reurl = 'https : //www.sec.gov/Archives/edgar/data/320193/000119312515356351/0001193125-15-356351.txt'response = requests.get ( url ) text = re.sub ( ' < . * ? > ' , `` , response.text ) print ( text ) | Get a clean string from HTML , CSS and JavaScript |
Python | I know that if a `` yield '' statement is present in a function it will be treated as a generator.But how does python interpreter works in that case when the function ( generator ) called for the first time.I mean when the code is interpreted i think first `` gen '' will get bind to a function object . Why it does n't ... | > > > def gen ( ) : ... print ( `` In gen '' ) ... yield 1 ... yield 2 ... > > > type ( gen ) < type 'function ' > > > > a = gen > > > type ( a ) < type 'function ' > > > > > > > b = a ( ) > > > type ( b ) < type 'generator ' > > > > b.next ( ) In gen1 > > > b.next ( ) 2 > > > | How python interpret a function as a generator |
Python | I want to print a dictionary inside a list like this : I do n't want quotations in name and id . However , I want them in the values portion of that dictionary . | [ { name : 'red ' , id : ' 1 ' } , { name : 'yellow ' , id : ' 2 ' } , { name : 'black ' , id : ' 3 ' } , { name : 'white ' , id : ' 4 ' } ] ` | Dictionary in list |
Python | I have been using AWS Elastic Beanstalk to run this web app for a while with no issues on Amazon 's Linux version Python 2.7 running on 64bit Amazon Linux/2.0.1.When I tried to `` upgrade '' to the latest Amazon Linux version : Python 2.7 version , Linux/2.7.7 or any version after 2.0.1 , I get this error : ImproperlyC... | MySQL-python==1.2.5mysqlclient==1.3.14 packages : yum : python27-devel : [ ] libmemcached-devel : [ ] gcc : [ ] libxml2-devel : [ ] libxslt-devel : [ ] | Django on AWS Elastic Beanstalk - No module named MySQLdb Error |
Python | I have a problem to write asyncio.sleep contained unit tests . Do I wait actual sleep time ... ? I used freezegun to mocking time.This library is really helpful when I try to run tests with normal callables . but I can not find answer to run tests which contains asyncio.sleep ! What I want : What I 'm doing : | async def too_many_sleep ( delay ) : await asyncio.sleep ( delay ) do_something ( ) def test_code ( ) : task = event_loop.create_task ( too_many_sleep ( 10000 ) ) # I want test like ` assert_called ( do_something ) ` without realtime delays def test_code ( ) : task = event_loop.create_task ( too_many_sleep ( 10000 ) ) ... | How to make unit test with ` asyncio.sleep ( ) ` contained code ? |
Python | The QuestionWhy , in CPython , doestake linear time , buttake quadratic time ? Proof : What I knowCPython has an optimisation for string addition when the string being added to has a reference count of 1.This is because strings in Python are immutable , and so normally they can not be edited . If multiple references ex... | def add_string ( n ) : s = `` for _ in range ( n ) : s += ' ' def add_string_in_list ( n ) : l = [ `` ] for _ in range ( n ) : l [ 0 ] += ' ' Timer ( partial ( add_string , 1000000 ) ) .timeit ( 1 ) # > > > 0.1848409200028982Timer ( partial ( add_string , 10000000 ) ) .timeit ( 1 ) # > > > 1.1123797750042286 Timer ( pa... | CPython string addition optimisation failure case |
Python | I built a wx python app that runs a background thread to perform some computation . However , my current implementation does not allow for unit testing.I very closely based my implementation off of the first example in this tutorial : http : //wiki.wxpython.org/LongRunningTasksThe code below uses wx.PostEvent ( ) and f... | import timefrom threading import *import unittestimport wx # Button definitionsID_START = wx.NewId ( ) ID_STOP = wx.NewId ( ) # Define notification event for thread completionEVT_RESULT_ID = wx.NewId ( ) def EVT_RESULT ( win , func ) : `` '' '' Define Result Event . '' '' '' win.Connect ( -1 , -1 , EVT_RESULT_ID , func... | How to have wxpython capture thread events in a unit test ? |
Python | I am in simple doubt ... I created the following dictionary : But , when I want to see the dictionary keys and values I got : See that the `` b '' and `` c '' has swapped their position . How can I make the position be the same of the moment that the dictionary was created ? | > > > alpha= { ' a ' : 10 , ' b ' : 5 , ' c ' : 11 } > > > alpha { ' a ' : 10 , ' c ' : 11 , ' b ' : 5 } | Items ordering in Python dictionary |
Python | Many Python builtin `` functions '' are actually classes , although they also have a straightforward function implementation . Even very simple ones , such as itertools.repeat . What is the motivation for this ? It seems like over-engineering to me.Edit : I am not asking about the purpose of itertools.repeat or any oth... | def repeat ( x ) : while True : yield x | Why are many Python built-in/standard library functions actually classes |
Python | i have the following problem : I want to integrate a 2D array , so basically reversing a gradient operator.Assuming i have a very simple array as follows : Then i construct my vectorfield as a complex-valued arreay ( x-vector = real part , y-vector = imaginary part ) : So the real part for example looks like thisNow i ... | shape = ( 60 , 60 ) sampling = 1k_mesh = np.meshgrid ( np.fft.fftfreq ( shape [ 0 ] , sampling ) , np.fft.fftfreq ( shape [ 1 ] , sampling ) ) k = k_mesh [ 0 ] + 1j * k_mesh [ 1 ] k_grad = np.gradient ( k , sampling ) def freq_array ( shape , sampling ) : f_freq_1d_y = np.fft.fftfreq ( shape [ 0 ] , sampling [ 0 ] ) f_... | Integrate a 2D vectorfield-array ( reversing np.gradient ) |
Python | I have a numpy array like this : And I do not understand what is the difference between candidates [ 0 ] : And candidates [ 0:1 ] : because I believe the two should give the exact same results ? I mean the later i.e . candidates [ 0:1 ] is supposed to represent the first element only , right ? So , what is the differen... | candidates = array ( [ [ 1 , 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 1 , 0 , 1 , 0 , 1 , 0 , 1 , 1 , 0 , 0 , 1 , 0 , 1 , 0 , 0 , 0 , 1 , 0 , 0 , 1 , 0 ] , [ 0 , 0 , 1 , 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 1 , 0 , 1 , 0 , 1 , 1 , 1 , 1 , 0 , 1 , 0 , 1 , 1 ] , [ 1 , 0 , 1 , 1 ,... | difference between A [ 0 ] and A [ 0:1 ] numpy arrays in python |
Python | I 'm given a set of lists , for instance : [ [ 0 , 1 , 3 ] , [ 0 , 2 , 12 ] , [ 6 , 9 , 10 ] , [ 2 , 4 , 11 ] , [ 2 , 7 , 13 ] , [ 3 , 5 , 11 ] , [ 3 , 7 , 10 ] , [ 4 , 10 , 14 ] , [ 5 , 13 , 14 ] ] I need to find the maximum number of disjoint subsets that this list contains . In this case , the answer is 4.Another ex... | def is_disjoint ( disjoints , i , j , k ) : disjoints_flat = list ( chain.from_iterable ( disjoints ) ) if ( i in disjoints_flat ) or ( j in disjoints_flat ) or ( k in disjoints_flat ) : return False return True ... . other code # disjoint determinationn_disjoints = 0disjoints = [ ] # sets is the inputfor set in sets :... | Largest possible number of disjoint subsets in a set |
Python | Qt silently catches exceptions in Python callbacks and exits the program with an error code . This can be demonstrated with a short example : When clicking the button we get clicked Process finished with exit code 1This answer ( from which I modified the example ) shows how to install a custom exception hook . So lets ... | import sysfrom PyQt5 import QtWidgets # _excepthook = sys.excepthook # def exception_hook ( exctype , value , traceback ) : # _excepthook ( exctype , value , traceback ) # sys.excepthook = exception_hookclass Test ( QtWidgets.QPushButton ) : def __init__ ( self , parent=None ) : QtWidgets.QWidget.__init__ ( self , pare... | Why does sys.excepthook behave differently when wrapped ? |
Python | I am trying to build a small LSTM that can learn to write code ( even if it 's garbage code ) by training it on existing Python code . I have concatenated a few thousand lines of code together in one file across several hundred files , with each file ending in < eos > to signify `` end of sequence '' .As an example , m... | setup ( name='Keras ' , ... ] , packages=find_packages ( ) ) < eos > import pyux ... with open ( 'api.json ' , ' w ' ) as f : json.dump ( sign , f ) < eos > file = open ( self.textfile , ' r ' ) filecontents = file.read ( ) file.close ( ) filecontents = filecontents.replace ( `` \n\n '' , `` \n '' ) filecontents = file... | Why does my keras LSTM model get stuck in an infinite loop ? |
Python | I have noticed some inconsistencies between Python and JavaScript when converting a string to base36 . Python Method : Result : 37713647386641447Javascript Method : Result : 37713647386641450What causes the different results between the two languages ? What would be the best approach to produce the same results irregar... | > > > print int ( 'abcdefghijr ' , 36 ) < script > document.write ( parseInt ( `` abcdefghijr '' , 36 ) ) ; < /script > | Converting string to base36 inconsistencies between languages . |
Python | I 'd like to recreate this expression with Python AST : And I can achieve this with the following AST structure : But the above AST structure is identical for 2 expression in a single line and 2 expressions , each in a separate line.I know that I can manually calculate and modify the nodes ' col_offset and lineno attri... | 1 == 2 ; 1 > = 2 Module ( body= [ Expr ( value=Compare ( left=Num ( n=1 ) , ops= [ Eq ( ) ] , comparators= [ Num ( n=2 ) ] ) ) , Expr ( value=Compare ( left=Num ( n=1 ) , ops= [ GtE ( ) ] , comparators= [ Num ( n=2 ) ] ) ) ] ) | Easily producing Python AST for multiple expressions in one line |
Python | i am having issues with regex matching in python i have a string as follows : my regular expression has two main groups bind together with | and that regular expression is as follows : Lets call them ( A | B ) . Where A = ( ( ? < =ICD\s : \s ) .*\n . * ) and B = ( ( ? < =ICD\s ) .* ) . According to documentation | work... | test_str = ( `` ICD : 12123575.007787 . 098.3 , \n '' `` 193235.1 , 132534.0 , 17707.1,1777029 , V40‚0 , 5612356,9899\n '' ) regex = r '' ( ( ? < =ICD\s : \s ) .*\n.* ) | ( ( ? < =ICD\s ) . * ) '' import reregex = r '' ( ( ? < =ICD\s : \s ) .*\n.* ) | ( ( ? < =ICD\s ) . * ) '' test_str = ( `` ICD : 12123575.007787 . 09... | Regex does n't stop evaluating after matching with first rule with OR operator |
Python | I have a really weird python problem . I have already asked several colleagues who all had no idea how it happened and how it could be solved.I have a shallow dict of strings that I receive from an API call and I want to assign some of those values to a new dict.This is what the first dict looks like . Just a bunch of ... | dict2= { } dict2 [ 'access_key ' ] = dict1 [ 'access_key ' ] dict2 [ 'secret_access_key ' ] = dict1 [ 'secret_access_key ' ] , dict2 [ 'session_token ' ] =dict1 [ 'session_token ' ] , dict2 [ 'region ' ] = dict1 [ 'region ' ] | Python turns strings into tuples after assigned to dictionary |
Python | I have a XML file : Using XML ElementTree , I would like to insert a tag < Opinion > that has an attribute category= . Say I have a list of chars list = [ ' a ' , ' b ' , ' c ' ] , is it possible to incrementally asign them to each text so I have : I am aware I can use the sentence id attribute but this would require a... | < sentence id= '' en_BlueRibbonSushi_478218345:2 '' > < text > It has great sushi and even better service. < /text > < /sentence > < sentence id= '' en_BlueRibbonSushi_478218345:3 '' > < text > The entire staff was extremely accomodating and tended to my every need. < /text > < /sentence > < sentence id= '' en_BlueRibb... | XML ElementTree - indexing tags |
Python | Tested this both on Ubuntu and ArchLinux , I getWhy ? | from ctypes import *libc = CDLL ( 'libc.so.6 ' ) libc.environ ( ) Segmentation fault | Why does Python segfault when attempting to call environ using ctypes on libc ? |
Python | Below I have setup a script which simply executes a search on a website . The goal is to capture JSON data utilizing Selenium from an event that is fired from an intermediate script , namely the POST request to `` https : //www.botoxcosmetic.com/sc/api/findclinic/FindSpecialists '' as seen in the included image , but w... | from selenium import webdriverbase_url = 'https : //www.botoxcosmetic.com/women/find-a-botox-cosmetic-specialist'driver = webdriver.Chrome ( ) driver.find_element_by_class_name ( 'normalZip ' ) .send_keys ( '10022 ' ) driver.find_element_by_class_name ( 'normalSearch ' ) .click ( ) | Capturing JSON data from intermediate events using Selenium |
Python | From time to time I face this dilemma . Suppose I have a function like this : I want to let the caller specify kwargs to pass to make_actor ( ) ( a_kwargs ) , and to act ( ) ( b_kwargs ) . The problem is , of course , that foo can only take **kwargs once . ( In almost all cases a_kwargs and b_kwargs share no common key... | def foo ( ... , **kwargs ) : ... actor = make_actor ( ... , **a_kwargs ) return actor.act ( ... , **b_kwargs ) def foo1 ( ... , **kwargs ) : ... a_kwargs = { k : kwargs.pop ( k ) for k in kwargs.keys ( ) if k in [ 'arg1 ' , 'arg2 ' , ... ] } actor = make_actor ( ... , **a_kwargs ) return actor.act ( ... , **kwargs ) de... | Splitting kwargs between function calls |
Python | If I have a script that builds eggs , basically by runningfor a number of setup.py files that use setuptools to define how eggs are built , is there an easy way to determine if there were any errors in building the egg ? A situation I had recently , was that there was a syntax error in a module . Setuptools spat out a ... | python setup.py bdist_egg -- exclude-source-files | How can I detect errors programatically when building an egg with setuptools ? |
Python | after upgrade to pip-19.3.1 | pip-compile requirements.inTraceback ( most recent call last ) : File `` /usr/local/bin/pip-compile '' , line 7 , in < module > from piptools.scripts.compile import cli File `` /usr/local/lib/python3.6/dist-packages/piptools/scripts/compile.py '' , line 11 , in < module > from .._compat import install_req_from_line , p... | Module 'pip._internal.download ' has no attribute 'is_file_url ' |
Python | If I have a python file like : And I type : make in vim , it nicely builds me a : cwindow filled with the relevant areas to move up the traceback . However , it defaults my cursor to the first frame of the call ( in name == 'main ' ) . Can I somehow change the default behaviour , so it takes me to the actual call of th... | def Bar ( ) : raise NotImplementedError def Foo ( ) : Bar ( ) if __name__ == '__main__ ' : Foo ( ) makeprg=python % errorformat= % A File `` % f '' \ , line % l % . % # , % Z % [ % ^ ] % \ @ = % m main.py 1 || Traceback ( most recent call last ) : 2 main.py|8| 3 || Foo ( ) 4 main.py|5| 5 || Bar ( ) 6 main.py|2| 7 || ra... | Vim w/Python : Make `` : make '' take me to the error |
Python | I have build a program ( using Django 1.9 ) to track tournaments . Each tournament consists of a series of bouts , and each bout has two people ( combatants ) associated with it.A tournament has a 'combatant_pool ' , which contains a subset of all combatant objects . The interface currently allows me to add/remove comb... | class combatant ( models.Model ) : first_name = models.CharField ( max_length=100 ) class tournament ( models.Model ) : combatant_pool = models.ManyToManyField ( combatant , blank=True ) class bout ( models.Model ) : parent_tournament = models.ForeignKey ( tournament , on_delete=models.CASCADE ) combatant_1 = models.Fo... | Limiting queryset for foreign key for inline formset in Django |
Python | Consider this snippet : To run the above mcve you 'll just need to run pip install lark-parser PyQt5 QScintillaI 'm trying to figure out how to modify LexerJson so the symbols [ ] { } will support folding . When using an existing class such as qscilexercpp.cpp the folding behaviour is given to you just for free , for i... | import sysimport textwrapimport refrom PyQt5.Qt import * # noqafrom PyQt5.Qsci import QsciScintillafrom PyQt5.Qsci import QsciLexerCustomfrom lark import Lark , inline_args , Transformerclass LexerJson ( QsciLexerCustom ) : def __init__ ( self , parent=None ) : super ( ) .__init__ ( parent ) self.create_grammar ( ) sel... | How do you add folding to QsciLexerCustom subclass ? |
Python | A call to isinstance returns True outside but False inside a map over a series ( and an applymap over a dataframe ) ... A call to isinstance for the single value in this series yields True.Inside a map over the series it gives True.But if we try something contingent on that value , say convert to a string ... ... it ap... | import pandas as pdimport pytzs = pd.Series ( [ pd.Timestamp ( 2018,5,11,6,0,0,0 , pytz.timezone ( 'UTC ' ) ) ] ) s0 2018-05-11 06:00:00+00:00dtype : datetime64 [ ns , UTC ] isinstance ( s.iloc [ 0 ] , pd.Timestamp ) True s.map ( lambda x : isinstance ( x , pd.Timestamp ) ) .iloc [ 0 ] True s.map ( lambda x : x.isoform... | Why does isinstance return the wrong value only inside a series map ? |
Python | This question is close to mine , but not quite : List minimum in Python with None ? . I need to allow for the possibility of all values in the list being None.I have a situation where I have to look up some numbers in a database , and they may either exist or come back as null . I need to find the minimum of those exis... | min_if_exists ( 1 , 2 ) returns 1min_if_exists ( 5 , None ) returns 5min_if_exists ( None , None ) returns None def min_if_exists ( a , b ) : return min ( a , b ) elif a : return aelif b : return belse : return None lowest = min ( x for x in ( a , b ) if x is not None ) def min_if_exists ( list_of_nums ) : not_a_none_e... | Minimum of numbers that are not None in Python |
Python | I am trying to wrap my head around python 's decorator . But there is something I do n't understand . This is my code , my question is related to func_decorate2 ( decorator with parameter ) .Will output : Why do I have underscore first in this example ? Thanks | def func_decorate ( f ) : def wrapper ( ) : print ( 'wrapped ' ) ; f ( ) return wrapper @ func_decoratedef myfunc1 ( ) : print ( 'func1 ' ) def func_decorate2 ( tag_name ) : def _ ( f ) : print ( 'underscore ' ) return f return _ @ func_decorate2 ( ' p ' ) def myfunc2 ( ) : print ( 'func2 ' ) print ( 'call func1 ' ) my... | Python Decorator executed on load/import |
Python | I 'm using type hints and mypy more and more . I however have some questions about when I should explicitly annotate a declaration , and when the type can be determined automatically by mypy.Ex : Should I writeIn this case ? Now if I have the following function : and somewhere in my code : Should I write : | def assign_volume ( self , volume : float ) - > None : self._volume = volume * 1000 self._volume : float = volume *1000 def return_volume ( self ) - > float : return self._volume my_volume = return_volume ( ) my_volume : float = return_volume ( ) | Type hints : when to annotate |
Python | I 'm trying to add a clipping path to a TIFF image . I made one TIFF file with GIMP that contains a clipping path and I can clip my image using it byBut I would like to append clipping path info as coordinates like GIMP does into the image file itself so later another process can read it ... I 've tried with ImagickDra... | $ img = new Imagick ( `` ./test.tiff '' ) ; $ img- > clipPathImage ( `` # 1 '' , false ) ; | Adding clippath information to an image |
Python | I have a file with lots of sections in this format : The file can be hundreds of thousands of lines long . The number of attributes and fields for each section can be different . I 'd like to build a few dictionaries to hold some of these values . I have a separate dictionary already which holds all the possible 'attri... | section_name_1 < attribute_1 : value > < attribute_2 : value > ... < attribute_n : value > { field_1 finish_num : start_num some_text ; field_2 finish_num : start_num some_text ; ... field_n finish_num : start_num some_text ; } ; section_name_2 ... ... and so on import os , refrom collections import defaultdictdef mapF... | How to iterate through this text file faster ? |
Python | I have two sets of strings ( A and B ) , and I want to know all pairs of strings a in A and b in B where a is a substring of b.The first step of coding this was the following : However , I wanted to know -- is there a more efficient way to do this with regular expressions ( e.g . instead of checking if a in b : , check... | for a in A : for b in B : if a in b : print ( a , b ) import collections prefix_table = collections.defaultdict ( set ) for k , b in enumerate ( B ) : for i in xrange ( len ( prot_seq ) -10 ) : j = i+10+1 prefix_table [ b [ i : j ] ] .add ( k ) for a in A : if len ( a ) > = 10 : for k in prefix_table [ a [ :10 ] ] : # ... | Efficient strings containing each other |
Python | I 'm very new to programming so I apologize in advance if my question is too silly . Executing this code in Python 2.6 prints letters a , b , c , d , each line of output appears after a second . This is expected behavior . But in Python 3.1 execution is blocked at line output=p.stdout.readline ( ) . How to correct this... | # ! /usr/bin/python2.6 import subprocess , time p=subprocess.Popen ( [ 'cat ' ] , stdin=subprocess.PIPE , stdout=subprocess.PIPE ) for i in 'abcd ' : p.stdin.write ( str.encode ( i+'\n ' ) ) output=p.stdout.readline ( ) print ( output ) time.sleep ( 1 ) | Why does this code behave differently in Python3.1 than in Python2.6 ? |
Python | I 've been creating this bot for 2 months then I stopped for 1 month . When I tried to run my bot again I always get this error ( In the real code , I replace 'TOKEN ' with real token . ) : This is my code : I 've tried to fix this problem for a day . | File `` main.py '' , line 10 , in < module > bot.run ( 'TOKEN ' ) File `` venv\lib\site-packages\discord\client.py '' , line 640 , in run return future.result ( ) File `` venv\lib\site-packages\discord\client.py '' , line 621 , in runner await self.start ( *args , **kwargs ) File `` venv\lib\site-packages\discord\clien... | Ca n't use bot.run ( 'TOKEN ' ) - Discord.py |
Python | I was reading this post and I wonder if someone can find the way to catch repetitive motifs into a more complex string.For example , find all the repetitive motifs inHere the repetitive motifs : 'AAACACGTACGTAATTCCGTGTGTCCCCTATACGTATACGTTT'So , the output should be something like this : This example comes from a typica... | string = 'AAACACGTACGTAATTCCGTGTGTCCCCTATACGTATACGTTT ' output = { 'ACGT ' : { 'repeat ' : 2 , 'region ' : ( 5,13 ) } , 'GT ' : { 'repeat ' : 3 , 'region ' : ( 19,24 ) } , 'TATACG ' : { 'repeat ' : 2 , 'region ' : ( 29,40 ) } } | A more complex version of `` How can I tell if a string repeats itself in Python ? '' |
Python | I ’ ve recently started working with azure for ML and am trying to use machine learning service workspace.I ’ ve set up a workspace with the compute set to NC6s-V2 machines since I need train a NN using images on GPU . The issue is that the training still happens on the CPU – the logs say it ’ s not able to find CUDA .... | script_params = { ' -- input_data_folder ' : ds.path ( 'dataset ' ) .as_mount ( ) , ' -- zip_file_name ' : 'train.zip ' , ' -- run_mode ' : 'train ' } est = Estimator ( source_directory='./scripts ' , script_params=script_params , compute_target=compute_target , entry_script='main.py ' , conda_packages= [ 'scikit-image... | Unable to use GPU to train a NN model in azure machine learning service using P100-NC6s-V2 compute . Fails wth CUDA error |
Python | I have a chain of functions , all defined elsewhere in the class : where inp is either a dictionary , or bool ( False ) .The desired result is that if inp , or any of the functions evaluate to False , False is returned by the function stack.I attempted to use ternary operators , but they do n't evaluate correctly.throw... | fus ( roh ( dah ( inp ) ) ) def func ( inp ) : return int ( inp [ 'value ' ] ) + 1 if inp else False def func ( inp ) : if inp == False : return False else : return inp [ 'value ' ] + 1 def validate_inp ( inp ) : def decorator ( func ) : def wrapper ( *args ) : return func ( inp ) if inp else False return wrapper retur... | Looking for idiomatic way to evaluate to False if argument is False in Python 3 |
Python | I have a function that opens a file called : `` table1.txt '' and outputs the comma separated values into a certain format.My function is : I figured out how to format it correctly so for a `` table1.txt file of : It would output : I am trying to figure out how to sort the file so that the team with the highest points ... | def sort_and_format ( ) : contents = [ ] with open ( 'table1.txt ' , ' r+ ' ) as f : for line in f : contents.append ( line.split ( ' , ' ) ) max_name_length = max ( [ len ( line [ 0 ] ) for line in contents ] ) print ( `` Team Points Diff Goals \n '' ) print ( `` -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -... | Python Sorting Contents of txt file |
Python | I have the following package structure : Within test_app.py , I do this : Now I 've seen the message : What should I do instead ? ( I could also change the structure of the package , but I would like to keep the test data within the tests - it is not necessary for running the application ) | .├── my_app│ ├── app.py│ ├── cli.py│ ├── db.py│ └── __init__.py├── setup.py├── tests│ ├── data│ │ └── foobar.gz│ ├── test_app.py│ └── test_database.py└── tox.ini import pkg_resourcespath = '../tests/data/foobar.gz'full_path = pkg_resources.resource_filename ( __name__ , path ) /usr/local/lib/python3.7/site-packages/pkg... | How can I get files within the tests in Python ? |
Python | Consider the following code snippet : Does the python interpreter automatically recognise the repeated references to the dictionary value and use a cached local reference instead ? , somewhat akin to the aliasing optimisations of C/C++ , becoming something like so : Obviously , it 's not a big deal to do this manually ... | dict [ name ] = 0dict [ name ] += 1dict [ name ] += 1 value = dict [ name ] value = 0value += 1value += 1 | Python interpreted code optimisation |
Python | I started learning Docker today and I 've been able to create my first custom image with a Python stack based on ubuntu:14.04 after a couple of hours , by experimenting with both Dockerfile build and by modifying an existing image and save it using the commit command.My Dockerfile is the following : So far so good , bu... | FROM ubuntu:14.04MAINTAINER Davide Zanotti < *** @ gmail.com > ENV DEBIAN_FRONTEND noninteractiveRUN apt-get update & & apt-get install -y \ software-properties-common \ build-essential \ automake \ checkinstall \ git \ & & add-apt-repository -y ppa : fkrull/deadsnakes & & apt-get update & & apt-get install -y python3.... | Proper workflow for web development with Docker |
Python | I 've been searching for hours to try and figure this out , and it seems like no one has ever put an example online - I 've just created a Django 1.2 rss feed view object and attached it to a url . When I visit the url , everything works great , so I know my implementation of the feed class is OK.The hitch is , I ca n'... | { % url app_name.lib.feeds.LatestPosts blog_name=name % } from app.lib.feeds import LatestPostsurlpatterns = patterns ( 'app.blog.views ' , ( r'^rss/ ( ? P < blog_name > [ A-Za-z0-9 ] + ) / $ ' , LatestPosts ( ) ) , # snip ... ) | How to reverse django feed url ? |
Python | Let me say first that I 'm NOT searching for automagical solutions here . I want to translate code from Python to Smalltalk because I 've noticed some very simple sentences can be automatically translated , examples : Assigning a variable to a valuePythonSmalltalkCreating a new instance of a classPythonSmalltalkA for l... | i = 1 i : = 1. instance = module.ClassName ( ) instance : = ClassName new . for a in [ 0,1,2 ] : print ( str ( a ) +str ( a ) ) # ( 0 1 2 ) do : [ : a | Transcript show : a + a ; cr ] | Translating code from Python to Smalltalk |
Python | I have a dictionary that looks like this : What 's the pythonic way of running format on all values in the dictionary ? For example with x = 'TEST ' the end result should be : NB : I 'm loading d from another module so can not use f-strings . | d = { 'hello ' : 'world { x } ' , 'foo ' : 'bar { x } ' } { 'hello ' : 'worldTEST ' , 'foo ' : 'barTEST ' } | Pythonic way to apply format to all strings in dictionary without f-strings |
Python | I 'm trying to come up with an example where positive look-around works butnon-capture groups wo n't work , to further understand their usages . The examples I '' m coming up with all work with non-capture groups as well , so I feel like I '' m not fully grasping the usage of positive look around . Here is a string , (... | string = '' 'ABC1 1.1.1.1 20151118 active ABC2 2.2.2.2 20151118 inactive xxx x.x.x.x xxxxxxxx active '' ' pattern =re.compile ( 'ABC\w\s+ ( \S+ ) \s+ ( ? =\S+\s+active ) ' ) # solutionpattern =re.compile ( 'ABC\w\s+ ( \S+ ) \s+ ( ? : \S+\s+active ) ' ) # solution w/out lookaround | functional difference between lookarounds and non-capture group ? |
Python | I have a list of names of columns ( cols ) that exist in one dataframe.I want to insert columns by those names in another dataframe.So I am using a for loop to iterate the list and create the columns one by one : I would like to get rid of the for loop , however.So I have tried multiple column assignment using the .loc... | cols = [ 'DEPTID ' , 'ACCOUNT ' , 'JRNL LINE DESCRIPTION ' , 'JRNL DATE ' , 'BASE AMOUNT ' , 'FOREIGN CURRENCY ' , 'FOREIGN AMOUNT ' , 'JRNL SOURCE ' ] for col in cols : # `` summary '' and `` obiee '' are dataframes summary.loc [ obiee [ 'mapid ' ] , col ] = obiee [ col ] .tolist ( ) cols = [ 'DEPTID ' , 'ACCOUNT ' , ... | How to create new columns using .loc syntax ? |
Python | I want to achieve the following . It 's essentially the composition or merging of an arbitrary number of dictionaries , with reference to a 'seed ' or root dictionary , accumulating all unchanged and updated values in the final result . You can assume the data will always be in this shape , you can also assume that eac... | seed = { 'update ' : False , 'data ' : { 'subdata ' : { 'field1 ' : 5 , 'field2 ' : '2018-01-30 00:00:00 ' } , 'field3 ' : 2 , 'field4 ' : None } , 'data_updates ' : { } , 'subdata_updates ' : { } , 'diffs ' : { } } update_1 = { 'update ' : True , 'data ' : { 'subdata ' : { 'field1 ' : 6 , 'field2 ' : '2018-01-30 00:00... | Python fold/reduce composition of multiple dictionaries |
Python | I 'd like to send a list of strings to a C function : This works for e.g . c_double , but fails when I try it with c_char_p , with the following error ( testing on Python 2.7.16 and 3.7.4 , and NumPy 1.16.5 , 1.17.2 ) : Is there a better way to do this ? I 'm also not wedded to using numpy , although it 's useful for c... | from ctypes import c_double , c_void_p , Structure , cast , c_char_p , c_size_t , POINTERimport numpy as npclass FFIArray ( Structure ) : `` '' '' Convert sequence of structs or types to C-compatible void array `` '' '' _fields_ = [ ( `` data '' , c_void_p ) , ( `` len '' , c_size_t ) ] @ classmethod def from_param ( c... | Numpy error when converting array of ctypes types to void pointer |
Python | I 'm trying to use Python to extract multiple XML elements from a mixed-content document . The use case is an email that contains email text but also contains multiple XML trees . Here 's the example document : I want to extract the XML trees so they can be parsed by an XML parser in a for loop . I 've perfected parsin... | Email text email text email text email text.email signature email signature. < ? xml version= '' 1.0 '' ? > < catalog > < book id= '' bk101 '' > < author > Gambardella , Matthew < /author > < title > XML Developer 's Guide < /title > < genre > Computer < /genre > < price > 44.95 < /price > < publish_date > 2000-10-01 <... | Extracting multiple xml trees from a mixed content document |
Python | Put simply , why do I get the following error ? I use python 2.6 . | > > > yes = True > > > 'no [ { 0 } ] yes [ { 1 } ] '.format ( ( `` `` , `` x '' ) if yes else ( `` x '' , `` `` ) ) Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > IndexError : tuple index out of range | How to pass tuple1 if ... else tuple2 to str.format ? |
Python | I have installed awsebcli in windows 10It was showing Now when I was trying to doeb -- version I got error I was trying to remove the colorama and install 0.3.9 version now it was showing eb is required 0.3.7 version only ... Please help . | 2.2 , ! =2.18.0 , < 2.19 , > =2.6.1- > docker-compose < 1.22.0 , > =1.21.2- > awsebcli ) ( 1.22 ) docker-compose 1.21.2 has requirement colorama < 0.4 , > =0.3.9 ; sys_platform == `` win32 '' , but you 'll have colorama 0.3.7 which is incompatible . raise VersionConflict ( dist , req ) .with_context ( dependent_req ) p... | aws eb cli Windows get version error on colorama |
Python | I have a list of 19 colors , which is a numpy array of size ( 19,3 ) : Now I have an image ( numpy array of size ( 1024,1024,3 ) ) , with colors that are somewhat close or equal to all of the colors defined above . However , my program requires that the image can only contain the colors above and not a closeby color , ... | colors = np.array ( [ [ 0 , 0 , 0 ] , [ 0 , 0 , 255 ] , [ 255 , 0 , 0 ] , [ 150 , 30 , 150 ] , [ 255 , 65 , 255 ] , [ 150 , 80 , 0 ] , [ 170 , 120 , 65 ] , [ 125 , 125 , 125 ] , [ 255 , 255 , 0 ] , [ 0 , 255 , 255 ] , [ 255 , 150 , 0 ] , [ 255 , 225 , 120 ] , [ 255 , 125 , 125 ] , [ 200 , 100 , 100 ] , [ 0 , 255 , 0 ] ... | Map colors in image to closest member of a list of colors , in Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.