lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | what I 'm trying to implement is a function that increments a string by one character , for example : I 've implemented function for the first two cases , however I ca n't think of any solution for the third case.Here 's my code : Any suggestions ? | 'AAA ' + 1 = 'AAB '' AAZ ' + 1 = 'ABA '' ZZZ ' + 1 = 'AAAA ' def new_sku ( s ) : s = s [ : :-1 ] already_added = False new_sku = str ( ) for i in s : if not already_added : if ( i < ' Z ' ) : already_added = True new_sku += chr ( ( ord ( i ) +1 ) % 65 % 26 + 65 ) else : new_sku += i return new_sku [ : :-1 ] | Addition of chars adding one character in front |
Python | I want to add a new column in a dataframe with values from some other dataframe . My new column name is a variable and I can not hardcode it.The problem is that , I am getting a new column named new_column.What I expect is a column named my_new_column_nameCan anyone please suggest a solution for this . | new_column = `` my_new_column_name '' df = df.assign ( new_column=other_df [ 'Column1 ' ] .values ) | How to pandas df.assign ( ) with variable names ? |
Python | I ’ m writing an application that collects and displays the data from a scientific instrument . One of the pieces of data is a spectrum : essentially just a list of values , plus a dictionary with some metadata . Once the data has been collected by the application it does not change , so both the list and the metadata ... | class Spectrum ( object ) : def __init__ ( self , values , metadata ) : self.values = values self.metadata = metadata # self.values and self.metadata should not change after this point . @ property def first_value ( self ) : return self.values [ 0 ] def multiply_by_constant ( self , c ) : return [ c*x for x in self.val... | Memoizing all methods by default |
Python | Similar to https : //stackoverflow.com/questions/12518499/pip-ignores-dependency-links-in-setup-pyI 'm modifying faker in anticipation to an open PR I have open with validators , and I want to be able to test the new dependency i will have.python setup.py test refuses to install the 0.13.0 version.If I move the trouble... | setup ( name='Faker ' , ... install_requires= [ `` python-dateutil > =2.4 '' , `` six > =1.10 '' , `` text-unidecode==1.2 '' , ] , tests_require= [ `` validators @ https : //github.com/kingbuzzman/validators/archive/0.13.0.tar.gz # egg=validators-0.13.0 '' , # TODO : this will change # noqa `` ukpostcodeparser > =1.1.1... | setup.py ignores full path dependencies , instead looks for `` best match '' in pypi |
Python | I am trying to emulate Chrome 's native messaging feature using Firefox 's add-on SDK . Specifically , I 'm using the child_process module along with the emit method to communicate with a python child process.I am able to successfully send messages to the child process , but I am having trouble getting messages sent ba... | var utf8 = new TextEncoder ( `` utf-8 '' ) .encode ( message ) ; var latin = new TextDecoder ( `` latin1 '' ) .decode ( utf8 ) ; emit ( childProcess.stdin , `` data '' , new TextDecoder ( `` latin1 '' ) .decode ( new Uint32Array ( [ utf8.length ] ) ) ) ; emit ( childProcess.stdin , `` data '' , latin ) ; emit ( childPr... | How to message child process in Firefox add-on like Chrome native messaging |
Python | I 'm trying to debug ( hit breakpoint ) a python script which is executed through a new process from C # .I have installed Child Process Debugging Power tool as that tool supposedly allows one to do that.According to its documentation it requires two things : The parent process must be debugged with the native debuggin... | ProcessStartInfo startInfo = new ProcessStartInfo ( ) ; Process p = new Process ( ) ; startInfo.CreateNoWindow = true ; startInfo.UseShellExecute = false ; startInfo.RedirectStandardOutput = false ; startInfo.RedirectStandardError = true ; startInfo.RedirectStandardInput = false ; ... p.StartInfo = startInfo ; p.Enable... | Mixed mode Debugging Python/C # using Child Process Debugging Power Tool |
Python | I generated a dendrogram plot for my dataset and I am not happy how the splits at some levels have been ordered . I am thus looking for a way to swap the two branches ( or leaves ) of a single split.If we look at the code and dendrogram plot at the bottom , there are two labels 11 and 25 split away from the rest of the... | import numpy as np # random data set with two clustersnp.random.seed ( 65 ) # for repeatability of this tutoriala = np.random.multivariate_normal ( [ 10 , 0 ] , [ [ 3 , 1 ] , [ 1 , 4 ] ] , size= [ 10 , ] ) b = np.random.multivariate_normal ( [ 0 , 20 ] , [ [ 3 , 1 ] , [ 1 , 4 ] ] , size= [ 20 , ] ) X = np.concatenate (... | Swap leafs of Python scipy 's dendrogram/linkage |
Python | ObjectiveI 've reviewed pandas documentation on merge but have a question on overriding values efficiently in a 'left ' merge . I can do this simply for one pair of values ( as seen here ) , but it becomes cluttered when trying to do multiple pairs.SetupIf I take the following dataframes : I can merge them : to getI wa... | a = pd.DataFrame ( { 'id ' : [ 0,1,2,3,4,5,6,7,8,9 ] , 'val ' : [ 100,100,100,100,100,100,100,100,100,100 ] } ) b = pd.DataFrame ( { 'id ' : [ 0,2,7 ] , 'val ' : [ 500 , 500 , 500 ] } ) df = a.merge ( b , on= [ 'id ' ] , how='left ' , suffixes= ( `` , '_y ' ) ) id val val_y0 0 100 500.01 1 100 NaN2 2 100 500.03 3 100 N... | Merge 'left ' , but override 'right ' values where possible |
Python | I need to find optimal discount for each product ( in e.g . A , B , C ) so that I can maximize total sales . I have existing Random Forest models for each product that map discount and season to sales . How do I combine these models and feed them to an optimiser to find the optimum discount per product ? Reason for mod... | # pre-processed data products_pre_processed_data = { key : pre_process_data ( df , key ) for key , df in df_basepack_dict.items ( ) } # rf models products_rf_model = { key : rf_fit ( df ) for key , df in products_pre_processed_data .items ( ) } from pyswarm import psodef obj ( x ) : model1 = products_rf_model.get ( ' A... | How to build hybrid model to find optimal discount of products ? |
Python | I 'm implementing a card game in Python , and for my class to handle players , PlayerHandler , I recently implemented __next__ to simply call next_player . Because gameplay can be thought of in an infinite loop ( The players will keep playing until they quit or win/lose ) , it did not make sense for it to stop iteratio... | class PlayerHandler ( ) : `` '' '' Holds and handles players and order '' '' '' def __init__ ( self , players=None , order=1 ) : if players is None : self.players = [ ] else : self.players = list ( players ) self.current_player = None self.next_player ( ) self.order = order def get_player ( self , interval ) : assert t... | Is an infinite for loop bad practice ? |
Python | Is the exact behavior of the str.__mod__ documented ? These two lines of code works just as expected : This line behaves as expected too : But what does this line and why it does n't raise any error ? P . S . | > > > 'My number is : % s . ' % 123'My number is : 123 . ' > > > 'My list is : % s . ' % [ 1 , 2 , 3 ] 'My list is : [ 1 , 2 , 3 ] . ' > > > 'Not a format string ' % 123Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > TypeError : not all arguments converted during string formatting > ... | Python 'string ' % [ 1 , 2 , 3 ] does n't raise TypeError |
Python | I 'm trying to add a new tuple to a list of tuples ( sorted by first element in tuple ) , where the new tuple contains elements from both the previous and the next element in the list . Example : ( 4,10 ) was constructed from and added in between ( 3,10 ) and ( 4,7 ) . I 've tried using enumerate ( ) to insert at the s... | oldList = [ ( 3 , 10 ) , ( 4 , 7 ) , ( 5,5 ) ] newList = [ ( 3 , 10 ) , ( 4 , 10 ) , ( 4 , 7 ) , ( 5 , 7 ) , ( 5 , 5 ) ] Construct ( x , y ) from ( a , y ) and ( x , b ) | Insert element to list based on previous and next elements |
Python | Is it possible to speed up the following code , but without using external modules ( NumPy , etc ) ? Just plain Python . Two lines of thought : speeding the computation in or faster building of the desired structure . The aim is to find the geometric average of an ord ( ) of an ASCII symbol and report it as a round val... | chr ( int ( round ( multiplOrds** ( 1.0/DLen ) , 0 ) ) ) KM < I def GA ( ) : InStr= '' 0204507890 '' InDict= { 0 : '' ABCDEFGHIJ '' , 1 : '' KLMNOPQRST '' , 2 : '' WXYZ # & / ( ) ? '' } OutStr = `` '' DLen = len ( InDict ) for pos in zip ( InStr , *InDict.values ( ) ) : if pos [ 0 ] == '' 0 '' : multiplOrds = 1 for mul... | faster geometric average on ASCII |
Python | From some of the answers on Stackoverflow , I came to know that from -5 to 256 same memory location is referenced thus we get true for : Now comes the twist ( see this line before marking duplicate ) : This is completely understood , but now if I do : Why ? | > > > a = 256 > > > a is 256True > > > a = 257 > > > a is 257 False > > > a = 257 ; a is 257True > > > a = 12345 ; a is 12345True | Uncommon behaviour of IS operator in python |
Python | Having the following function : It is clearly stated in PEP 8 that no spaces should be used around the = sign when used to indicate a keyword argument or a default parameter value.If we want to type-annotate the x parameter . How should we do it ? Is there a preferred way ? Or even better , is it specified in some PEP ... | def foo ( x=1 ) : print ( x ) def foo ( x : int=1 ) : def foo ( x : int=1 ) : def foo ( x : int = 1 ) : | Type annotation style ( to space or not to space ) |
Python | I 'm running into a very strange issue ever since I have ported my code from one computer to another . I 'm using pandas version 0.25.1 on this system , but am unsure on the pandas version I was using previously . The issue is as follows : I create a simple , unsorted ( mock ) dataframe on which I want to sort values a... | In [ 1 ] : import pandas as pd ... : import numpy as npIn [ 2 ] : test = pd.DataFrame ( { `` group '' : [ `` A '' , `` A '' , `` A '' , `` B '' , `` B '' , `` B '' , `` C '' , `` C '' ] , ... : `` count '' : [ 2 , 3 , 1 , 2 , 1 , 3 , 1 , 2 ] , ... : `` value '' : [ 10 , np.nan , 30 , np.nan , 19 , np.nan , 25 , np.nan ... | GroupBy with ffill deletes group and does not put group in index |
Python | I need some help to evaluate what will be the right design of a twisted matrix application . Or any url to help to do so.background : i now use logging capacity included with twistedmatrix by using FileLogObserver , and a custom DailyLogFile to propage and save data to file system and for later analyze.Now , I m going ... | feed = socket.socket ( socket.AF_INET , socket.SOCK_STREAM ) feed.connect ( ( `` localhost '' , MYPORT ) ) feed.send ( mytimestamp , myeventdata ) producerTimedEventLog1 -- - > |producerTimedEventLog2 -- - > | ... | -- - > loggerReceiverComputingData -- - > lighstreamer process -- - > mozilla or whatever webclient ... ... | python , twistedmatrix ... logging through socket |
Python | In documenting a Python function , I find it more Pythonic to say : …rather than…When i really does n't need to be a list . ( Foo will happily operate on a set , tuple , etc . ) The problem is generators . Generators typically only allow 1 iteration . Most functions are OK with generators or iterables that only allow a... | def Foo ( i ) : `` '' '' i : An interable containing… '' '' '' def Foo ( i ) : `` '' '' i : A list of … '' '' '' | Python documentation : iterable many times ? |
Python | I am using django-follow to allow users to `` follow '' objects - in this example , Actors in films.I am pulling back a list of film actors usingBut what I also want to do is suggest films to the user based on the actors they are following . This does not need to be a complex algorithm of what they already like and sug... | actors_user_is_following = Follow.objects.get_follows ( Actor ) .filter ( user=request.user.id ) context [ 'follows ' ] = { 'actors ' : Follow.objects.get_follows ( Actor ) .filter ( user=request.user.id ) , 'genres ' : Follow.objects.get_follows ( Genre ) .filter ( user=request.user.id ) , } actor_ids = [ ] for actor ... | Find related objects and display relation |
Python | I 'm trying to scrape this website using Python and Selenium , it requires you to select a date from drop-down box then click search to view the planning applications.URL : https : //services.wiltshire.gov.uk/PlanningGIS/LLPG/WeeklyList.I have the code working to select the first index of the drop-down box and press se... | from selenium import webdriverfrom selenium.webdriver.support.ui import Selectfrom selenium.webdriver.chrome.options import Optionsoptions = Options ( ) options.add_argument ( ' -- headless ' ) options.add_argument ( ' -- disable-gpu ' ) driver = webdriver.Chrome ( '/Users/weaabduljamac/Downloads/chromedriver ' , chrom... | How to open the option items of a select tag ( dropdown ) in different tabs/windows ? |
Python | My goal is to make a circle shape out of lines in pygame , using random endpoints around the edge of a circle and a constant starting point ( the middle of the circle ) . So I decided that I would give the pygame.draw.line function : screen , aRandomColor , startingPosition , and endingPosition as arguments . Ending po... | import mathimport randomdef findY ( pos1 , pos2 , distance , bothValues=False ) : p1 =pos1 p2 = pos2 x1 = float ( p1 [ 0 ] ) y1 = float ( p1 [ 1 ] ) x2 = float ( p2 [ 0 ] ) d = float ( distance ) y2 = y1 - math.sqrt ( d**2 - ( x1-x2 ) **2 ) _y2 = y1 + math.sqrt ( d**2 - ( x1-x2 ) **2 ) if bothValues==True : return y2 ,... | python distance formula coordinate plane error |
Python | I set up a simple custom function that takes some default arguments ( Python 3.5 ) : and timed different calls to it with or without specifying argument values : Without specifying arguments : Specifying arguments : As you can see , there is a somewhat noticeable increase in time required for the call specifying argume... | def foo ( a=10 , b=20 , c=30 , d=40 ) : return a * b + c * d % timeit foo ( ) The slowest run took 7.83 times longer than the fastest . This could mean that an intermediate result is being cached 1000000 loops , best of 3 : 361 ns per loop % timeit foo ( a=10 , b=20 , c=30 , d=40 ) The slowest run took 12.83 times long... | Why do argument-less function calls execute faster ? |
Python | We have N users with P avg . points per user , where each point is a single value between 0 and 1 . We need to distribute the mass of each point using a normal distribution with a known density of 0.05 as the points have some uncertainty . Additionally , we need to wrap the mass around 0 and 1 such that e.g . a point a... | from typing import List , Anyimport numpy as npimport scipy.statsimport matplotlib.pyplot as pltD = 50BINS : List [ float ] = np.linspace ( 0 , 1 , D + 1 ) .tolist ( ) def probability_mass ( distribution : Any , x0 : float , x1 : float ) - > float : `` '' '' Computes the area under the distribution , wrapping at 1 . Th... | Speeding up normal distribution probability mass allocation |
Python | Is there a builtin or canonical way to consume the first and all successive results for a ndb.get_multi_async call in the order of their completion ? I would expect , and this illustrates , it along the lines of : One way to remove the future consumed is to check futures to see whether it is done.There is a race condit... | def yield_next ( futures ) : while futures : yield ndb.Future.wait_any ( futures ) # We have to remove the yielded future from the futures . # How do we know which future was removed ? # ... futures.remove ( ? ? ? ) for model in yield_next ( ndb.get_multi_async ( keys ) ) : ... | ndb aysnc `` yield next '' to consume get_multi_async |
Python | I am very confused by what is reported by numpy.ndarray.nbytes.I just created an identity matrix of size 1 million ( 10^6 ) , which therefore has 1 trillion rows ( 10^12 ) . Numpy reports that this array is 7.28TB , yet the python process only uses 3.98GB of memory , as reported by OSX activity monitor.Is the whole arr... | import numpy as npx = np.identity ( 1e6 ) x.size # 1000000000000x.nbytes / 1024 ** 4 # 7.275957614183426y = 2 * x # python console exits and terminal shows : Killed : 9 | Why does this giant ( non-sparse ) numpy matrix fit in RAM |
Python | When the fold panels expand , it goes outside of the frame and scroll bars are not appearing . I tried using a ScrolledPanel , but did not help . Any idea what I am missing here ? | import wxfrom wx.lib import scrolledpanelimport wx.lib.agw.foldpanelbar as fpbimport wx.lib.scrolledpanel as spclass MyPanel ( sp.ScrolledPanel ) : def __init__ ( self , parent ) : sp.ScrolledPanel.__init__ ( self , parent=parent , size=parent.GetSize ( ) , style = wx.ALL|wx.EXPAND ) # self.SetAutoLayout ( 1 ) self.Set... | Scrollbars are not appearing on expanding FoldPanelBar in wxPython |
Python | I 've got a system in which I often ( but not constantly ) have to find the next item in a tuple . I 'm currently doing this like so : All elements are unique and I am not stuck with the tuple , I can make it something else earlier in the program if needed.Since I need to do this a lot , I was wondering whether there i... | mytuple = ( 2,6,4,8,7,9,14,3 ) currentelement = 4def f ( mytuple , currentelement ) : return mytuple [ mytuple.index ( currentelement ) + 1 ] nextelement = f ( mytuple , currentelement ) | Most efficient way of finding the next element in a tuple |
Python | In the xarray documentation for the function apply_ufunc it says : and in the documentation 's page on Parallel Computing then there is a note : For the majority of NumPy functions that are already wrapped by dask , it ’ s usually a better idea to use the pre-existing dask.array function , by using either a pre-existin... | dask : ‘ forbidden ’ , ‘ allowed ’ or ‘ parallelized ’ , optional How to handle applying to objects containing lazy data in the form of dask arrays : ‘ forbidden ’ ( default ) : raise an error if a dask array is encountered . ‘ allowed ’ : pass dask arrays directly on to func . ‘ parallelized ’ : automatically parallel... | What 's the difference between dask=parallelized and dask=allowed in xarray 's apply_ufunc ? |
Python | I want to sort a list by each item 's digit.Example : How the algorithm should work : Compare each digit of current item in myList with myCmpItemFor the first item in the list it would be like that : Difference between 5 and 1 is 4Difference between 1 and 1 is 0Difference between 1 and 1 is 0Difference between those tw... | myCmpItem = '511'myList = [ '111 ' , '222 ' , '333 ' , '444 ' , '555 ' , '123 ' ] ( some magic ) mySortedList = [ '111 ' , '222 ' , '333 ' , '123 ' , '444 ' , '555 ' ] | Order a list by all item 's digits in Python |
Python | Update : The list are filled with strings I edited the list to show thisI have 3 different list such asI want to combine them such as Or any other form that allows me to then sort them by the numbers in the list titled sections.In this case it would be I need it like this so I can eventually export a sorted list by Sec... | Section = [ ( ' 1 ' , ' 1.1 ' , ' 1.2 ' ) , ( ' 1 ' , ' 2 ' , ' 2.2 ' , ' 3 ' ) , ( ' 1 ' , ' 1.2 ' , ' 3.2 ' , ' 3.5 ' ) ] Page = [ ( ' 1 ' , ' 1 ' , ' 3 ' ) , ( ' 1 ' , ' 2 ' , ' 2 ' , ' 2 ' ) , ( ' 1 ' , ' 2 ' , ' 3 ' , ' 5 ' ) ] Titles = [ ( 'General ' , 'Info ' , 'Titles ' ) , ( 'More ' , 'Info ' , 'Section ' , 'H... | Combing 2D list of tuples and then sorting them in Python |
Python | Here 's my template code for my comment queryset : I 'm using django el pagination to implement ajax pagination . On the 3rd line you can see I initially load 10 comments . With this package , comes a { % show_more % } element I can add which , when clicked , will load the rest of the comments . However , this { % show... | { % block comments % } { % load el_pagination_tags % } { % paginate 10 comment_list % } { % for i in comment_list % } < div class='comment_div ' > < div class= '' left_comment_div '' > < p > { { i.comment_text } } < /p > < /div > < /div > { % include 'comment/comments.html ' with comment_list=i.replies.all % } < /div >... | Element disappears when I add an { % include % } tag inside my for loop |
Python | I 'm getting some data from an external system ( Salesforce Marketing Cloud ) over API and I 'm getting the data back in the format below : It 's tantalisingly close to JSON , I 'd like to format it like a JSON file so that I can import it into our database . Any ideas of how I can do this ? Thanks | Results : [ ( List ) { Client = ( ClientID ) { ID = 113903 } PartnerKey = None CreatedDate = 2013-07-29 04:43:32.000073 ModifiedDate = 2013-07-29 04:43:32.000073 ID = 1966872 ObjectID = None CustomerKey = `` 343431CD-031D-43C7-981F-51B778A5A47F '' ListName = `` PythonSDKList '' Category = 578615 Type = `` Private '' De... | Transforming string output to JSON |
Python | bool ( ) and operator.truth ( ) both test whether a value is truthy or falsy and they seem rather similar from the docs , it even says in the truth ( ) docs that : This is equivalent to using the bool constructor.However , truth ( ) is over twice as fast as bool ( ) from a simple test ( Python 3.6 timings shown , but 2... | from timeit import timeitprint ( timeit ( 'bool ( 1 ) ' , number=10000000 ) ) # 2.180289956042543print ( timeit ( 'truth ( 1 ) ' , setup='from operator import truth ' , number=10000000 ) ) # 0.7202018899843097 | What are the differences between bool ( ) and operator.truth ( ) ? |
Python | I 'm trying to teach myself python ( and programming in general ) and am a little confused about variable assignment . I understand that if I havethat b refers to the same object in memory as a does . So if I wanted to create a new list , b , with the same values as a currently has , how would I achieve that ? Also , c... | > > > a = [ 1,2,3 ] > > > b = a > > > a = [ 1 , 2 , 3 ] > > > b = a > > > x = a [ 1 ] > > > a [ 1 ] = 4 > > > print a , b , x [ 1 , 4 , 3 ] [ 1 , 4 , 3 ] 2 | understanding python variable assignment |
Python | For example : Formatted string literals were introduced in python3.6if i use # ! /usr/bin/env python3 , it will throw a syntax error if there is an older version of python installed . If i use # ! /usr/bin/env python3.6 , it wo n't work if python3.6 is n't installed , but a newer version is.How do i make sure my progra... | testvar = `` test '' print ( f '' The variable contains \ '' { testvar } \ '' '' ) | How to write shebang when using features of minor versions |
Python | Currently , I am working with a pandas.DataFrame that I need to divide the entire dataframe by a certain value except for one row . It is easy to divide the entire dataframe by one value , however I would like to keep one of the rows the exact same . For example , if I had a dataframe like below : I want to divide all ... | A B C D10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 1 1 1 1 10000 10000 10000 10000 10000 10000 10000 10000 A B C D10 10 10 1010 10 10 1010 10 10 1010 10 10 10 1 1 1 1 10 10 10 10 10 10 10 10 | How to divide all rows in a panda Dataframe except for one specific row ? |
Python | I 'm trying to extend a method with a single keyword argument while remaining impartial to the rest of the method 's signature ; I just want to pass that on . Attempt 0 : This does not work : I fully understand why the above does not work , but I 'm looking for a nice way to make it work . This is my current ( ugly ) w... | class SomeSuperclass ( object ) : pass # in reality : some implementation for some_methodclass SomeClass ( SomeSuperclass ) : def some_method ( self , my_kwarg=42 , *args , **kwargs ) : super ( SomeClass , self ) .some_method ( *args , **kwargs ) do_something_interesting_with ( my_kwarg ) SomeClass ( ) .some_method ( '... | Python : What is an elegant idiom for extending method with one or more keyword arguments ? |
Python | I 'm working with a DataFrame having the following structure : My goal is to view only the groups having exactly one brand X associated to them . Since group number 2 has two observations equal to brand X , it should be filtered out from the resulting DataFrame . The output should look like this : I know I should do a ... | import pandas as pddf = pd.DataFrame ( { 'group ' : [ 1,1,1,2,2,2,2,3,3,3 ] , 'brand ' : [ ' A ' , ' B ' , ' X ' , ' C ' , 'D ' , ' X ' , ' X ' , ' E ' , ' F ' , ' X ' ] } ) print ( df ) group brand0 1 A1 1 B2 1 X3 2 C4 2 D5 2 X6 2 X7 3 E8 3 F9 3 X group brand0 1 A1 1 B2 1 X3 3 E4 3 F5 3 X | Filtering DataFrame on groups where count of element is different than 1 |
Python | In PEP 3103 , Guido is discussing adding a switch/case statement to Python with the various schools of thought , methods and objects . In that he makes this statement : Another objection is that the first-use rule allows obfuscated code like this : To the untrained eye ( not familiar with Python ) this code would be eq... | def foo ( x , y ) : switch x : case y : print 42 def foo ( x , y ) : if x == y : print 42 | PEP 3103 : Difference between switch case and if statement code blocks |
Python | I am writing a program to match string with alpha numeric.I have tried on but could not find.please tell me regular expression for alphanumeric except o , O , I , ii have tried many , but some times one character failing , i am new to regexMy requirements are : Takes all alphabet and numberNeed to exclude Q , O and I s... | [ A-HJ-NPR-Za-hj-npr-z0-9 ] $ | Any word containing only alphabet , numbers but not Q , I , O , no other character |
Python | I 'm trying to convert a post title to CamelCase to create a twitter hashtag , I 'm using strip but its returning a object instead I dont know if this is the right way ? Which returns < built-in method strip of unicode object at 0x031ECB48 > in the template var , the result I 'm looking for is like this MyPostTitle int... | # views.pydef post_create ( request ) : if not request.user.is_authenticated ( ) : raise Http404 form_class = PostCreateForm if request.method == 'POST ' : form = form_class ( request.POST , request.FILES ) if form.is_valid ( ) : instance = form.save ( commit=False ) instance.creator = request.user instance.slug = slug... | Convert post title to CamelCase |
Python | A few days ago twitter updated some aspects of their API because of the GDPR changes . Starting today some of my applications have been breaking in a very odd way which I did n't expect would be affected by the GDPR changes . Maybe it has nothing to do with these changes but it is mysterious timing since they changed t... | client = Client ( twitter_consumer_key , twitter_consumer_secret ) url = `` https : //api.twitter.com/1.1/application/rate_limit_status.json ? resources=help , users , search , statuses '' print client.request ( url ) { u'rate_limit_context ' : { u'application ' : u'AZljARxCJ6b4rPtCGJIuk4O ' } , u'resources ' : { } } c... | Twitter API in python GDPR update |
Python | My data file looks like this : As can be seen , the last column ends with a semicolon , so when I read into pandas , the column is inferred as type object ( ending with the semicolon.How do I make pandas ignore that semicolon ? | data.txtuser , activity , timestamp , x-axis , y-axis , z-axis0,33 , Jogging,49105962326000 , -0.6946376999999999,12.680544,0.50395286 ; 1,33 , Jogging,49106062271000,5.012288,11.264028,0.95342433 ; 2,33 , Jogging,49106112167000,4.903325,10.882658000000001 , -0.08172209 ; 3,33 , Jogging,49106222305000 , -0.61291564,18.... | pandas read csv ignore ending semicolon of last column |
Python | I 'm trying to make sure running help ( ) at the Python 2.7 REPL displays the __doc__ for a function that was wrapped with functools.partial . Currently running help ( ) on a functools.partial 'function ' displays the __doc__ of the functools.partial class , not my wrapped function 's __doc__ . Is there a way to achiev... | def foo ( a ) : `` '' '' My function '' '' '' passpartial_foo = functools.partial ( foo , 2 ) | Allow help ( ) to work on partial function object |
Python | I know this is a primitive question but what should I add in my code for it to output the training accuracy of the Neural Network in addition to the loss , I checked PyTorch tutorials and they show how to add training/testing accuracy in image classification but I do not know how to do that in my simple XOR solving NN ... | # Step 1 : importing our dependenciesimport torchfrom torch.autograd import Variableimport numpy as np # Our datax = Variable ( torch.Tensor ( [ [ 0 , 0 , 1 ] , [ 0 , 1 , 1 ] , [ 1 , 0 , 1 ] , [ 0 , 1 , 0 ] , [ 1 , 0 , 0 ] , [ 1 , 1 , 1 ] , [ 0 , 0 , 0 ] ] ) ) y = Variable ( torch.Tensor ( [ [ 0 ] , [ 1 ] , [ 1 ] , [ 1... | Add Training and Testing Accuracy to a Simple Neural Network in PyTorch |
Python | In the interpreter you can just write the name of an object e.g . a list a = [ 1 , 2 , 3 , u '' hellö '' ] at the interpreter prompt like this : or you can do : which seems equivalent for lists . At the moment I am working with hdf5 to manage some data and I realized that there is a difference between the two methods m... | > > > a [ 1 , 2 , 3 , u'hell\xf6 ' ] > > > print a [ 1 , 2 , 3 , u'hell\xf6 ' ] with tables.openFile ( `` tutorial.h5 '' , mode = `` w '' , title = `` Some Title '' ) as h5file : group = h5file.createGroup ( `` / '' , 'node ' , 'Node information ' ) tables.table = h5file.createTable ( group , 'readout ' , Node , `` Rea... | What is the difference between ` > > > some_object ` and ` > > > print some_object ` in the Python interpreter ? |
Python | I try to understand more thoroughly descriptor and explicit attribute name look-up order.I read descriptor howto and it states as follows : The details of invocation depend on whether obj is an object or a class : ... For classes , the machinery is in type.__getattribute__ ( ) which transforms B.x into B.__dict__ [ ' x... | In [ 47 ] : object.__class__Out [ 47 ] : type In [ 48 ] : object.__dict__ [ '__class__ ' ] .__get__ ( None , object ) Out [ 48 ] : < attribute '__class__ ' of 'object ' objects > if instance is None : return self | __get__ of descriptor __class__ of object class does n't return as expected |
Python | Is it possible to get the following minimal example working with experimental_compile=True ? I 've seen some big speedups with this argument hence I am keen to figure out how to get it working . Thanks ! | import tensorflow as tfprint ( tf.__version__ ) # === > 2.2.0-dev20200409x = tf.reshape ( tf.range ( 25 , dtype=tf.float32 ) , [ 5 , 5 ] ) row_lengths = tf.constant ( [ 2 , 1 , 2 ] ) ragged_tensor = tf.RaggedTensor.from_row_lengths ( x , row_lengths ) for i , tensor in enumerate ( ragged_tensor ) : print ( f '' i : { i... | XLA ca n't deduce compile time constant output shape for strided slice when using ragged tensor and while loop |
Python | I 'm trying to use reverse ( ) in a unit test , but it is not able to resolve the url.tests.py : The test case fails in the first line of the test with the following error : Does `` 0 patterns tried '' means the test is not even able to find the root urls.py ? Or is there something else that I misconfigured ? proj/sett... | from django.core.urlresolvers import reversefrom rest_framework import statusfrom rest_framework.test import APITestCaseclass MyTest ( APITestCase ) : def test_cust_lookup ( self ) : url = reverse ( 'v1 : customer ' ) # Other code NoReverseMatch : Reverse for 'customer ' with arguments ' ( ) ' and keyword arguments ' {... | reverse ( ) raises NoReverseMatch when two apps use the same namespace |
Python | Currently I 've the next dataframe : I want to create a new dataframe with dummies for col2 , like this : Using the following code generates different columns for each of the letters in the column list : Using the following code generates different columns for each of the letters in the list of the column according to ... | import pandas as pddf= pd.DataFrame ( { `` ID '' : [ ' 1 ' , ' 2 ' , ' 3 ' , ' 4 ' , ' 5 ' ] , `` col2 '' : [ [ ' a ' , ' b ' , ' c ' ] , [ ' c ' , 'd ' , ' e ' , ' f ' ] , [ ' f ' , ' b ' , ' f ' ] , [ ' a ' , ' c ' , ' b ' ] , [ ' b ' , ' a ' , ' b ' ] ] } ) print ( df ) ID col20 1 [ a , b , c ] 1 2 [ c , d , e , f ]... | Create dummies for non-unique lists into column in Python |
Python | I have a procedure which requires me to check each value in a List against every other value in the same List . If I identify something that meets some requirement , I add it to another List to be removed after this procedure is finished.Pseudo-code : This looks ugly to me . Naming conventions for the variables are dif... | for value1 in my_list : for value2 in my_list : if meets_requirements ( value1 , value2 ) : to_be_removed.append ( value2 ) | Alternative to Double Iteration |
Python | It 's considered bad Python to use imports like this : When you are doing a relative import and this would work : Is there a tool that can detect these non-dotted relative imports in my code and warn me so I could update them to the dotted syntax ? My project has hundreds of Python modules and I would like to do this a... | import my_module from . import my_module | Tool to detect non-dotted relative imports in Python ? |
Python | I would like have a function return the largest of N list . With two items in the list I can write : which I run with f ( [ l1 , l2 ] ) .However , with more lists , it becomes a succession of if statements , and it is ugly.How would you very efficiently return the largest of N lists ? | l1 = [ 3 , 4 , 5 ] l2 = [ 4 , 5 , 6 , 7 ] def f ( L ) : if ( len ( L [ 0 ] ) > len ( L [ 1 ] ) ) : return L [ 0 ] else : return L [ 1 ] | Python - return largest of N lists |
Python | There is a strange behavior of isinstance if used in __main__ space.Consider the following codea.py : b.pymain.pyWhen I run main.py , I get True , as expected , but when I run a.py , I am getting False . It looks like the name of A is getting the prefix __main__ there.How can I get a consistent behavior ? I need this t... | class A ( object ) : passif __name__ == `` __main__ '' : from b import B b = B ( ) print ( isinstance ( b , A ) ) from a import Aclass B ( A ) : pass from a import Afrom b import Bb = B ( ) print ( isinstance ( b , A ) ) | Calling isinstance in main Python module |
Python | But when i execute | $ ./pypy -OPython 2.7.2 ( a3e1b12d1d01 , Dec 04 2012 , 13:33:26 ) [ PyPy 1.9.1-dev0 with GCC 4.6.3 ] on linux2Type `` help '' , `` copyright '' , `` credits '' or `` license '' for more information.And now for something completely different : `` amd64 and ppc are onlyavailable in enterprise version '' > > > > assert 1=... | how to disable pypy assert statement ? |
Python | I would like to perform an operation on an argument based on the fact that it might be a map-like object or a sequence-like object . I understand that no strategy is going to be 100 % reliable for type-like checking , but I 'm looking for a robust solution.Based on this answer , I know how to determine whether somethin... | def ismap ( arg ) : # How to implement this ? def isseq ( arg ) : return hasattr ( arg , '' __iter__ '' ) def operation ( arg ) : if ismap ( arg ) : # Do something with a dict-like object elif isseq ( arg ) : # Do something with a sequence-like object else : # Do something else if hasattr ( arg , 'keys ' ) and hasattr ... | How to distinguish between a sequence and a mapping |
Python | Let 's say I have a Python list representing ranges for some variables : This represents that variable i ranges from 1 to 5 , and inside that loop variable j ranges from 1 to 2 . I want a dictionary for each possible combination : The reason is that I want to iterate over them . But because the whole space is too big ,... | conditions = [ [ ' i ' , ( 1 , 5 ) ] , [ ' j ' , ( 1 , 2 ) ] ] { ' i ' : 1 , ' j ' : 1 } { ' i ' : 1 , ' j ' : 2 } { ' i ' : 2 , ' j ' : 1 } { ' i ' : 2 , ' j ' : 2 } { ' i ' : 3 , ' j ' : 1 } { ' i ' : 3 , ' j ' : 2 } { ' i ' : 4 , ' j ' : 1 } { ' i ' : 4 , ' j ' : 2 } { ' i ' : 5 , ' j ' : 1 } { ' i ' : 5 , ' j ' : 2... | ` yield ` inside a recursive procedure |
Python | I have a multiline plot in bokeh and I 'd like to select some multilines using the lasso tool.This does not work by default : The lasso tool does not select any lines.Of course , the question is how a line should be considered as selected : Is it selected if one point of the line is in the lasso area or if all points a... | from bokeh.io import output_file , showfrom bokeh.plotting import figurefrom bokeh.models import MultiLineplot = figure ( plot_width=400 , plot_height=400 , tools= '' lasso_select '' ) renderer = plot.multi_line ( [ [ 1 , 2 , 3 , 4 , 5 ] , [ 0,1 ] ] , [ [ 2 , 5 , 8 , 2 , 7 ] , [ 1,0 ] ] ) selected_circle = MultiLine ( ... | Select Multilines using Lasso Tool |
Python | Why does this code print `` d , d , d , d '' , and not `` a , b , c , d '' ? How can I modify it to print `` a , b , c , d '' ? | cons = [ ] for i in [ ' a ' , ' b ' , ' c ' , 'd ' ] : cons.append ( lambda : i ) print ' , '.join ( [ fn ( ) for fn in cons ] ) | Variable scope inside lambda |
Python | I have been looking at open source code for python and many of them have a directory in src with .c and .h files . For instance , there is a directory called protocol which has .c and .h files ( these .c files have static PyObject * ) . if I want to import this directory so that I can use these functions , what 's need... | # include `` Python.h '' # include `` structmember.h '' # define PROTOCOL_MODULE # include `` protocolmodule.h '' PyProtocol_newARPObjectFromPacket_RETURN PyProtocol_newARPObjectFromPacket PyProtocol_newARPObjectFromPacket_PROTO ; PyProtocol_injectARP_RETURN PyProtocol_injectARP PyProtocol_injectARP_PROTO ; PyProtocol_... | Python with C libraries |
Python | This is a twofold question , because I 'm out of ideas on how to implement this most efficiently.I have a dictionary of 150,000 words , stored into a Trie implementation , here 's what my particular implementation looks like : A user is given a provided with two words . With the goal being to find the shortest path of ... | var start = `` dog '' ; var end = `` cat '' ; var alphabet = [ a , b , c , d , e ... . y , z ] ; var possible_words = [ ] ; for ( var letter_of_word = 0 ; letter_of_word < start.length ; letter_of_word++ ) { for ( var letter_of_alphabet = 0 ; letter_of_alphabet < alphabet.length ; letter_of_alphabet++ ) { var new_word ... | Shortest Path between two Trie Nodes |
Python | For example , something like : I know that the in operator can do this for strings : But I 'm looking for something that operates on iterables . | > > > [ 1 , 2 , 3 ] .contains_sequence ( [ 1 , 2 ] ) True > > > [ 1 , 2 , 3 ] .contains_sequence ( [ 4 ] ) False > > > `` 12 '' in `` 123 '' True | Is there a Python builtin for determining if an iterable contained a certain sequence ? |
Python | I want to create a list ( or collection in general ) by calling a method x times . In Python it would be something like this.I tried to code something similar in JDK 8.It works , but somehow it does n't feel allright . Is there a more proper way of doing it ? | self.generated = [ self.generate ( ) for _ in range ( length ) ] this.generated = IntStream.range ( 0 , length ) .mapToObj ( n - > this.generate ( ) ) .collect ( Collectors.toList ( ) ) ; | How to generate a list of given length in Java 8 ? |
Python | The input is an integer that specifies the amount to be ordered.There are predefined package sizes that have to be used to create that order.e.g.for an input order 13 the output should be : So far I 've the following approach : But this will lead to the wrong result:1x9 + 1x3 remaining : 1 | Packs3 for $ 55 for $ 99 for $ 16 2x5 + 1x3 remaining_order = 13package_numbers = [ 9,5,3 ] required_packages = [ ] while remaining_order > 0 : found = False for pack_num in package_numbers : if pack_num < = remaining_order : required_packages.append ( pack_num ) remaining_order -= pack_num found = True break if not fo... | Fill order from smaller packages ? |
Python | how come the output of this is `` holiday '' instead of `` holiday ! '' ? Is it because the 3 line of codes are outside the function ? If so , why would it matter if it 's outside the function since it 's after the change function ? | def change ( s ) : s = s + `` ! `` word = `` holiday '' change ( word ) print word | concatenating strings ? |
Python | What 's the most efficient ( in time ) way of checking if two relatively short ( about 3-8 elements ) lists are shifted copies of one another ? And if so , determine and return the offset ? Here is the example code and output I 'd like : Lists may have duplicate entries . If more than one offset is valid , return any o... | > > > def is_shifted_copy ( list_one , list_two ) : > > > # TODO > > > > > > is_shifted_copy ( [ 1 , 2 , 3 ] , [ 1 , 2 , 3 ] ) 0 > > > is_shifted_copy ( [ 1 , 2 , 3 ] , [ 3 , 1 , 2 ] ) 1 > > > is_shifted_copy ( [ 1 , 2 , 3 ] , [ 2 , 3 , 1 ] ) 2 > > > is_shifted_copy ( [ 1 , 2 , 3 ] , [ 3 , 2 , 1 ] ) None > > > is_shift... | In Python , efficiently determine if two lists are shifted copies of one another |
Python | I have a Pandas DataFrame that looks like this : I would like to have another matrix which gives me the number of non-zero elements for the intersection of every column except for MemberID . For example , the intersection of columns A and B would be 2 ( because MemberID 1 and 3 have non-zero values for A and B ) , inte... | MemberID A B C D1 0.3 0.5 0.1 02 0 0.2 0.9 0.33 0.4 0.2 0.5 0.34 0.1 0 0 0.7 A B C DA 3 2 2 2B 2 3 3 2C 2 3 3 2D 2 2 2 3 df = pd.DataFrame ( [ [ 0.3 , 0.5 , 0.1 , 0 ] , [ 0 , 0.2 , 0.9 , 0.3 ] , [ 0.4 , 0.2 , 0.5 , 0.3 ] , [ 0.1 , 0 , 0 , 0.7 ] ] , columns=list ( 'ABCD ' ) ) | Count of rows where given columns of a DataFrame are non-zero |
Python | I have been trying to understand why python behaves this way , in the block of code below . I have done my research but could n't find a good answer so I came here to see if anyone can point me in the right direction or provide a good clarification . I understand that it has to do with some old ALGOL principle , but I ... | var = 5def func1 ( ) : print ( var ) func1 ( ) def func2 ( ) : var = 8 print ( var ) func2 ( ) def func3 ( ) : print ( var ) var = 8func3 ( ) | Why does python behave this way with variables ? |
Python | This scipy documentation page about F2Py states : [ Callback functions ] may also be explicitly set in the module . Then it is not necessary to pass the function in the argument list to the Fortran function . This may be desired if the Fortran function calling the python callback function is itself called by another Fo... | subroutine test ( py_func ) use iso_fortran_env , only stdout = > output_unit ! f2py intent ( callback ) py_funcexternal py_funcinteger py_func ! f2py integer y , x ! f2py y = py_func ( x ) integer : : ainteger : : ba = 12write ( stdout , * ) aend subroutine import testdef func ( x ) : return x * 2test.test ( func ) py... | How to expose Python callbacks to Fortran using modules |
Python | Supposing I have written a set of classes to be used in a python file and use them in a script ( or python code in a different file ) . Now both the files require a set of modules to be imported . Should the import be included only once , or in both the files ? File 1 : my_module.py.File 2 : Should I be adding the line... | import osclass myclass ( object ) : def __init__ ( self , PATH ) : self.list_of_directories = os.listdir ( PATH ) import osimport my_modulemy_module.m = myclass ( `` C : \\User\\John\\Desktop '' ) list_ = m.list_of_directoriesprint os.getcwd ( ) | Importing the same modules in different files |
Python | I have this unique requirement which can be explained by this code.This is working code but not memory efficient.In short , I want each item of sub-list to be indexable and should return the sublist.The above method works but It takes a lot of memory when data is large . Is there any better , memory and CPU friendly wa... | data = [ [ `` A 5408599 '' , `` B 8126880 '' , `` A 2003529 '' , ] , [ `` C 9925336 '' , `` C 3705674 '' , `` A 823678571 '' , `` C 3205170186 '' , ] , [ `` C 9772980 '' , `` B 8960327 '' , `` C 4185139021 '' , `` D 1226285245 '' , `` C 2523866271 '' , `` D 2940954504 '' , `` D 5083193 '' , ] ] temp_dict = { item : ind... | Python dictionary with multiple keys pointing to same list in memory efficient way |
Python | I recently added a new feature to my yolov3 implementation which is models are currently loaded directly from DarkNet cfg files for convenience , I tested the code with yolov3 configuration as well as yolov4 configuration they both work just fine except for v4 training . Shortly after I start training I get a shapes mi... | if __name__ == '__main__ ' : tr = Trainer ( ( 608 , 608 , 3 ) , '../Config/yolo4.cfg ' , '../Config/beverly_hills.txt ' , 1344 , 756 , score_threshold=0.1 , train_tf_record='../Data/TFRecords/beverly_hills_train.tfrecord ' , valid_tf_record='../Data/TFRecords/beverly_hills_test.tfrecord ' ) tr.train ( 100 , 8 , 1e-3 , ... | Shape mismatch problem in tensorflow 2.2 training using yolo4.cfg |
Python | I have the following dataset : plot dataI want to select the points in the green areas ( see graph below ) . The points in the second quadrant were easy to select but not the points in the green area in the third quadrant.This is how i selected points in the second quadrants : after this I got stuck.Considering the con... | df = pd.DataFrame ( np.random.rand ( 50,2 ) , columns=list ( 'AB ' ) ) plt.scatter ( x=df.A , y=df.B ) x = plt.axhline ( y=0.4 , c= ' k ' ) y = plt.axvline ( x=0.4 , c= ' k ' ) plt.plot ( [ 0.2 , 0.3 ] , [ 0 , 0.4 ] , c= ' k ' ) df [ ( df [ ' A ' ] < 0.4 ) & ( df [ ' B ' ] > 0.4 ) ] | Selecting points above/under lines |
Python | In a bizarre turn of events , I 've ended up in the following predicament where I 'm using the following Python code to write the assembly generated by Numba to a file : The assembly code is successfully written to the file but I ca n't figure out how to execute it . I 've tried the following : However , the linking st... | @ jit ( nopython=True , nogil=True ) def six ( ) : return 6with open ( `` six.asm '' , `` w '' ) as f : for k , v in six.inspect_asm ( ) .items ( ) : f.write ( v ) $ as -o six.o six.asm $ ld six.o -o six.bin $ chmod +x six.bin $ ./six.bin ld : warning : can not find entry symbol _start ; defaulting to 00000000004000f0s... | Executing the assembly generated by Numba |
Python | This problem originated when I tried to apply a more functional approach to problems in python . What I tried to do is simply square a list of numbers , no biggie.As it turns out , this did n't work . TypeError : pow ( ) takes no keyword argumentsConfused I checked if pow ( b=2 , a=3 ) did . It didn't.I 've checked the... | from operator import powfrom functools import partial squared = list ( map ( partial ( pow , b=2 ) , range ( 10 ) ) def pow ( a , b ) : return a ** b | Python library functions taking no keyword arguments |
Python | I am trying to adjust this DCGAN code to be able to work with 2x80 data samples.All generator layers are tf.nn.deconv2d other than h0 , which is ReLu . Generator filter sizes per level are currently : Because of the nature of my data I would like them to be initially generated as 2 x ... , i.e . for filters to be 2 x 5... | Generator : h0 : s_h16 x s_w16 : 1 x 5Generator : h1 : s_h8 x s_w8 : 1 x 10Generator : h2 : s_h4 x s_w4 : 1 x 20Generator : h3 : s_h2 x s_w2 : 1 x 40Generator : h4 : s_h x s_w : 2 x 80 ValueError : Shapes ( 64 , 1 , 40 , 64 ) and ( 64 , 2 , 40 , 64 ) are not compatible Traceback ( most recent call last ) : File `` /hom... | How to increase the size of deconv2d filters for a fixed data size ? |
Python | I have two lists , A & B , and I would like to test whether A is contained in B . By `` contained '' I mean that the elements of A appear in the exact same order within B with no other elements between them . What I 'm looking for is very similar to the behavior of A in B if they were strings . Some elements of A will ... | > > > [ 2 , 3 , 4 ] containedin [ 1 , 2 , 3 , 4 , 5 ] True > > > [ 2 , 3 , 4 ] containedin [ 1 , 1 , 2 , 2 , 3 , 3 , 4 , 4 , 5 , 5 ] False > > > [ 2 , 3 , 4 ] containedin [ 5 , 4 , 3 , 2 , 1 ] False > > > [ 2 , 2 , 2 ] containedin [ 1 , 2 , 3 , 4 , 5 ] False > > > [ 2 , 2 , 2 ] containedin [ 1 , 1 , 2 , 2 , 3 , 3 , 4 ,... | Test whether list A is contained in list B |
Python | Is there a way to color a point according to the colormap used by the contour function ? I realize that I can specify a colormap , but presumably the contour function does somescaling and/or normalization of the data ? Here 's an example : So in the plot below , the points with the highest density would be colored brow... | import numpy as npimport scipy.stats as ssdef plot_2d_probsurface ( data , resolution=20 , ax = None , xlim=None , ylim=None ) : # create a function to calcualte the density at a particular location kde = ss.gaussian_kde ( data.T ) # calculate the limits if there are no values passed in # passed in values are useful if... | Color points according to their contour color |
Python | I 'm still newbie in tensorflow so I 'm sorry if this is a naive question . I 'm trying to use the inception_V4 model pretrained on ImageNet dataset published on this site . Also , I 'm using their network as it is , I mean the one published on their site.Here is how I call the network : Since I need to retrain the Inc... | def network ( images_op , keep_prob ) : width_needed_InceptionV4Net = 342 shape = images_op.get_shape ( ) .as_list ( ) H = int ( round ( width_needed_InceptionV4Net * shape [ 1 ] / shape [ 2 ] , 2 ) ) resized_images = tf.image.resize_images ( images_op , [ width_needed_InceptionV4Net , H ] , tf.image.ResizeMethod.BILIN... | Retrain InceptionV4 's Final Layer for New Categories : local variable not initialized |
Python | So I have a function that can either work quietly or verbosely . In quiet mode it produces an output . In verbose mode it also saves intermediate calculations to a list , though doing so takes extra computation in itself . Before you ask , yes , this is an identified bottleneck for optimization , and the verbose output... | def f ( x , verbose=False ) : result = 0 verbosity = [ ] for _ in x : foo = # something quick to calculate result += foo if verbose : verbosity += # something slow to calculate based on foo return { `` result '' : result , `` verbosity '' : verbosity } # `` verbose '' changes syntax of return value , yuck ! return resu... | Pythonic way to efficiently handle variable number of return args |
Python | I need to merge two iterators . I wrote this function : This function works . But I think it 's too complicated . Is it possible to make this function easiest using Python Standard Libraries ? | def merge_no_repeat ( iter1 , iter2 , key=None ) : `` '' '' a = iter ( [ ( 2 , ' a ' ) , ( 4 , ' a ' ) , ( 6 , ' a ' ) ] ) b = iter ( [ ( 1 , ' b ' ) , ( 2 , ' b ' ) , ( 3 , ' b ' ) , ( 4 , ' b ' ) , ( 5 , ' b ' ) , ( 6 , ' b ' ) , ( 7 , ' b ' ) , ( 8 , ' b ' ) ] ) key = lambda item : item [ 0 ] fusion_no_repeat ( a , ... | Merge two sorted iterators without replace |
Python | Hello this might be a very basic question , but because I am new to programming and python and I really want to learn , am asking . I am making a program that takes input from the user , of the `` Playing Card '' Suit he has . And the program only accepts the correct suit.For example ; Diamonds , Hearts , Clubs , Spade... | if suit == `` Diamonds '' : return `` Accepted '' if suit == `` Hearts '' : return `` Accepted '' if suit == `` Clubs '' : return `` Accepted '' if suit == `` Spades '' : return `` Accepted '' else : return `` Wrong input '' | Better way , of writing a Long `` if '' statements ? |
Python | I am taking a programming class in college and one of the exercises in the problem sheet was to write this code : using only one `` for '' loop , and no `` while '' or `` if '' .The purpose of the code is to find the sum of the even and the sum ofthe odd numbers from zero to the number inputted and print it to thescree... | number = int ( input ( ) ) x = 0y = 0for n in range ( number ) : if n % 2 == 0 : x += n else : y += nprint ( x ) print ( y ) | How to sum even and odd values with one for-loop and no if-condition ? |
Python | This is my first question , and I apologize if its a bit long on the code-example side . As part of a job application I was asked to write a Bit Torrent file parser that exposed some of the fields . I did the code , and was told my code was `` not quite at the level that we require from a team lead '' . Ouch ! That 's ... | # ! /usr/bin/env python2 `` '' '' Bit Torrent Parsing Parses a Bit Torrent file . A basic parser for Bit Torrent files . Visit http : //wiki.theory.org/BitTorrentSpecification for the BitTorrent specification. `` '' '' __author__ = `` ... . '' __version__ = `` $ Revision : 1.0 $ '' __date__ = `` $ Date : 2012/10/26 11:... | Python - Is this code lacking List Comprehensions and Generators |
Python | I 'm building a project and I have run into the following problem : I have implemented several subclasses , each of them having about 250 lines of code . Semantically , they should go together in the same module and I want to import them withBut then my module file has thousands of lines , which makes maintaining its c... | from mymodule import SubclassA , SubclassB from subclassa import SubclassAfrom subclassb import SubclassB | Python : Maintaining code in modules |
Python | I have used some example code that uses str ( ) instead of my normal habit of `` to denote an empty string . Is there some advantage for using str ( ) ? Eg : It does seem to be slower . | # ... .. d = dict ( ) # ... .. # ... .. if v is None : d [ c.name ] = str ( ) else : d [ c.name ] = v $ python -m timeit `` ' . '.join ( str ( n ) + '' for n in range ( 100 ) ) '' 100000 loops , best of 3 : 12.9 usec per loop $ python -m timeit `` ' . '.join ( str ( n ) +str ( ) for n in range ( 100 ) ) '' 100000 loops... | Python str ( ) vs. `` - which is preferred |
Python | My first question , please be gentle . I searched but could not find an answer here or elsewhere.Note that this question does not apply to unpacking of arguments like *args.In the python 3.3 documentation for os.removexattr the following is stated : Note that the third argument is a star : *I assumed that this means ``... | os.removexattr ( path , attribute , * , follow_symlinks=True ) Removes the extended filesystem attribute attribute from path . attribute should be bytes or str . If it is a string , it is encoded with the filesystem encoding . This function can support specifying a file descriptor and not following symlinks . import os... | Python documentation for os.removexattr -- what does the '* ' ( star ) argument mean ? |
Python | I have studied generators feature and i think i got it but i would like to understand where i could apply it in my code.I have in mind the following example i read in `` Python essential reference '' book : Do you have any other effective example where generators are the best tool for the job like tail -f ? How often d... | # tail -f def tail ( f ) : f.seek ( 0,2 ) while True : line = f.readline ( ) if not line : time.sleep ( 0.1 ) continue yield line | Where do you use generators feature in your python code ? |
Python | I am dealing with sub-surface measurements from a borehole where each measurement type covers a different range of depths . Depth is being used as the index in this case . I need to find the depth ( index ) of the first and/or last occurrence of data ( non-NaN value ) for each measurement type.Getting the depth ( index... | df = pd.DataFrame ( [ [ 500 , np.NaN , np.NaN , 25 ] , [ 501 , np.NaN , np.NaN , 27 ] , [ 502 , np.NaN , 33 , 24 ] , [ 503 , 4 , 32 , 18 ] , [ 504 , 12 , 45 , 5 ] , [ 505 , 8 , 38 , np.NaN ] ] ) df.columns = [ 'Depth ' , 'x1 ' , 'x2 ' , 'x3 ' ] df.set_index ( 'Depth ' ) | Find index of the first and/or last value in a column that is not NaN |
Python | I 've been trying to understand the section on memoization in Chapter 8 of Real World OCaml ( RWO ) . I was n't getting it , so I decided to translate the OCaml code into Python . This exercise turned out to be useful , because ( 1 ) I did finally understand what RWO was saying , and ( 2 ) I wrote some faster Python co... | from time import timedef unfib ( n ) : `` 'Unmemoized Fibonacci '' ' if n < = 1 : return 1 else : return unfib ( n-1 ) + unfib ( n-2 ) def memoize ( f ) : `` ' A simple memoization function '' ' hash = { } def memo_f ( x ) : if not hash.has_key ( x ) : res = f ( x ) hash [ x ] = res return hash [ x ] return memo_f # Si... | Why does Python 's decorator syntax give faster memoization code than plain wrapper syntax ? |
Python | I 'm trying to debug some Cython code with gdb that is wrapping C++ code to be called from Python . I followed the instructions in the documentation but I 'm getting some errors while debugging that are unrelated to my code . Example : I 'm also getting this one sometimes ( usually after the first one ) : To debug the ... | ( gdb ) cy print some_variablePython Exception < type 'exceptions.AttributeError ' > 'PyDictObjectPtr ' object has no attribute 'items ' : Error occurred in Python : 'PyDictObjectPtr ' object has no attribute 'items ' Python Exception < class 'gdb.error ' > There is no member named ob_sval . : Error occurred in Python ... | Error printing variables while debugging Cython |
Python | I currently have a Fortran function that I want to optimize using SciPy wrapping it using Ctypes . Is this possible ? Perhaps I 've done something wrong in my implementation . For example , assume I have : cost.f90that I compile with : and then try to find a ( local ) minimum with : cost.pyI expect a local minimum f2 (... | module cost_fn use iso_c_binding , only : c_float implicit nonecontains function sin_2_cos ( x , y ) bind ( c ) real ( c_float ) : : x , y , sin_2_cos sin_2_cos = sin ( x ) **2 * cos ( y ) end function sin_2_cosend module cost_fn gfortran -fPIC -shared -g -o cost.so cost.f90 # ! /usr/bin/env pythonfrom ctypes import *i... | Wrong result from scipy.optimize.minimize used on Fortran function using ctypes |
Python | I need to deal with a two objects of a class in a way that will return a third object of the same class , and I am trying to determine whether it is better to do this as an independent function that receives two objects and returns the third or as a method which would take one other object and return the third.For a si... | from collections import namedtupleclass Point ( namedtuple ( 'Point ' , ' x y ' ) ) : __slots__ = ( ) # Attached to class def midpoint ( self , otherpoint ) : mx = ( self.x + otherpoint.x ) / 2.0 my = ( self.y + otherpoint.y ) / 2.0 return Point ( mx , my ) a = Point ( 1.0 , 2.0 ) b = Point ( 2.0 , 3.0 ) print a.midpoi... | Independent function or method |
Python | I 'd like to manipulate a list of lambda functions . This list of lambda functions all contain the same function within it , which I 'd like to manipulate so that the function within it has an additional argumentSee below for my exampleIs it possible to change this list of functions to the following without having to r... | def base_function ( *args ) : for arg in args : print arglist_of_functions = [ lambda new_arg : base_function ( new_arg , 'arg_1 ' ) , lambda new_arg : base_function ( new_arg , 'arg_2 ' ) , lambda new_arg : base_function ( new_arg , 'arg_3 ' ) ] list_of_functions = [ lambda new_arg : base_function ( new_arg , 'arg_1 '... | How to manipulate a function within a lambda with python ? |
Python | After answering this question , there are some interesting but confused findings I met in tensorflow 2.0 . The gradients of logits looks incorrect to me . Let 's say we have logits and labels here . Since logits is already a prob distribution , so I set from_logits=False in the loss function . I thought tensorflow will... | logits = tf.Variable ( [ [ 0.8 , 0.1 , 0.1 ] ] , dtype=tf.float32 ) labels = tf.constant ( [ [ 1 , 0 , 0 ] ] , dtype=tf.float32 ) with tf.GradientTape ( persistent=True ) as tape : loss = tf.reduce_sum ( tf.keras.losses.categorical_crossentropy ( labels , logits , from_logits=False ) ) grads = tape.gradient ( loss , lo... | Why are gradients incorrect for categorical crossentropy ? |
Python | I have a long string that I build with a bunch of calculated values . I then write this string to a file.I have it formatted like : I would like to add comment to what each value represents but commenting with # or `` ' does n't work . Here 's an example : I figured out it does n't work : ) so I 'm wondering what code ... | string = str ( a/b ) +\ '\t'+str ( c ) \ '\t'+str ( d ) \ ... '\n ' string = str ( a/b ) +\ # this value is something '\t'+str ( c ) \ # this value is another thing '\t'+str ( d ) \ # and this one too ... '\n ' | Is line wrap comment possible in Python ? |
Python | I have a bunch of code that looks similar to this : Is there a nicer way to write out this logic ? This makes my code really painful to read . I thought try..finally would work , but I assumed wrong | try : auth = page.ItemAttributes.Author except : try : auth = page.ItemAttributes.Creator except : auth = None | Is there a nice way to handle exceptions in Python ? |
Python | It is stated that strings are immutable objects , and when we make changes in that variable it actually creates a new string object.So I wanted to test this phenomenon with this piece of code : And I got the following IDs : So , if each string is different from each other , then why do the strings 2-8 and 9-11 have the... | result_str = `` '' print ( `` string 1 ( unedited ) : '' , id ( result_str ) ) for a in range ( 1,11 ) : result_str = result_str + str ( a ) print ( f '' string { a+1 } : '' , id ( result_str ) ) string 1 ( unedited ) : 2386354993840string 2 : 2386357170336string 3 : 2386357170336string 4 : 2386357170336string 5 : 2386... | Why do different strings have the same ID in Python ? |
Python | right now I 'm using closures to generate functions like in this simplified example : These generated functions are then passed to the init-method of a custom class which stores them as instance attributes . The disadvantage is that that makes the class-instances unpickleable . So I 'm wondering if there is a way to cr... | def constant_function ( constant ) : def dummyfunction ( t ) : return constant return dummyfunction | Generate functions without closures in python |
Python | I 'm a few months into learning python.After going through pyramid tutorials I 'm having trouble understanding a line in the init.pyI 'm lost about settings=settings in the configurator argument.What is this telling python ? | from pyramid.config import Configuratorfrom sqlalchemy import engine_from_configfrom .models import ( DBSession , Base , ) def main ( global_config , **settings ) : `` '' '' This function returns a Pyramid WSGI application. `` '' '' engine = engine_from_config ( settings , 'sqlalchemy . ' ) DBSession.configure ( bind=e... | python : constructor argument notation |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.