text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
Python : I am getting confused by contradictory explanations of what exactly the term axis means in numpy and how these constructs are numbered.Here 's one explanation : Axes are defined for arrays with more than one dimension.A 2-dimensional array has two corresponding axes : the first running vertically downwards acr... | clear authoritative explanation of numpy axis numbers ? |
Python : I do HTTP requests on Python 3.7 , but if I have some errors during the execution and the script stops , all new HTTP requests ( even after restart the script ) have the errors : [ Errno 10054 ] An existing connection was forcibly closed by the remote host.I have to disable/enable my network , to remove the er... | Existing connection error after script restart |
Python : I would like to use the full width of the 18mm strips in my Brother P950NW printer for an image . At the moment , I am using ESC/P ( not ESC/POS , which this printer does not seem to support ) , but if it 's not possible with that I 'm fine with any other protocol this printer supports . ( Update : with Brothe... | Use full page width with Brother P950NW |
Python : Is there a pythonic way to raise a column in DataFrame ( xRaw ) to consecutive powers ? Is there something like <code> xRaw [ : ,k ] = xRaw.pow ( k ) for k in range ( 1,6 ) | How to raise a column in pandas DataFrame to consecutive powers |
Python : I have a lambda function that I 'd like to add to and make a little more robust . However , I also want to follow PEP 8 and keep my line under 79 characters , correct indention , etc . but am having trouble thinking of how to split up the line.The line is currently : So far , I can get to this : but the third ... | How to break up lambda function in to its own function ? ( Lambda is currently 125+ characters ) |
Python : I 'm doing a simple sparse matrix exponentiation , a**16 , using scipy-0.17 . ( Note , not element-wise multiplication ) . However , on my machines ( running Debian stable and Ubuntu LTS ) this is ten times slower than using a for loop or doing something silly like a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a . This does n... | Scipy sparse matrix exponentiation : a**16 is slower than a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a ? |
Python : Given the following setup : The decorator works as expected : However its __name__ is not double as desired : Is it possible to force the name of the generator ? Alternatively , is it possible to dig around in the generator object and retrieve the name double ? <code> def mapper ( f ) : def wrapper ( items ) :... | Changing the __name__ of a generator |
Python : I have the following dataclass : Is there any way to simplify to_dict method ? I do n't want to list all of the fields using if . <code> @ dataclassclass Image : content_type : str data : bytes = b '' id : str = `` '' upload_date : datetime = None size : int = 0 def to_dict ( self ) - > Dict [ str , Any ] : re... | How to create dict from class without None fields ? |
Python : I currently have 2 buttons hooked up to my Raspberry Pi ( these are the ones with ring LED 's in them ) and I 'm trying to perform this codeOn the surface it looks like a fairly easy script . When a button press is detected : remove the eventsprint the message wait 2 seconds before adding the events and turnin... | Python button functions oddly not doing the same |
Python : I 'm quit new to Python and web-scraping . And I ca n't even achieve the first step of scraping a website : login . Before I try to use mechanize or selenium , I want to use requests first . Can someone help me ? The website I have been trying to log into is here.For those who do n't have an account and want t... | How can I use python request to login this website ? |
Python : I quite often find that this would be useful but I 'm not sure there 's any way to do this . I 'm often working on a python project where I start the project with a virtual environment for the project and a Jupyter notebook . I start adding libraries to the virtual environment as I experiment in the Jupyter no... | Use Python Virtual Environment in Jupyter Notebook |
Python : So Ive been giving the following code in a kind of sort of python class . Its really a discrete math class but he uses python to demonstrate everything . This code is supposed to demonstate a multiplexer and building a xor gate with it.In the xor2 function I dont understand the syntax behind return mux41 ( 0,1... | 2 inputs to a function ? |
Python : I just conducted an interesting test : Obviously , the __iadd__ method is more efficient than the __add__ method , not requiring the allocation of a new class . If my objects being added were sufficiently complicated , this would create unnecessary new objects , potentially creating huge bottlenecks in my code... | Why does n't python take advantage of __iadd__ for sum and chained operators ? |
Python : I have some doubt about python 's class variables . As my understanding , if I define a class variable , which is declared outside the __init__ ( ) function , this variable will create only once as a static variable in C++ . This seems right for some python types , for instance , dict and list type , but for t... | Python Class Variables Question |
Python : I am using Python 2 's cmd module to make a command line for a program . Everything works nicely as long as I do n't add color to my prompt.Working code : When I change my code as below , if I enter a long command or try to search in the command history , some characters stick to my prompt.Problem code : You c... | Some characters stick to my colorized prompt in Python cmd |
Python : I have a DF : OP : I am trying to count the number of people reporting under each person in the column Name.Logic is : Count the number of people reporting individually and people reporting under in the chain . For example with Smith ; John and Caleb reports to Smith so 2 + 1 with Mia reporting to John ( who a... | Multiple aggregated Counting in Pandas |
Python : I want to be able to be able to save or insert programmatically pdb commands , here is a example : So here I am creating a command that will happen on my breakpoint where I will print the text `` Here is my breakpoint ! '' and then continue.Now my problem is that I have to write all that manually every time I ... | insert pdb commands programmatically |
Python : I am trying to convert Tensorflow 's official basic word2vec implementation to use tf.Estimator . The issue is that the loss function ( sampled_softmax_loss or nce_loss ) gives an error when using Tensorflow Estimators . It works perfectly fine in the original implementation . Here 's is Tensorflow 's official... | Converting Tensorflow Graph to use Estimator , get 'TypeError : data type not understood ' at loss function using ` sampled_softmax_loss ` or ` nce_loss ` |
Python : I 'm trying to make a command that makes the bot basically in sleep mode , this is meant to make the bot stop responding to commands ( or on_messages if possible ) Trying to use client.pause ( Boolean ) and it did n't give errors i do n't know what it does exactly but nothing happensBelow is where I am so far ... | How to make bot sleep and stop responding to commands ( or on_messages ) |
Python : I wonder if anyone can offer any ideas or advice on the following coding problem please , where I 'm particularly interested in a fast Python implementation ( i.e . avoiding Pandas ) .I have a ( dummy example ) set of data like : containing data for 2 users ( `` user1 '' and `` user2 '' ) at a given day/place ... | Fast combination of non-unique rows in numpy array , mapped to columns ( i.e . fast pivot table problem , without Pandas ) |
Python : ( Although this question is specifically about Flask , it can be generalised as per the title ) I 'm trying to use Flask 's app.route ( ) decorator inside a class . However , the Flask app is initialised as an instance variable , i.e . self.server is set to the app . This means that I ca n't use the decorator ... | Using a decorator function defined as an instance variable |
Python : How can i change the __cmp__ function of an instance ( not in class ) ? Ex : <code> class foo : def __init__ ( self , num ) : self.num = numdef cmp ( self , other ) : return self.num - other.num # Change __cmp__ function in class worksfoo.__cmp__ = cmpa = foo ( 1 ) b = foo ( 1 ) # returns Truea == b # Change _... | How can i change the __cmp__ function of an instance ( not in class ) ? |
Python : Is there any difference — performance or otherwise — between generator expressions and generator functions ? I 'm asking because I want to decide how I should decide between using the two . Sometimes generator functions are clearer and then the choice is clear . I am asking about those times when code clarity ... | Difference between generator expression and generator function |
Python : I have this code : ... and sometimes , the exception somehow gets raised . How could this ever happen ? Once in a while , several times a day , it returns seemingly random Comment instances . Usually it behaves as expected and returns None.This is the id field of the Comment table : id int ( 11 ) NOT NULL AUTO... | Foo.objects.get ( id=None ) returns Foo instance , sometimes |
Python : I have created a small program which takes an NHL city and then draws the path the team travels throughout their season . The resulting graphic is messy : So I got the idea that it would be interesting if I animated the flight paths , sort of like watching an Indiana Jones movie , where the line grows from one... | How to animate matplotlib 's drawgreatcircle function ? |
Python : Writing some test cases and my mind wanders , assuming there is a better way to write something like this . I have a list , its numbers transition from all odd values to all even , does n't matter where . I need to assert this is the case , here 's what I came up with : Seems like a long way to go . Suggestion... | Pythonic method of determining if a list 's contents change from odd to even values |
Python : I 'm looking at the following piece of code : and ca n't understand what += \ means ? <code> totalDistance += \ GetDistance ( xCoords [ i ] , yCoords [ i ] , xCoords [ i+1 ] , yCoords [ i+1 ] ) | What does placing \ at the end of a line do in python ? |
Python : I have a list that looks like : mot = [ 0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,0,0,0 ] I need to append to a list , the index when the element changes from 0 to 1 ( and not from 1 to 0 ) .I 've tried to do the following , but it also registers when it changes from 1 to 0.Also , but not as import... | How to find the index where values in a list , increase value ? |
Python : I have the following code , which is making me scratch my head - Which yields the following output - Why is n't eq ( ) outputting comparing d to d ( True ) ? The reason I 'm monkey patching __eq__ instead of simply implementing it in my Element class is because I 'm testing how monkey patching works before I i... | Why is my object properly removed from a list when __eq__ is n't being called ? |
Python : I 'm learning python from Think Python by Allen Downey and I 'm stuck at Exercise 6 here . I wrote a solution to it , and at first look it seemed to be an improvement over the answer given here . But upon running both , I found that my solution took a whole day ( ~22 hours ) to compute the answer , while the a... | Exercise 6 of Chapter 12 ( Tuples ) of Think Python by Allen Dwney |
Python : I have random 2d arrays which I make usingI would like to determine if the matrix has two pairs of pairs of rows which sum to the same row vector . I am looking for a fast method to do this . My current method just tries all possibilities.A method that worked for n = 100 would be really great . <code> import n... | Find two pairs of pairs that sum to the same value |
Python : The output produced by running perl -V is packed with useful information ( see example below ) . Is there anything like it for Python ? Example output : Not to be confused with the much less informative perl -v : <code> % perl -VSummary of my perl5 ( revision 5 version 10 subversion 1 ) configuration : Platfor... | What is Python 's equivalent of `` perl -V '' |
Python : I 'm pulling JSON data from an API , with output like this : There are about 250k objects in the list . I am able to iterate through the objects in the list and do an update_one via PyMongo in this way : But with 250k records this takes a long time . I 'm trying to use update_many but ca n't figure out how to ... | PyMongo : How to do bulk update of huge JSON data in MongoDB |
Python : Let 's say I have a module foo and a submodule foo.bar . If I want to use a method in foo.bar , do I need to import foo.bar directly or is importing foo sufficient ? For example , the following throws an error : and the following works : But I 'm not sure if this is generally what 's needed , or if there 's so... | Do I need to import submodules directly ? |
Python : I am perfectly aware of that..This will return True.But what I want to do here is this.I want the return to be True , but this returns False.I can do this : But I am wondering if there is any better or efficient way of doing it . <code> sample= [ [ 1 , [ 1,0 ] ] , [ 1,1 ] ] [ 1 , [ 1,0 ] ] in sample sample= [ ... | How do I search a list that is in a nested list ( list of list ) without loop in Python ? |
Python : I have a database of keywords used in searches by people of different groups . Something like : and so onI want to see which keywords are most characteristic of a given group . I 'm trying to do what OkCupid did in their blog : http : //blog.okcupid.com/index.php/the-real-stuff-white-people-like/Can anyone rec... | Which keywords most distinguish two groups of people ? |
Python : I have the following code I am trying to understand : Can anyone explain how this works ? As far as I have understood , __call__ is what is called when object ( ) is called - calling the object as a function . What I do n't understand is how nums.sort ( key=DistanceFrom ( 10 ) ) . How does this work ? Can anyo... | Understanding __call__ and list.sort ( key ) |
Python : I 'm trying to replicate a simple bitwise Javascript operation in Python . [ Javascript ] [ Python ] Having read the following : Bitwise OR in ruby vs javascriptit sounds like the issue here is that 0xA867Df55 ( 2825379669 ) in Javascript is larger than the largest signed 32-bit int ( 2147483647 ) , which is c... | Replicating Javascript bitwise operation in Python |
Python : There 's a logfile with text in the form of space-separated key=value pairs , and each line was originally serialized from data in a Python dict , something like : The keys are always just strings . The values could be anything that ast.literal_eval can successfully parse , no more no less . How to process thi... | Converting key=value pairs back into Python dicts |
Python : So I have a one liner : All it does is make a Decimal object holding 100.0 , and compares it to .01 ( the float ) in various ways.My result is : From the docs : `` A rich comparison method may return the singleton NotImplemented if it does not implement the operation for a given pair of arguments . `` So reall... | Python 's behavior for rich comparison ( Or , when Decimal ( '100.0 ' ) < .01 ) |
Python : If you put the following into App Engine Shell you get '50.49 ' . This result is consistent on both the 2.5 and 2.7 runtimes.However if I put the same thing into my local MacBook Pro running python 2.7.1 I get '50.48'.Why is this different and how can I get consistency between my local machine and App Engine '... | Why does App Engine show different float rounding results compared to my local machine ? |
Python : I have input of a whole lot of math expressions and equations , and I 'd like to print out latex representation for each on them . So far I have tried Sage and sympy , but the tricky part is to not-reorder terms in expressions.So , if my input is this , something that can be eval-ed in python : I want output t... | python math expressions to latex , verbatim ( no reordering , factoring , etc . ) |
Python : I want to use sort function of python but it does not work well . <code> sorted ( [ ' ا ' , ' ب ' , ' پ ' , ' ح ' , ' س ' , ' ص ' , ' ف ' , ' ک ' , ' ک ' , ' ک ' , ' م ' , ' م ' ] ) = [ ' ا ' , ' ب ' , ' ح ' , ' س ' , ' ص ' , ' ف ' , ' م ' , ' م ' , ' پ ' , ' ک ' , ' ک ' , ' ک ' ] | sort Persian strings for python |
Python : According to the docs : http : //code.google.com/appengine/docs/python/datastore/datamodeling.html # Referencesthe automatically created reverse reference object is a Query object , so there is possible iteration over it and making fetch calls.But : I have one model : and second model : And when I try to acces... | Appengine reverse reference problem |
Python : I have a really simple bit of code , where I have a group of file names and I need to open each one and extract some data to later manipulate.So I 've tried a few different modules to read in excel files , including directly using pandas.read_excel ( ) and this is the optimum method , managing to get the time ... | Speeding Up Excel Data to Pandas |
Python : I have this initial string.And also have a tuple with strings : I want a function so that from the initial string and the tuple with strings I obtain this : I know how to do it imperatively by finding the word in the initial string for every word and then loop character by character in all initial string with ... | String coverage optimization in Python |
Python : I am fairly new to python and I came upon this code to find a single element in a list Here is the code : I just ca n't seem to understand what the line is doing <code> def single_number ( arr ) : ones , twos = 0 , 0 for x in arr : ones , twos = ( ones ^ x ) & ~twos , ( ones & x ) | ( twos & ~x ) assert twos =... | single element in a list |
Python : I understand the pandas docs explain that this is the convention , but I was wondering why ? For example : Returns the following : <code> import pandas as pdimport numpy as npdf = pd.DataFrame ( np.random.randn ( 6,4 ) , index=list ( 'abcdef ' ) , columns=list ( 'ABCD ' ) ) print ( df [ ( df.A < .5 ) | ( df.B ... | Why does pandas use ( & , | ) instead of the normal , pythonic ( and , or ) ? |
Python : I want to extract a number before a specific substring ( `` per cent '' ) I tried to used the split functionExpected result : `` 7.5 '' Actual result : `` The percentage of success for Team A is around 7.5 '' <code> str1= '' The percentage of success for Team A is around 7.5 per cent . What about their season ... | Python Extract a decimal number before a specific substring |
Python : My question is analogous to this one but in the context of importing R to Python via RPy . Specifically , when I runat the beginning of my python script , there is a chunk of message dumped to the screen ( or output device ) , starting with I wanted to implement the quiet_require from here but do n't see how i... | import rpy quietly |
Python : I have 2700 records in MongoDB . Each document has a size of approximately 320KB . The engine I use is wiredTiger and the total size of collection is about 885MB . My MongoDB config is as below : My connection is via socket : And collection stats reveal this result : How can I understand that MongoDB uses swap... | Why 2700 records ( 320KB each ) should take 30 seconds to be fetched ? |
Python : A few years ago , someone posted on Active State Recipes for comparison purposes , three python/NumPy functions ; each of these accepted the same arguments and returned the same result , a distance matrix . Two of these were taken from published sources ; they are both -- or they appear to me to be -- idiomati... | Why Does Looping Beat Indexing Here ? |
Python : After seeing this question and its duplicate a question still remained for me.I get what is and == do and why if I runI get True . The question here would be WHY this happens : So I did my research and I found this . The answer says Python interpreter uses string pooling . So if it sees that two strings are th... | Python Interpreter String Pooling Optimization |
Python : The past days I 've been trying get a better understanding of computational complexity and how to improve Python code . For this I have tried out different functions for calculating Fibonacci numbers , comparing how long the script runs if I make small changes . I 'm calculating Fibonacci numbers using a list ... | Why does computational time decrease when removing unnecessary items from a list in Python |
Python : I am trying to implement my Keras neural network in Go using the tfgo package . The model includes 2 regular inputs and two Keras embedding layers . It looks like this : I 'm trying to load the model in Go , so far I think I 've been able to include the regular input layers like this : But when I run the code ... | Opening Keras model with embedding layer in Tensorflow in Golang |
Python : I 'm trying to convert calculator input to LaTeX . if a user inputs this : I have to convert it to this : however I am having issues with determining when a numerator begins and ends . Any suggestions ? <code> ( 3x^ ( x+ ( 5/x ) + ( x/33 ) ) +y ) / ( 32 + 5 ) frac { 3x^ ( x+frac { 5 } { x } +frac { x } { 33 } ... | determining numerator and denominator in a relatively complex mathematical expression using python |
Python : I would like to create a scrollable screen in text mode , like the one obtained when typing help ( object ) in the interpreter . Is there a cross-platform module I can use to easily implement this ? For example : <code> > > > def jhelp ( object ) : > > > text = # get text for object > > > display_text ( text )... | How to create a scrollable screen in text mode with Python |
Python : When I 'm trying to read data from sqlalchemy df=pd.read_sql_table ( table , con , schema ) getting runtime error : runtime/cgo : could not obtain pthread_keys tried 0x115 0x116 0x117 0x118 0x119 0x11a 0x11b 0x11c 0x11d 0x11e 0x11f 0x120 0x121 0x122 0x123 0x124 0x125 0x126 0x127 0x128 0x129 0x12a 0x12b 0x12c 0... | teradatasql : runtime/cgo : could not obtain pthread_keys |
Python : I have one file of 100GB having 1 to 1000000000000 separated by new line . In this some lines are missing like 5 , 11 , 19919 etc . My Ram size is 8GB.How to find the missing elements.My idea take another file for i in range ( 1,1000000000000 ) read the lines one by one using the generator . can we use yield s... | How to diff the two files using Python Generator |
Python : Why does the following comparison of two variables return ( 1 , False , 2 ) , instead of just True . <code> a = 1b = 2a , b == 1,2 | What is wrong with the comparison a , b == 1,2 ? |
Python : I have a list of objects with a method , say cleanup ( ) , that I need to invoke on all of them . I understand there are at least two ways : orMy question ( s ) : Is one more Pythonic than the other ? Are there other better ways ? I see the former being used often in the code base ( at work ) here , but it bug... | Is it more Pythonic to use map ( ) to call a function on a list , or more traditional iteration ? |
Python : I have a Python script that needs some data that 's stored in a file that will always be in the same location as the script . I have a setup.py for the script , and I want to make sure it 's pip installable in a wide variety of environments , and can be turned into a standalone executable if necessary.Currentl... | Is this the approved way to acess data adjacent to/packaged with a Python script ? |
Python : How do I `` lock '' an object in Python ? Say I have : I 'd modify foo as much as I want : But then I 'd like to be able to `` lock '' it such that when I tryIs that possible in Python ? <code> class Foo : def __init__ ( self ) : self.bar = [ ] self.qnx = 10 foo = Foo ( ) foo.bar.append ( 'blah ' ) foo.qnx = 2... | Lock mutable objects as immutable in python |
Python : Was wondering if anyone had any thoughts on the use of Python 's global vs. referencing the module itself . While in the past I used global when needed , I 've found it somewhat clearer to do the second method ( and recently have tended to favor this syntax ) : Obviously both of them work fine , but if anyone ... | Python 's use of global vs specifying the module |
Python : The following makes sense to me : Given that lists are mutable , I would expect [ ] to be a new empty list object every time it appears in an expression . Using this explanation however , the following surprises me : Why ? What is the explanation ? <code> > > > [ ] is [ ] False id ( [ ] ) == id ( [ ] ) True | When does Python create new list objects for empty lists ? |
Python : I would like to implement the following algorithm . For n and k , consider all combinations with repetitions in sorted order where we choose k numbers from { 0 , ..n-1 } with repetitions . For example , if n=5 and k =3 we have : [ ( 0 , 0 , 0 ) , ( 0 , 0 , 1 ) , ( 0 , 0 , 2 ) , ( 0 , 0 , 3 ) , ( 0 , 0 , 4 ) , ... | How to implement a simple greedy multiset based algorithm in python |
Python : given the following DataFrame , grouped with : I would like to transform it to : So , it moves the diagonal to the beginning of the line and fills the void with zeros.Does panda have any easy way of doing it ? <code> dataset = z.groupby ( [ 'app ' , 'regmonth ' , 'loginsmonth ' ] ) .sum ( ) .unstack ( ) .filln... | Python Pandas : transforming - moving values from diagonal |
Python : I have a class with an attribute that will be a pandas DataFrame ( ) . I 'd like to set up the class such that if any DataFrame ( ) method is called on it , that method will be applied to the DataFrame ( ) .I have set up this scenario already : So I can do this : Out [ 1 ] : 'Charlie'Out [ 2 ] : Empty DataFram... | pass an undefined method call to an attribute containing a different object |
Python : I am extremely new to object-oriented programming , and am trying to begin learning in python by making a simple card game ( as seems to be traditional ! ) . I have done the following example which works fine , and teaches me about making multiple instances of the PlayingCard ( ) class to create an instance of... | A good way to make classes for more complex playing card types than those found in a standard deck ? |
Python : The f-string is one of the new features in Python 3.6.But when I try this : I ca n't figure out why the left curly brace ' { ' remains in the result . I supposed that the result should be same with the str.format : In PEP-0498 it does n't answer this explicitly . So what causes that the left curly brace ' { ' ... | Why does the symbol ' { ' remain when f '' \ { 10 } '' is evaluated in Python 3.6 ? |
Python : I 've been reading through some of the MIT opencourseware quizes and they had a question that goes like this : 6 ) Consider the two functions specified below that are used to play a “ guess a number game. ” Here 's my implementation : And here 's the answer sheet implementation provided by the teacher : This i... | Why is the speed difference between these 2 functions so large ? |
Python : I was wondering , is there a function in Python that returns a dict object that contains nonlocal variables used in enclosing functions ? Like vars ( ) or locals ( ) for local variables or globals ( ) for global ones.Update : As thebjorn noted , nonlocal variables that are actually used in the nested function ... | Is there a way to get a dict object with nonlocal variables ? |
Python : How to express by using list comprehension ? Newbie needs help . Thanks a lot.code below : <code> lst = [ 'chen3gdu',2 , [ 'chengdu ' , 'suzhou ' ] ] result = [ ] for elem in lst : if type ( elem ) == list : for num in elem : result.append ( num ) else : result.append ( elem ) | Python list comprehension for if else statemets |
Python : Why does Python confuse the string `` < stdin > '' with a file matching that filename ? I did n't want Python trying to just read whatever files from my disk if it encountered an unhandled exception . You can also get it with the `` < string > '' filename : Is there any way to prevent that behaviour , or is it... | Why does Python read from the current directory when printing a traceback ? |
Python : On SymPy 0.7.5 ( Python 2.7.8-64-bit ) . I 'm unable to get the constant term from an expression when the constant term is zero or absent ( an absent constant is the same of a zero constant , right ? ) . I can get the constant term from an expression with expr.coeff ( x , 0 ) . E.g . : Now , how can I get 0 in... | sympy : How to get zero for absent constant term |
Python : SetupTwo WSGI servers running locally on different ports . One server returns an html page containing javascript that does a cross-origin ajax request to the other WSGI server using jQuery.origin_server.py Serves the html at http : //localhost:9010.cors_server.py Serves the cross-origin resource that the javas... | Excessive Latency on CORS AJAX Request to Local WSGI Server in Chrome |
Python : I am trying to make an enum-type class in Python but it gets so lengthly when you have to doand I 've tried to set it up like the following , but ended up not working.How would I accomplish this in the simplest way possible ? <code> VARIABLE1 , VARIABLE2 , VARIABLE3 , VARIABLE3 , VARIABLE4 , VARIABLE5 , VARIAB... | Python Multi-lined Artificial enums using range |
Python : I 'm trying to count the number of white dots after thresholding but my code does n't seem to be detecting anythingInput imageMy output is as follows <code> # Standard imports # ! /usr/bin/python # Standard importsimport cv2import numpy as np ; # Read and threshold imageim = cv2.imread ( `` CopperSEM.tif '' , ... | OpenCV blob detector is n't detecting white blobs |
Python : Here is the Website I am trying to scrape http : //livingwage.mit.edu/The specific URLs are from And on each one of these URLs , I need the last row of the second table : Example for http : //livingwage.mit.edu/states/01 Required annual income before taxes $ 20,260 $ 42,786 $ 51,642 $ 64,767 $ 34,325 $ 42,305 ... | Python- > Beautifulsoup- > Webscraping- > Looping over URL ( 1 to 53 ) and saving Results |
Python : I am working on a project that aims to augment the Python socket messages with partial ordering information . The library I 'm building is written in Python , and needs to be interposed on an existing system 's messages sent through the socket functions.I have read some of the resources out there , namely the ... | Why is merging Python system classes with custom classes less desirable than hooking the import mechanism ? |
Python : I have a character string 'aabaacaba ' . Starting from left , I am trying to get substrings of all sizes > =2 , which appear later in the string . For instance , aa appears again in the string and so is the case with ab . I wrote following regex code : and I get [ 'aa ' ] as answer . Regular expression misses ... | regex string and substring |
Python : I had thought that in Python we usually tested whether a default argument was passed by testing the argument with some sort of default value.I ca n't think of any other 'natural ' default value that dict.pop would have used.Is dict.pop using some other means to test for the optional argument ? Or is it using s... | How does dict.pop ( ) detect if an optional argument has been passed ? |
Python : For example , in the code below I would like to obtain the list [ 1,2,3 ] using x as a reference . <code> In [ 1 ] : pasta= [ 1,2,3 ] In : [ 2 ] : pastaOut [ 2 ] : [ 1 , 2 , 3 ] In [ 3 ] : x='pas'+'ta'In [ 4 ] : xOut [ 4 ] : 'pasta ' | How can I use a string with the same name of an object in Python to access the object itself ? |
Python : I was trying to experimentally determine Python 's maximum recursion depth with the following code : But when I ran it , this happened : Why is my program not exiting right away when it encountered RuntimeError the first time , but continued to run for 5 more calls to recursive ( ) ? <code> def recursive ( i )... | While testing python max recursion depth , why am I hitting RuntimeError multiple times ? |
Python : I just noticed something surprising . Consider the following example : When we run this , we rightfully receive the following warning : asyncio.sleep ( n ) This is because in wait_n we called asyncio.sleep ( n ) without await.But now consider the second example : This time we are using a lambda and surprisingl... | What mechanism makes Python lambdas work without await keyword ? |
Python : I am outputting content from my models to my templates , however some model fields call data stored in other models . This happens only in a few fields . I am wondering whether using an if tag to evaluate this would be more efficient compared to storing the django tags inside the models . Answers to this quest... | Storing and escaping Django tags and filters in Django models |
Python : Before anyone starts in , I know that talking about `` speed '' in a programming language is n't always the most ... useful discussion . That said , speed is the issue here.I tackled Project Euler problem 5 in both languages and , while my implementations in both languages look fairly similar to my eye , the r... | How can I make this Project Euler solution execute in Python at the same speed as Java ? |
Python : When I try to print an unicode string on my dev server it works correctly but production server raises exception.Actually it is twisted application and print forwards to log file.repr ( ) of strings are the same . Locale set to en_US.UTF-8.Are there any configs I need to check to make it work the same on the b... | Python print works differently on different servers |
Python : Something weird happens in this code : romeo.txt is taken from http : //www.pythonlearn.com/code/romeo.txtResult : As you can see , there are two 'the ' . Why is that ? I can run this part of code again : After running this code a second time it deletes the remaining 'the ' , but why does n't it work the first... | Why does 'the ' survive after .remove ? |
Python : I 've generated a list of combinations , using itertools and I 'm getting a result that looks like this : What is the most time-complexity wise efficient way of removing unordered duplicates , such as x [ 0 ] and x [ 1 ] are the duplicates . Is there anything built in to handle this ? My general approach would... | What is the most time efficient way to remove unordered duplicates in a 2D array ? |
Python : I 'm relatively new to Python and I was interested in finding out the simplest way to create an enumeration.The best I 've found is something like : Which sets APPLE to 0 , BANANA to 1 , etc.But I 'm wondering if there 's a simpler way . <code> ( APPLE , BANANA , WALRUS ) = range ( 3 ) | What 's the cleanest way to set up an enumeration in Python ? |
Python : I have the following DataFrame that uses a three-level MultiIndex : I 'd like to slice the index such that I keep all of the first level while only keeping the following combinations of the second two levels : ( 'foo ' , 'one ' ) and ( 'bar ' , 'two ' ) . That is , I 'd like my output to look something like th... | Pandas DataFrame - How to retrieve specific combinations of MultiIndex levels |
Python : I 'm trying to keep a dictionary of open files for splitting data into individual files . When I request a file from the dictionary I would like it to be opened if the key is n't there . However , it does n't look like I can use a lambda as a default.e.g.This does n't work because f is set to the function , ra... | is it possible to use a lambda as a dictionary default ? |
Python : I know there are already other posts about this out there , but my movement system is a little from the ones that I have found , so subsequently I am asking this question.My movement system is based on a named tuple called Move ( up , left , right , down ) Then there is this : I tried adding a fifth variable t... | Pygame : Can someone help me implement double jumping ? |
Python : I often keep track of duplicates with something like this : I am dealing with massive amounts of data so do n't want to maintain the processed set in memory . I have a version that uses sqlite to store the data on disk , but then this process runs much slower.To cut down on memory use what do you think of usin... | python data type to track duplicates |
Python : I am using the splinter 0.7.3 module in python 2.7.2 on a Linux platform to scrape a directory listing on a website using the default Firefox browser.This is the snippet of code that iterates through the paginated web listing by clicking the 'Next ' link in the html.I know that the links are working , as I am ... | Splinter saves bodiless html |
Python : I 've written a script in Python in association with selenium to click on each of the signs available in a map . However , when I execute my script , it throws timeout exception error upon reaching this line wait.until ( EC.staleness_of ( item ) ) . Before hitting that line , the script should have clicked onc... | Unable to click on signs on a map |
Python : I 'm working on a small program displaying moving rowing boats . The following shows a simple sample code ( Python 2.x ) : As you can see a boat has a pace and rows with a number of strokes per minute . Everytime the method move ( deltaT ) is called it moves a certain distance according to the pace.The above b... | Code to resemble a rowing stroke |
Python : I have encountered the following function in MATLAB that sequentially flips all of the dimensions in a matrix : Where X has dimensions ( M , N , P ) = ( 24,24,100 ) . How can I do this in Python , given that X is a NumPy array ? <code> function X=flipall ( X ) for i=1 : ndims ( X ) X = flipdim ( X , i ) ; ende... | How do you sequentially flip each dimension in a NumPy array ? |
Python : I just play around with Python and found just interesting thing : my computer ( i5 , 3 GHz ) just hang out after several hours of attempting to compute 10 ** 10 ** 10 . I know Math is n't a purpose Python was created for , but I wonder is n't there a way to help Python to compute it . What I have so far is my ... | n**n**n heuristics in Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.