text
stringlengths
46
37.3k
title
stringlengths
12
162
Python : For example , if our source list is : And I need something like this : I try like this , but this not work correctly : <code> input = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , ... ] output = { 1 : [ 1 ] , 2 : [ 2,3 ] , 3 : [ 4,5,6 ] , 4 : [ 7,8,9 , ... ] , ... } groups = { } N = 1group = [ 1 , 2 , 3 , 4 , 5 , 6 , ...
Slicing a list and group
Python : I 'm trying to detect contiguous spans in which the relevant variable changes linearly within certain data in a DataFrame . There may be many spans within the data that satisfy this . I started my aproach using ransac based on Robust linear model estimation using RANSAC . However I 'm having issues using the e...
How to detect contiguous spans in which data changes linearly within a DataFrame ?
Python : During one of the recent code reviews , I 've stumbled upon the problem that was not immediately easy to spot - there was assertTrue ( ) used instead of assertEqual ( ) that basically resulted into a test that was testing nothing . Here is a simplified example : The problem here is that the test would pass ; a...
Detecting incorrect assertion methods
Python : When working with built-in types like int and float in Python , it 's common to employ exception handling in cases where input might be unreliable : Are there any prominent edge-cases to be aware of when using str ( ) ? I really do n't like using a broad Exception since there are cases like NameError that sign...
Potential Exceptions using builtin str ( ) type in Python
Python : I have a DataFrame that has integers for column names that looks like this : I 'd like to rename the columns . I tried using the followingHowever that does n't change the column names . Do I need to do something else to change column names when they are numbers ? <code> 1 2 3 4 Red 7 3 2 9 Blue 3 1 6 4 df = df...
Renaming Pandas DataFrame columns that are numbers
Python : I am trying to do a more elegant version of this code . This just basically appends a string to categorynumber depending on the number . Would appreciate any help . <code> number = [ 100,150,200,500 ] categoryNumber = [ ] for i in range ( 0 , len ( number ) ) : if ( number [ i ] > =1000 ) : categoryNumber.appe...
How to do elif statments more elegantly if appending to array in python
Python : I am using pythreejs to visualize some 3D models.When visualizing the models on a Jupyter notebook , everything works as expected.But when trying to embed the widget in an HTML document , I am facing two problems : It seems the camera , on load , is looking at ( 0 , 0 , 0 ) , not as expected , and once you int...
Embed widgets with pythreejs : wrong perspective and camera look-at
Python : Let 's say I have the following two models : Now I want to calculate the sum of ( field_a * field_b * factor ) of all objects in the Child model . I can calculate the sum of ( field_a * field_b ) with aggregate ( value=Sum ( F ( 'field_a ' ) *F ( 'field_b ' ) , output_field=DecimalField ( ) ) ) . My question i...
Django : How do I use a foreign key field in aggregation ?
Python : I 'm learning python and came across this example of a simulation of a model I 've seen before . One of the functions looked unnecessarily long , so I thought it would be good practice to try to make it more efficient . My attempt , while requiring less code , is about 1/60th as fast . Yes , I made it 60 times...
Why is my ( newbie ) code so slow ?
Python : When working with Python 3 dictionaries , I keep having to do something like this : I seem to remember there being a native way to do this , but was looking through the documentation and could n't find it . Do you know what this is ? <code> d=dict ( ) if ' k ' in d : d [ ' k ' ] +=1else : d [ ' k ' ] =0
How to natively increment a dictionary element 's value ?
Python : I would like to generate a list of all possible 4-tuple pairs given an array of size n. n is at least 8 , so it is always possible to find at least 1 pair . As an example that helps to understand the problem I use a smaller version of the problem , 2-tuple pairs given an arrayy of size 5 . The expected result ...
Generate all 4-tuple pairs from n elements
Python : I have these files in my project : main is the main file that will be directly execute in console.module1 will be imported into main and throws Module1Exception.module2 will be imported into module1 , throws Module2Exception and uses lib that throws NormalException and CriticalException exceptions.On all excep...
Python - good practice to catch errors
Python : I have no idea if this question make much sense or not but i am so confused about it . I have a post list view and it is rendering some of the post here.My question is how can I split the sections of the page.something like this.what should be the approach of making this kind of view.this is my posts view.py p...
how to split post view on the same page in django
Python : I have a pandas dataframe as such : This represents a tree that looks like thisI want to produce something that looks like this : or What is the fastest way to do so without looping . I have a really large dataframe . <code> parent child parent_level child_levelA B 0 1B C 1 2B D 1 2X Y 0 2X D 0 2 Y Z 2 3 A X /...
Identifying root parents and all their children in trees
Python : I 'm trying to figure out how decorator works in python.But , there are two things that I ca n't make clear , so I appreciate it if anyone helps me understand how decorator works in python ! This is the sample code I 've just written to see how it works.OUTPUT 1The first thing I do n't understand is why it out...
How decorator works ?
Python : This is a follow-up and complication to this question : Extracting contents of a string within parentheses.In that question I had the following string -- And I wanted to get a list of tuples in the form of ( actor , character ) -- To generalize matters , I have a slightly more complicated string , and I need t...
Using regex to extract information from a string
Python : I have a pandas DataFrame with about 200 columns . Roughly , I want to do thisI 'm not sure what are the best practices when it comes to handling pandas DataFrames , how should I handle this ? Will my pseudocode work , or is it not recommended to modify a pandas dataframe in a for loop ? <code> for col in df.c...
Delete pandas column if column name begins with a number
Python : Lets say I have A ( KxMxN ) and B ( KxLxN ) matrices , where L , M , N are small and K is a large number . I would like to calculate the outer product of using the last 2 dimensions along the 1st dimension to get matrix C ( KxMxL ) . I can do this by running a for loop for each index k in `` K '' and use numpy...
How to efficiently calculate the outer product of two series of matrices in numpy ?
Python : I 'm a bit baffled why 2to3 is bothering embracing my print arguments that are already in functional style to be wrapped in an extra set of parenthesis . For examplebecomesAre these essentially conservative false positives ? I 'm thinking maybe the trailing ) in the format function is throwing its logic . <cod...
Python 2to3 adding extra parenthesis around functional argument
Python : I am writing a function that takes in a file object , e.g.The first thing I want to do in the function is ensure that the passed-in file object was opened with newline= '' . How do I do this ? Thanks.PS . I believe this question is only applicable to Python 3 because newline= '' only exists in Python 3 ( note ...
In Python , how to assert passed-in file object was opened with newline= '' ?
Python : I converted one sample dataframe to .arrow file using pyarrowThis creates a file test.arrowThen in NodeJS I load the file with arrowJS.https : //arrow.apache.org/docs/js/This prints likeI was expecting this table will have a length 3 and table.get ( 0 ) gives the first row instead of null.This is the table sce...
Converted apache arrow file from data frame gives null while reading with arrow.js
Python : This question is for fun ; I do n't expect the answer to be useful.When I see people doing things with reduce ( ) in Python , they often take advantage of a builtin function in Python , often from the operator module.This works : But usually you would see this : What 's strange to me is that the operator modul...
Is there a builtin function version of ` and ` and/or ` or ` in Python ?
Python : I 've been trying to learn Python and have come across this issue . I ca n't figure out how the current output came about.I expected the output to be : <code> d= { 'k1':1 , 'k2':2 , 'k3':3 } for key , value in d.keys ( ) : print ( key ) Output : kkk k1k2k3
Why isnt the output showing k1 , k2 , k3 ?
Python : I 'm working on a web server running Python3.6 , Django 2.0 and Channels 2.0.2 . I 'd like to build some tests to make sure my websocket consumers are behaving themselves , unfortunately , whenever I run the tests they are all ignored completely.I 've been following the official Channels documentation on testi...
Django Ignoring Asynch Tests Completely ( Django Channels )
Python : I 've got the following code which produces the following figureI graphed the data using hexbins , as noted belowI 'd like to change the size of the hexagons based on the density of the points plotted in the area that a hexagon covers . For example , the hexagons in the bottom left ( where the points are compa...
Hex size in matplotlib hexbins based on density of nearby points
Python : I am starting out with python and trying to construct an XML request for an ebay web service : Now , my question is : Say , this is my function : Where , keyword is the only required field . So , how should I construct the method ? The ways can be : Create an object , pass it to the func ( object ) : The java ...
**kwargs vs 10 arguments in a python function ?
Python : I 'm trying to get make an API for the first time and I 've made my app but it says I have to do a local authentication with instructions here : Link to TDAmeritrade authenticationBut it says I have to go on https : //auth.tdameritrade.com/auth ? response_type=code & redirect_uri= { URLENCODED REDIRECT URI } &...
Authentication for API & Python
Python : Python 3.8 introduces new shared memory features . We are trying to use the SharedMemoryManager and a NameError is thrown.I thought that we might do something wrong in our complex scenario , so I broke it down using python documentation snippets.This is pretty much taken from the multiprocessing docs ( except ...
Why do we get a NameError when trying to use the SharedMemoryManager ( python 3.8 ) as a replacement for the BaseManager ?
Python : I have a nested list which contains different objects , they 're duplicate pairs of objects in the nested list and i 'm trying to remove them but i keep getting a TypeError : unorderable types : practice ( ) < practice ( ) I know this error is caused by me trying to work with objects rather than integers but i...
How to Sort Python Objects
Python : With PEP 563 , from __future__ import annotations changes type annotations so that they are evaluated lazily , which provides a bunch of benefits like forward references.However , this seems to play badly with other features , like dataclasses . For example , I have some code that inspects the type parameters ...
New annotations break inspection of dataclasses
Python : I have two files - one contains the addresses ( line numbers ) and the other one data , like this : address file : data fileI want to randomize the data file based on the numbers of address filesso I get : I want to do it either in python or in bash , but did n't yet find any solution . <code> 2467135 1.000451...
Pick up lines from a file based on line numbers in another file
Python : Say I have two celery tasks : So when you go to run run_flakey_things it 'll fall over straight away because the first item in the sequence raises an exception . What I would like is to run the task for all items in the sequence in order as map does , but continue to run on exception , raising a new exception ...
How to handle errors in celery 's Task.map
Python : All topics in twitter can be found in this linkI would like to scrape all of them with each of the subcategory inside.BeautifulSoup does n't seem to be useful here . I tried using selenium , but I do n't know how to match the Xpaths that come after clicking the main category.I know I can click the main categor...
How to scrape all topics from twitter
Python : I was recently reading some code online , and saw this block : What is happening here ? Why would True ever not be in globals ? I 've never come across anything like this during my ~10 years as a professional python programmer ! <code> if 'True ' not in globals ( ) : globals ( ) [ 'True ' ] = not None globals ...
Why are True and False being set in globals by this code ?
Python : I 'm trying to implement the fold_by_level SublimeText3 feature on a QScintilla component but I do n't know very well how to do it , so far I 've come up with this code : The docs I 've followed are https : //www.scintilla.org/ScintillaDoc.html # Folding and http : //pyqt.sourceforge.net/Docs/QScintilla2/class...
How to implement SublimeText fold-by-level feature in QScintilla
Python : I have 110 PDFs that I 'm trying to extract images from . Once the images are extracted , I 'd like to remove any duplicates and delete images that are less than 4KB . My code to do that looks like this : This process can take a while , so I 've started to dabble in multithreading . Feel free to interpret that...
How to properly utilize the multiprocessing module in Python ?
Python : Is there any reason x == x is not evaluated quickly ? I was hoping __eq__ would check if its two arguments are identical , and if so return True instantly . But it does n't do it : For built-ins , x == x always returns True I think ? For user-defined classes , I guess someone could define __eq__ that does n't ...
Slow equality evaluation for identical objects ( x == x )
Python : When in a Python interactive session : On the other hand , when running the following program : The output is : Why a is b has different outcome in the above two cases ? I am aware of this answer ( and of course the difference between the == and is operators ! that is the point of the question ! ) but are n't ...
Python not interning strings when in interactive mode ?
Python : I have an array which looks like this for example : I have another two arrays which are like : and What I want is to pick value 2891 from the 2nd array to the first array in the corresponding position and also 643 from the third array to the first array in the corresponding position so that the final array sho...
Python numpy array replacing
Python : I am working on a script that uses itertools to generate desired combinations of given parameters . I am having trouble generating the appropriate 'sets ' however when some variables are linked , i.e . excluding certain combinations . Consider the following : If I want to generate all possible combinations of ...
Python itertools - Create only a subset of all possible products
Python : The code runs successfully offline , however , when uploaded to a code challenge site it gives me a RuntimeError . I am unsure why it is doing this.My code : Note : `` masing-masing '' in English means `` each '' . `` bersisa '' in English means `` remainder '' .Inputting some test input 15 and 3 gives the exp...
Runtime error with python code online , works offline
Python : I have been using PIL ImageI am trying to draw text on an image . I want this text to have a black outline like most memes . I 've attempted to do this by drawing a shadow letter of a bigger font behind the letter in front . I 've adjusted the x and y postions of the shadow accordingly . The shadow is slightly...
Outline text on image in Python
Python : I read a post recently where someone mentioned that there is no need for using enums in python . I 'm interested in whether this is true or not.For example , I use an enum to represent modem control signals : Is n't it better that I use if signal == Signals.CTS : than if signal == `` CTS '' : , or am I missing...
No need for enums
Python : I am writing code to combine functions from the python rawdog RSS reader library and the BeautifulSoup webscraping library . There is a conflict somewhere in the innards that I am trying to overcome . I can replicate the problem with this simplified code : It does not matter what order or where I do the import...
python conflicts in two external packages
Python : Where is the difference when I write something on one line , seperated by a , and on two lines . Apparently I do not understand the difference , because I though the two functions below should return the same.But <code> def fibi ( n ) : a , b = 0 , 1 for i in range ( n ) : a , b = b , a + b return aprint ( fib...
Difference between writing something on one line and on several lines
Python : Given a python list of bytes values : How can the list be broken into chunks where each chunk has the maximum memory size below a certain ceiling ? For example : if the ceiling were 7 bytes , then the original list would be broken up into a list of listsAnd each sublist would be at most 7 bytes , based on accu...
Split a Python List into Chunks with Maximum Memory Size
Python : Is there any alternative to prevent typing repeated long paths while importing modules in python.Current code : I tried following code : But unfortunately it did not work . I can not do from a.b.c.d.e.f.g import * since there might be too many modules within the ref_path.If I am able to do this , I could easil...
Repeated import path patterns in python
Python : I am learning TensorFlow and was implementing a simple neural network as explained in MNIST for Beginners in TensorFlow docs . Here is the link . The accuracy was about 80-90 % , as expected.Then following the same article was MNIST for Experts using ConvNet . Instead of implementing that I decided to improve ...
Why does this neural network learn nothing ?
Python : I 'm doing some matrix operations , sometimes involving matrices whose entries have constant values . But for some reason , I can not get the matrix operation to combine the results into a single polynomial , even when the result is simple . for example , consider the following : The problem with this , is tha...
How to combine polynomials in matrix operations in Sympy ?
Python : I 'm trying to sum +1 to some specific cells of a numpy array but I ca n't find any way without slow loops : Resulting in : X [ coords [ : ,0 ] , coords [ : ,1 ] += 1 returnsAny help ? <code> coords = np.array ( [ [ 1,2 ] , [ 1,2 ] , [ 1,2 ] , [ 0,0 ] ] ) X = np.zeros ( ( 3,3 ) ) for i , j in coords : X [ i , ...
Accumulate constant value in Numpy Array
Python : I have met a snippet of Python 3 code : After I run it , I thought at first that the output should be : But actually the result is : How can this happen ? What happened under the hood ? If I run for i in gen ( ) : print ( i ) , there will be an infinite loop which is what I expected . What is the difference be...
try-finally in Python 3 generator
Python : I am new to Python and trying to build a practice project that reads some XML . For some reason this if statement is triggered even for blank whitespace lines : Any ideas why ? <code> if ' < ' and ' > ' in line :
Legit python if statement ?
Python : I have a script that finds test names and is widely used in our company . It operates on the command line like so : Inside the script is the equivalent of : ( Not sure what all these arguments do , I personally only use the first two ) . These lines are then proceeded by the code that uses these arguments.I wa...
How do I refactor a script that uses argparse to be callable inside another Python script ?
Python : My structure is thus : companynamespace/__init__.py is emptyprojectpackage/__init__.py has this line : When I open up a python console and type import companynamespace.projectpackage ( PYTHONPATH is set correctly for this ) , I get AttributeError : 'module ' object has no attribute 'projectpackage ' on the imp...
Package Import woes in Python
Python : I have found myself many times , with things that I need to be all or at least one equal to something , and I would write something like that : orIf the number of things is small its ok , but it is still not elegant.So , is there a better way for a significant number of things , to do the above ? Thanks . <cod...
How do you use OR , AND in conditionals ?
Python : I 've implemented a python class to generate data as follows : It runs as expected and I get following However , I want to do the same thing for dictionary . Why am I not able to iterate over dictionary like this ? I expect following outputBut when I run above code , I get following error : We can iterate over...
Iterating over dictionary using __getitem__ in python
Python : I have an array of integers of length 150 and the integers range from 1 to 3 . For example , I would like to convert/map/transform Is there an efficient way to do that ? So the outputs is like <code> array ( [ 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1...
Converting an array of integers to a `` vector ''
Python : I am trying to wrap an existing C library using cython . The library uses callbacks which I would like to redirect to execute python code.Lets say that the corresponding line in the header is the following : where the return code is used to signal an error . The API tocreate a corresponding C struct is as foll...
Cython function pointers and exceptions
Python : I have been happily using R for doing data analysis . By data analysis I mean : given a relatively small table ( < 1 mio rows , < 100 columns ) , answer 'complicated ' questions about the data like 'for each instance , what was the last event that happened before a specific point in time varying with the insta...
Simple data operations : R vs python
Python : Let Os be a partially ordered set , and given any two objects O1 and O2 in Os , F ( O1 , O2 ) will return 1 if O1 is bigger than O2 , -1 if O1 is smaller than O2 , 2 if they are incomparable , and 0 if O1 is equal to O2.I need to find the subset Mn of elements is Os that are the minimum . That is for each A in...
Find in a dynamic pythonic way the minimum elements in a partially ordered set
Python : Given an object that can be a nested structure of dict-like or array-like objects . What is the pythonic way to set a value on that object given a dotted path as a string ? Example : The above call/assignment should replace the 3 in the example with a 5.Note : The path can contain list indices as well as keys ...
How to set attribute on an object given a dotted path ?
Python : I have the following function : I 'm running mypy , and it 's telling me that NotImplemented is of type `` Any '' , which it obviously does n't like.Is there any better type I can use to remove this error ? Or should I just put a type : ignore in and move on ? ( In addition , is my use of NotImplemented in the...
What is the type of NotImplemented ?
Python : Found this puzzle inside an image . According to my thinking the total number of ways should be2*comb ( 7 , i ) for i < - 1 to 7 where comb is defined as follows . Is my approach correct ? I am concerned with the result that I get and not the function written below.Do n't mind me asking too many questions in a...
combinatorics implementation and puzzle
Python : The following python code uses PyOpenCL to fill the array a_plus_b with the sum of the elements in array b ( this is n't my actual objective , but it 's the simplest code I can find that still shows the problem ) .Gives the output : However , if I change width from 32 to 33 , the array is no longer the same el...
Why is this opencl code non-deterministic ?
Python : In java , I use the function all the time . Is there an equivalent function in python ? <code> variable = something == 1 ? 1 : 0
Equivalent for ? in Java for Python ?
Python : I have found a similar question here , but the answer does not seem to work for me.I use Flask User ( which extends Flask Login , I believe ) and for the most part it works very well . I have built my own completely fresh templates for sign in and registration , rather than using their provided ones . Followin...
Overriding Flask-User/Flask-Login 's default templates
Python : I have 2-time series data frames . Both contain values [ 0,1 ] only . The first one is called init_signal and the second is called end_signal . The idea is to create a new data frame when init_signal has a 1 , it will find the NEXT 1 in end_signal.The example below merges both the init_signal and end_signal as...
Setting values given two column
Python : The Python docs say that the metaclass of a class can be any callable . All the examples I see use a class . Why not use a function ? It 's callable , and fairly simple to define . But it is n't working , and I do n't understand why.Here 's my code : Here 's the output : The metaclass method is defined for bot...
Why is n't my metaclass function getting invoked for subclasses ?
Python : I have some data stored in a list that I would like to group based on a value.For example , if my data isand I want to group it by the first value in each tuple to gethow would I go about it ? More generally , what 's the recommended way to group data in python ? Is there a recipe that can help me ? <code> dat...
A recipe to group/aggregate data ?
Python : I 'm using argparse to manage command line options , and I want manage two options , -- check and -- nocheck.I 'm actually doing something like this in mybadscript.py : The problem is that if launch the script this way : python mybadscript.py -- nocheck -- checkcheck will be set to False . This is incorrect , ...
How to manage precedence in argparse ?
Python : I want to split a string like : intoWhat 's an elegant way to do this in Python ? If it makes it easier , it can be assumed that the string will only contain a 's , b 's and c 's . <code> 'aaabbccccabbb ' [ 'aaa ' , 'bb ' , 'cccc ' , ' a ' , 'bbb ' ]
Split string into strings of repeating elements
Python : I am trying to generate a 2D vector from a 1D vector where the element is shifted along the row by an increment each row . i would like my input to look like this : im unaware of a way to do this without using a for loop , and computational efficieny is important for the task im using this for . Is there a way...
mapping a 2d delay vector from a 1d vector in numpy
Python : What I 'm trying to do is recursively process a list . I 'm new to python so when all the code was written and sent to be executed I faced a strange problem : the list returns changed after calling the recursive function . To test this I wrote that : And called the function : Here was the result : What I expec...
python : recurcive list processing changes original list
Python : The following code models a system that can sample 3 different states at any time , and the constant transition probability between those states is given by the matrix prob_nor . Threrefore , each point in trace depends on the previous state.The loop in the above code makes it run pretty slow , specially when ...
Vectorize numpy code with operation depending on previous value
Python : I 'm looking for a clean way to do this in Python : Let 's say I have two iterators `` iter1 '' and `` iter2 '' : perhaps a prime number generator , and itertools.count ( ) . I know a priori that both are are infinite and monotonically increasing . Now I want to take some simple operation of two args `` op '' ...
`` sorted 1-d iterator '' based on `` 2-d iterator '' ( Cartesian product of iterators )
Python : this was in a recent test of mine and i just ca n't get list comprehension down . So basically this function was supposed to return the length of the largest list ( which is what i 'm assuming based on the correct answers ) I would have understood that if it were n't for this part of the function : when i see ...
Can you explain the following function ?
Python : I have a dataframe that looks like this : I want to have one bar for old freq and one for new freq . Currently I have graph that looks like this : This is what the code looks like : How do I add another bar ? Explanation about DF : It has frequencies relevant to each hour in a specific date.Edit : One approach...
Plotly : How to animate a bar chart with multiple groups using plotly express ?
Python : I 'm trying to submit a PR for scikit-image , but I get a Travis-CI error : I suppose that this might be a circular import error , but I do n't quite get how to resolve the issue . I 've already included frangi_filter and hessian_filter into filter 's module __init__.py.I 've also tried relative import , which...
Trouble with relative / absolute functions import in scikit-image
Python : I 'm using Python 's `` re '' module as follows : All I 'm doing is getting the HTML of this site , and looking for this particular snippet of code : However , it continues to print an empty array . Why is this ? Why ca n't re.findall find this snippet ? <code> request = get ( `` http : //www.allmusic.com/albu...
Python 's `` re '' module not working ?
Python : I 've been experimenting with Python as a begninner for the past few hours . I wrote a recursive function , that returns recurse ( x ) as x ! in Python and in Java , to compare the two . The two pieces of code are identical , but for some reason , the Python one works , whereas the Java one does not . In Pytho...
Why do these two similar pieces of code produce different results ?
Python : Consider two functions of SymPy symbols e and i : This will produceHowever , assume that e and i are both small and we can neglect both terms that are order three or higher . Using Sympy ’ s series tool or simply adding an O-notation Order class can handle this : Looks great . However , I am still left with mi...
Remove mixed-variable terms in SymPy series expansion
Python : I have a DataFrame : I want to calculate how many times a transition has occurred . Here in the ID column a- > b is considered as a transition , similarly for b- > d , d- > d , d- > a , b- > c , c- > b , b- > a . I can do this using Counter like : I also need to get min and max of the sec column of those trans...
Calculate min and max value of a transition with index of first occurrence in pandas
Python : I 'm relatively new to Python and would like to know if I 'm reinventing a wheel or do things in a non-pythonic way - read wrong.I 'm rewriting some parser originally written in Lua . There is one function which accepts a field name from imported table and its value , does some actions on value and stores it i...
Dictionary based switch-like statement with actions
Python : I 've just upgraded to Canopy 1.7.1 ; I think this problem stems from the change in IPython version from 2.4.1 to 4.1.2.The issue I have is that calling a DataFrame object in Python seems to use the __print__ method , i.e . there 's no difference between typing print df and df into the interpreter , and unfort...
HTML not rendering properly with Canopy 1.7.1.3323 / IPython 4.1.2
Python : When I have to compare the contents of two array-like objects -- for instance lists , tuples or collection.deques -- without regard for the type of the objects , I useIs there any more idiomatic/faster/better way to achieve this ? <code> list ( an_arrayish ) == list ( another_arrayish )
What are the best ways to compare the contents of two list-like objects ?
Python : How can I create a list from another list using python ? If I have a list : How can I create the list of only those letters that follow slash `` / '' i.e.A code would be very helpful . <code> input = [ ' a/b ' , ' g ' , ' c/d ' , ' h ' , ' e/f ' ] desired_output = [ ' b ' , 'd ' , ' f ' ]
How to create a list from another list using specific criteria in Python ?
Python : I am interested in calculating a large NumPy array . I have a large array A which contains a bunch of numbers . I want to calculate the sum of different combinations of these numbers . The structure of the data is as follows : My question is if there is a more elegant and memory efficient way to calculate this...
Vectorize large NumPy multiplication
Python : I implemented exponentially weighted moving average ( ewma ) in python3 and in Haskell ( compiled ) . It takes about the same time . However when this function is applied twice , haskell version slows down unpredictably ( more than 1000 times , whereas python version is only about 2 times slower ) . Python3 ve...
Similar code ( for exponentially weighted deviation ) is slower in Haskell than in Python
Python : I 'm searching for the best algorithm to resolve this problem : having a list ( or a dict , a set ) of small sentences , find the all occurrences of this sentences in a bigger text . The sentences in the list ( or dict , or set ) are about 600k but formed , on average , by 3 words . The text is , on average , ...
Find lots of string in text - Python
Python : I have a ( large ) integer array likewith few unique entries and I 'd like to convert it into a dictionary of indices , i.e. , What 's the most efficient way of doing so ? ( NumPy welcome . ) <code> materials = [ 0 , 0 , 47 , 0 , 2 , 2 , 47 ] # ... d = { 0 : [ 0 , 1 , 3 ] , 2 : [ 4 , 5 ] , 47 : [ 2 , 6 ] , }
Convert array of integers into dictionary of indices
Python : The following reverses a list `` in-place '' and works in Python 2 and 3 : Why/how ? Since reversed gives me an iterator and does n't copy the list beforehand , and since [ : ] = replaces `` in-place '' , I am surprised . And the following , also using reversed , breaks as expected : Why does n't the [ : ] = f...
Why does ` mylist [ : ] = reversed ( mylist ) ` work ?
Python : for convenience I want to create subclasses of datetime.timedelta . The idea is to define a class as such : so I can quickly create timedeltas like that : However , the code above produces a timedelta of n days instead of n hours . As an example , look at the following ipython session : I 'm not able to explai...
Strange behaviour when subclassing datetime.timedelta
Python : I 'm looking to reverse a set of strings while keeping them in the same positions and also trying not to use slicing or reverse ( ) . So if I had : Using the reverse function , it would return : I made a function that does everything correct except for positioning : which returns ; How can I get this reversed ...
Reversing string characters while keeping them in the same position
Python : I 've tried all the solutions mentioned on the internet so far nothing worked for me.I have a python code , to speed it up , I want that my code runs the heavy calculations in a C function.I already wrote this C function.Then , to share the library , I did this in the terminal : which returns no error . The pr...
Using a C function in Python
Python : I 'm writing a metaclass , and I want an additional method to be called between __new__ and __init__ . If I were calling the method before __new__ or after __init__ I could write e.g.My temptation is to writeand just reproduce the functionality of type.__call__ myself . But I 'm afraid there might be some subt...
Does the default type.__call__ do more than call __new__ and __init__ ?
Python : Python 's built-in xml.etree package supports parsing XML files with namespaces , but namespace prefixes get expanded to the full URI enclosed in brackets . So in the example file in the official documentation : The actor tag gets expanded to { http : //people.example.com } actor and fictional : character to {...
How can I make my code more readable and DRYer when working with XML namespaces in Python ?
Python : I would like to write a data converter tool . I need analyze the bitstream in a file to display the 2D cross-sections of a 3D volume.The dataset I am trying to view can be found here : https : //figshare.com/articles/SSOCT_test_dataset_for_OCTproZ/12356705.It 's the file titled : burned_wood_with_tape_1664x512...
Using a Data Converter to Display 3D Volume as Images
Python : Suppose i have a project structure like thisI want to check which file uses a class or a function from another file . I have a class called Test in main.pyI used that class in model_a , But in model_b i usedI want to to check which file uses another file , just like tree command , just a folder name is enough ...
How to check does a file imports from another file in Python
Python : I am trying to send 100 requests at a time to a server http : //httpbin.org/uuid using the following code snippet I am using FastAPI with Asyncio to achieve the lowest time possible around 3 seconds or less but using the above method I am getting an overall time of 66 seconds that is more than a minute . I als...
How can I send an HTTP request from my FastAPI app to another site ?
Python : Why on Earth does n't the interpreter raise SyntaxError everytime I do this : I just wanted to add ' c ' to the list of strings , and forgot to append the comma . I would expect this to cause some kind of error , as it 's cleary incorrect . Instead , what I got : And this is never what I want . Why is it autom...
Problem with list of strings in python