lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | Is there a common pattern for propagating details of both errors and warnings ? By errors I mean serious problems that should cause the flow of code to stop . By warnings I mean issues that merit informing the user of a problem , but are too trivial to stop program flow.I currently use exceptions to deal with hard erro... | > > > import logging > > > > > > def process_item ( item ) : ... if item : ... if item == 'broken ' : ... logging.warning ( 'soft error , continue with next item ' ) ... else : ... raise Exception ( 'hard error , can not continue ' ) ... > > > process_item ( 'good ' ) > > > process_item ( None ) Traceback ( most recent... | Is there a pattern for propagating details of both errors and warnings ? |
Python | So I was looking at some code online and I came across a line ( at line 286 ) : if depth > 0 and best < = -MATE_VALUE is None and nullscore > -MATE_VALUE : The part I had trouble understanding was the best < = -MATE_VALUE is None . So I fired up the interpreter to see how a statement such as value1 > value2 is value3 w... | > > > 5 > 2 is TrueFalse > > > ( 5 > 2 ) is True True > > > 5 > ( 2 is True ) True | Comparison operators and 'is ' - operator precedence in python ? |
Python | I 'm trying to merge list items with previous items if they do n't contain a certain prefix , and adding a \n between said list items when doing so . I tried something likebut always get the list index out of range error.My apologies if this is badly worded , or seems like an obvious fix , I 'm fairly new to python/pro... | prefix = ' ! 'cmds = [ ' ! test ' , 'hello ' , 'world ' , ' ! echo ' , ' ! embed ' , 'oh god ' ] output = [ ' ! test\nhello\nworld ' , ' ! echo ' , ' ! embed\noh god ' ] for i in list ( range ( 0 , len ( cmds ) ) ) : if not cmds [ i+1 ] .startswith ( prefix ) : cmds [ i ] += cmds.pop ( i+1 ) prefix = ' ! 'cmds = [ ' ! ... | Merge list item with previous list item |
Python | Do you know a simpler way to achieve the same result as this ? I have this code : I also tried with this : | color1 = input ( `` Color 1 : `` ) color2 = input ( `` Color 2 : `` ) if ( ( color1== '' blue '' and color2== '' yellow '' ) or ( color1== '' yellow '' and color2== '' blue '' ) ) : print ( `` { 0 } + { 1 } = Green '' .format ( color1 , color2 ) ) if ( color1 + color2 == '' blueyellow '' or color1 + color2 == '' yellow... | Best way to determine the equality of two data sets in python ? |
Python | I have a list with about 800000 elements ( small strings ) that are loaded into a Queue which is then consumed by different worker processes from a multiprocessing pool . I 've found out that both in PyPy and in Python ( 2.7 and 3.6 respectively ) , even though I 've set the Queue 's maxsize explicitly to 0 , the Queue... | from multiprocessing import Queueq = Queue ( maxsize=0 ) for i in range ( int ( 1e7 ) ) : q.put ( i ) print ( i ) Python 2.7.13 ( 990cef41fe11 , Mar 21 2019 , 12:15:10 ) [ PyPy 7.1.0 with GCC 4.2.1 Compatible Apple LLVM 10.0.0 ( clang-1000.11.45.5 ) ] on darwinType `` help '' , `` copyright '' , `` credits '' or `` lic... | Python Multiprocessing Queue when set to infinite is capped at 32768 ( 2^15 ) |
Python | Why the first code outputs 51 and the second code outputs 21 . I understand the second code should output 21 , but the way I understood , the first code should also output 21 ( The value of b changed to 20 and then is calling the function f ) . What am I missing ? Output : 51Output : 21Edit : This is different from How... | b = 50def f ( a , b=b ) : return a + bb = 20print ( f ( 1 ) ) b = 50b = 20def f ( a , b=b ) : return a + bprint ( f ( 1 ) ) | how python interpreter treats the position of the function definition having default parameter |
Python | I have this problem : I hav this code that is trying to count bigrams in a text file . An if statement checks wether the tuple is in a dictionary . If it is , the value ( counter ) is one-upped . If it does n't exist , the code shoud create a key-value pair with the tuple as key and the value 1.However , whenever I run... | for i in range ( len ( temp_list ) -1 ) : temp_tuple= ( temp_list [ i ] , temp_list [ i+1 ] ) if bigramdict [ temp_tuple ] in bigramdict : bigramdict [ temp_tuple ] = bigramdict [ temp_tuple ] +1 else : bigramdict [ temp_tuple ] = 1 | KeyError on If-Condition in dictionary Python |
Python | I have a user-own metric to implement as follows : The pd.DataFrame ( ) of pred and valid have the same columns and dt has no intersections . And the all the values of serial_number in valid is a subset of all the values of serial_number in pred.The label column only has 2 values : 0 or 1.Here is the sample of pred and... | def metric ( pred : pd.DataFrame ( ) , valid : pd.DataFrame ( ) ) : date_begin = valid.dt.min ( ) date_end = valid.dt.max ( ) x = valid [ valid.label == 1 ] .dt.min ( ) # p p_n_tpp_df = valid [ ( valid.dt > = x ) & \ ( valid.dt < = x + timedelta ( days=30 ) ) & \ ( p_n_tpp_df.label == 1 ) ] p_n_pp_df = valid [ ( valid.... | How to optimize such codes as follows in python ? |
Python | I 've discovered surprising python behaviour while had investigating thread Why is reading lines from stdin much slower in C++ than Python ? .If I run simple python code from that thread it works with speed 11.5M LPS , and when I decompose the whole script into single function code speeds up to 23M LPS.Why this simple ... | # ! /usr/bin/env pythonfrom __future__ import print_functionimport timeimport syscount = 0start_time = time.time ( ) for line in sys.stdin : count += 1delta_sec = time.time ( ) - start_timeif delta_sec > = 0 : lines_per_sec = int ( round ( count/delta_sec ) ) print ( `` Read { 0 : n } lines in { 1 : .2f } seconds . LPS... | Why mesh python code slower than decomposed one ? |
Python | I have had a tough time with this problem on leetcode.I 've had to look up solutions because for some reason , my code would always end up having some issue . The current code I have , still loops infinitely when looking for a target number in the array that does not exist . I am looking for some help on understanding ... | if nums [ mid ] == target or nums [ low ] == target or nums [ high ] == target : return target print ( search ( [ 1 , 2 , 3 ] , 1 ) ) print ( search ( [ 1 ] , 1 ) ) print ( search ( [ 2 , 1 ] , 1 ) ) def search ( nums , target ) : low = 0 high = len ( nums ) -1 while low < = high : mid = ( low + high ) // 2 if nums [ m... | Search in Rotated Sorted Array in O ( log n ) time |
Python | How can I set the niceness for each process in a multiprocessing.Pool ? I understand that I can increment niceness with os.nice ( ) , but how do call it in the child process after creating the pool ? If I call it in the mapped function it will be called every time the function executes , rather than once when the proce... | import multiprocessing as mp NICENESS = 19DATA = range ( 100000 ) def foo ( bar ) : return bar * 2pool = mp.Pool ( 100 ) # Somehow set niceness of each process to NICENESSpool.map ( foo , DATA ) | Set niceness of each process in a multiprocessing.Pool |
Python | You know how when you download something and the downloads folder contains a file with the same name , instead of overwriting it or throwing an error , the file ends up with a number appended to the end ? For example , if I want to download my_file.txt , but it already exists in the target folder , the new file will be... | import osdef new_name ( name , newseparator= ' _ ' ) # name can be either a file or directory name base , extension = os.path.splitext ( name ) i = 2 while os.path.exists ( name ) : name = base + newseparator + str ( i ) + extension i += 1 return name | A way to create files and directories without overwriting |
Python | Here 's the functionality I mean , and I do it pretty frequently so maybe I 'm just reimplementing a built-in that I have n't seen : Does Python let me do this with built-ins ? | import itertoolsdef first ( fn , *args ) : for x in itertools.chain ( *args ) : value = fn ( x ) if value : return value # Example use : example = { 'answer ' : 42 , 'bring ' : 'towel ' } print first ( example.get , [ 'dolphin ' , 'guide ' , 'answer ' , 'panic ' , 'bring ' ] ) # Prints 42 | Is there a built-in Python function which will return the first True-ish value when mapping a function over an iterable ? |
Python | I 'm trying to write a decorator that takes a few arguments , and can decorate arbitrary functions . After reading a few code examples , and stepping through the debugger I 've figured out how to write it . But I do n't fully understand why it works.What I do n't fully grasp is how/why the function f exists in the scop... | def bar ( arg1 ) : def inner_bar ( f ) : def inner_inner_bar ( *args , **kwargs ) : new_args = ( x + arg1 for x in args ) return f ( *new_args , **kwargs ) return inner_inner_bar return inner_bar @ bar ( 4 ) def foo ( x , y ) : print ( `` Sum is { 0 } '' .format ( x+y ) ) if __name__ == `` __main__ '' : foo ( 1 , 2 ) S... | Understanding Closures For Decorators |
Python | I would like to assign an another function to len in __init__.py file of my package the following way : It works fine , but only in the __init__.py file . How can I make it affect other modules in my package ? | llen = lenlen = lambda x : llen ( x ) - 1 | Overriding len in __init__.py - python |
Python | I have a SymPy expression that in string format looks likeWhen pretty-printed in LaTeX form ( including notebook 's LaTeX output ) , it is too tall and not very easy to read.How can I combine the fraction and put it before the parenthesis ? Like this : Code example : Prints and showsI would like to see both in latex ( ... | -t* ( a+b+c ) /2 ( -t/2 ) * ( a+b+c ) from sympy import symbols , Function , Derivative , var , init_printing , pprint , latexinit_printing ( ) def T ( y ) : var ( 'mu ' ) return -1 / ( 2 * mu ) * Derivative ( y , x , x ) def V ( y ) : var ( ' x ' ) V = Function ( ' V ' , commutative=True ) ( x ) return V * ydef K ( y ... | How to put fraction before the parenthesis in SymPy output ? |
Python | How to break this line of code in Python to stay within the 79-character limit of PEP 8 ? | config [ `` network '' ] [ `` connection '' ] [ `` client_properties '' ] [ `` service '' ] = config [ `` network '' ] [ `` connection '' ] [ `` client_properties '' ] [ `` service '' ] .format ( service=service ) | How to break this line of code in Python ? |
Python | I am running Matlab2017 on windows 10.I call a python script that runs some Speech Recognition task on cloud with something like this : When the above command is called , the python script runs the input audio file on the ASR cloud engine , and as it runs , I can see Speech Recognition scores for the audio file from Py... | userAuthCode=1 ; % authentication code for user account to be run on cloud cmd = [ ' C : \Python27\python.exe runASR.py userAuthCode ] ; system ( cmd ) ; for i=1 : 2 userAuthCode=i ; cmd = [ ' C : \Python27\python.exe runASR.py userAuthCode ] ; runtime = java.lang.Runtime.getRuntime ( ) ; pid ( i ) = runtime.exec ( cmd... | Calling multiple instances of python scripts in matlab using java.lang.Runtime.getRuntime not working |
Python | I 've created a script to get the html elements from a target page by sending two https requests subsequently . My script can does the thing flawlessly . However , I had to copy the four values from chrome dev tools to fill in the four keys within payload in order to send the final http requests to reach the target pag... | import requestsfrom bs4 import BeautifulSoupurl = 'https : //booking.discoverqatar.qa/SearchHandler.aspx ? 'second_url = 'https : //booking.discoverqatar.qa/PassengerDetails.aspx ? 'params = { 'Module ' : ' H ' , 'txtCity ' : '' , 'hdnCity ' : '2947 ' , 'txtHotel ' : '' , 'hdnHotel ' : '' , 'fromDate ' : '05/11/2019 ' ... | Unable to let my script generate few values automatically to be used within payload |
Python | I 'm testing the output of a simulation to see if it enters a loop at some point , so I need to know if the output repeats itself . For example , there may be 400 digits , followed by a 400000 digit cycle . The output consists only of digits from 0-9 . I have the following regex function that I 'm using to match repeti... | def repetitions ( s ) : r = re.compile ( r '' ( .+ ? ) \1+ '' ) for match in r.finditer ( s ) : if len ( match.group ( 1 ) ) > 1 and len ( match.group ( 0 ) ) /len ( match.group ( 1 ) ) > 4 : yield ( match.group ( 1 ) , len ( match.group ( 0 ) ) /len ( match.group ( 1 ) ) ) | How can you parallelize a regex search of one long string ? |
Python | The join ( ) function accepts an iterable as parameter . However , I was wondering why having : This : Is significantly faster than : The same occurs with long strings ( i.e . text * 10000000 ) .Watching the memory footprint of both executions with long strings , I think they both create one and only one list of chars ... | text = 'asdfqwer ' `` .join ( [ c for c in text ] ) `` .join ( c for c in text ) | Python : understanding iterators and ` join ( ) ` better |
Python | I 'm trying to understand what Python dictionaries must be doing internally to locate a key . It seems to me that hash would be evaluated first , and if there 's a collision , Python would iterate through the keys till it finds one for which eq returns True . Which makes me wonder why the following code works ( test co... | class MyClass ( object ) : def __eq__ ( self , other ) : return False def __hash__ ( self ) : return 42if __name__=='__main__ ' : o1 = MyClass ( ) o2 = MyClass ( ) d = { o1 : 'o1 ' , o2 : 'o2 ' } assert ( o1 in d ) # 1 assert ( d [ o1 ] =='o1 ' ) # 2 assert ( o2 in d ) # 3 assert ( d [ o2 ] =='o2 ' ) # 4 | What 's the order of __hash__ and __eq__ evaluation for a Python dict ? |
Python | Here is my little sample dataframe : I want to use pandas string method to convert the 'col1 ' , ' col2 ' and 'col3'to 10-decimal-place strings ( so that ' 0.0002 ' becomes ' 0.0002000000 ' , ' 8.333333333333333e-05 ' becomes ' 0.0000833333 ' , and ' 0.00014285714285714287 ' becomes ' 0.0001428571 ' ) . What 's the mos... | import pandas as pdimport numpy as npsize = 10000arr1 = np.tile ( [ 1/5000,1/12000,1/7000 ] , ( size,1 ) ) df = pd.DataFrame ( arr1 , columns = [ 'col1 ' , 'col2 ' , 'col3 ' ] ) df [ [ 'col1 ' , 'col2 ' , 'col3 ' ] ] = df [ [ 'col1 ' , 'col2 ' , 'col3 ' ] ] .astype ( str ) | pandas string method to handle decimal places |
Python | I have the following Pywinauto code and timings waiting is 0.5 seconds instead of immediate . How to get itimmediately ? To click a button and go to the next message : When I run , the interval between clicks is 0.5 seconds : However , when I move my mouse frantically , it goes faster : What exactly am I doing wrong ? ... | from pywinauto import application , timings , mouseimport timeapp = application.Application ( ) app.connect ( title = 'Mensagem ' ) app = app.Mensagemapp2 = app.TBPanel2buttonCoord = int ( ( app2.rectangle ( ) .right - app2.rectangle ( ) .left ) /2/2 ) , int ( ( app2.rectangle ( ) .bottom - app2.rectangle ( ) .top ) /2... | Pywinauto timings waiting 0.5 seconds instead of immediate |
Python | I wrote two simple functions to determine if a string is a palindrome . I thought they were equivalent , but 2 does n't work . Why is this ? 12 | def is_palindrome ( string ) : if string == string [ : :-1 ] : return True else : return False def is_palindrome ( string ) : if string == reversed ( string ) : return True else : return False | Determining if string is palindrome |
Python | I 'd like to create a generalized __eq__ ( ) method for the following Class . Basically I 'd like to be able to add another property ( nick ) without having to change __eq__ ( ) I imagine I can do this somehow by iterating over dir ( ) but I wonder if there is a way to create a comprehension that just delivers the prop... | class Person : def __init__ ( self , first , last ) : self.first=first self.last=last @ property def first ( self ) : assert ( self._first ! = None ) return self._first @ first.setter def first ( self , fn ) : assert ( isinstance ( fn , str ) ) self._first=fn @ property def last ( self ) : assert ( self._last ! = None ... | Generalized __eq__ ( ) method in Python |
Python | I am trying to copy data from a hdf5 dataset ( f_one , in the below screenshot ) into a numpy array , but am finding that I 'm losing some precision.The last line of the screenshot ( the last print statement ) should read subid2 [ 0 ] == subid2 [ 1 ] . I just accidentally deleted the 2 before taking the screenshot . Th... | f_one [ 'SubhaloID ' ] [ 0 ] == f_one [ 'SubhaloID ' ] [ 1 ] | Loss of precision when transferring data from hdf5 dataset to numpy array |
Python | I read the official documentation of collections.namedtuple today and found _tuple in the __new__ method . I did not find where the _tuple was defined.You can try running the code below in Python , it does not raise any error.Update : What are the advantages ofIs that just to let tuple be a protected value ? Am I right... | > > > Point = namedtuple ( 'Point ' , [ ' x ' , ' y ' ] , verbose=True ) class Point ( tuple ) : 'Point ( x , y ) ' __slots__ = ( ) _fields = ( ' x ' , ' y ' ) def __new__ ( _cls , x , y ) : 'Create a new instance of Point ( x , y ) ' return _tuple.__new__ ( _cls , ( x , y ) ) # Here . Why _tuple ? from builtins import... | Is there a use for _tuple in Python ? |
Python | I need some help completing the Mirror Credentials API insertion from my Python server code . We are using the Python Google API library to insert a special auth token into the Mirror API , but I 'm getting a blank result from mirror.accounts ( ) .insert ( ) .execute ( ) where I should be getting at least an error or c... | with open ( os.path.join ( os.path.dirname ( __file__ ) , 'mirror-credentials.json ' ) ) as f : credentials_json = json.load ( f ) credentials = SignedJwtAssertionCredentials ( service_account_name=credentials_json [ 'client_email ' ] , private_key=credentials_json [ 'private_key ' ] , scope='https : //www.googleapis.c... | How do you insert Google Glass Mirror credentials from python server side code ? |
Python | I just ca n't figure out what `` == '' means at the second line : - It is not a test , there is no if statement ... - It is not a variable declaration ... I 've never seen this before , the thing is data.ctage==cat is a pandas Series and not a test ... | for cat in data [ `` categ '' ] .unique ( ) : subset = data [ data.categ == cat ] # Création du sous-échantillon print ( `` - '' *20 ) print ( 'Catégorie : ' + cat ) print ( `` moyenne : \n '' , subset [ 'montant ' ] .mean ( ) ) print ( `` mediane : \n '' , subset [ 'montant ' ] .median ( ) ) print ( `` mode : \n '' , ... | Why does using `` == '' return a Series instead of bool in pandas ? |
Python | I want to take an arbitrary number of paths that represent nested tar archives , and perform an operation on the innermost archive . The trouble is , the nesting can be arbitrary , so the number of context managers I need is also arbitrary.Take , for example : I ca n't use the with statement 's nesting syntax because t... | ARCHIVE_PATH = `` path/to/archive.tar '' INNER_PATHS = ( `` nested/within/archive/one.tar '' , `` nested/within/archive/two.tar '' , # Arbitary number of these ) def list_inner_contents ( archive_path , inner_paths ) : with TarFile ( archive_path ) as tf1 : with TarFile ( fileobj=tf1.extractfile ( inner_paths [ 0 ] ) )... | How can I nest an arbitrary number of Python file context managers ? |
Python | Why does the midpoint algorithm for Binary Search userather than | low + ( high-low ) /2 ( low + high ) /2 | Explain the difference between these Midpoint Algorithms |
Python | I have a C++ CameraManager class that manages a list of Camera objects . The camera objects are managed by a std : :list , as shared pointers , i.e . each list item is of type : shared_ptr < Camera > .I can obtain a Camera from a CameraManager object asCreating a Python module using Swig , the above is translated to py... | std : :shared_ptr < Camera > c = cameraManager.getCamera ( ) ; camera = cameraManager.getCamera ( ) % include < std_shared_ptr.i > % shared_ptr ( Camera ) % include `` aiCamera.h '' typedef CameraSP std : :shared_ptr < Camera > ; class MVR_API MVRObject { public : MVRObject ( ) ; MVRObject ( const MVRObject & obj ) ; v... | Wrapping shared pointer object with SWIG do n't give access to class member functions |
Python | I am designing a Python app by calling a C++ DLL , I have posted my interaction between my DLL and Python 3.4 here . But now I need to do some process in streaming involving a threading based model and my callback function looks to put in a queue all the prints and only when my streaming has ended , all the Info is pri... | def callbackU ( OutList , ConList , nB ) : for i in range ( nB ) : out_list_item = cast ( OutList [ i ] , c_char_p ) .value print ( `` { } \t { } '' .format ( ConList [ i ] , out_list_item ) ) return 0 from threading import Lockprint_lock = Lock ( ) def save_print ( *args , **kwargs ) : with print_lock : print ( *args ... | Python 'print ' in a c++ based threading model |
Python | I need a smart copy function for reliable and fast file copying & linking . The files are very large ( from some gigabytes to over 200GB ) and distributed over a lot of folders with people renaming files and maybe folders during the day , so I want to use hashes to see if I 've copied a file already , maybe under a dif... | import hashlibdef calculate_sha256 ( cls , file_path , chunk_size=2 ** 10 ) : `` ' Calculate the Sha256 for a given file . @ param file_path : The file_path including the file name . @ param chunk_size : The chunk size to allow reading of large files . @ return Sha256 sum for the given file. `` ' sha256 = hashlib.sha25... | Is this `` fast hash '' function dangerous ? |
Python | If you add an integer to a list , you get an error raised by the __add__ function of the list ( I suppose ) : If you add a list to a NumPy array , I assume that the __add__ function of the NumPy array converts the list to a NumPy array and adds the listsBut what happens in the following ? How does the list know how to ... | > > > [ 1,2,3 ] + 3Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > TypeError : can only concatenate list ( not `` int '' ) to list > > > np.array ( [ 3 ] ) + [ 1,2,3 ] array ( [ 4 , 5 , 6 ] ) > > > [ 1,2,3 ] + np.array ( [ 3 ] ) array ( [ 4 , 5 , 6 ] ) | Addition of list and NumPy number |
Python | Is there a way to conveniently split a dataset into training and testing sets , keeping records that belong to a same group together ? Take for example a table that records independent and dependent variables for every person_id in such a way that every person may have one or more entries : Now , I want to split the da... | import pandas as pdtbl = pd.DataFrame ( dict ( person_id=list ( 'aaabbcccdeeefffhiijj ' ) , random_variable=np.linspace ( 0 , 1 , 20 ) , dependent_variable=np.arange ( 20 ) ) ) import numpy as npsalt = str ( np.random.rand ( ) ) # randomness source hash_values = tbl [ 'person_id ' ] .apply ( lambda p : hash ( salt + p ... | Grouped sampling in scikit-learn |
Python | I have a list of strings and integers and want to sort the list , preserving the numbers like sowould becomeIn short , it only sorts the strings in the list , not the integers , which stay in place . I 've tried using the key parameter with list.sort ( ) but have n't managed to achieve what I want.Can anyone help me wi... | [ `` Hello '' , 1 , 2 , `` World '' , 6 , `` Foo '' , 3 ] [ `` Foo '' , 1 , 2 , `` Hello '' , 6 , `` World '' , 3 ] | How to sort a list , only sorting strings ? |
Python | this is my first question , so sorry ... I 'm a beginner with python and coding in general , and i wanted to create a class called 'Map ' that would have the following class variables : If i put the variables outside of the class it works.What am I doing wrong ? ? Thanks for the help . | class Map : height = 11 width = 21 top = [ [ ' # ' ] *width ] middle = [ [ ' # ' ] + [ ' ' ] * ( width-2 ) + [ ' # ' ] for i in range ( height-2 ) ] field = top + middle + topb = Map ( ) Shell : > > > middle = [ [ ' # ' ] + [ ' ' ] * ( width-2 ) + [ ' # ' ] for i in range ( height-2 ) ] NameError : name 'width ' is not... | Python beginner Class variable Error |
Python | I want to be able to calculate the exact length of an SVG Arc . I can do all the manipulations rather easily . But , I am unsure of whether there is a solution at all or the exact implementation of the solution . Here 's the exact solution for the circumference of the ellipse . Using popular libraries is fine . I fully... | from scipy import pi , sqrtfrom scipy.special import hyp2f1def exact ( a , b ) : t = ( ( a - b ) / ( a + b ) ) ** 2 return pi * ( a + b ) * hyp2f1 ( -0.5 , -0.5 , 1 , t ) a = 2.667950e9b = 6.782819e8print ( exact ( a , b ) ) | Calculating the exact length of an SVG Arc in Python ? |
Python | I am training an LSTM network in Python Tensorflow on audio data . My dataset is a bunch of wave files which read_wavfiles turns into a generator of numpy arrays . I decided to try training my network with the same dataset 20 times , and wrote some code as follows.The full code , including the sufficiently free data ( ... | from with_hyperparams import stftfrom model import lstm_networkimport tensorflow as tfdef read_wavfile ( ) : for file in itertools.chain ( DATA_PATH.glob ( `` **/*.ogg '' ) , DATA_PATH.glob ( `` **/*.wav '' ) ) : waveform , samplerate = librosa.load ( file , sr=hparams.sample_rate ) if len ( waveform.shape ) > 1 : wave... | Loss goes up back to starting value after re-initializing dataset |
Python | Is it possible to modify a class so as to make available a certain method decorator , without having to explicitly import it and without having to prefix it ( @ something.some_decorator ) : I do n't think this is possible with a class decorator , because that is applied too late . The option that seems more promising i... | class SomeClass : @ some_decorator def some_method ( self ) : pass | How to make new decorators available within a class without explicitly importing them ? |
Python | I 'm writing a python spirograph program , and I need some help with converting part of it into a function . The code is attempting to reproduce the result illustrated in the video I found here . One line rotates around the origin , and then another rotates off the end of that , etc.With a little bit of research into (... | x , y = 0 , 0lines = [ ] while 1 : point1 = rotate ( ( 0,50 ) , x ) point2 = map ( sum , zip ( rotate ( ( 0 , 50 ) , y ) , point1 ) ) if x == 0 : oldpoint2 = point2 else : canvas.create_line ( oldpoint2 [ 0 ] , oldpoint2 [ 1 ] , point2 [ 0 ] , point2 [ 1 ] ) lines.append ( canvas.create_line ( 0 , 0 , point1 [ 0 ] , po... | Rephrase spirograph code into function |
Python | In Python most examples of yield from explain it with saying that is similar to On the other hand it does n't seem to be exactly the same and there 's some magic thrown in . I feel a bit uneasy about using a function that does magic that I do n't understand . What do I have to know about the magic of yield from to avoi... | yield from foo ( ) for x in foo ( ) : yield x | Difference between ` yield from foo ( ) ` and ` for x in foo ( ) : yield x ` |
Python | I need to do a python script toRead a csv file with the columns ( person_id , name , flag ) . The file has 3000 rows.Based on the person_id from the csv file , I need to call a URL passing the person_id to do a GEThttp : //api.myendpoint.intranet/get-data/1234The URL will return some information of the person_id , like... | import pandas as pdimport requestsids = pd.read_csv ( f '' { path } /data.csv '' , delimiter= ' ; ' ) person_rents = df = pd.DataFrame ( [ ] , columns=list ( 'person_id ' , 'carId ' , 'price ' , 'rentStatus ' ) ) for id in ids : response = request.get ( f'endpoint/ { id [ `` person_id '' ] } ' ) json = response.json ( ... | How to update a pandas dataframe , from multiple API calls ? |
Python | I have two vectors . I would like a `` cross product '' -esque function that will take each value from the first vector and raise it to the exponent of each value in a second vector , returning a matrix . Is there anything built in to numpy that does this ? It could be done with loops but I 'm looking for something eff... | > > > cross_exp ( [ 1,2 ] , [ 3,4 ] ) [ [ 1 , 1 ] , [ 8 , 16 ] ] | `` cross product '' but raise to exponent instead of multiply |
Python | What is the most fast way to calculate function likeOne possible way is : But seems numpy goes through array element by element.Is there any way to use something conceptually similar to np.exp ( x ) to achieve better performance ? | # here x is just a numberdef f ( x ) : if x > = 0 : return np.log ( x+1 ) else : return -np.log ( -x+1 ) # here x is an arraydef loga ( x ) cond = [ x > = 0 , x < 0 ] choice = [ np.log ( x+1 ) , -np.log ( -x+1 ) return np.select ( cond , choice ) | Fast way to calculate conditional function |
Python | Cython appears to use a wrong striding whenever I assign a single value to a slice of a multi-dimensional memory view , except when the slice is along the first dimension . I give a complete example below : If we run this in Python ( e.g . python3 -c 'import bug ; bug.bug ( ) ' ) , we getprinted out , as expected . I n... | # bug.pyimport numpy as npdef bug ( ) : # cdef int [ : , : :1 ] a a = 2*np.ones ( ( 2 , 2 ) , dtype=np.intc ) a [ : , :1 ] = 1 print ( np.asarray ( a ) ) [ [ 1 2 ] [ 1 2 ] ] # Makefilepython = python3python_config = $ ( python ) -configCC = gccCFLAGS = $ ( shell $ ( python_config ) -- cflags ) -fPICCFLAGS += $ ( shell ... | Cython : Assigning single element to multidimensional memory view slice |
Python | I 'm looking to make a bash alias that will change the results of ls . I am constantly dealing with large sequences of files , that do not follow the same naming conventions . The only common thing about them is that the number is 4 padded ( sorry not really sure of correct way to say that ) and immediately precedes th... | filename_v003_0001.geofilename_v003_0002.geofilename_v003_0003.geofilename_v003_0004.geofilename_v003_0005.geofilename_v003_0006.geofilename_v003_0007.geofilename_v003_0032.geofilename_v003_0033.geofilename_v003_0034.geofilename_v003_0035.geofilename_v003_0036.geotestxxtest.0057.exrtestxxtest.0058.exrtestxxtest.0059.ex... | Bash alias to automatically detect arbitrarily named file sequences ? |
Python | What is the right way to use htt ( p|ps ) in second argument within proxy when I make a requests to a https site ? The proxy I used below is just a placeholder.When I try like this ( it works ) : when I try like this ( it works as well ) : Is the second htt ( p|ps ) in proxy just a placeholder and What if I make a requ... | proxies = { 'https ' : 'http : //79.170.192.143:34394 ' , } proxies = { 'https ' : 'https : //79.170.192.143:34394 ' , } | Right usage of second argument in proxy |
Python | Does Python defined the value of `` NaN > 0 '' ? In my Python interpreter , I get : but is this guaranteed ? If I understand correctly , the IEEE 754 standard assigns False to any comparison involving NaN . However , I ca n't find anything in the Python documentation that indicates that this standard is followed . I ev... | > > > float ( 'nan ' ) > 0False | Does Python define the value of `` NaN > 0 '' ? |
Python | Could someone explain me this strange result on python 2.6.6 ? | > > > a = `` xx '' > > > b = `` xx '' > > > a.__hash__ ( ) == b.__hash__ ( ) True > > > a is bTrue # ok.. was just to be sure > > > a = `` x '' * 2 > > > b = `` x '' * 2 > > > a.__hash__ ( ) == b.__hash__ ( ) True > > > a is bTrue # yeah.. looks ok so far ! > > > n = 2 > > > a = `` x '' * n > > > b = `` x '' * n > > > ... | Strange result in python |
Python | I 've tried to understand how a certain singleton decorator implementation for a class works , but I only got confused.Here 's the code : @ deco is a syntatic sugar for cls = deco ( cls ) , so in this code , when we define our cls class and wrap it with this singleton decorator , cls wo n't be a class anymore , but a f... | def singleton ( cls ) : instance = None @ functools.wraps ( cls ) def inner ( *args , **kwargs ) : nonlocal instance if instance is None : instance = cls ( *args , **kwargs ) return instance return inner | How decorators work with classes in python |
Python | I have several possible files which could hold my data ; they can be compressed in different ways , so to open them I need to use file ( ) , gzip.GzipFile ( ) and other which also return a file object ( supporting the with interface ) .I want to try each of them until one succeeds in opening , so I could do something l... | try : with gzip.GzipFile ( fn + '.gz ' ) as f : result = process ( f ) except ( IOError , MaybeSomeGzipExceptions ) : try : with xCompressLib.xCompressFile ( fn + '.x ' ) as f : result = process ( f ) except ( IOError , MaybeSomeXCompressExceptions ) : try : with file ( fn ) as f : result = process ( f ) except IOError... | Several ` with ` s in ` try ` s |
Python | I am learning about Functions and Classes in Python 3.4.2 , and I got a little sidetracked by the output from this code snippet : When it prints the phone number , it spaces the digits out like this : x x x - x x x - x x x x rather than xxx-xxx-xxxx . Is there a way to remove the spaces between the characters ? I 've l... | print ( `` This program will collect your demographic information and output it '' ) print ( `` '' ) class Demographics : # This class contains functions to collect demographic info def phoneFunc ( ) : # This function will collect user 's PN , including area code phoneNum = str ( input ( `` Enter your phone number , ar... | Inserting strings into lists in Python ( v. 3.4.2 ) |
Python | The following code behaves differently in Python 2 and Python 3 , and I 'm not sure why.The result in Python 3 : The result in Python 2 : ad infinitum until a recursion ceiling is reached . What is the difference in the behavior of `` dir '' ? Edit : And is there a workaround ? self.dict is the obvious choice but it do... | class Dataset ( object ) : def __getattr__ ( self , item ) : if not item in dir ( self ) : print ( item ) a = Dataset ( ) a.Hello > Hello __members____members____methods__ ... | Difference in `` dir '' between Python 2 and 3 |
Python | Consider the following python snippet ( I am running Python 3 ) This produces the output hello johny as expectedHowever , generates an UnboundLocalError : local variable ' x ' referenced before assignment.Why does the first snippet work , whereas the second does n't ? | name = `` Sammy '' def greet ( ) : name = 'johny ' def hello ( ) : print ( 'hello ' + name ) # gets 'name ' from the enclosing 'greet ' hello ( ) greet ( ) x = 50def func1 ( ) : x = 20 def func2 ( ) : print ( `` x is `` , x ) # Generates error here x = 2 print ( `` Changed the local x to `` , x ) func2 ( ) func1 ( ) pr... | Scoping rules in python |
Python | Is there a more elegant way to write the following piece of Python ? I want to accumulate the results of foo ( ) in a list , but I do n't need the iterator i . | [ foo ( ) for i in range ( 10 ) ] | Omit iterator in list comprehension ? |
Python | I have a list of tuples , the list can vary in length between ~8 - 1000 depending on the length of the tuples . Each tuple in the list is unique . A tuple is of length N where each entry is a generic word.An example tuple can be of length N ( Word 1 , Word 2 , Word 3 , ... , Word N ) For any tuple in the list , element... | l = [ ( ' A ' , ' B ' , `` , `` ) , ( ' A ' , ' B ' , ' C ' , `` ) , ( `` , `` , `` , 'D ' ) , ( ' A ' , `` , `` , 'D ' ) , ( `` , ' B ' , `` , `` ) ] filtered_l = [ ( A , B , C , '' ) , ( A , '' , '' , D ) ] | Efficiently remove partial duplicates in a list of tuples |
Python | I have a 3D numpy array data and another array pos of indexes ( an index is a numpy array on its own , which makes the latter array a 2D array ) : I want to select and/or mutate the elements from data using the indexes from pos . I can do the selection using a for loop or a list comprehension : But this does not seem t... | import numpy as npdata = np.arange ( 8 ) .reshape ( 2 , 2 , -1 ) # array ( [ [ [ 0 , 1 ] , # [ 2 , 3 ] ] , # # [ [ 4 , 5 ] , # [ 6 , 7 ] ] ] ) pos = np.array ( [ [ 1 , 1 , 0 ] , [ 0 , 1 , 0 ] , [ 1 , 0 , 0 ] ] ) # array ( [ [ 1 , 1 , 0 ] , # [ 0 , 1 , 0 ] , # [ 1 , 0 , 0 ] ] ) [ data [ tuple ( i ) ] for i in pos ] # [ ... | Indexing a numpy array with a numpy array of indexes |
Python | I have a bunch of wordlists on a server of mine , and I 've been planning to make a simple open-source JSON API that returns if a password is on the list1 , as a method of validation . I 'm doing this in Python with Flask , and literally just returning if input is present.One small problem : the wordlists total about 1... | from flask import Flaskfrom flask.views import MethodViewfrom flask.ext.pymongo import PyMongoimport jsonapp = Flask ( __name__ ) mongo = PyMongo ( app ) class HashCheck ( MethodView ) : def post ( self ) : return json.dumps ( { 'result ' : not mongo.db.passwords.find ( { 'pass ' : request.form [ `` password '' ] ) } )... | Lookup speed : State or Database ? |
Python | I want to know which would be an efficient method to invert dictionaries in python . I also want to get rid of duplicate values by comparing the keys and choosing the larger over the smaller assuming they can be compared . Here is inverting a dictionary : | inverted = dict ( [ [ v , k ] for k , v in d.items ( ) ] ) | Inverting Dictionaries in Python |
Python | When writing project-specific pytest plugins , I often find the Config object useful to attach my own properties . Example : Obviously , there 's no fizz attribute in _pytest.config.Config class , so running mypy over the above snippet yields ( Note that pytest does n't have a release with type hints yet , so if you wa... | from _pytest.config import Configdef pytest_configure ( config : Config ) - > None : config.fizz = `` buzz '' def pytest_unconfigure ( config : Config ) - > None : print ( config.fizz ) conftest.py:5 : error : `` Config '' has no attribute `` fizz '' conftest.py:8 : error : `` Config '' has no attribute `` fizz '' from... | Typechecking dynamically added attributes |
Python | Here is what I 'm trying to do : I want to be able to finish the `` OAuth token dance '' and gain an access token so I can then use that to connect to googles IMAP api for a user.Here are my problems : I feel like I 've tried almost everything . I 've tried using the GDClient , GDataService , and Django Social Auth OAu... | def index ( request ) : scopes = [ 'https : //docs.google.com/feeds/ ' , 'https : //www.google.com/calendar/feeds/ ' ] client = gdata.docs.client.DocsClient ( source='Trinity-EmailManager-v1 ' ) client.ssl = True client.http_client.debug = True oauth_callback_url = settings.GOOGLE_CALLBACK_URL request_token = client.Ge... | Does anyone know of any good complete resources to achieve google authentication using python ? |
Python | everyone . Please see example below . I 'd like to supply a string to 'schedule_action ' method which specifies , what Bot-class method should be called . In the example below I 've represented it as 'bot.action ( ) ' but I have no idea how to do it correctly . Please help | class Bot : def work ( self ) : pass def fight ( self ) : passclass Scheduler : def schedule_action ( self , action ) : bot = Bot ( ) bot.action ( ) scheduler = Scheduler ( ) scheduler.schedule_action ( 'fight ' ) | Python script is running . I have a method name as a string . How do I call this method ? |
Python | OK the code is pretty basic . Since I 'm using multiple threads , and I want shared variables between them , I 'm using a global.Why does the code in ThreadClass sometimes not execute when I hit `` C '' ? I know it 's a concurrency problem , but I 'm not sure how to fix it . I 've reading up on semaphores and locking l... | import threadingbuff_list = [ ] class ThreadClass ( threading.Thread ) : global buff_list def run ( self ) : while ( True ) : if ( `` C '' == raw_input ( ) ) : buff_list.append ( `` C '' ) print buff_listclass ThreadClass2 ( threading.Thread ) : global buff_list def run ( self ) : while ( True ) : if ( `` B '' == raw_i... | Basic threading in python |
Python | Something that looks like this but I want the image and text editable.Instead of having something like : Is it possible for the colour in the text to be an image instead , or an animation ? EDIT : For those curious ... when I imported the imaged , I had to change the end of the code a bitThe screen.fill comes after the... | title = menuFont.render ( `` COMPUTER INFORMATION ! `` , 1 , BLACK ) screen.blit ( title , Rect ( 50 , 100 , 400 , 400 ) ) screen.blit ( texture , ( 50 , 50 ) ) screen.fill ( BG_COLOR ) screen.blit ( text_surface , ( 50 , 170 ) ) pg.display.update ( ) clock.tick ( 30 ) | Pygame Text : Instead of colour , let the text show an image , or animation |
Python | How to determine the variables to be removed from our model based on the Correlation coefficient .See below Example of variables : correlation matrix heat map of Independent variables '' : Questions:1 ) How to remove the one high correlated variable from Correlation-value calculated between two variablesEx : correlatio... | Top 10 Absolute Correlations : Variable 1 Variable 2 Correlation Value pdays pmonths 1.000000 emp.var.rate euribor3m 0.970955 euribor3m nr.employed 0.942545 emp.var.rate nr.employed 0.899818 previous pastEmail 0.798017 emp.var.rate cons.price.idx 0.763827 cons.price.idx euribor3m 0.670844 contact cons.price.idx 0.58589... | Correlation coefficient explanation -- Feature Selection |
Python | I have paired values in a csv file . Neither of the paired values are necessarily unique . I would like to split this large list into independent complete sets for further analysis.To illustrate , my `` megalist '' is like : Most importantly , the output would preserve the list of paired values ( i.e. , not consolidate... | megalist = [ [ ' a ' , ' b ' ] , [ ' a ' , 'd ' ] , [ ' b ' , 'd ' ] , [ ' b ' , ' f ' ] , [ ' r ' , 's ' ] , [ 't ' , ' r ' ] ... ] completeset1 = [ [ ' a ' , ' b ' ] , [ ' a ' , 'd ' ] , [ ' b ' , 'd ' ] , [ ' b ' , ' f ' ] ] completeset2 = [ [ ' r ' , 's ' ] , [ 't ' , ' r ' ] ] ... import sys , csvimport networkx a... | Split a tuple of tuples ( or list of lists ) of paired values into independent complete sets ? |
Python | I stumbled upon a floor division result of a np.float32 or np.float64 , which I do not understandI 'm using numpy 1.15.4 in Python 3.6.7I know , that i can workaround by abs ( ) and such , but why am I getting a `` -0.0 '' instead of `` 0.0 '' in the first place ? ? | > > > import numpy as np > > > np.float32 ( 0 ) //1-0.0 | Weird result of floor division in numpy |
Python | In my dataset I have two categorical columns which I would like to numerate . The two columns both contain countries , some overlap ( appear in both columns ) . I would like to give the same number in column1 and column2 for the same country.My data looks somewhat like : Currenty I am transforming the data like : Howev... | import pandas as pdd = { 'col1 ' : [ 'NL ' , 'BE ' , 'FR ' , 'BE ' ] , 'col2 ' : [ 'BE ' , 'NL ' , 'ES ' , 'ES ' ] } df = pd.DataFrame ( data=d ) df from sklearn.preprocessing import LabelEncoderdf.apply ( LabelEncoder ( ) .fit_transform ) o = { 'col1 ' : [ 2,0,1,0 ] , 'col2 ' : [ 0,2,4,4 ] } output = pd.DataFrame ( da... | Transform multiple categorical columns |
Python | Python has a great syntax for null coalescing : This sets c to a if a is not False , None , empty , or 0 , otherwise c is set to b . ( Yes , technically this is not null coalescing , it 's more like bool coalescing , but it 's close enough for the purpose of this question . ) There is not an obvious way to do this for ... | c = a or b from functools import reducedef or_func ( x , y ) : return x or ydef null_coalesce ( *a ) : return reduce ( or_func , a ) | Multi-argument null coalesce and built-in `` or '' function in Python |
Python | I have used SqlAlchemy to create a table , Record . Each record has a field , date , which stores a DateTime . I want to find all records whose date is more recent than eight hours ago.I came up with four ways to write a filter , all involving simple arithmetic comparing the current time , the record 's time , and an e... | from sqlalchemy import Column , Integer , DateTimefrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy.orm import sessionmakerfrom sqlalchemy import create_engineimport datetimeBase = declarative_base ( ) class Record ( Base ) : __tablename__ = 'record ' id = Column ( Integer , primary_key=True ) date... | Why does this query give different results depending on how I arrange my DateTime arithmetic ? |
Python | I 've recently looked into using list ( ) , dict ( ) , tuple ( ) in place of [ ] , { } , and ( ) , respectively when needing to create an empty one of of the three . The reasoning is that it seemed more readable . I was going to ask for opinions on the style , but then I decided to test performance . I did this : I tri... | > > > from timeit import Timer > > > Timer ( 'for x in range ( 5 ) : y = [ ] ' ) .timeit ( ) 0.59327821802969538 > > > from timeit import Timer > > > Timer ( 'for x in range ( 5 ) : y = list ( ) ' ) .timeit ( ) 1.2198944904251618 | Why are list ( ) , dict ( ) , and tuple ( ) slower than [ ] , { } , and ( ) ? |
Python | If we compare the lists generated by applying the dir ( ) built-in to the object superclass and to a 'dummy ' , bodyless class , such aswe find that the A class has three attributes ( '__dict__ ' , '__module__ ' and '__weakref__ ' ) that are not present in the object class.Where does the A class inherit these additiona... | class A ( ) : pass | Where do classes get their default '__dict__ ' attributes from ? |
Python | I 'm working on an app that requires me to filter through large amount of records . I 've been reading about caching QuerySets and related stuff and found some good material.After this , I wish to put this qs in cache for later use . I want to apply all the other filters without hitting the database . something likebut... | qs = MyModel.objects.filter ( Q ( < initial_filter_to_narrow_down_size > ) ) cache.set ( 'qs ' , qs ) | caching queryset |
Python | I created a caesar shift program in python , see below : I have to shift the following code : As you can see , it contains comments.How do I make that code into a string ? The comments are stopping my python script from giving any output.Thanks | from string import maketransoriginalChar = ( raw_input ( `` Enter a letter : `` ) ) numToInc = int ( raw_input ( `` Enter a number : `` ) ) code = `` '' for x in originalChar : newChar = ( chr ( ord ( x ) + numToInc ) ) code = code + newChartranstab = maketrans ( chr ( 32+numToInc ) , `` `` ) print code.translate ( tra... | Python : Caesar shift - inputting string that contains multiple `` # ' { ] $ values |
Python | I deployed a large 3D model to aws sagemaker . Inference will take 2 minutes or more . I get the following error while calling the predictor from Python : In Cloud Watch I also see some PING time outs while the container is processing : How do I increase the invocation time out ? Or is there a way to make async invocat... | An error occurred ( ModelError ) when calling the InvokeEndpoint operation : Received server error ( 0 ) from model with message `` Your invocation timed out while waiting for a response from container model . Review the latency metrics for each container in Amazon CloudWatch , resolve the issue , and try again . '' ' ... | How to increase AWS Sagemaker invocation time out while waiting for a response |
Python | I 've been working on some quick and dirty scripts for doing some of my chemistry homework , and one of them iterates through lists of a constant length where all the elements sum to a given constant . For each , I check if they meet some additional criteria and tack them on to another list . I figured out a way to mee... | # iterate through all 11-element lists where the elements sum to 8.for a in range ( 8+1 ) : for b in range ( 8-a+1 ) : for c in range ( 8-a-b+1 ) : for d in range ( 8-a-b-c+1 ) : for e in range ( 8-a-b-c-d+1 ) : for f in range ( 8-a-b-c-d-e+1 ) : for g in range ( 8-a-b-c-d-e-f+1 ) : for h in range ( 8-a-b-c-d-e-f-g+1 )... | Creating an array of numbers that sum to a given number |
Python | I have a program which recieves inputs in the form of text for example : where A.4.1-1/1 etc . are variables with a value TRUE or FALSE . so far i have parsed up the text into the logical parts for the above example I have a list that looks like this : I am just wondering is it possible to actually perform the logic on... | IF ( A.4.1-1/1 OR A.4.1-1/2 ) AND A.4.4-1/9 AND ( A.4.4-1/12 OR A.4.4-1/13 OR A.4.4-1/14 OR A.4.4-1/15 ) THEN R ELSE N/A [ 'IF ' , ' ( ' , ' A.4.1-1/1 ' , 'OR ' , ' A.4.1-1/2 ' , ' ) ' , 'AND ' , ' A.4.4-1/9 ' , 'AND ' , ' ( ' , ' A.4.4-1/12 ' , 'OR ' , ' A.4.4-1/13 ' , 'OR ' , ' A.4.4-1/14 ' , 'OR ' , ' A.4.4-1/15 ' ,... | Implementing logic from text |
Python | I have the following piece of code doing exactly what i want ( it is part of a kriging method ) . But the problem is that it goes too slow , and i wish to know if there is any option to push the for-loop down to numpy ? If i push out the numpy.sum , and use the axis argument there , it speeds up a little bit , but appa... | # n = 2116print GRZVV.shape # ( 16309 , 2116 ) print GinvVV.shape # ( 2117 , 2117 ) VVg = numpy.empty ( ( GRZVV.shape [ 0 ] ) ) for k in xrange ( GRZVV.shape [ 0 ] ) : GRVV = numpy.empty ( ( n+1 , 1 ) ) GRVV [ n , 0 ] = 1 GRVV [ : n , 0 ] = GRZVV [ k , : ] EVV = numpy.array ( GinvVV * GRVV ) # GinvVV is numpy.matrix VV... | How to push the for-loop down to numpy |
Python | Problem : I can not distribute a cx_freeze generated .exe to another machine , because it seems the exe contains references to absolute paths on the machine that generated the .exe . I also had to include vcruntime140.dll direktly , because `` include_msvcr '' : True didnt copy the file.SetupWin 10Python 3.7.2cx_freeze... | from os.path import dirnamefrom cx_Freeze import setup , Executablefrom config import settingsimport os.pathimport sysimport globPYTHON_INSTALL_DIR = os.path.dirname ( os.path.dirname ( os.__file__ ) ) DEPENDENCY_DIR = os.path.join ( os.getcwd ( ) , 'dependencies ' ) os.environ [ 'TCL_LIBRARY ' ] = os.path.join ( DEPEN... | Absolute paths after freezing with cx_freeze ( Qt5 / PySide2 App ) |
Python | I want to find the fastest way to do the job of switch in C. I 'm writing some Python code to replace C code , and it 's all working fine except for a bottleneck . This code is used in a tight loop , so it really is quite crucial that I get the best performance.Optimsation Attempt 1 : First attempt , as per previous qu... | real 0m37.309suser 0m33.263ssys 0m4.002s real 0m2.595suser 0m2.526ssys 0m0.028s | Fastest Python equivalent to switch for array of integers |
Python | I wrote the code for a simple TCP client : I would like to know , how `` generate `` multiple clients TCP using Threads instead of opening multiple instances of the terminal and run the script several times . | from socket import * # Configurações de conexão do servidor # O nome do servidor pode ser o endereço de # IP ou o domínio ( ola.python.net ) serverHost = 'localhost ' # ip do servidorserverPort = 50008 # Mensagem a ser mandada codificada em bytesmenssagem = [ b'Ola mundo da internet ! ' ] # Criamos o socket e o conecta... | How `` generate `` multiple TCP clients using Threads instead of opening multiple instances of the terminal and run the script several times ? |
Python | What regex can I use to match `` . # , # . '' within a string . It may or may not exist in the string . Some examples with expected outputs might be : The last one is n't too important and I would only expect that . # , # . would appear once . Most files I 'm processing , I would expect to fall into the first through f... | Test1.0,0.csv - > ( 'Test1 ' , ' 0,0 ' , 'csv ' ) ( Basic Example ) Test2.wma - > ( 'Test2 ' , 'wma ' ) ( No Match ) Test3.1100,456.jpg - > ( 'Test3 ' , '1100,456 ' , 'jpg ' ) ( Basic with Large Number ) T.E.S.T.4.5,6.png - > ( 'T.E.S.T.4 ' , ' 5,6 ' , 'png ' ) ( Does n't strip all periods ) Test5,7,8.sss - > ( 'Test5,... | Python/Regex - Match . # , # . in String |
Python | While ago I was interviewed for a Data Scientist role . Strangely , without asking about Machine Learning or Data Science or even Statistics , I was given a small task to join two pandas dataframes , and compare various methods for doing so . I was not given a criteria that what the expectation was . I 've provided mul... | # Randomly generated historical data about how many megabytes were downloaded from the Internet . `` HoD '' is the Hour of the Day ! hist_df = pd.DataFrame ( columns= [ 'HoD ' , 'Volume ' ] ) hist_df [ 'HoD ' ] = np.random.randint ( 0 , 24 , 365 * 24 ) hist_df [ 'Volume ' ] = np.random.uniform ( 1 , 1000 , 365 * 24 ) #... | Pandas Interview Question - Compare Pandas-Joins and Ideally Provide the Fastest Method |
Python | I 've drawn samples from a multivariate normal distribution and would like to get the gradient of their log probability with respect to the mean . Since there are many samples , this requires a Jacobian : Now I would like to get the derivative of each entry in logprobs with respect to each entry in mu.A simple solution... | import torchmu = torch.ones ( ( 2 , ) , requires_grad=True ) sigma = torch.eye ( 2 ) dist = torch.distributions.multivariate_normal.MultivariateNormal ( mu , sigma ) num_samples=10samples = dist.sample ( ( num_samples , ) ) logprobs = dist.log_prob ( samples ) grads = [ ] for logprob in logprobs : grad = torch.autograd... | how to get jacobian with pytorch for log probability of multivariate normal distribution |
Python | I 'm working through Exercism.io gigasecond problem : '' Calculate the moment when someone has lived for 10^9 seconds . `` My method was to convert the datetime input to a timestamp , add 10**9 , then convert back . My answers are very close , but the test suite ( provided by Exercism ) fails because the hour arg is of... | def add_gigasecond ( birth_date ) : gigadate = birth_date.timestamp ( ) + 10**9 print ( datetime.fromtimestamp ( gigadate ) .__repr__ ( ) ) gigadate = birth_date + timedelta ( seconds=10**9 ) print ( gigadate.__repr__ ( ) ) tests = [ datetime ( 2011 , 4 , 25 ) , datetime ( 1977 , 6 , 13 ) , datetime ( 1959 , 7 , 19 ) ,... | Difference between time addition using timestamp vs using timedelta ? |
Python | Take the following string : If I were to split it using : I would get : Then , to each element of the new list I would run a function , say : How could I rejoin it using the original separators ? In the above example , the rejoining process would result with : | `` Hello , world , how-are you ? h '' import rex = re.split ( `` [ ^a-zA-Z ] '' , string ) [ `` Hello '' , '' world '' , '' how '' , '' are '' , '' you '' , '' h '' ] y = map ( str.upper , x ) `` HELLO , WORLD , HOW-ARE-YOU ? H '' | Split a list and rejoin it using the same separator |
Python | If I was to write a file with this content : Would it then be very non-pythonic to do it with a generator using send ? I have never seen generators used like this elsewhere.I am asking , because the method above would be hugely beneficial to me instead of opening multiple different file streams in a contextlib stack . ... | # You have been defeated ! # It 's merely a flesh wound ! We are the knights who say Ni ! We are the knights who say Ni ! We are the knights who say Ni ! def write ( file , header ) : with open ( file , ' w ' ) as f : f.write ( header ) line = ( yield ) while True : f.write ( line ) line = ( yield ) returnfile='holygra... | Is it pythonic to use generators to write header and body of a file ? |
Python | Problem statement : There are 5 projects and 15 employees and the numbers against each column shows the interest of each employee in a given project . Each project can have a maximum of 3 employees . Scores are from 1-5 1 being the highest preference and 5 being the lowest preference . I have to divide the employees am... | df = pd.read_csv ( io.StringIO ( `` '' '' employee proj_A proj_B proj_C proj_D proj_E A1 1 5 3 4 2 B1 5 4 1 2 3 C1 2 3 4 1 5 A2 4 2 1 3 5 B2 4 5 3 2 1 C2 3 1 2 5 4 A3 1 2 4 3 5 B3 2 3 1 5 4 C3 5 3 4 1 2 A4 4 5 3 2 1 B4 5 3 4 2 1 C4 1 2 3 4 5 A5 1 3 2 5 4 B5 2 1 3 5 4 C5 2 1 4 5 4 `` '' '' ) , sep=r '' \s+ '' ) import p... | How to find set of lowest sum of distinct column elements in python ? |
Python | I know that Python does n't support tail-call optimization . Does that mean a recursive procedure with an iterative process like the factorial I defined below would consume O ( n ) memory , or does the fact that there are no deferred operations mean that space would be O ( 1 ) ? | def factorial ( n , accum=1 ) : if n == 0 : return accum else : return factorial ( n-1 , accum * n ) | Does the python stack grow with an iterative process that is executed by a recursive procedure ? |
Python | I have a list l of sets . To take the union of all the sets in l I do : I have a feeling there is a more economical/functional way of writing this . Can I improve upon this ? | union = set ( ) for x in l : union |= x | Taking the union of sets |
Python | I 'm trying to coordinate colors on a networkx network chart with the colors on seaborn charts . When I use the same color pallet ( Dark2 ) and same group ids , the two plots still come out different . To be clear , the nodes in group 0 should be the same as the bars in group 0 . The same should hold true for groups 1 ... | import pandas as pdimport networkx as nximport matplotlib.pyplot as pltimport seaborn as sns # create dataframe of connectionsdf = pd.DataFrame ( { 'from ' : [ ' A ' , ' B ' , ' C ' , ' A ' ] , 'to ' : [ 'D ' , ' A ' , ' E ' , ' C ' ] } ) # create graphG = nx.Graph ( ) for i , r in df.iterrows ( ) : G.add_edge ( r [ 'f... | Can I coordinate colors between seaborn and networkx ? |
Python | I want to wrap a function with specified arguments , something like functools.partial , but it does n't work as expected : the output : But ... What I want is : I know it works if I use functools.partial , but I want to know the real problem in my code ... Does the lambda wrapper use a global variable source ? | source_codes = ( 0 , 1 , 2 ) def callback ( source , *args ) : print 'callback from source : ' , sourcefuncs = [ ] for source in source_codes : funcs.append ( lambda *args : callback ( source , *args ) ) for i , func in enumerate ( funcs ) : print 'source expected : ' , i func ( ) print source expected : 0callback from... | failed to wrap function with lambda |
Python | When starting up celery , it retries connecting to my rabbitmq broker , which gives it the necessary time to load . This is good , because I 'm using docker and I ca n't guarantee the order in which services start and precisely which service will be up when.However , while trying to connect to the local mysql server I ... | OperationalError : ( 2002 , `` Ca n't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock ' ( 2 ) '' ) | Configure celery to wait for backend service to start |
Python | I have a numpy array of size nxm . I want the number of columns to be limited to k and rest of the columns to be extended in new rows . Following is the scenario -Initial array : nxmFinal array : pxkwhere p = ( m/k ) *nEg . n = 2 , m = 6 , k = 2Initial array : Final array : I tried using reshape but not getting the des... | [ [ 1 , 2 , 3 , 4 , 5 , 6 , ] , [ 7 , 8 , 9 , 10 , 11 , 12 ] ] [ [ 1 , 2 ] , [ 7 , 8 ] , [ 3 , 4 ] , [ 9 , 10 ] , [ 5 , 6 ] , [ 11 , 12 ] ] | How to slice and extend a 2D numpy array ? |
Python | Assume that a ray actor is defined as belowIs it thread-safe to have other actors call methods of Buffer without any lock ? | @ ray.remoteclass Buffer : def __init__ ( self ) : self.memory = np.zeros ( 10 ) def modify_data ( self , indices , values ) : self.memory [ indices ] = values def sample ( self , size ) : indices = np.random.randint ( 0 , 10 , size ) return self.memory [ indices ] | Is ray thread safe ? |
Python | I just saw the followingin hereWhat is the purpose of using parenthesis ( ) in import statement ? Why shall someone use parenthesis while we can live without it ? is it recommended ? | from flask_login import ( LoginManager , login_required , login_user , current_user , logout_user , UserMixin ) | python : what is the purpose of using ( ) in python imports ? |
Python | I have a web service ( Python 3.7 , Flask 1.0.2 ) with a workflow consisting of 3 steps : Step 1 : Submitting a remote compute job to a commercial queuing system ( IBM 's LSF ) Step 2 : Polling every 61 seconds for the remote compute job status ( 61 seconds because of cached job status results ) Step 3 : Data post-proc... | with Connection ( redis.from_url ( current_app.config [ 'REDIS_URL ' ] ) ) : q = Queue ( ) job1 = q.enqueue ( step1 ) job2 = q.enqueue ( step2 , depends_on=job1 ) job3 = q.enqueue ( step3 , depends_on=job2 ) with Connection ( redis.from_url ( current_app.config [ 'REDIS_URL ' ] ) ) : q = Queue ( ) s = Scheduler ( 'defa... | How to create a `` depends_on `` relationship between scheduled and queued jobs in python-rq |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.