lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | 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 across rows ... | > > > b = np.arange ( 12 ) .reshape ( 3,4 ) > > > barray ( [ [ 0 , 1 , 2 , 3 ] , [ 4 , 5 , 6 , 7 ] , [ 8 , 9 , 10 , 11 ] ] ) | 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 error . It ... | import requestsimport jsonimport urllib.requestimport socket if __name__ == '__main__ ' : params = json.dumps ( { `` toto '' : `` ABCD '' } ) .encode ( 'utf-8 ' ) try : head = { 'content-type ' : 'application/json ' } # replace http by https , to generate the error , re-writte http , and it will never work again url = ... | 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 Brother 's Wind... | import socketimport structdef escp ( density_code=72 ) : stack_size_in_bytes = { 72 : 6 } [ density_code ] height = 200 width = 130 yield b'\x1bia\x00 ' # ESC/P command mode : ESC/P standard yield b'\x1b @ ' # Initialize yield b'\x1bim\x00\x00 ' # margin : 0 yield b'\x1biXE2\x00\x00\x00 ' # barcode margin : 0 yield b'\... | 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 | 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 line ( if... | styled_df = df.style.apply ( lambda x : [ `` background : rgba ( 255,0,0 , .3 ) '' if ( 'BBC ' in x [ 'newsSource ' ] or 'Wall ' in x [ 'newsSource ' ] ) and idx==0 else `` '' for idx , v in enumerate ( x ) ] , axis = 1 ) styled_df = df.style.apply ( lambda x : [ `` background : rgba ( 255,0,0 , .3 ) '' if ( 'BBC ' in ... | 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't make s... | import scipy.sparsefrom time import timea=scipy.sparse.rand ( 2049,2049 , .002 ) print ( `` Trying exponentiation ( a**16 ) '' ) t=time ( ) x=a**16print ( repr ( x ) ) print ( `` Exponentiation took % f seconds\n '' % ( time ( ) -t ) ) print ( `` Trying expansion ( a*a*a* ... *a*a ) '' ) t=time ( ) y=a*a*a*a*a*a*a*a*a*... | 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 ? | def mapper ( f ) : def wrapper ( items ) : for x in items : yield f ( x ) wrapper.__name__ = f.__name__ # This has no effect ! return wrapper @ mapperdef double ( x ) : return x * 2 > > > [ x for x in double ( [ 1,2,3 ] ) ] [ 2 , 4 , 6 ] > > > double ( [ 1,2 ] ) .__name__ '' wrapper '' | 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 . | @ dataclassclass Image : content_type : str data : bytes = b '' id : str = `` '' upload_date : datetime = None size : int = 0 def to_dict ( self ) - > Dict [ str , Any ] : result = { } if self.id : result [ 'id ' ] = self.id if self.content_type : result [ 'content_type ' ] = self.content_type if self.size : result [ '... | 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 turning the LED... | # ! /usr/bin/env pythonimport RPi.GPIO as GPIOimport timeGPIO.setmode ( GPIO.BCM ) GPIO.setwarnings ( False ) GPIO.setup ( 17 , GPIO.OUT ) # green LEDGPIO.setup ( 18 , GPIO.OUT ) # red LEDGPIO.setup ( 4 , GPIO.IN , GPIO.PUD_UP ) # green buttonGPIO.setup ( 27 , GPIO.IN , GPIO.PUD_UP ) # red buttondef remove_events ( ) :... | 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 to help me... | import requestss = requests.Session ( ) headers = { 'User-Agent ' : 'Mozilla/5.0 ( Windows NT 10.0 ; Win64 ; x64 ) AppleWebKit/537.36 ( KHTML , like Gecko ) Chrome/59.0.3071.115 Safari/537.36 ' } payload = { 'username ' : 'USERNAME ' , 'password ' : 'PASSWORD ' , 'submit.x ' : '21 ' , 'submit.y ' : '12 ' } s.post ( 'ht... | 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 notebook . ... | pip freeze > requirements.txt | 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,1,0 ) ( ... | def mux41 ( i0 , i1 , i2 , i3 ) : return lambda s1 , s0 : { ( 0,0 ) : i0 , ( 0,1 ) : i1 , ( 1,0 ) : i2 , ( 1,1 ) : i3 } [ ( s1 , s0 ) ] def xor2 ( a , b ) : return mux41 ( 0,1,1,0 ) ( a , b ) | 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 . I woul... | ~ $ python3 # I also conducted this on python 2.7.6 , with the same resultPython 3.4.0 ( default , Apr 11 2014 , 13:05:11 ) [ GCC 4.8.2 ] on linuxType `` help '' , `` copyright '' , `` credits '' or `` license '' for more information. > > > class Foo ( object ) : ... def __add__ ( self , other ) : ... global add_calls ... | 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 those base... | class A : dict1= { } list1=list ( ) int1=3 def add_stuff ( self , k , v ) : self.dict1 [ k ] =v self.list1.append ( k ) self.int1=k def print_stuff ( self ) : print self.dict1 , self.list1 , self.int1a1 = A ( ) a1.add_stuff ( 1 , 2 ) a1.print_stuff ( ) a2=A ( ) a2.print_stuff ( ) { 1 : 2 } [ 1 ] 1 { 1 : 2 } [ 1 ] 3 | 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 can see th... | from cmd import Cmdclass App ( Cmd ) : def __init__ ( self ) : Cmd.__init__ ( self ) self.prompt = `` PG [ `` + ( str ( 'username ' ) , 'green ' ) + '' @ '' + str ( 'hostname ' ) + '' ] : `` def do_exit ( self , line ) : `` ' `` ' return TrueApp ( ) .cmdloop ( ) from cmd import Cmdclass App ( Cmd ) : def __init__ ( sel... | 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 already re... | data = [ [ `` John '' , '' 144 '' , '' Smith '' , '' 200 '' ] , [ `` Mia '' , '' 220 '' , '' John '' , '' 144 '' ] , [ `` Caleb '' , '' 155 '' , '' Smith '' , '' 200 '' ] , [ `` Smith '' , '' 200 '' , '' Jason '' , '' 500 '' ] ] data_frame = pd.DataFrame ( data , columns = [ `` Name '' , '' ID '' , '' Manager_name '' ,... | 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 want to h... | ( Pdb ) b doc/filename.py:365 Breakpoint 1 at doc/filename.py:365 ( Pdb ) commands # command to be applied to all breaks ( com ) silent # makes it not print the break message ( com ) print `` Here is my breakpoint ! `` ( com ) c # continues without stopping on break | 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 basic wo... | batch_size = 128embedding_size = 128 # Dimension of the embedding vector.skip_window = 1 # How many words to consider left and right.num_skips = 2 # How many times to reuse an input to generate a label.num_sampled = 64 # Number of negative examples to sample.def my_model ( features , labels , mode , params ) : with tf.... | 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 . | @ client.command ( pass_context=True ) async def sleep ( ctx ) : client.pause = True @ client.command ( pass_context=True ) async def awake ( ctx ) : client.pause = False | 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 , where t... | | User | Day | Place | Foo | Bar | 1 10 5 True False 1 11 8 True False 1 11 9 True False 2 11 9 True False 2 12 1 False True 1 12 2 False True | Day | Place | User 1 Foo | User 1 Bar | User 2 Foo | User 2 Bar | 11 9 True False True False user = np.array ( [ 1 , 1 , 1 , 2 , 2 , 1 ] , dtype=int ) day = np.array ( [ 10 , ... | 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 , as self... | class MyClass : def __init__ ( self ) : self.server = Flask ( __name__ ) @ self.server.route ( '/ ' ) def home ( ) : return ' < h1 > Success < /h1 > ' | Using a decorator function defined as an instance variable |
Python | How can i change the __cmp__ function of an instance ( not in class ) ? Ex : | 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 __cmp__ function in instance that way doesnt workdef cmp2 ( self , other ) : return -1a.__cmp_... | 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 does not ... | In [ 1 ] : def f ( ) : ... : yield from range ( 4 ) ... : In [ 2 ] : def g ( ) : ... : return ( i for i in range ( 4 ) ) ... : In [ 3 ] : f ( ) Out [ 3 ] : < generator object f at 0x109902550 > In [ 4 ] : list ( f ( ) ) Out [ 4 ] : [ 0 , 1 , 2 , 3 ] In [ 5 ] : list ( g ( ) ) Out [ 5 ] : [ 0 , 1 , 2 , 3 ] In [ 6 ] : g (... | 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_INCREMEN... | try : parent_comment = models.Comment.all_objects.get ( id=parent_comment_id ) except models.Comment.DoesNotExist : parent_comment = Noneif parent_comment is not None and parent_comment_id is None : raise Exception ( `` WTF django/mysql '' ) SELECT ` canvas_comment ` . ` id ` , ` canvas_comment ` . ` visibility ` , ` c... | 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 point to... | import matplotlib.pyplot as pltfrom mpl_toolkits.basemap import Basemapfig = plt.figure ( figsize= ( 10 , 10 ) ) m = Basemap ( projection='merc ' , resolution=None , llcrnrlon=-125 , llcrnrlat=25 , # LL = lower left urcrnrlon=-60 , urcrnrlat=55 ) # UR = upper right m.etopo ( scale=0.5 , alpha=0.5 ) # Ottawa to Anaheim ... | 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 . Suggestions on how ... | values = [ 1 , 3 , 5 , 7 , 5 , 3 , 5 , 3 , 5 , 7 , 4 , 6 , 8 , 4 , 2 , 2 , 8 , 6 ] # find all the indexes of odd and even valuesodds = [ i for ( i , v ) in enumerate ( values ) if v % 2 == 1 ] evens = [ i for ( i , v ) in enumerate ( values ) if v % 2 == 0 ] # indexes should be a continuous sequence : 0 , 1 , 2 , 3 ...... | 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 ? | 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 important , is ... | i = 0 while i ! = len ( mot ) -1 : if mot [ i ] ! = mot [ i+1 ] : mot_daily_index.append ( i ) i += 1 | 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 implement ... | class Element : def __init__ ( self , name ) : self.name = name def __repr__ ( self ) : return self.namedef eq ( self , other ) : print ( 'comparing { } to { } ( { } ) '.format ( self.name , other.name , self.name == other.name ) ) return self.name == other.nameElement.__eq__ = eqelements = [ Element ( ' a ' ) , Elemen... | 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 author 's ... | known_red = { 'sprite ' : 6 , ' a ' : 1 , ' i ' : 1 , `` : 0 } # Global dict of known reducible words , with their length as valuesdef compute_children ( word ) : `` '' '' Returns a list of all valid words that can be constructed from the word by removing one letter from the word '' '' '' from dict_exercises import wor... | 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 . | import numpy as npfrom itertools import combinationsn = 50A = np.random.randint ( 2 , size= ( n , n ) ) for pair in combinations ( combinations ( range ( n ) , 2 ) , 2 ) : if ( np.array_equal ( A [ pair [ 0 ] [ 0 ] ] + A [ pair [ 0 ] [ 1 ] ] , A [ pair [ 1 ] [ 0 ] ] + A [ pair [ 1 ] [ 1 ] ] ) ) : print `` Pair found ''... | 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 : | % perl -VSummary of my perl5 ( revision 5 version 10 subversion 1 ) configuration : Platform : osname=linux , osvers=2.6.32-5-amd64 , archname=x86_64-linux-gnu-thread-multi uname='linux brahms 2.6.32-5-amd64 # 1 smp tue jun 14 09:42:28 utc 2011 x86_64 gnulinux ' config_args='-Dusethreads -Duselargefiles -Dccflags=-DDEB... | 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 properly ... | [ [ { 'employeeId ' : 1 , 'lastName ' : 'Smith ' } , { 'employeeId ' : 2 , 'lastName ' : 'Flores ' } ] ] json_this = json.dumps ( json_list [ 0 ] ) json_that = json.loads ( json_this ) for x in json_that : collection.update_one ( { `` employeeId '' : x [ 'employeeId ' ] } , { `` $ set '' : x } , upsert=True ) | 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 something w... | import foofoo.bar.my_method ( ) import foo.barfoo.bar.my_method ( ) | 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 . | sample= [ [ 1 , [ 1,0 ] ] , [ 1,1 ] ] [ 1 , [ 1,0 ] ] in sample sample= [ [ 1 , [ 1,0 ] ] , [ 1,1 ] ] [ 1,0 ] in sample sample= [ [ 1 , [ 1,0 ] ] , [ 1,1 ] ] for i in range ( len ( sample ) ) : [ 1,0 ] in sample [ i ] | 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 recommend su... | group1person1 : x , y , zgroup1person2 : x , z , d ... group2person1 : z , d , l ... | 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 anyone please... | > > > class DistanceFrom ( object ) : def __init__ ( self , origin ) : self.origin = origin def __call__ ( self , x ) : return abs ( x - self.origin ) > > > nums = [ 1 , 37 , 42 , 101 , 13 , 9 , -20 ] > > > nums.sort ( key=DistanceFrom ( 10 ) ) > > > nums [ 9 , 13 , 1 , 37 , -20 , 42 , 101 ] | 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 causing an... | > 0xA867Df55 2825379669 > 0xA867Df55 ^ 0 -1469587627 > > > 0xA867DF552825379669L > > > 0xA867DF55 ^ 02825379669L > > > ( 0xA867DF55 & 0x1FFFFFFF ) ^ 0141025109L | 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 this logfile... | ' '.join ( [ f ' { k } = { v ! r } ' for k , v in d.items ( ) ] ) > > > to_dict ( `` key='hello world ' '' ) { 'key ' : 'hello world ' } > > > to_dict ( `` k1='v1 ' k2='v2 ' '' ) { 'k1 ' : 'v1 ' , 'k2 ' : 'v2 ' } > > > to_dict ( `` s='1234 ' n=1234 '' ) { 's ' : '1234 ' , ' n ' : 1234 } > > > to_dict ( `` '' '' k4='k5=... | 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 really there a... | import decimal ; h = decimal.Decimal ( '100.0 ' ) ; ( h > .01 , h < .01 , h.__gt__ ( .01 ) , h.__lt__ ( .01 ) ) > > > import decimal ; h = decimal.Decimal ( '100.0 ' ) ; ( h > .01 , h < .01 , h.__gt__ ( .01 ) , h.__lt__ ( .01 ) ) ( False , True , NotImplemented , NotImplemented ) from decimal import Decimalh = Decimal ... | 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 's servers... | > > a = ' % 0.2f ' % ( round ( float ( u'50.485 ' ) , 2 ) , ) > > a'50.49 ' > > a = ' % 0.2f ' % ( round ( float ( u'50.485 ' ) , 2 ) , ) > > a'50.48 ' | 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 that will ... | ( C - A*x ) / B \frac { C - A x } { B } \frac { - ( A x - C ) } { B } \frac { 1 } { B } ( C - A x ) etc ... sage : var ( ' A B C x y ' ) ( A , B , C , x , y ) sage : latex ( y == ( C - A*x ) / B ) y = -\frac { A x - C } { B } > > > from sympy import * > > > x = Symbol ( ' x ' ) > > > A = Symbol ( ' A ' ) > > > B = Symb... | 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 . | 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 access reverse... | class User ( db.Model ) : name = db.StringProperty ( ) ... class Thing ( db.Model ) : owner = db.ReferenceProperty ( User ) ... for thing in user.thing_set : ... user.thing_set.fetch ( 100 ) < type 'exceptions.TypeError ' > : '_ReverseReferenceProperty ' object is not iterable < type 'exceptions.AttributeError ' > : '_... | 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 to open t... | for file in unique_file_names [ 1 : ] : file_name = rootdir + `` / '' + str ( file ) test_time = time.clock ( ) try : wb_loop = load_workbook ( file_name , read_only=True , data_only=True ) ws_loop = wb_loop [ `` SHEET1 '' ] df = pd.DataFrame ( ws_loop.values ) print ( `` Opening Workbook : `` , time.clock ( ) -test_ti... | 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 replaced ... | 'bananaappleorangestrawberryapplepear ' ( 'apple ' , 'plepe ' , 'leoran ' , 'lemon ' ) 'bananaxxxxxxxxxgestrawberryxxxxxxxar ' | 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 | def single_number ( arr ) : ones , twos = 0 , 0 for x in arr : ones , twos = ( ones ^ x ) & ~twos , ( ones & x ) | ( twos & ~x ) assert twos == 0 return onesarr1 = [ 5 , 3 , 4 , 3 , 5 , 5 , 3 ] print ( single_number ( arr1 ) ) ones , twos = ( ones ^ x ) & ~twos , ( ones & x ) | ( twos & ~x ) assert twos==0 | 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 : | 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 > .5 ) ] ) print ( df [ ( df.A < .5 ) or ( df.B > .5 ) ] ) A B C Da -0.284669 -0.277413 2.524311 -1.386008b -0.190307 0.325620 -0.367727 0.347600c ... | 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 '' | str1= '' The percentage of success for Team A is around 7.5 per cent . What about their season ? `` print ( str1.split ( `` per cent '' ,1 ) [ 0 ] ) | 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 it fits in... | from rpy import * Parsing output : R version 2.13.2 ( 2011-09-30 ) Copyright ( C ) 2011 The R Foundation for Statistical Computing ... ... | 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 ? How to... | systemLog : destination : file path : /usr/local/var/log/mongodb/mongo.log logAppend : truestorage : dbPath : /usr/local/var/mongodb engine : wiredTiger wiredTiger : engineConfig : cacheSizeGB : 1 statisticsLogDelaySecs : 0 journalCompressor : snappy collectionConfig : blockCompressor : snappy indexConfig : prefixCompr... | 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 -- idiomatic numpy c... | from numpy.matlib import repmat , repeatdef calcDistanceMatrixFastEuclidean ( points ) : numPoints = len ( points ) distMat = sqrt ( sum ( ( repmat ( points , numPoints , 1 ) - repeat ( points , numPoints , axis=0 ) ) **2 , axis=1 ) ) return distMat.reshape ( ( numPoints , numPoints ) ) from numpy import mat , zeros , ... | 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 the same , ... | a = `` ab '' b = `` ab '' a == b a = `` ab '' b = `` ab '' a is b # Returns True a = `` ab '' b = `` ab '' a is b # Returns True , as expected knowing Interpreter uses string poolinga = `` a_b '' b = `` a_b '' a is b # Returns True , again , as expected knowing Interpreter uses string poolinga = `` a b '' b = `` a b ''... | 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 , adding ... | import timeimport numpy as npdef fib_stack1 ( n ) : `` '' '' Original function `` '' '' assert type ( n ) is int , 'Expected an integer as input . ' if n < 2 : return n else : stack = [ 0 , 1 ] for i in range ( n-1 ) : stack.append ( stack [ -1 ] + stack [ -2 ] ) return stack [ -1 ] def fib_stack2 ( n ) : `` '' '' Modi... | 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 , it remi... | embedding_layer = Embedding ( vocab_size , 100 , weights= [ embedding_matrix ] , input_length=100 , trainable=False ) sequence_input = Input ( shape= ( max_length , ) , dtype='int32 ' ) embedded_sequences = embedding_layer ( sequence_input ) text_lstm = Bidirectional ( LSTM ( 256 ) ) ( embedded_sequences ) text_lstm = ... | 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 ? | ( 3x^ ( x+ ( 5/x ) + ( x/33 ) ) +y ) / ( 32 + 5 ) frac { 3x^ ( x+frac { 5 } { x } +frac { x } { 33 } ) +y } { 32 + 5x } | 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 : | > > > def jhelp ( object ) : > > > text = # get text for object > > > display_text ( text ) # display a scrollable screen . How do I do this ? > > > > > > l = [ 1,2,3 ] > > > jhelp ( l ) | 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 0x12d 0x12... | class TeradataWriter : def __init__ ( self ) : print ( `` in init '' ) def read_data_from_teradata ( self ) : try : print ( 'Create main ' ) import pdb ; pdb.set_trace ( ) eng = self.create_connection_engine ( ) df = pd.read_sql_table ( `` table_name '' , eng , schema= '' schema '' ) print ( df ) except Exception as ex... | 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 statement ... | def difference ( a , b ) : with open ( a , ' r ' ) as f : aunique=set ( f.readlines ( ) ) with open ( b , ' r ' ) as f : bunique=set ( f.readlines ( ) ) with open ( ' c ' , ' a+ ' ) as f : for line in list ( bunique - aunique ) : f.write ( line ) | 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 . | 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 bugs me that... | map ( lambda x : x.cleanup ( ) , _my_list_of_objects ) for x in _my_list_of_objects : x.cleanup ( ) | 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.Currently the scr... | def fetch_wordlist ( ) : wordlist = 'wordlist.txt ' try : import importlib.resources as res return res.read_binary ( __file__ , wordlist ) except ImportError : pass try : import pkg_resources as resources req = resources.Requirement.parse ( 'makepw ' ) wordlist = resources.resource_filename ( req , wordlist ) except Im... | 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 ? | class Foo : def __init__ ( self ) : self.bar = [ ] self.qnx = 10 foo = Foo ( ) foo.bar.append ( 'blah ' ) foo.qnx = 20 lock ( foo ) foo.bar.append ( 'blah ' ) # raises some exception.foo.qnx = 20 # raises some exception . | 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 has any s... | import sysmod = sys.modules [ __name__ ] counter = 0def incrementGlobal ( ) : global counter counter += 1def incrementMod ( ) : mod.counter += 1 | 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 ? | > > > [ ] 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 ) , ( 0 , 1 ,... | ( 0 , 0 , 0 ) , ( 0 , 0 , 1 ) , ( 0 , 0 , 2 ) , ( 0 , 0 , 3 ) , ( 0 , 0 , 4 ) ( 0 , 1 , 1 ) , ( 0 , 1 , 2 ) , ( 0 , 1 , 3 ) , ( 0 , 1 , 4 ) ( 0 , 2 , 2 ) , ( 0 , 2 , 3 ) , ( 0 , 2 , 4 ) ( 0 , 3 , 3 ) , ( 0 , 3 , 4 ) ( 0 , 4 , 4 ) import itertoolsfor multiset in itertools.combinations_with_replacement ( range ( 5 ) ,3 )... | 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 ? | dataset = z.groupby ( [ 'app ' , 'regmonth ' , 'loginsmonth ' ] ) .sum ( ) .unstack ( ) .fillna ( 0 , inplace=False ) cnt loginsmonth 2014-02-01 2014-03-01 2014-04-01 2014-05-01 app regmonth 1 2014-02-01 6069 1837 107 54 2014-03-01 0 10742 2709 1394 2014-04-01 0 0 5584 1107 2014-05-01 0 0 0 3044 2014-06-01 0 0 0 0 cnt ... | 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 DataFrame ( ) I d... | import pandas as pdclass A ( object ) : def __init__ ( self ) : self.df = pd.DataFrame ( ) self.name = 'Charlie ' def get_name ( self ) : return self.name def head ( n=5 ) : return self.df.head ( n ) a = A ( ) a.get_name ( ) a.head ( ) | 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 the Deck... | class PlayingCard ( object ) : def __init__ ( self , suit , val ) : self.suit = suit self.value = val def print_card ( self ) : print ( `` { } of { } '' .format ( self.value , self.suit ) ) class Deck ( object ) : def __init__ ( self ) : self.playingcards = [ ] self.build ( ) def build ( self ) : for s in [ `` Spades '... | 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 ' { ' to remain... | > > > f '' \ { 10 } '' '\\ { 10 ' > > > `` \ { } '' .format ( 10 ) '\\10 ' | 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 is the cmp... | def cmpGuess ( guess ) : '' '' '' Assumes that guess is an integer in range ( maxVal ) . returns -1 if guess is < than the magic number , 0 if it is equal to the magic number and 1 if it is greater than the magic number . `` `` '' def findNumber ( maxVal ) : '' '' '' Assumes that maxVal is a positive integer . Returns ... | 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 are inclu... | > > > def func1 ( ) : ... x=33 ... def func2 ( ) : ... # Without the next line prints { } ... print ( x ) ... print ( locals ( ) ) ... func2 ( ) ... > > > func1 ( ) | 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 : | 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 hardcode... | $ echo `` Your code is bad and you should feel bad '' > `` < stdin > '' $ pythonPython 3.6.0 ( default , Dec 28 2016 , 19:53:26 ) [ GCC 4.8.5 20150623 ( Red Hat 4.8.5-11 ) ] on linuxType `` help '' , `` copyright '' , `` credits '' or `` license '' for more information. > > > 2 + ' 2'Traceback ( most recent call last )... | 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 these ca... | isympy # # Load sympy etc ... ( x + 3 ) .coeff ( x , 0 ) # - > 3 ok ( x ) .coeff ( x , 0 ) # - > 0 ok ( 4*x**2 + 3*x ) .coeff ( x , 0 ) # - > 0 ok ( 4*x ) .coeff ( x , 0 ) # - > 4 ( 4*x**2 ) .coeff ( x , 0 ) # - > 4 why not 0 ? ! pythonPython 2.7.8 ( default , Sep 14 2014 , 18:20:38 ) [ GCC 4.2.1 ( Apple Inc. build 566... | 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 javascript wil... | # ! /usr/bin/env pythonfrom wsgiref.simple_server import make_serverdef origin_html ( environ , start_response ) : status = '200 OK ' response_headers = [ ( 'Content-Type ' , 'text/html ' ) ] start_response ( status , response_headers ) f = open ( './index.html ' , 'rb ' ) return [ f.read ( ) ] httpd = make_server ( 'l... | 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 ? | VARIABLE1 , VARIABLE2 , VARIABLE3 , VARIABLE3 , VARIABLE4 , VARIABLE5 , VARIABLE6 , VARIABLE7 , VARIABLE8 , ... , VARIABLE14 = range ( 14 ) VARIABLE1 , VARIABLE2 , VARIABLE3 , ... VARIABLE14 = range ( 14 ) | 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 | # Standard imports # ! /usr/bin/python # Standard importsimport cv2import numpy as np ; # Read and threshold imageim = cv2.imread ( `` CopperSEM.tif '' , cv2.IMREAD_GRAYSCALE ) ret2 , LocalTH1 = cv2.threshold ( im,0,255 , cv2.THRESH_BINARY+cv2.THRESH_OTSU ) # Without Filtering # Set up the detector with default paramet... | 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 $ 47,345 ... | http : //livingwage.mit.edu/states/01http : //livingwage.mit.edu/states/02http : //livingwage.mit.edu/states/04 ( For some reason they skipped 03 ) ... all the way to ... http : //livingwage.mit.edu/states/56 import requests , bs4res = requests.get ( 'http : //livingwage.mit.edu/states/01 ' ) res.raise_for_status ( ) s... | 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 answer by... | class vector_clock : def __init__ ( self ) : `` '' '' Initiate the clock with the object `` '' '' self.clock = [ 0,0 ] def sendMessage ( self ) : `` '' '' Send Message to the server `` '' '' self.msg = `` This is the test message to that will be interposed on '' self.vector_clock.increment ( 0 ) # We are clock position... | 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 ab patter... | re.findall ( r ' ( [ a-z ] { 2 , } ) ( ? : [ a-z ] * ) ( ? : \1 ) ' , 'aabaacaba ' ) | 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 some more ... | d = dict ( ) d.pop ( 'hello ' , None ) # No exception thrownd.pop ( 'hello ' , 0 ) # No exception thrownd.pop ( 'hello ' ) # KeyError | 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 . | 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 ( ) ? | def recursive ( i ) : i = i + 1 try : recursive ( i ) except RuntimeError : print 'max depth == % d ' % i exit ( 0 ) recursive ( 0 ) [ hive ~ ] $ python recursive.py max depth == 999max depth == 998max depth == 997max depth == 996max depth == 995max depth == 994 | 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 surprisingly the cod... | import asyncioasync def wait_n ( n ) : asyncio.sleep ( n ) async def main ( fn ) : print ( `` meh '' ) await fn ( 1 ) print ( `` foo '' ) loop = asyncio.get_event_loop ( ) loop.run_until_complete ( main ( wait_n ) ) awaitable_lambda.py:5 : RuntimeWarning : coroutine 'sleep ' was never awaited import asyncioasync def ma... | 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 question say t... | < p > We focus on : < /p > { % for item in services % } { % url service_view item.id as service_url % } < ul > < li > < a href= '' service_url '' > { { item.title } } < /a > < /li > < /ul > { % endfor % } | 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 runtime is... | public class Problem5 { public static void main ( String [ ] args ) { boolean found = false ; for ( int i = 20 ; ! found ; i += 20 ) { if ( DivisThrough20 ( i ) ) { found = true ; System.out.println ( i ) ; } } } private static boolean DivisThrough20 ( int number ) { boolean result = true ; for ( int i = 19 ; result & ... | 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 both serve... | File `` /home/user/twistedapp/server.py '' , line 97 , in stringReceived print `` sent : '' + jsonFile `` /usr/lib/python2.6/dist-packages/twisted/python/log.py '' , line 555 , in write d = ( self.buf + data ) .split ( '\n ' ) exceptions.UnicodeDecodeError : 'ascii ' codec ca n't decode byte 0xd1 in position 28 : ordin... | 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 time ? C... | fh = open ( 'romeo.txt ' , ' r ' ) lst = list ( ) for line in fh : line = line.split ( ) for word in line : lst.append ( word ) for word in lst : numberofwords = lst.count ( word ) if numberofwords > 1 : lst.remove ( word ) lst.sort ( ) print len ( lst ) print lst 27 [ 'Arise ' , 'But ' , 'It ' , 'Juliet ' , 'Who ' , '... | 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 be to cr... | nums = [ -5,5,4 , -3,0,0,4 , -2 ] x = [ x for x in set ( itertools.combinations ( nums , 4 ) ) if sum ( x ) ==target ] > > > x = [ ( -5 , 5 , 0 , 4 ) , ( -5 , 5 , 4 , 0 ) , ( 5 , 4 , -3 , -2 ) , ( 5 , -3 , 4 , -2 ) ] | 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 . | ( 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 this : Is i... | In [ 1 ] : iterables = [ [ 1 , 2 ] , [ 'foo ' , 'bar ' ] , [ 'one ' , 'two ' ] ] ... : midx = pd.MultiIndex.from_product ( iterables ) ... : df = pd.DataFrame ( np.random.randn ( 8 ) , index=midx ) ... : dfOut [ 1 ] : 01 foo one -0.217594 two -1.361612 bar one 2.477790 two 0.8744092 foo one 0.403577 two 0.076111 bar on... | 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 , rather than... | files = { } for row in data : f = files.get ( row.field1 , lambda : open ( row.field1 , ' w ' ) ) f.write ( 'stuff ... ' ) f = files.get ( row.field1 ) if not f : f = files [ row.field1 ] = open ( row.field1 , ' w ' ) | 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 to the tup... | def update ( self , move , blocks ) : # check if we can jump if move.up and self.on_ground : self.yvel -= self.jump_speed # simple left/right movement if move.left : self.xvel = -self.move_speed if move.right : self.xvel = self.move_speed # if in the air , fall down if not self.on_ground : self.yvel += 0.3 # but not to... | 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 using hashes ... | processed = set ( ) for big_string in strings_generator : if big_string not in processed : processed.add ( big_string ) process ( big_string ) processed = set ( ) for big_string in string_generator : key = hash ( big_string ) if key not in ignored : processed.add ( key ) process ( big_string ) | 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 seeing ou... | links = True i = 0 while links : with open ( 'html/register_ % 03d.html ' % i , ' w ' ) as f : f.write ( browser.html.encode ( 'utf-8 ' ) ) links = browser.find_link_by_text ( 'Next ' ) print 'links : ' , links if links : links [ 0 ] .click ( ) i += 1 links : [ < splinter.driver.webdriver.WebDriverElement object at 0x2... | 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 once but It ... | from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as EClink = `` https : //www.findapetwash.com/ '' driver = webdriver.Chrome ( ) driver.get ( link ) wait = WebDriverWait ( driver , 1... | 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 boat just ... | import timeclass Boat : def __init__ ( self , pace , spm ) : self.pace = pace # velocity of the boat in m/s self.spm = spm # strokes per minute self.distance = 0 # distance travelled def move ( self , deltaT ) : self.distance = self.distance + ( self.pace * deltaT ) boat1 = Boat ( 3.33 , 20 ) while True : boat1.move ( ... | 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 ? | function X=flipall ( X ) for i=1 : ndims ( X ) X = flipdim ( X , i ) ; endend | 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 observati... | n = 8 ** ( 8 ** 8 ) n2 = 8 ** ( 2 ** 24 ) # measured by timeit > 4.449993866728619e-07 > 1.8300124793313444e-07 | 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.