text stringlengths 46 37.3k | 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 do... | 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 re... | 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 fil... | 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_in... | 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 ha... | 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 ? <code> so... | 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 ? <code> where... | 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 o... | 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 th... | 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... | 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 ? <code> now = datet... | 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 ' ] ) ? <code> from ddr import Opti... | 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 : - ) <code> import RDF , Redlandsto... | 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 ? <code> A = [ [ ] ] *2A [ 0 ] .append ( `` a '' ) A [ 1 ] .append ( `` b '' ) B = [ [ ] , [ ] ] B [ 0 ] .append ( `` a '' ) B [ 1 ] .append ( `` 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 ineffi... | 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... | 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 <code> data1 = { 'node1 ' : [ 2,2,3,6 ] , 'node2 ' : [ 6,7,7,28 ] , 'weight ' : [ 1,2,1,1 ... | 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... | 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 th... | 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 , ... | 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 ... | 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 )... | 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 grou... | 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 ? <code> from Son import Sonclass Mother : def __init__ ( self ) : self.sons = [ ] def add_son ( self , son : Son ) : self.sons.... | 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 sol... | 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... | 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 followi... | 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 i... | 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 name... | 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 : <code> -- -title : `` **warnings test** '' output : pdf_document -- -... | 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 :... | 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 thi... | 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 some... | 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 a... | 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 ... | 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 her... | 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... | 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 ? <code> > > > from contextlib import contextmanager > > > @ contextmanager ... def frob... | 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 ... | 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 loo... | 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 ite... | 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 ... | 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 `` SimpleCo... | 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 gue... | 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 ... | 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 t... | 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... | 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 be... | 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 a... | 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 awa... | 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 ... | 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 fro... | 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 ( als... | 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 o... | 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 trie... | 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 :... | 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 : <code> tutorials/maindir/├── dir1│ ├── file11.py│ ├── file12.py│ ├── _... | 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 <code> 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... | 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... | 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 ? <code> import time , tkintercanvas=tkinter.Canvas ( width=1900 , height=1000 , bg='w... | 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 cu... | 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 comp... | 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 decorato... | 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... | 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 tri... | 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 ? <code> import Imageimport osimport sys # sen_pos = ( pixel_x , pixel_y ) def sen ( sen_pos ) : os... | 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 elem... | 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... | 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 condit... | 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 , s... | 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 [ ] ? <code> > > > 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 ... | 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 . <code> N=2df = pd.DataFrame ( [ [ np.nan , 2 , np.nan , 0 ] , [ 3 , 4 , np.nan , 1 ] , [ np.... | 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 . T... | 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 num... | 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 <code> [ uwsgi ] master = 1buffer-size = 65535die-on-term = true # HTTPhttp-socket = 0.0.... | 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... | `` 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 ! <code> outcome = F... | 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 ... | 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 valu... | 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 ... | 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 ... | 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 retu... | 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 sent... | 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 . <code> test_string = `` Hello ! This is a test . I love to eat apples . `` fruits = [ 'apples ' , 'oranges ' , 'bananas ' ] for f... | 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 . <code> np.random.seed ( 0 ) a = pd.DataFrame ( np.random.randn ( ... | 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 ... | 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... | 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 u... | 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 ? <code> # Random class as ... | 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 som... | 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 w... | 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 w... | 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 N... | 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... | 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 : <code> < 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 <code> 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... | 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 ... | 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 emai... | 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 . Example... | 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.