lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | I 'm trying to code the following variant of the Bump function , applied component-wise : ,where σ is trainable ; but it 's not working ( errors reported below ) .My attempt : Here 's what I 've coded up so far ( if it helps ) . Suppose I have two functions ( for example ) : Error Report : ... Moreover , it does not se... | def f_True ( x ) : # Compute Bump Function bump_value = 1-tf.math.pow ( x,2 ) bump_value = -tf.math.pow ( bump_value , -1 ) bump_value = tf.math.exp ( bump_value ) return ( bump_value ) def f_False ( x ) : # Compute Bump Function x_out = 0*x return ( x_out ) class trainable_bump_layer ( tf.keras.layers.Layer ) : def __... | Implementing a trainable generalized Bump function layer in Keras/Tensorflow |
Python | I can use a custom class to extend Python 's string formatting : I can then use this class to format arguments which are passed to a strings format method : While this works it seems awkward that the custom format specifier is in the base string , but the arguments passed to it 's format method are actually responsible... | class CaseStr ( str ) : def __format__ ( self , fmt ) : if fmt.endswith ( ' u ' ) : s = self.upper ( ) fmt = fmt [ : -1 ] elif fmt.endswith ( ' l ' ) : s = self.lower ( ) fmt = fmt [ : -1 ] else : s = str ( self ) return s.__format__ ( fmt ) unformatted_string = 'uppercase : { s : u } , lowercase : { s : l } 'print unf... | How to provide custom formatting from format string ? |
Python | I have a variable like If I have to import osI can write then I get no errorBut how can I import k ( k is actually os ) I tried then I got error there is no module.I tried naming k = 'os ' instead of k = os.Still I am getting the same errorUpdate : Actually I have to import DATABASES variable from settings file in the ... | k = os import os import k from os.environ [ 'DJANGO_SETTINGS_MODULE ' ] import DATABASES | using variable in import command |
Python | I am new to Python . I come from C++.In some code reviews , I 've had several peers wanting me to move things from init and del to a start and stop method . Most of them time , this goes against the RAII that was beaten into my head with decades of C++.https : //en.wikipedia.org/wiki/Resource_acquisition_is_initializat... | class Poop : def __init__ : # Get some Windows Resource def __del__ : # Release some Windows Resourcedef foo ( ) : poop = Poop ( ) raise Exception ( `` Poop happens '' ) | Resource Aquisition Is Initialization , in Python |
Python | I have created a Flask app and start to build my project , but when I use breakpoint in any file for debugging , vscode will automatically stop at this line HTTPServer.serve_forever ( self ) in flask default module.Thing is annoying since it will jump to this line and ignore my original breakpoint , make me hard to deb... | { `` name '' : `` Python : Custom Flask '' , `` type '' : `` python '' , `` request '' : `` launch '' , `` program '' : `` $ { workspaceFolder } /venv/bin/activate '' , `` module '' : `` flask '' , `` env '' : { `` ENV '' : `` .local '' } , `` args '' : [ `` run '' , ] } def serve_forever ( self ) : self.shutdown_signa... | Running flask in VSCode cause HTTPServer.serve_forever ( self ) breakpoint everytime |
Python | I have a dataframe like this : My goal is to remove the duplicate rows , but the order of source and target columns are not important . In fact , the order of two columns are not important and they should be removed . In this case , the expected result would beIs there any way to this without loops ? | source target weight 1 2 5 2 1 5 1 2 5 1 2 7 3 1 6 1 1 6 1 3 6 source target weight 1 2 5 1 2 7 3 1 6 1 1 6 | how remove rows in a dataframe that the order of values are not important |
Python | For instance , there are os.path.walk , os.walk and assuming another md.walk , and assume os is imported but md is not . I desire a function likewhile can return os.path.walk , os.walk and md.walk.Or if it 's difficult to know there is a md.walk , how to get the imported os.path.walk and os.walk ? | whereis ( 'walk ' ) | In Python , given a function name , how to get all the modules containing the function ? |
Python | I 'm using the code below for segmenting the articles from an image of newspaper.for instancethe input image isand the output image is : There are three problems : the output rectangles are n't complete in all cases.Images also are segmented inside articles as part of articles . But what I need is to segment only the t... | def segmenter ( image_received ) : # Process 1 : Lines Detection img = image_received gray = cv2.cvtColor ( img , cv2.COLOR_BGR2GRAY ) # convert to binary gray image edges = cv2.Canny ( gray , 75 , 150 ) # determine contours lines = cv2.HoughLinesP ( edges , 0.017 , np.pi / 180 , 60 , minLineLength=100 , maxLineGap=0.1... | use python open-cv for segmenting newspaper article |
Python | I am new to Python and I am currently using Python 2 . I have some source files that each consists of a huge amount of data ( approx . 19 million lines ) . It looks like the following : My task is to search the 3rd column of each file for some target words and every time a target word is found in the corpus the 10 word... | apple \t N \t applen & aposgarden \t N \t gardenb\ta\md great \t Adj \t greatnice \t Adj \t ( unknown ) etc def get_target_to_dict ( file ) : targets_dict = { } with open ( file ) as f : for line in f : targets_dict [ line.strip ( ) ] = { } return targets_dicttargets_dict = get_target_to_dict ( 'targets_uniq.txt ' ) # ... | python - increase efficiency of large-file search by readlines ( size ) |
Python | I have an object obj and a number of functions that each change the values of the attributes of obj . I want my input to be something likeThis should be passed to a function closure ( ) that computes all possible applictions of the functions above , meaning func1 ( func2 ( obj ) ) , func3 ( func1 ( func1 ( obj ) ) ) et... | def func1 ( obj ) : # ... def func2 ( obj ) : # ... def func3 ( obj ) : # ... obj = MyObject ( ) obj.attr=22 print closure ( obj ) [ 22 , 64 , 21 , 104 ] # first path to 104 through , func1 ( obj ) , func1 ( func1 ( obj ) ) , func1 ( func1 ( func3 ( obj ) ) ) [ 22 , 73 , 104 ] # second path to 104 through , func3 ( obj... | Computing the `` closure '' of the attributes of an object given functions that change the attributes |
Python | Say I got some string with format % H : % M : % S , e.g . 04:35:45 . I want to convert them to datetime.datetime object , year/month/day are the same as datetime.datetime.now ( ) .I tried This wo n't work since year/month/day are read-only properties . So what 's the best solution for this ? | now = datetime.now ( ) datetime_obj = datetime.strptime ( time_string , `` % H : % M : % S '' ) datetime_obj.year = now.yeardatetime_obj.month = now.monthdatetime_obj.day = now.day | What 's the best way to create datetime from `` % H : % M : % S '' |
Python | ab.pyOptions.pyI am not sure what is going on for env = dict ( ( var , os.getenv ( var , 0 ) ) for var in vars_of_interest ) as I am fairly new to pythonis env a function in python in Options.py ? what is dict ( ) ? Is var the variable from int ( Options.env [ 'GG_DEBUG_ELMO ' ] ) ? | from ddr import OptionsdebugElmo = int ( Options.env [ 'GG_DEBUG_ELMO ' ] ) postdevElmo = int ( Options.env [ 'GG_POST_DEV_ELMO ' ] ) vars_of_interest = ( 'AA_PYTHON ' , 'GG_POST_DEV_ELMO ' , 'GG_DEBUG_ELMO ' , ) env = dict ( ( var , os.getenv ( var , 0 ) ) for var in vars_of_interest ) | Understanding python code |
Python | I 've currently skimming through the Python-bindings for Redland and have n't found a clean way to do transactions on the storage engine via it . I found some model-transactions within the low-level Redland module : Do these also translate down to the storage layer ? Thanks : - ) | import RDF , Redlandstorage = RDF.Storage ( ... ) model = RDF.Model ( storage ) Redland.librdf_model_transaction_start ( model._model ) try : # Do something Redland.librdf_model_transaction_commit ( model._model ) model.sync ( ) except : Redland.librdf_model_transaction_rollback ( model._model ) | Storage transactions in Redland 's Python bindings ? |
Python | Yields : One would expect that the A list would be the same as the B list , this is not the case , both append statements were applied to A [ 0 ] and A [ 1 ] .Why ? | A = [ [ ] ] *2A [ 0 ] .append ( `` a '' ) A [ 1 ] .append ( `` b '' ) B = [ [ ] , [ ] ] B [ 0 ] .append ( `` a '' ) B [ 1 ] .append ( `` b '' ) print `` A : `` + str ( A ) print `` B : `` + str ( B ) A : [ [ ' a ' , ' b ' ] , [ ' a ' , ' b ' ] ] B : [ [ ' a ' ] , [ ' b ' ] ] | What does [ [ ] ] *2 do in python ? |
Python | I have a data frame that contains a group ID , two distance measures ( longitude/latitude type measure ) , and a value . For a given set of distances , I want to find the number of other groups nearby , and the average values of those other groups nearby . I 've written the following code , but it is so inefficient tha... | distances = [ 1,2 ] df = pd.DataFrame ( np.random.randint ( 0,100 , size= ( 100 , 4 ) ) , columns= [ 'Group ' , 'Dist1 ' , 'Dist2 ' , 'Value ' ] ) # get one row per group , with the two distances for each rowdf_groups = df.groupby ( 'Group ' ) [ [ 'Dist1 ' , 'Dist2 ' ] ] .mean ( ) # create KDTree for quick searchingtre... | Speeding up calculation of nearby groups ? |
Python | I 'm trying to figure out how to output the frequency of my First_Name column in my data frame ; per row . So far I was successful in doing so but I would also like to know how to count both NaN values and Non-NaN values per row.Below is a data frame with two columns : First_Name and Favorite_Color.I wanted to see if I... | import pandas as pdd = { 'First_Name ' : [ `` Jared '' , `` Lily '' , `` Sarah '' , `` Bill '' , `` Bill '' , `` Alfred '' , None ] , 'Favorite_Color ' : [ `` Blue '' , `` Blue '' , `` Pink '' , `` Red '' , `` Yellow '' , `` Orange '' , `` Red '' ] } df = pd.DataFrame ( data=d ) df [ 'countNames ' ] = df.groupby ( 'Fir... | Count NaN per row with Pandas |
Python | I want to rename the node1 and node 2 in the data1 according in increasing order.Nodes are 2 3 6 7 28 so they become 1 2 3 4 5 respectively.So the dataframe becomes-The data looked like this beforebut now looks like this | data1 = { 'node1 ' : [ 2,2,3,6 ] , 'node2 ' : [ 6,7,7,28 ] , 'weight ' : [ 1,2,1,1 ] , } df1 = pd.DataFrame ( data1 , columns = [ 'node1 ' , 'node2 ' , 'weight ' ] ) data1 = { 'node1 ' : [ 1,1,2,3 ] , 'node2 ' : [ 3,4,4,5 ] , 'weight ' : [ 1,2,1,1 ] , } df1 = pd.DataFrame ( data1 , columns = [ 'node1 ' , 'node2 ' , 'we... | Reordering nodes in increasing order in pandas dataframe |
Python | Is there any elegant way of splitting a list/dict into two lists/dicts in python , taking in some arbitrary splitter function ? I could easily have two list comprehensions , or two selects , but it seems to me there should be some better way of doing it that avoids iterating over every element twice.I could do it easil... | # given dict cows , mapping cow names to weight # fast solutionfatcows = { } thincows = { } for name , weight in cows : if weight < 100 : thincows [ name ] = weight else : fatcows [ name ] = weight # double-list-comprehension solution would befatcows = { name : weight for name , weight in cows.items ( ) if weight > 100... | elegantly splitting a list ( or dict ) into two via some arbitrary function in python |
Python | I am trying to use Foreman / Honcho to manage my Procfile-based Django application . When I start the app view the normal python manage.py runserver , everything works fine . However , when I start the app via honcho start or foreman start web , I am receiving this error : This is with attempting to install the django-... | 11:59:31 system | web.1 started ( pid=27959 ) 11:59:31 web.1 | [ 2016-04-26 11:59:31 -0700 ] [ 27959 ] [ INFO ] Starting gunicorn 19.4.511:59:31 web.1 | [ 2016-04-26 11:59:31 -0700 ] [ 27959 ] [ INFO ] Listening at : http : //0.0.0.0:5000 ( 27959 ) 11:59:31 web.1 | [ 2016-04-26 11:59:31 -0700 ] [ 27959 ] [ INFO ] Using... | Django - Foreman can not find installed modeles |
Python | For writing “ piecewise functions ” in Python , I 'd normally use if ( in either the control-flow or ternary-operator form ) .Now , with NumPy , the mantra is to avoid working on single values in favour of vectorisation , for performance . So I reckon something like this would be preferred : As Leon remarks , the follo... | def spam ( x ) : return x+1 if x > =0 else 1/ ( 1-x ) def eggs ( x ) : y = np.zeros_like ( x ) positive = x > =0 y [ positive ] = x+1 y [ np.logical_not ( positive ) ] = 1/ ( 1-x ) return y | How to write conditional code that 's compatible with both plain Python values and NumPy arrays ? |
Python | After installing Yosemite , I had to upgrade numpy , PyOpenGL , etc.Now , a previously-working program is giving me the following stack trace : It looks like PyOpenGL wants my array to be contiguous . Looking at the source in numpy_formathandler.pyx in PyOpenGL : And PyArray_ISCARRAY ( arr ) `` Evaluates true if the da... | file `` latebind.pyx '' , line 44 , in OpenGL_accelerate.latebind.Curry.__call__ ( src/latebind.c:1201 ) File `` /opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/OpenGL/GL/VERSION/GL_1_5.py '' , line 89 , in glBufferData return baseOperation ( target , size , data , usage ) File `... | OpenGL says `` from_param received a non-contiguous array '' |
Python | I have a `` seed '' GeoDataFrame ( GDF ) ( RED ) which contains a 0.5 arc minutes global grid ( ( 180*2 ) * ( 360*2 ) = 259200 ) . Each cell contains an absolute population estimate . In addition , I have a `` leech '' GDF ( GREEN ) with roughly 8250 adjoining non-regular shapes of various sizes ( watersheds ) .I wrote... | import geopandas as gpdimport timefrom datetime import datetimefrom shapely.geometry import Polygon # ============================================================================= # Geometries for testing # =============================================================================polys1 = gpd.GeoSeries ( [ Polygon (... | How can I improve the performance of my script ? |
Python | Suppose I have dataframe df1 which includes two columns - A & B . Value of A represents the lower range and value of B represents the upper range.I 've another dataframe which includes two columns - C & D containing a different range of numbers.Now I want to list all the pairs from df2 that fall under the groups ( betw... | A B10.5 20.530.5 40.550.5 60.5 C D12.34 15.9013.68 19.1333.5 35.6035.12 38.7650.6 59.1 Key Values ( 10.5 , 20.5 ) [ ( 12.34 , 15.90 ) , ( 13.68 , 19.13 ) ] ( 30.5 , 40.5 ) [ ( 33.5 , 35.60 ) , ( 35.12 , 38.76 ) ] ( 50.5 , 60.5 ) [ ( 50.6 , 59.1 ) ] | How to list all the pairs of numbers which fall under a group of range ? |
Python | Let 's say I have two classes in two files : and Plus a main fileObviously , I have a circular dependency . How to deal with this kind of behaviour without losing the type hint stuff ? | from Son import Sonclass Mother : def __init__ ( self ) : self.sons = [ ] def add_son ( self , son : Son ) : self.sons.append ( son ) from Mother import Motherclass Son : def __init__ ( self , mother : Mother ) : self.mother = mother mother.add_son ( self ) from Mother import Motherfrom Son import Sonif __name__ == '__... | Circular imports in classes |
Python | I only want to show Chip , but I get both Chip AND Dale.It does n't seem to matter which 32 bit character I put in , tkinter seems to duplicate them - it 's not just chipmunks.I 'm thinking that I may have to render them to png and then place them as images , but that seems a bit ... heavy-handed.Any other solutions ? ... | import tkinter as tk # Python 3.8.3class Application ( tk.Frame ) : def __init__ ( self , master=None ) : self.canvas = None self.quit_button = None tk.Frame.__init__ ( self , master ) self.grid ( ) self.create_widgets ( ) def create_widgets ( self ) : self.canvas = tk.Canvas ( self , width=500 , height=420 , bg='yello... | Tkinter and 32-bit Unicode duplicating – any fix ? |
Python | In querying an API that has a paginated list of unknown length I found myself doing essentiallythe split between work and fetch_one makes it very easy to test , but the signalling via instance variables means I ca n't have more than one work going on at the same time , which sucks . I came up with what I think is a cle... | def fetch_one ( self , n ) : data = json.load ( urlopen ( url_template % n ) ) if data is None : self.finished = True return for row in data : if row_is_weird ( row ) : self.finished = True return yield prepare ( row ) def work ( self ) : n = 1 self.finished = False while not self.finished : consume ( self.fetch_one ( ... | What do you call an iterator with two different `` done '' states ? |
Python | I am writing a Python program to animate a tangent line along a 3D curve . However , my tangent line is not moving . I think the problem is line.set_data ( np.array ( Tangent [ : ,0 ] ) .T , np.array ( Tangent [ : ,1 ] ) .T ) in animate ( i ) but I ca n't figure out . Any help will be appreciated . The following is the... | from mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.animation import FuncAnimationimport matplotlibmatplotlib.use ( 'tkagg ' ) plt.style.use ( 'seaborn-pastel ' ) fig = plt.figure ( ) ax = plt.axes ( projection='3d ' ) ax = plt.axes ( projection='3d ' ) # Data for a three-di... | Animation of tangent line of a 3D curve |
Python | I am implementing a really lightweight Web Project , which has just one page , showing data in a diagram . I use Django as a Webserver and d3.js as plotting routine for this diagram . As you can imagine , there are just a few simple time series which have to be responded by Django server , so I was wondering if I simpl... | X = np.array ( [ 123,23,1,32,123,1 ] ) @ csrf_exemptdef getGraph ( request ) : global X return HttpResponse ( json.dumps ( X ) ) | django vars in ram |
Python | So I have some god forsaken legacy code that uses the reserved word property , um wrong . In a base class that gets inherited they have basically implemented.Which runs without error . If you add another method below that you get , Which throws : Because you know you have overwritten property in the local namespace.You... | class TestClass ( object ) : def __init__ ( self , property ) : self._property = property @ property def property ( self ) : return self._propertytest = TestClass ( 'test property ' ) print ( test.property ) class TestClass2 ( object ) : def __init__ ( self , property ) : self._property = property @ property def proper... | Misuse of 'property ' reserved word |
Python | I am trying to hide some python warnings when knitting an Rmd file . The usual chunk setup `` warning=F , message=F '' does n't seem to work for python chunks.Example of Rmd file with a python chunk that , purposefully , generates warnings : | -- -title : `` **warnings test** '' output : pdf_document -- - `` ` { python , echo=F , warning=F , message=F } import pandas as pdd = { 'col1 ' : [ 1 , 1 , 2 , 2 ] , 'col2 ' : [ 0 , 0 , 1 , 1 ] } df = pd.DataFrame ( data=d ) df [ df.col1==1 ] [ 'col2 ' ] =2 `` ` | Suppress warnings when using a python chunk inside an Rmd file |
Python | df : What I 'm trying to do : I am trying to run the code below on each element ( word ) in df col1 on each corresponding element in each of the sublists in col2 , and put the scores in a new column.So for the first row in col1 , run the get_top_matches function on this : What the new column should look like : I do n't... | col1 [ 'aa ' , 'bb ' , 'cc ' , 'dd ' ] [ 'this ' , 'is ' , ' a ' , 'list ' , ' 2 ' ] [ 'this ' , 'list ' , ' 3 ' ] col2 [ [ 'ee ' , 'ff ' , 'gg ' , 'hh ' ] , [ 'qq ' , 'ww ' , 'ee ' , 'rr ' ] ] [ [ 'list ' , ' a ' , 'not ' , ' 1 ' ] , [ 'not ' , 'is ' , 'this ' , ' 2 ' ] ] [ [ 'this ' , 'is ' , 'list ' , 'not ' ] , [ '... | Run a function for each element in two lists in Pandas Dataframe Columns |
Python | I am trying to get the highest version of a string in Python . I was trying to sort the list but that of course doesnt work as easily as Python will sort the string representation.For that I am trying to work with regex but it somehow doesnt match.The Strings look like this : My Regex looks like this.I was thinking abo... | topic_v10_ext2topic_v20_ext2topic_v2_ext2topic_v5_ext2topic_v7_ext2 version_no = re.search ( `` ( ? : _v ( [ 0-9 ] + ) ) ? `` , v.name ) | Get the highest String Version number in Python |
Python | I 'm working with MongoDB on my current project and a little confused about the proper way to build support for concurrent modifications.I have an array of objects . When a request comes in , I want to inspect the last element in that array and make a conditional decision on how to respond . My code looks something lik... | # Find the last object ID in the array.last_element_id = str ( document [ 'objects ' ] [ -1 ] ) if last_element_id ! = the_element_id_the_request_is_responding_to : db.documents.insert ( { ... } ) else : # Append the response to the end of the array . document [ 'objects ' ] .append ( new_element_id ) db.documents.save... | MongoDB Atomicity Concerns -- Modifying a document in memory |
Python | A game engine provides me with a Player class with a steamid property ( coming from C++ , this is just a basic example on what it would look like in Python ) : I then proceed to subclass this class while adding a gold attribute : Now I need to store the player 's gold to a database with the player 's steamid as a prima... | # game_engine.pyclass Player : def __init__ ( self , steamid ) : self.__steamid = steamid @ property def steamid ( self ) : return self.__steamid # my_plugin.pyclass MyPlayer ( game_engine.Player , Base ) : gold = Column ( Integer ) from sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy.ext.hybrid impor... | Use base class 's property/attribute as a table column ? |
Python | Currently I have created a color map based on the distance of the nodes in the network to a specific target . The one thing I am not being able to do is a color bar . I would like the color bar to show me how much time the color indicates.The time data is in data [ 'time ' ] .Each color will indicate how long it will t... | import networkx as nximport matplotlib.pyplot as pltimport osmnx as oximport pandas as pdfrom shapely.wkt import loads as load_wktimport numpy as npimport matplotlib.cm as cmox.config ( log_console=True , use_cache=True ) place = { 'city ' : 'Lisbon ' , 'country ' : 'Portugal ' } G = ox.graph_from_place ( place , netwo... | How to create a color bar in an osmnx plot |
Python | I am building an encryption program which produces a massive integer.It looks something like this : when i do it takes over 28 minutes.Is there any possible way to convert an integer like this quicker that using the built in str ( ) function ? the reason i need it to be a string is because of this function here : | a = plaintextOrd**bigNumber a = str ( a ) def divideStringIntoParts ( parts , string ) : parts = int ( parts ) a = len ( string ) //parts new = [ ] firstTime = True secondTime = True for i in range ( parts ) : if firstTime : new.append ( string [ : a ] ) firstTime = False elif secondTime : new.append ( string [ a : a+a... | Is it possible to convert a really large int to a string quickly in python |
Python | So , I have an iterable of 3-tuples , generated lazily . I 'm trying to figure out how to turn this into 3 iterables , consisting of the first , second , and third elements of the tuples , respectively . However , I wish this to be done lazily.So , for example , I wish [ ( 1 , 2 , 3 ) , ( 4 , 5 , 6 ) , ( 7 , 8 , 9 ) ] ... | def transpose ( iterable_of_three_tuples ) : teed = itertools.tee ( iterable_of_three_tuples , 3 ) return map ( lambda e : e [ 0 ] , teed [ 0 ] ) , map ( lambda e : e [ 1 ] , teed [ 1 ] ) , map ( lambda e : e [ 2 ] , teed [ 2 ] ) | Lazily transpose a list in Python |
Python | Using the with statement , we can enter many context handlers using only one level of indentation/nesting : But this does n't seem to work : How can we enter n context managers without having to manually write out each one ? | > > > from contextlib import contextmanager > > > @ contextmanager ... def frobnicate ( n ) : ... print ( 'frobbing { } '.format ( n ) ) ... yield ... > > > frob1 = frobnicate ( 1 ) > > > frob2 = frobnicate ( 2 ) > > > with frob1 , frob2 : ... pass ... frobbing 1frobbing 2 > > > frobs = [ frobnicate ( 1 ) , frobnicate ... | How to __enter__ n context managers ? |
Python | I have written a script in python that uses sympy to compute a couple of vector/matrix formulas . However , when I try to convert those to functions that I can evaluate with sympy.lambdify , I get a SyntaxError : EOL while scanning string literalHere 's some code with the same error , so that you can see what I mean . ... | import sympyx = sympy.MatrixSymbol ( ' x',3,1 ) f = sympy.lambdify ( x , x.T*x ) | Converting expression involving tranpose of vector to numerical function with lambdify |
Python | I have a data frame like this : I want to create a data frame from above df in such a way that , if col1 values are not consecutive , it will create another row with the next col1 value and col2 value will be the just the above value.the data frame I am looking for should beI could do it using a simple for loop , But i... | dfcol1 col2 1 A 3 B 6 A 10 C dfcol1 col2 1 A 2 A 3 B 4 B 5 B 6 A 7 A 8 A 9 A 10 C | Fill rows with consecutive values and above rows using pandas |
Python | I know the simple way to search would be to have a list containing the strings , and just do if string in list , but it gets slow , and I 've heard dictionary keys practically have no slowdown with large sets due to the fact they 're not ordered.However , I do n't need any extra information relating to the items , so i... | import time , randomtotalRange = 100000searchFor = 5000 # Create a list of 10 million characterssearchableList = [ ] for i in range ( totalRange ) : searchableList.append ( random.randint ( 0 , totalRange ) ) # Create dictonary with keys set to 'None'searchableDict = { } for i in searchableList : searchableDict [ i ] =... | What 's the most efficient way to search a list millions of times ? |
Python | I 'm coding a little script that gets metadata from a sound file and creates a string with the desired values . I know I 'm doing something wrong but I ai n't sure why , but it 's probably the way I am iterating the if 's . When I run the code : I get the desired result or an error , randomly : RESULT : ERROR : | import os , mutagenXPATH= `` /home/xavier/Code/autotube/tree/def '' DPATH= '' /home/xavier/Code/autotube/tree/down '' def get_meta ( ) : for dirpath , directories , files in os.walk ( XPATH ) : for sound_file in files : if sound_file.endswith ( '.flac ' ) : from mutagen.flac import FLAC metadata = mutagen.flac.Open ( o... | Understanding why this python code works randomly |
Python | SimpleCookie is apparently a generic type and thus the following code ( test.py ) gives an error when checked with mypy : test.py:3 : error : Need type annotation for 'cookie'Now if I change test.py line 3 to : I get the following error : test.py:3 : error : Missing type parameters for generic type `` SimpleCookie '' S... | from http.cookies import SimpleCookiecookie = SimpleCookie ( ) cookie : SimpleCookie = SimpleCookie ( ) from http.cookies import Morsel , SimpleCookiecookie : SimpleCookie [ str , Morsel ] = SimpleCookie ( ) cookie : SimpleCookie [ str ] = SimpleCookie ( ) | SimpleCookie generic type |
Python | I have a DataFrame looks like below : while the real data I 'm using has hundreds of columns , I want to manipulate these columns using different functions like min , max as well as self-defined function like : Instead of wirting many lines , I want to have a function like : Is this possible in Python ( my guess is 'ye... | df = { 'col_1 ' : [ 1,2,3,4,5,6,7,8,9,10 ] , 'col_2 ' : [ 1,2,3,4,5,6,7,8,9,10 ] , 'col_3 ' : [ ' A ' , ' A ' , ' A ' , ' A ' , ' A ' , ' B ' , ' B ' , ' B ' , ' B ' , ' B ' ] } df = pd.DataFrame ( df ) def dist ( x ) : return max ( x ) - min ( x ) def HHI ( x ) : ss = sum ( [ s**2 for s in x ] ) return ss def myfunc (... | define a function use other function names as parameter |
Python | I have problem for Running/deploying custom script with shub-image.setup.pyin this file I have who are my differents filse that I want sentI deploy with this command Before I used shub-image version 0.2.5 et shub version 2.5.1 and I it worked well . But now I use shub version 2.7.0 ( shub image is now part of shub 2.70... | from setuptools import setup , find_packagessetup ( name = 'EU-Crawler ' , version = ' 1.0 ' , packages = find_packages ( ) , scripts = [ 'bin/launcher.py ' , 'bin/DE_WEB_launcher.py ' , 'bin/ES_WEB_launcher.py ' , 'bin/FR_WEB_launcher.py ' , 'bin/IT_WEB_launcher.py ' , 'bin/NL_WEB_launcher.py ' , 'bin/DE_MOBILE_launch... | Not able Running/deploying custom script with shub-image |
Python | Is there a reliable , automatic way ( such as a command-line utility ) to check if two Python files are equivalent modulo whitespace , semicolons , backslash continuations , comments , etc. ? In other words , that they are identical to the interpreter ? For example , this : should be considered equivalent to this : | import syssys.stdout.write ( 'foo\n ' ) sys.stdout.write ( 'bar\n ' ) import syssys.stdout.\ write ( 'foo\n ' ) ; sys.stdout.\ write ( 'bar\n ' ) # This is an unnecessary comment | comparing Python code for equivalence |
Python | I am experiencing different behaviour on the same code using the python console and a python script.The code is as follows : When running the code in the python console , the output is a new frame that contains the google main page.When running the code as a script , the result is a void frame . It closes very fast but... | import gtkimport webkitwin = gtk.Window ( ) win.show ( ) web = webkit.WebView ( ) win.add ( web ) web.show ( ) web.open ( `` http : //www.google.com '' ) | Different behaviour between python console and python script |
Python | Since my data set is time series where I have 30 different data frame and each of data frame have more than 10,000 number of rows . I want to examine , the trend before the temperature value goes below 40.So , I want to subset row when the temperature value is below than 40 and I also want to subset 24 rows before the ... | df=temperature_df.copy ( ) drop_temperature_df=pd.DataFrame ( ) # get the index during drop temperaturedrop_temperature_index=np.array ( df [ df [ temperature ] < 40 ] .index ) # subset the data frame for 24 hours before drop temperaturefor i , index in enumerate ( drop_temperature_index ) : drop_temperature_df=drop_te... | How to subset row of condition with some of N rows before the condition meet , more faster than my code ? |
Python | I have problems with getting my plot look like I want it to look using matplotlib.I have aggregated data ( Y ) as float corresponding to dates ( X ) as datetime64 format . My data starts on 2019/04/23 and ends on 2019/08/02 . Unfortunately , the data is not complete , I 'm missing a period between 2019/06/18 and 2019/0... | DATETIME LEVEL0 2019-04-23 16:30:00 0.0870741 2019-04-23 16:35:00 0.0930892 2019-04-23 16:40:00 0.0811033 2019-04-23 16:45:00 0.0931174 2019-04-23 16:50:00 0.0931315 2019-04-23 16:55:00 0.0871456 2019-04-23 17:00:00 0.0871597 2019-04-23 17:05:00 0.0871748 2019-04-23 17:10:00 0.087188 | Fill up missing datetime with NaN or supress straight line in line plot |
Python | Suppose I have a model Event . I want to send a notification ( email , push , whatever ) to all invited users once the event has elapsed . Something along the lines of : Now , of course , the crucial part is to invoke onEventElapsed whenever timezone.now ( ) > = event.end.Keep in mind , end could be months away from th... | class Event ( models.Model ) : start = models.DateTimeField ( ... ) end = models.DateTimeField ( ... ) invited = models.ManyToManyField ( model=User ) def onEventElapsed ( self ) : for user in self.invited : my_notification_backend.sendMessage ( target=user , message= '' Event has elapsed '' ) | Django run tasks ( possibly ) in the far future |
Python | I am trying to send of list of files to my Django Website . Each set is transmitted with the following info : File name , File size , File location , File typeNow , suppose I have 100 such sets of data , and I want to send it to my Django Website , what is the best method I Should use ? PS : I was thinking of using JSO... | { `` files '' : [ { `` filename '' : '' Movie1 '' , `` filesize '' : '' 702 '' , `` filelocation '' : '' C : / '' , `` filetype '' : '' avi '' } , { `` filename '' : '' Movie2 '' , `` filesize '' : '' 800 '' , `` filelocation '' : '' C : / '' , `` filetype '' : '' avi '' } , { `` filename '' : '' Movie3 '' , `` filesiz... | How do I post a lot of data to Django ? |
Python | I am trying to replicate the behaviour of tf.nn.dynamic_rnn using the low level api tf.nn.raw_rnn . In order to do so , I am using the same patch of data , setting the random seed and using the same hparams for the creation of the cell and recurrent neural network . However , the outputs that are generated from both im... | X = np.array ( [ [ [ 1.1 , 2.2 , 3.3 ] , [ 4.4 , 5.5 , 6.6 ] , [ 0.0 , 0.0 , 0.0 ] ] , [ [ 1.1 , 2.2 , 3.3 ] , [ 4.4 , 5.5 , 6.6 ] , [ 7.7 , 8.8 , 9.9 ] ] , [ [ 1.1 , 2.2 , 3.3 ] , [ 0.0 , 0.0 , 0.0 ] , [ 0.0 , 0.0 , 0.0 ] ] ] , dtype=np.float32 ) X_len = np.array ( [ 2 , 3 , 1 ] , dtype=np.int32 ) tf.reset_default_gra... | Tensorflow : Replicating dynamic_rnn behaviour with raw_rnn |
Python | It 's documented that the definition order in classes is preserved ( see also PEP 520 ) : If the metaclass has no __prepare__ attribute , then the class namespace is initialised as an empty ordered mapping.Is the definition order also preserved in module objects ? I 've experimented with the module above ( also swappin... | # foo_bar.pydef foo ( ) : passdef bar ( ) : pass > > > import foo_bar > > > for name in foo_bar.__dict__ : ... if not name.startswith ( ' _ ' ) : ... print ( name ) ... foobar | Is definition order available in a module namespace ? |
Python | I have a list of data such as below : I 'm trying to find the two consecutive numbers with the greatest distance between them out of this list.In this case , the answer would be [ 47 , 747 ] because they are listed right next to each other in the list and 747 - 47 = 700 which is a greater difference than any other pair... | [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 , 17 , 18 , 19 , 20 , 21 , 22 , 23 , 24 , 25 , 26 , 27 , 28 , 29 , 30 , 31 , 32 , 33 , 34 , 35 , 36 , 37 , 38 , 39 , 40 , 41 , 42 , 43 , 44 , 45 , 46 , 47 , 747 , 752 , 753 , 754 , 755 , 756 , 757 , 758 , 759 , 760 , 761 , 762 , 763 , 764 , 765 ... | Get `` edge numbers '' from list |
Python | ProblemI have the following Pandas dataframe : I want to get the following groups : Group 1 : for each ID , all False rows until the first True row of that IDGroup 2 : for each ID , all False rows after the last True row of that IDGroup 3 : all true rowsCan this be done with pandas ? What I 've triedI 've triedbut this... | data = { 'ID ' : [ 100 , 100 , 100 , 100 , 200 , 200 , 200 , 200 , 200 , 300 , 300 , 300 , 300 , 300 ] , 'value ' : [ False , False , True , False , False , True , True , True , False , False , False , True , True , False ] , } df = pandas.DataFrame ( data , columns = [ 'ID ' , 'value ' ] ) group = df.groupby ( ( df [ ... | Group pandas dataframe in unusual way |
Python | I have a list of available items that I can use to create a new list with a total length of 4 . The length of the available item list never exceeds 4 items . If the list has less than 4 elements I want to populate it with the available elements beginning at the start element.Example 1 : Example 2 : Example 3 : I have t... | available_items = [ 4 , 2 ] Result - > [ 4 , 2 , 4 , 2 ] available_items = [ 9 , 3 , 12 ] Result - > [ 9 , 3 , 12 , 9 ] available_items = [ 3 ] Result - > [ 3 , 3 , 3 , 3 ] available_items = [ 3 , 5 ] required_items = 4if len ( available_items ) == 1 : new_items = [ available_items [ 0 ] ] * required_itemselse : new_it... | Repeat items in list to required length |
Python | Contents : now I have a code giving me following output which I do n't get.Code : :OutPut : :I do n't get why dir1 and tutorials are there in the dir ( ) 's output.maindir.__init__.py 's Code : EDIT 1 : : So if the code is : The output is : | tutorials/maindir/├── dir1│ ├── file11.py│ ├── file12.py│ ├── __init__.py│ └── __pycache__│ ├── file11.cpython-36.pyc│ └── __init__.cpython-36.pyc├── dir2│ ├── file21.py│ ├── file22.py│ └── __init__.py├── file1.py├── file2.py├── __init__.py└── __pycache__ ├── file1.cpython-36.pyc └── __init__.cpython-36.pyc print ( `` ... | import in python 3 , explain the output please |
Python | consider numpy array aAnd dfaNow consider numpy array bIt appears the same as aTHIS ! CRASHES MY PYTHON ! ! BE CAREFUL ! ! ! However | import numpy as npimport pandas as pd a = np.array ( [ None , None ] , dtype=object ) print ( a ) [ None None ] dfa = pd.DataFrame ( a ) print ( dfa ) 00 None1 None b = np.empty_like ( a ) print ( b ) [ None None ] ( a == b ) .all ( ) True dfb = pd.DataFrame ( b ) # Fine so farprint ( dfb.values ) [ [ None ] [ None ] ]... | Why does printing a dataframe break python when constructed from numpy empty_like |
Python | Background - TLDR : I have a memory leak in my projectSpent a few days looking through the memory leak docs with scrapy and ca n't find the problem.I 'm developing a medium size scrapy project , ~40k requests per day.I am hosting this using scrapinghub 's scheduled runs.On scrapinghub , for $ 9 per month , you are esse... | class Pipeline ( object ) : def process_item ( self , item , spider ) : item [ 'stock_jsons ' ] = json.loads ( item [ 'stock_jsons ' ] ) [ 'subProducts ' ] return item class mainItem ( scrapy.Item ) : date = scrapy.Field ( ) url = scrapy.Field ( ) active_col_num = scrapy.Field ( ) all_col_nums = scrapy.Field ( ) old_pr... | Scrapy hidden memory leak |
Python | I am trying to create stopwatch . I have done it but I would like to pause and continue the time whenever I want . I have tried some things but I have no idea how to do it . Is there anybody who would explain me how to do it ? | import time , tkintercanvas=tkinter.Canvas ( width=1900 , height=1000 , bg='white ' ) canvas.pack ( ) canvas.create_text ( 950,300 , text= ' : ' , font='Arial 600 ' ) def write ( x_rec , y_rec , x_text , rep ) : canvas.create_rectangle ( x_rec,0 , y_rec,750 , outline='white ' , fill='white ' ) if rep < 10 : canvas.crea... | Pause and continue stopwatch |
Python | I need to position the year of copyright at the beginning of a string . Here are possible inputs I would have : From these inputs , I need to always have the output in the same format -How would I do this with a combination of string formatting and regex ? This needs to be cleaned up , but this is what I am currently d... | ( c ) 2012 10 DC Comics2012 DC Comics10 DC Comics . 201210 DC Comics , ( c ) 2012.10 DC Comics , Copyright 2012Warner Bros , 2011Stanford and Sons , Ltd. Inc. ( C ) 2011 . All Rights Reserved ... .etc ... 2012 . 10 DC Comics.2011 . Warner Bros.2011 . Stanford and Sons , Ltd. Inc. All Rights Reservedetc ... # # # copyri... | Re-order copyright with regex |
Python | Assume that we have a list of strings and we want to create a string by concatenating all element in this list . Something like this : Since strings are immutable objects , I expect that python creates a new str object and copy contents of result and element at each iteration . It makes O ( M * N^2 ) time complexity , ... | def foo ( str_lst ) : result = `` for element in str_lst : result += element return result N = 1000000 # 1 millionstr_lst = [ ' a ' for _ in range ( N ) ] foo ( str_lst ) # It takes around 0.5 secondsN = 2000000 # 2 millionstr_lst = [ ' a ' for _ in range ( N ) ] foo ( str_lst ) # It takes around 1.0 secondsN = 1000000... | Python string concatenation internal details |
Python | I am using a decorator to extend certain classes and add some functionality to them , something like the following : Unfortunaltely , MyClass is no longer pickleable due to the non global LocalClassI need to pickle my classes . Can you recommend a better design ? Considering that there can be multiple decorators on a c... | def useful_stuff ( cls ) : class LocalClass ( cls ) : def better_foo ( self ) : print ( 'better foo ' ) return LocalClass @ useful_stuffclass MyClass : def foo ( self ) : print ( 'foo ' ) AttributeError : Ca n't pickle local object 'useful_stuff. < locals > .LocalClass ' | Extending a class in Python inside a decorator |
Python | I want to implement the following problem in numpy and here is my code . I 've tried the following numpy code for this problem with one for loop . I am wondering if there is any more efficient way of doing this calculation ? I really appreciate that ! I 've thought of np.expand_dims ( X , 2 ) .repeat ( Y.shape [ 0 ] , ... | k , d = X.shapem = Y.shape [ 0 ] c1 = 2.0*sigma**2c2 = 0.5*np.log ( np.pi*c1 ) c3 = np.log ( 1.0/k ) L_B = np.zeros ( ( m , ) ) for i in xrange ( m ) : if i % 100 == 0 : print i L_B [ i ] = np.log ( np.sum ( np.exp ( np.sum ( -np.divide ( np.power ( X-Y [ i , : ] ,2 ) , c1 ) -c2,1 ) +c3 ) ) ) print np.mean ( L_B ) | How can I optimize the calculation over this function in numpy ? |
Python | I have implemented a web service using Falcon . This service stores a state machine ( pytransitions ) that is passed to service 's resources in the constructor . The service is runs with gunicorn.The web service launches a process on start using RxPy . The event returned in the on_next ( event ) is used to trigger a tr... | class TochoLevel ( object ) : def __init__ ( self , tochine ) : self.tochine = tochine def on_get ( self , req , res ) : res.status = falcon.HTTP_200 res.body = self.tochine.statedef get_machine ( ) : states = [ `` low '' , `` medium '' , `` high '' ] transitions = [ { 'trigger ' : 'to_medium ' , 'source ' : [ 'low ' ,... | Python web service subscribed to reactive source produces strange behavior in object |
Python | I wrote a simple program for Maemo by Python to check some pixel 's color every time that my function is called . But this function runs very slowly ( 3-5 seconds each call ) . Is there any faster way to do this ? | import Imageimport osimport sys # sen_pos = ( pixel_x , pixel_y ) def sen ( sen_pos ) : os.system ( `` gst-launch v4l2src device=/dev/video0 num-buffers=1 ! ffmpegcolorspace ! jpegenc ! filesink location=cam.jpg '' ) frame = Image.open ( `` cam.jpg '' ) col = frame.getpixel ( ( sen_pos [ 0 ] , sen_pos [ 1 ] ) ) avecol ... | use maemo camera by python |
Python | I have a list of links and want to know the joined path/cycle.My links look like this : And I want the answer to be a cycle like that ( or any other matching cycle ) : So you take the first element of the first sublist , then you take the second element and you look for the next sublist starting with this element , and... | [ [ 0 , 3 ] , [ 1 , 0 ] , [ 3 , 1 ] ] [ 0,3,1 ] | How to join links in Python to get a cycle ? |
Python | I have a list of strings.I want to add integers to the strings , resulting in an output like this : I want to save this to a .txt file , in this format : The attempt : Right now I can save to the file myFile.txt but the text in the file reads : Any tips on more pythonic ways to achieve my goal are very welcome , | theList = [ ' a ' , ' b ' , ' c ' ] newList = [ 'a0 ' , 'b0 ' , 'c0 ' , 'a1 ' , 'b1 ' , 'c1 ' , 'a2 ' , 'b2 ' , 'c2 ' , 'a3 ' , 'b3 ' , 'c3 ' ] a0b0c0a1b1c1a2b2c2a3b3c3 theList = [ ' a ' , ' b ' , ' c ' ] newList = [ ] for num in range ( 4 ) : stringNum = str ( num ) for letter in theList : newList.append ( entry+strin... | Pythonic way to modify all items in a list , and save list to .txt file |
Python | This seems to be a pretty common pattern : I want to know if there is a better way to achieve this . As far as single line if statements go , I could do this much : But then I 'm stuck with incrementing currid and sticking if the else case was executed and sticking c- > id1 into the dictionary if the if condition passe... | for row in reader : c1=row [ 0 ] if ids.has_key ( c1 ) : id1=ids.get ( c1 ) else : currid+=1 id1=currid ids [ c1 ] =currid id1=ids.get ( c1 ) if ids.has_key ( c1 ) else currid+1 | Pythonic way to increment and assign ids from dictionary |
Python | I am looking for a efficient and fast way to do the following in Python 3.x . I am open to using third party libraries such as Numpy as long as the performance is there.I have a list of ranges containing hundreds of thousands of entries . They 're not actually range ( ) 's , but rather the boundary numbers , such as : ... | list_a = [ ( 1 , 100 ) , ( 300 , 550 ) , ( 551 , 1999 ) ] ( 0 , 600 ) contains list_a [ 0 ] and list_a [ 1 ] ( 550 , 2000 ) contains list_a [ 2 ] ( 2000 , 2200 ) does not contain an existing range for start , end in get_next_range ( ) : for r in list_a : if r [ 0 ] > = start and r [ 1 ] < = end : # do something else : ... | Python , find if a range contains another smaller range from a list of ranges |
Python | Why is it that numpy arrays can not be indexed within a single bracket [ ] ? | > > > allData.shapeOut [ 72 ] : ( 8L , 161L ) > > > mask = allData [ 2 , : ] > > > allData [ [ 0,1,3 ] , : ] [ : ,mask == 1 ] # works fine > > > allData [ [ 0,1,3 ] , mask == 1 ] # error : ValueError : shape mismatch : objects can not be broadcast to a single shape | Numpy array can not index within a single [ ] |
Python | I want to fill missing value with the average of previous N row value , example is shown below : DataFrame is like : Result should be : I am wondering if there is elegant and fast way to achieve this without for loop . | N=2df = pd.DataFrame ( [ [ np.nan , 2 , np.nan , 0 ] , [ 3 , 4 , np.nan , 1 ] , [ np.nan , np.nan , np.nan , 5 ] , [ np.nan , 3 , np.nan , np.nan ] ] , columns=list ( 'ABCD ' ) ) A B C D0 NaN 2.0 NaN 01 3.0 4.0 NaN 12 NaN NaN NaN 53 NaN 3.0 NaN NaN A B C D0 NaN 2.0 NaN 01 3.0 4.0 NaN 12 NaN ( 4+2 ) /2 NaN 53 NaN 3.0 Na... | Fill missing value by averaging previous row value |
Python | I build a image classification model in R by keras for R.Got about 98 % accuracy , while got terrible accuracy in python.Keras version for R is 2.1.3 , and 2.1.5 in pythonfollowing is the R model code : I try to rebuild a same model in python , with same input data.While , got totally different performance . The accura... | model=keras_model_sequential ( ) model=model % > % layer_conv_2d ( filters = 32 , kernel_size = c ( 3,3 ) , padding = 'same ' , input_shape = c ( 187,256,3 ) , activation = 'elu ' ) % > % layer_max_pooling_2d ( pool_size = c ( 2,2 ) ) % > % layer_dropout ( .25 ) % > % layer_batch_normalization ( ) % > % layer_conv_2d (... | Different accuracy between python keras and keras in R |
Python | I 'm trying to write a code to edit a list and make it a palindrome . Everything is working except my input still gives me one error . When I enter a non-int into get_number_2 , it crashes.I use the input from get_number_2 for the rest of the code as get_number does n't work when I check if its between two numbers . Is... | def get_number ( ) : num = raw_input ( `` Please enter number between 100,000 and 1,000,0000 : `` ) if not num.isdigit ( ) : print `` -- -- -- -- -- -- -- -- -- -- -- -- -- - '' print `` Invalid input : numbers only '' print `` -- -- -- -- -- -- -- -- -- -- -- -- -- - '' my_main ( ) else : return numdef get_number_2 ( ... | Simple Python input error |
Python | I am trying to send all requests /other to another server , say google for example . As far as I understand the config I should be able to do something like this in the config file : This does not work as the log just has | [ uwsgi ] master = 1buffer-size = 65535die-on-term = true # HTTPhttp-socket = 0.0.0.0:80 # Appmodule = manage : app # Async processesgevent = 100processes = 4route-if = equal : $ { PATH_INFO } ; /other http:216.58.204.78 , www.google.com error routing request to http server 216.58.204.78 [ pid : 9|app : -1|req : -1/11 ... | Using uWSGI to proxy certain requests |
Python | When checking if an empty string variable is populated with certain characters , the expression is always evaluated as true . If the newly created string value is empty , it should be false , it does not contain any characters let alone the ones being checked for.When I hard-code a random character that is not the char... | difficulty = `` while difficulty not in 'EMH ' : print ( 'Enter difficulty : E - Easy , M - Medium , H - Hard ' ) difficulty = input ( ) .upper ( ) | `` not in '' identity operator not working when checking empty string for certain characters |
Python | I have a sample piece of code below that I need some help on . The code sets the 'outcome ' variable to False in the beginning and only should become True if all the 'if ' conditions are met . Is there a more efficient way of doing this ? I am trying to avoid nested 'if ' statements.Thanks ! | outcome = False while True : if a ! = b : print ( `` Error - 01 '' ) break if a [ `` test_1 '' ] ! = `` test_value '' : print ( `` Error - 02 '' ) break if `` test_2 '' not in a : print ( `` Error - 03 '' ) break if a [ `` test_3 '' ] == `` is long data string '' : print ( `` Error - 04 '' ) break outcome = True break | Multiple if conditions , without nesting |
Python | This is for Python 2.6.I could not figure out why a and b are identical : But if there is a space in the string , they are not : If this is normal behavior , could someone please explain what is going on.Edit : Disclaimer ! This is not being used to check for equality . I actually wanted to explain to someone else that... | > > > a = `` some_string '' > > > b = `` some_string '' > > > a is bTrue > > > a = `` some string '' > > > b = `` some string '' > > > a is bFalse | Is this a bug ? Variables are identical references to the same string in this example ( Python ) |
Python | I want to simulate suicide burn to learn and understand rocket landing . OpenAI gym already has an LunarLander enviroment which is used for training reinforcement learning agents . I am using this enviroment to simulate suicide burn in python . I have extracted the coordinates ( x , y ) from the first two values of sta... | velocity ( v ) = delta_y/ delta_tacceleartion ( a ) = delta_v/delta_t import gymenv = gym.make ( 'LunarLander-v2 ' ) env.seed ( 0 ) g = 1delta_t = 1action = 0state = env.reset ( ) # x0 = state [ 0 ] y0 = state [ 1 ] v0 = 0for t in range ( 3000 ) : state , reward , done , _ = env.step ( action ) y = state [ 1 ] if done ... | Simulation of suicide burn in openai-gym 's LunarLander |
Python | Let spam be an instance of some class Spam , and suppose that spam.ham is an object of some built-in type , say dict . Even though Spam is not a subclass of dict , I would like its instances to have the same API as a regular dict ( i.e . the same methods with the same signatures ) , but I want to avoid typing out a baz... | def apimethod ( self , this , that ) : return self.ham.apimethod ( this , that ) class Spam ( object ) : def __init__ ( self ) : self.ham = dict ( ) def __getattr__ ( self , attr ) : return getattr ( self.ham , attr ) > > > spam = Spam ( ) > > > spam.keys ( ) [ ] > > > spam [ 'eggs ' ] = 42Traceback ( most recent call ... | How to automate the delegation of __special_methods__ in Python ? |
Python | I 'm working on a pure Python file parser for event logs , which may range in size from kilobytes to gigabytes . Is there a module that abstracts explicit .open ( ) /.seek ( ) /.read ( ) /.close ( ) calls into a simple buffer-like object ? You might think of this as the inverse of StringIO . I expect it might look some... | with FileBackedBuffer ( '/my/favorite/path ' , 'rb ' ) as buf : header = buf [ 0:0x10 ] footer = buf [ 0x10000000 : ] | Is there a Python module for transparently working with a file 's contents as a buffer ? |
Python | I 'm trying to solve this problem on the easy section of coderbyte and the prompt is : Have the function ArrayAdditionI ( arr ) take the array of numbers stored in arr and return the string true if any combination of numbers in the array can be added up to equal the largest number in the array , otherwise return the st... | def ArrayAddition ( arr ) : arr = sorted ( arr , reverse=True ) large = arr.pop ( 0 ) storage = 0placeholder = 0for r in range ( len ( arr ) ) : for n in arr : if n + storage == large : return True elif n + storage < large : storage += n else : continue storage = 0 if placeholder == 0 : placeholder = arr.pop ( 0 ) else... | looping through loops in python ? |
Python | I have a list of dictionaries , and I would like to obtain those that have the same value in a key : I want to keep those items that have the same 'name ' , so , I would like to obtain something like : I 'm trying ( not successfully ) : I have clear my problem with this code , but not able to do the right sentence | my_list_of_dicts = [ { 'id ' : 3 , 'name ' : 'John ' } , { 'id ' : 5 , 'name ' : 'Peter ' } , { 'id ' : 2 , 'name ' : 'Peter ' } , { 'id ' : 6 , 'name ' : 'Mariah ' } , { 'id ' : 7 , 'name ' : 'John ' } , { 'id ' : 1 , 'name ' : 'Louis ' } ] duplicates : [ { 'id ' : 3 , 'name ' : 'John ' } , { 'id ' : 5 , 'name ' : 'Pe... | keep duplicates by key in a list of dictionaries |
Python | Which is the fastest way to search if a string contains another string based on a list ? This one works fine , but is too slow for me when the string is large and the list is long . | test_string = `` Hello ! This is a test . I love to eat apples . `` fruits = [ 'apples ' , 'oranges ' , 'bananas ' ] for fruit in fruits : if fruit in test_string : print ( fruit+ '' contains in the string '' ) | Fastest way to check if a string contains a string from a list |
Python | I have 2 dataframes like this ... I 'd like to find the average of values in a for the 4 groups in b . This ... ... works for doing one group at a time , but I was wondering if anyone could think of a cleaner method.My expected result isThanks . | np.random.seed ( 0 ) a = pd.DataFrame ( np.random.randn ( 20,3 ) ) b = pd.DataFrame ( np.random.randint ( 1,5 , size= ( 20,3 ) ) ) a [ b==1 ] .sum ( ) .sum ( ) / a [ b==1 ] .count ( ) .sum ( ) 1 -0.0887152 -0.3400433 -0.0455964 0.582136dtype : float64 | GroupBy operation using an entire dataframe to group values |
Python | I 'm looking for techniques that allow users to override modules in an application or extend an application with new modules.Imagine an application called pydraw . It currently provides a Circle class , which inherits Shape . The package tree might look like : Now suppose I 'd like to enable dynamic discovery and loadi... | /usr/lib/python/└── pydraw ├── __init__.py ├── shape.py └── shapes ├── circle.py └── __init__.py /home/someuser/python/└── pydraw ├── __init__.py ├── shape.py < -- new superclass └── shapes ├── __init__.py └── square.py < -- new user class | What are prevalent techniques for enabling user code extensions in Python ? |
Python | My question is similar to this one , but with some modifications . First off I need to use python and regex . My string is : 'Four score and seven years ago . ' and I want to split it by every 6th character , but in addition at the end if the characters do not divide by 6 , I want to return blank spaces.I want to be ab... | re.findall ( ' . { % s } ' % 6 , 'Four score and seven years ago . ' ) # split into strings [ 'Four s ' , 'core a ' , 'nd sev ' , 'en yea ' , 'rs ago ' ] | greedy regex split python every nth line |
Python | I 've noticed a ( seemingly ) strange behaviour with assignments , which has led me several times to do programming mistakes . See the following example first : As expected , the value of the unique element of t does not change , even after the value of i has been incremented.See now the following : I do n't understand... | > > > i = 0 > > > t = ( i , ) > > > t ( 0 , ) > > > i += 1 > > > t ( 0 , ) > > > l = [ 0 ] > > > t = ( l , ) > > > t ( [ 0 ] , ) > > > l [ 0 ] += 1 > > > t ( [ 1 ] , ) # < - ? > > > t [ 0 ] [ 0 ] += 1 | Assignment rules |
Python | My twisted program works but now I have a problem with one of my reactors not passing priority to the others . I want the controlListener reactor to do one iteration and then pass priority to the printstuffs reactor . here is the output I want it to do something like etc . Any ideas ? | # Random class as proof of concept class printStuffs ( object ) : print `` counting `` printerCount = 0 def count ( self ) : self.printerCount = self.printerCount + 1 print ( `` the counter is at `` + str ( self.printerCount ) ) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #... | Twisted logic error |
Python | traits_pickle_problem.pyThe above code reports a dynamic trait . Everything works as expected in this code . However , using a new python process and doing the following : causes no report of the list append . However , re-establishing the listener separately as follows : makes it work again . Am I missing something or... | from traits.api import HasTraits , Listimport cPickleclass Client ( HasTraits ) : data = Listclass Person ( object ) : def __init__ ( self ) : self.client = Client ( ) # dynamic handler self.client.on_trait_event ( self.report , 'data_items ' ) def report ( self , obj , name , old , new ) : print 'client added -- ' , n... | Dynamic traits do not survive pickling |
Python | I 'm developing a Python program to detect names of cities in a list of records . The code I 've developed so far is the following : The code works well to detect when a city in the aCities ' list is found in the accounting record but as the any ( ) function just returns True or False I 'm struggling to know which city... | aCities = [ 'MELBOURNE ' , 'SYDNEY ' , 'PERTH ' , 'DUBAI ' , 'LONDON ' ] cxTrx = db.cursor ( ) cxTrx.execute ( 'SELECT desc FROM AccountingRecords ' ) for row in cxTrx.fetchall ( ) : if any ( city in row [ 0 ] for city in aCities ) : # print the name of the city that fired the any ( ) function else : # no city name fou... | How can I know which element in a list triggered an any ( ) function ? |
Python | I 'm really new to Python and I 'm stuck with the below problem that I need to solve.I 've a log file from Apache Log as below : I 've to return the 10 most requested objects and their cumulative bytes transferred . I need to include only GET requests with Successful ( HTTP 2xx ) responses . So the above log would resu... | [ 01/Aug/1995:00:54:59 -0400 ] `` GET /images/opf-logo.gif HTTP/1.0 '' 200 32511 [ 01/Aug/1995:00:55:04 -0400 ] `` GET /images/ksclogosmall.gif HTTP/1.0 '' 200 3635 [ 01/Aug/1995:00:55:06 -0400 ] `` GET /images/ksclogosmall.gif HTTP/1.0 '' 403 298 [ 01/Aug/1995:00:55:09 -0400 ] `` GET /images/ksclogosmall.gif HTTP/1.0 ... | Add values of keys and sort it by occurrence of the keys in a list of dictionaries in Python |
Python | I 'm trying to read a text file that contains a lot of non-traditional line breaks.There are two files , both with 18846 lines . But when I read one of these files in python3 and break into lines , it results in 19010 lines.This is not repeated either with python2 nor with unix commands like awk 'END { print NR } ' fil... | content = content.replace ( u '' \v '' , `` '' ) content = content.replace ( u '' \x0b '' , `` '' ) content = content.replace ( u '' \f '' , `` '' ) content = content.replace ( u '' \x0c '' , `` '' ) content = content.replace ( u '' \x1c '' , `` '' ) content = content.replace ( u '' \x1d '' , `` '' ) content = content.... | How to break string in lines only based on \n in python3 ? |
Python | Lets say I have a list : The list contains mesurements , that are not very accurate : that is the real value of an element is +-2 of the recorded value . So 14,15 and 16 can have the same value . What I want to do is to uniquefy that list , taking into account the mesurement errors . The output should therefor be : orI... | L = [ 15,16,57,59,14 ] l_out = [ 15,57 ] l_out = [ ( 14,15,16 ) , ( 57,59 ) ] | Python : Uniquefying a list with a twist |
Python | Recently the ms-python extension ( v2020.5.86806 ) for vscode implements grouping of variables in the debug console/variable explorer.They appear as : Is there a way to disable this behavior ? EDIT : Screenshot added : | < object > > special variables > function variables | How can I disable/hide the grouping of variables in vscode-python |
Python | In other words , I want to do something likeinstead of | A [ [ -1 , 0 , 1 ] , [ 2 , 3 , 4 ] ] += np.ones ( ( 3 , 3 ) ) A [ -1:3 , 2:5 ] += np.ones ( ( 1 , 3 ) ) A [ 0:2 , 2:5 ] += np.ones ( ( 2 , 3 ) ) | Is it possible in numpy to use advanced list slicing and still get a view ? |
Python | PrefaceI want to have 2 classes Interval and Segment with the following properties : Interval can have start & end points , any of them can be included/excluded ( I 've implemented this using required flag parameters like start_inclusive/end_inclusive ) .Segment is an Interval with both endpoints included , so user do ... | > > > Interval ( 0 , 1 , start_inclusive=True , end_inclusive=True ) Segment ( 0 , 1 ) class Interval : def __new__ ( cls , start : int , end : int , * , start_inclusive : bool , end_inclusive : bool ) - > 'Interval ' : if cls is not __class__ : return super ( ) .__new__ ( cls ) if start == end : raise ValueError ( 'De... | Instantiate a child in __new__ with different __new__ signature for a child |
Python | On my Anaconda Python distribution , copying a Numpy array that is exactly 16 GB or larger ( regardless of dtype ) sets all elements of the copy to 0 : Here is np.__config__.show ( ) for this distribution : For comparison , here is np.__config__.show ( ) for my system Python distribution , which does not have this prob... | > > > np.arange ( 2 ** 31 - 1 ) .copy ( ) # works finearray ( [ 0 , 1 , 2 , ... , 2147483644 , 2147483645 , 2147483646 ] ) > > > np.arange ( 2 ** 31 ) .copy ( ) # wait , what ? ! array ( [ 0 , 0 , 0 , ... , 0 , 0 , 0 ] ) > > > np.arange ( 2 ** 32 - 1 , dtype=np.float32 ) .copy ( ) array ( [ 0.00000000e+00 , 1.00000000e... | Why does copying a > = 16 GB Numpy array set all its elements to 0 ? |
Python | I have a Django app being served with nginx+gunicorn with 3 gunicorn worker processes . Occasionally ( maybe once every 100 requests or so ) one of the worker processes gets into a state where it starts failing most ( but not all ) requests that it serves , and then it throws an exception when it tries to email me abou... | [ 2015-04-29 10:41:39 +0000 ] [ 20833 ] [ ERROR ] Error handling requestTraceback ( most recent call last ) : File `` /home/django/virtualenvs/homestead_django/local/lib/python2.7/site-packages/gunicorn/workers/sync.py '' , line 130 , in handle File `` /home/django/virtualenvs/homestead_django/local/lib/python2.7/site-... | How to debug intermittent errors from Django app served with gunicorn ( possible race condition ) ? |
Python | I have an abstract class with three methods that are is a sense equivalent - they could all be defined in terms of each other using some expensive conversion functions . I want to be able to write a derived class which would only need to override one of the methods and automatically get the other two . ExampleI know I ... | class FooBarBaz ( object ) : def foo ( self , x ) : return foo_from_bar ( self.bar ( x ) ) # OR return foo_from_baz ( self.baz ( x ) ) def bar ( self , x ) : return bar_from_foo ( self.foo ( x ) ) # OR return bar_from_baz ( self.baz ( x ) ) def baz ( self , x ) : return baz_from_bar ( self.bar ( x ) ) # OR return baz_f... | How to define three methods circularly ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.