lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | I have a rather unusual request , I think ... I 'll explain the why after I explain the what.WhatI want to detect whenever my object is written to stdout , so that I can perform side effects at that time . So , for example , when I type : it should perform side effects . I 've made my class be a subclass of str and ove... | sys.stdout.write ( instance_of_my_class ) | Python - detect when my object is written to stdout ? |
Python | I 'd like to render an ASCII art world map given this GeoJSON file.My basic approach is to load the GeoJSON into Shapely , transform the points using pyproj to Mercator , and then do a hit test on the geometries for each character of my ASCII art grid.It looks ( edit : mostly ) OK when centered one the prime meridian :... | import functoolsimport jsonimport shutilimport sysimport pyprojimport shapely.geometryimport shapely.ops # Load the mapwith open ( 'world-countries.json ' ) as f : countries = [ ] for feature in json.load ( f ) [ 'features ' ] : # buffer ( 0 ) is a trick for fixing polygons with overlapping coordinates country = shapel... | Creating an ASCII art world map |
Python | I am a beginner learning Python from Learn Python the hard way . It 's my first programming language that I learn and I am stuck at an exercise . Exercise : '' Explain why the 4.0 is used instead of just 4 . `` I honestly ca n't find any reason why he would use a floating point at line 2 other than to to serve as an ex... | cars = 100space_in_a_car = 4.0 # Why does he uses 4.0 instead of 4 here ? drivers = 30passengers = 90cars_not_driven = cars - driverscars_driven = driverscarpool_capacity = cars_driven * space_in_a_caraverage_passengers_per_car = passengers / cars_drivenprint `` There are '' , cars , `` cars available . `` print `` The... | Why does he uses a floating point in this example ? |
Python | I 'm trying to write a context manager decorator using Python 's contextlib.ContextDecorator class.Is there a way to access the decorated function 's parameters within the context manager ? Here 's an example of what I 'm doing : Given the above , this : should be equivalent to : I 've scoured the docs for contextlib a... | from contextlib import ContextDecoratorclass savePen ( ContextDecorator ) : def __enter__ ( self ) : self.prevPen = self.dc.GetPen ( ) # AttributeError return self def __exit__ ( self , *exc ) : self.dc.SetPen ( self.prevPen ) return False @ savePen ( ) def func ( dc , param1 , param2 ) : # do stuff , possibly changing... | Is there a way to access a function 's attributes/parameters within a ContextDecorator ? |
Python | I am trying to use indentedBlock in pyparsing ( which looks awesome to me ) to dissect some nested indentations , but am struggling a bit with comprehending its description in the API reference ( or the more specific examples under http : //pyparsing.wikispaces.com or the mentioning in How do I parse indents and dedent... | - a1_el - b1_el x1_attr : 1 x2_attr : 2 - b2_el - c1_el # I am a comment - b3_el x1_attr : 1 < a1_el > < b1_el x1_attr= '' 1 '' x2_attr= '' 2 '' / > < b2_el > < c1_el/ > < ! -- I am a comment -- > < /b2_el > < b3_el x1_attr= '' 1 '' / > < /a1_el > | Simple demonstration of using pyparsing 's indentedBlock recursively |
Python | Given a list of tuples to sort , python will sort them according to first element in tuple , then second element and so on . This works great.Now I want to sort them by third element , then first element and then the second element which I can do by either providing a key function or a cmp function . except i take a ma... | > > > A [ ( 3 , 2 , 1 ) , ( 0 , 3 , 0 ) , ( 2 , 1 , 0 ) , ( 2 , 2 , 3 ) , ( 0 , 3 , 2 ) , ( 2 , 1 , 1 ) , ( 3 , 3 , 2 ) , ( 3 , 2 , 0 ) ] > > > sorted ( A ) [ ( 0 , 3 , 0 ) , ( 0 , 3 , 2 ) , ( 2 , 1 , 0 ) , ( 2 , 1 , 1 ) , ( 2 , 2 , 3 ) , ( 3 , 2 , 0 ) , ( 3 , 2 , 1 ) , ( 3 , 3 , 2 ) ] > > > A [ ( 3 , 2 , 1 ) , ( 0 , 3... | sort list of tuples by reordering tuples |
Python | QuestionHow do I measure the performance of the various functions below in a concise and comprehensive way.ExampleConsider the dataframe dfI want to sum up the Value column grouped by distinct values in Group . I have three methods for doing it.Are they the same ? How fast are they ? | df = pd.DataFrame ( { 'Group ' : list ( 'QLCKPXNLNTIXAWYMWACA ' ) , 'Value ' : [ 29 , 52 , 71 , 51 , 45 , 76 , 68 , 60 , 92 , 95 , 99 , 27 , 77 , 54 , 39 , 23 , 84 , 37 , 99 , 87 ] } ) import pandas as pdimport numpy as npfrom numba import njitdef sum_pd ( df ) : return df.groupby ( 'Group ' ) .Value.sum ( ) def sum_fc... | What techniques can be used to measure performance of pandas/numpy solutions |
Python | Given this Dask DataFrame : How can I set_index on 'symbol ' column ( which is category [ known ) ? | Dask DataFrame Structure : date value symbolnpartitions=2 object int64 category [ known ] ... ... ... ... Dask Name : from-delayed , 6 tasks2130 df = df.set_index ( 'symbol ' ) Traceback ( most recent call last ) : [ ... ] TypeError : Categorical is not ordered for operation maxyou can use .as_ordered ( ) to change the... | How to set index on categorical type ? |
Python | When sampling randomly from distributions of varying sizes I was surprised to observe that execution time seems to scale mostly with the size of the dataset being sampled from , not the number of values being sampled . Example : The output is : This seems counterintuitive . Maybe I 'm dense , but the problem seems simi... | import pandas as pdimport numpy as npimport time as tm # generate a small and a large datasettestSeriesSmall = pd.Series ( np.random.randn ( 10000 ) ) testSeriesLarge = pd.Series ( np.random.randn ( 10000000 ) ) sampleSize = 10tStart = tm.time ( ) currSample = testSeriesLarge.sample ( n=sampleSize ) .valuesprint ( 'sam... | Why does random sampling scale with the dataset not the sample size ? ( pandas .sample ( ) example ) |
Python | Let 's assume that I have the following table in python pandashere , in the first row , the word 'dumb ' is contained in both columns . In the second row , 'smart ' is contained in both columns . In the third row , 'pretty ' is contained in both columns , and in the final row , 'is ' and 'rich ' are contained in both c... | friend_description friend_definition James is dumb dumb dude Jacob is smart smart guy Jane is pretty she looks pretty Susan is rich she is rich friend_description friend_definition word_overlap overlap_count James is dumb dumb dude dumb 1 Jacob is smart smart guy smart 1 Jane is pretty she looks pretty pretty 1 Susan i... | Counting a number of same words between two columns in python pandas |
Python | The Django aggregation documentation give this example that counts the number of Books related to each Publisher and returns a query set with the top 5 publishers annotated with thier book count ( like appending a new field with this count ) : But I need to count only a specific type of book . Something like.Is there a... | > > > pubs = Publisher.objects.annotate ( num_books=Count ( 'book ' ) ) .order_by ( '-num_books ' ) [ :5 ] > > > pubs [ 0 ] .num_books1323 > > > pubs = Publisher.objects.annotate ( num_books=Count ( 'book__type= '' nonfiction '' ' ) ) .order_by ( '-num_books ' ) [ :5 ] > > > biggest_systems = Entity.objects.filter ( re... | In Django is there a way to aggregate over relationships with a condition on the related object |
Python | I am trying to make Label scrollable horizontally and want halign : '' right and valign : middle as per below code | ScrollView : Label : id : maindisplay text : '' 0 '' font_size : '' 50sp '' text_size : None , self.height [ 1 ] # Set the text wrap box height size_hint_x : None width : self.texture_size [ 0 ] # Following part is not working halign : 'right ' valign : 'middle ' | Align text to edge of Label in ScrollView in kivy |
Python | I have a bokeh plot with date on the x-axis ( data [ `` obs_date '' ] ) and I want another x-axis at the top covering the same range but shown in a different format ( mjd below ) .I have tried to add the second axis with : However , because bokeh adds a small buffer to the limits of the plot , using min max of data [ `... | plot.extra_x_ranges = { `` MJD '' : Range1d ( start=Time ( min ( data [ `` obs_date '' ] ) ) .mjd , end=Time ( max ( data [ `` obs_date '' ] ) ) .mjd ) } plot.add_layout ( LinearAxis ( x_range_name= '' MJD '' , axis_label= '' MJD '' , axis_label_text_font_size= '' 16pt '' ) , `` above '' ) | bokeh plotting second axis - how to get limits of primary axis ? |
Python | I am writing an application which will execute a group of several synchronous chains of tasks asynchronously.In other words , I might have the pipeline foo ( a , b , c ) - > boo ( a , b , c ) for some list of bs . My understanding is to create a chain of foo ( a , b , c ) | boo ( a , b , c ) for each b in this list . T... | # ! /usr/bin/env python3import functoolsimport timefrom celery import chain , group , Celeryfrom celery.utils.log import get_task_loggerlogger = get_task_logger ( __name__ ) app = Celery ( `` my_app '' , broker='redis : //localhost:6379/0 ' , backend='redis : //localhost:6379/0 ' ) @ app.taskdef foo ( a , b , c ) : log... | Groups of chains with positional arguments in partial tasks using Celery |
Python | Related here . Instructions here guide with example : but what does it mean ? Suppose I want to replace `` hh < right @ gmail.com > '' with `` hhh < right @ gmail.com > '' , what would that line look like ? What do the terms username , mapping and filename mean ? I can find this part `` username mapping filename '' fro... | john=John Smith < John.Smith @ someplace.net > tom=Tom Johnson < Tom.Johnson @ bigcity.com > cmdtable = { `` convert '' : ( convert , [ ( ' A ' , 'authors ' , `` , _ ( 'username mapping filename ' ) ) , ( 'd ' , 'dest-type ' , `` , _ ( 'destination repository type ' ) ) , ( `` , 'filemap ' , `` , _ ( 'remap file names ... | hg convert -- authors wrongUsers < -- what is the format of the file ? |
Python | I am new to python and programming ( so please go easy ) and hope someone can help.I have bike trip duration as dtype : object Duration14h 26min . 2sec.0h 8min . 34sec.0h 12min . 17sec.I would ideally like to create a new column holding the calculated minute duration as an integer . So h needs *60 , and seconds rounded... | def ConvertDuration ( Minutes ) : return Minutes.split ( ' ' ) [ 0 ] .split ( ' . ' ) [ 1 ] .strip ( ) WashBike [ 'DurationMin ' ] = pd.DataFrame ( { 'Duration ' : WashBike [ 'Duration ' ] .apply ( ConvertDuration ) } ) WashBike [ 'DurationInt ' ] = WashBike [ 'Duration ' ] .str.strip ( ' ' ) .str.strip ( ' . ' ) .str.... | Python : converting Trip duration of h min sec and leave only minute count |
Python | If one has run then the built-in all , and several other functions , are shadowed by numpy functions with the same names . The most common case where this happens ( without people fully realizing it ) is when starting ipython with ipython -- pylab ( but you should n't be doing this , use -- matplotlib , which does n't ... | from numpy import * | re-import aliased/shadowed python built-in methods |
Python | As a current task , I need to calculate eigenvalues and eigenvectors for a 120*120 matrix . For start , I tested those calculations on a simple 2 by 2 matrix in both Java ( Apache Commons Math library ) and Python 2.7 ( Numpy library ) . I have a problem with eigenvector values not matching , as show below : Output of ... | //Javaimport org.apache.commons.math3.linear.EigenDecomposition ; import org.apache.commons.math3.linear.MatrixUtils ; import org.apache.commons.math3.linear.RealMatrix ; public class TemporaryTest { public static void main ( String [ ] args ) { double [ ] [ ] testArray = { { 2 , -1 } , { 1 , 1 } } ; RealMatrix testMat... | Difference in calculating eigenvectors wih Java and Python |
Python | Let be this little snippet : If we run it we 'll see it 's creating a little scene with a grid and QGraphicsTextItem on it , like this : What I 'm trying to figure out here is how to snap the QGraphicsTextItem on the grid intersections each time I move it or resize it ( when I 'm writing some text ) , how can i guarant... | import sysfrom PyQt5 import QtWidgetsfrom PyQt5 import QtCorefrom PyQt5 import QtGuifrom PyQt5.QtWidgets import QMenufrom PyQt5.QtGui import QKeySequencefrom PyQt5.QtCore import Qtfrom PyQt5.QtGui import QCursorfrom PyQt5.QtWidgets import QGraphicsObjectfrom PyQt5.QtCore import QRectFfrom PyQt5.QtGui import QBrushfrom ... | How to snap to grid a QGraphicsTextItem ? |
Python | This works and happily prints 81 : But why ? Is n't the method given the extra `` self '' argument and should be utterly confused ? For comparison , I also tried it with my own Pow function : The direct function call prints 81 and the method call crashes as expected , as it does get that extra instance argument : Why/h... | class X : mypow = powprint ( X ( ) .mypow ( 3 , 4 ) ) def Pow ( x , y , z=None ) : return x ** yclass Y : myPow = Powprint ( Pow ( 3 , 4 ) ) print ( Y ( ) .myPow ( 3 , 4 ) ) Python 3 : TypeError : unsupported operand type ( s ) for ** or pow ( ) : ' Y ' and 'int'Python 2 : TypeError : unsupported operand type ( s ) for... | Why does ` class X : mypow = pow ` work ? What about ` self ` ? |
Python | I 'm using the zeep package to access some API on https , and on every connection it prints out a warning ( to stderr ) : Some searching I did turned up that the line responsible is this , which implies that this the result of the logging level of the module . Changing the log level seems to require editing this file.T... | Forcing soap : address location to HTTPS import zeepclient = zeep.CachingClient ( 'https : //api.somedomain.com/Services/ApiService.svc ? singleWsdl ' ) client.service.VerifyLogin ( 'user ' , 'pass ' ) | zeep - disable warning `` Forcing soap : address location to HTTPS '' |
Python | I 've been moving around some settings to make more defined local and production environments , and I must have messed something up.Below are the majority of relevant settings . If I move the production.py settings ( which just contains AWS-related settings at the moment ) to base.py , I can update S3 from my local mac... | from cobev.settings.base import * INSTALLED_APPS = [ ... 'whitenoise.runserver_nostatic ' , 'django.contrib.staticfiles ' , ... 'storages ' , ] ... STATIC_URL = '/static/'STATICFILES_DIRS = [ os.path.join ( BASE_DIR , `` global_static '' ) , os.path.join ( BASE_DIR , `` media '' , ) ] MEDIA_ROOT = os.path.join ( BASE_D... | Django collectstatic not working on production with S3 , but same settings work locally |
Python | I want to create an object of a class based on value of a field . For eg : What is a pythonic way to avoid if else here . I was thinking to create a dictionary with r_type being key and classname being value , and do a get of the value and instantiate , is it a proper way , or there is something better idiomatic way in... | if r_type == 'abc ' : return Abc ( ) elif r_type == 'def ' : return Def ( ) elif r_type == 'ghi ' : return Ghi ( ) elif r_type == 'jkl ' : return Jkl ( ) | Avoid if else to instantiate a class - python |
Python | I 've been experimenting with the mathematical abilities of Python and I came upon some interesting behavior . It 's related to the following expression : However , if you evaluate the expression with the standard order of operations in mind , the answer should be 420.25 . I 've also double checked with WolframAlpha , ... | ( 4+4 ) +3/4/5*35- ( 3* ( 5+7 ) ) -6+434+5+5+5 > > > 415 | Why does Python evaluate this expression incorrectly ? |
Python | I saw a comment that lead me to the question Why does Python code run faster in a function ? .I got to thinking , and figured I would try it myself using the timeit library , however I got very different results : ( note : 10**8 was changed to 10**7 to make things a little bit speedier to time ) Did I use timeit correc... | > > > from timeit import repeat > > > setup = `` '' '' def main ( ) : for i in xrange ( 10**7 ) : pass '' '' '' > > > stmt = `` '' '' for i in xrange ( 10**7 ) : pass '' '' '' > > > min ( repeat ( 'main ( ) ' , setup , repeat=7 , number=10 ) ) 1.4399558753975725 > > > min ( repeat ( stmt , repeat=7 , number=10 ) ) 1.44... | Is it REALLY true that Python code runs faster in a function ? |
Python | I have a problem with understanding the memory_profilers output . Basically , it looks like this : On the 9th line we can clearly see , that we use some memory . Now , I measured the size of this list with sys.getsizeof ( ) . And I double checked if it is in fact a list of ints : And this is what I got : Well , now the... | Filename : tspviz.pyLine # Mem usage Increment Line Contents================================================ 7 34.589844 MiB 34.589844 MiB @ profile ( precision=6 ) 8 def parse_arguments ( ) : 9 34.917969 MiB 0.328125 MiB a = [ x**2 for x in range ( 10000 ) ] print ( sys.getsizeof ( a ) ) print ( type ( a [ 0 ] ) ) 876... | Reading the output of Pythons memory_profiler |
Python | I am trying to understand descriptors better.I do n't understand why in the foo method the descriptors __get__ method does n't get called.As far as I understand descriptors the __get__ method always get called when I access the objects attribute via dot operator or when I use __getattribute__ ( ) .According to the Pyth... | class RevealAccess ( object ) : def __init__ ( self , initval=None , name='var ' ) : self.val = initval self.name = name def __get__ ( self , obj , objtype ) : print ( 'Retrieving ' , self.name ) return self.val def __set__ ( self , obj , val ) : print ( 'Updating ' , self.name ) self.val = valclass MyClass ( object ) ... | Understanding Python Descriptors |
Python | I 'm trying to use the library gittle to clone a git repository , I followed the examples in the readme , here is my code.When I try to run this , I got this exception : The result of pip freeze ( python2.7 ) : Thank you . | repo_path = '/path/to/dir/'repo_url = 'git @ gitlab.myproject/proj.git'key = open ( '/path/to/.ssh/id_rsa ' ) auth = GittleAuth ( pkey=key ) repo = Gittle.clone ( repo_url , repo_path , auth=auth ) Traceback ( most recent call last ) : File `` gitCmd2.py '' , line 26 , in < module > gitinit ( ) File `` gitCmd2.py '' , ... | Gittle - `` unexpected keyword argument 'pkey ' '' |
Python | I am trying to use psycopg2 's connection pool with python 's multiprocess library . Currently , attempting to share the connection pool amongst threads in the manner described above causes : The following code should reproduce the error , which the caveat that the reader has to set up a simple postgres database.What I... | psycopg2.OperationalError : SSL error : decryption failed or bad record mac from multiprocessing import Poolfrom psycopg2 import poolimport psycopg2import psycopg2.extrasconnection_pool = pool.ThreadedConnectionPool ( 1 , 200 , database='postgres ' , user='postgres ' , password='postgres ' , host='localhost ' ) class C... | Sharing a postgres connection pool between python multiproccess |
Python | I have a pandas dataframe with two columns like this , I want to cumulative sum over the column , Value . But while creating the cumulative sum if the value becomes negative I want to reset it back to 0.I am currently using a loop shown below to perform this , I am looking for a more efficient way to perform this in pu... | Item Value0 A 71 A 22 A -63 A -704 A 85 A 0 sum_ = 0cumsum = [ ] for val in sample [ 'Value ' ] .values : sum_ += val if sum_ < 0 : sum_ = 0 cumsum.append ( sum_ ) print ( cumsum ) # [ 7 , 9 , 3 , 0 , 8 , 8 ] | Perfrom cumulative sum over a column but reset to 0 if sum become negative in Pandas |
Python | I 'm writing an plugin framework and I want to be able to write a decorator interface , which will convert user class to ABC class and substitute all methods with abstractmethods . I can not get it working and I suppose the problem is connected with wrong mro , but I can be wrong.I basically need to be albe to write : ... | @ interfaceclass X : def test ( self ) : passx = X ( ) # should fail , because test will be abstract method . from abc import ABCMetaclass Interface ( metaclass=ABCMeta ) : passdef interface ( cls ) : newcls = type ( cls.__name__ , ( Interface , cls ) , { } ) # substitute all methods with abstract ones for name , func ... | Creating dynamic ABC class based on user defined class |
Python | I am using Python 2.x , and trying to understand the logic of string formatting using named arguments . I understand : '' { } and { } '' .format ( 10 , 20 ) prints '10 and 20'.In like manner ' { name } and { state } '.format ( name= ' X ' , state= ' Y ' ) prints X and YBut why this is n't working ? It prints `` Hi ! My... | my_string = `` Hi ! My name is { name } . I live in { state } '' my_string.format ( name='Xi ' , state='Xo ' ) print ( my_string ) | Named string format arguments in Python |
Python | I know exceptions in python are fast when it comes to the try but that it may be expensive when it comes to the catch.Does this mean that : is faster than this ? | try : some codeexcept MyException : pass try : some codeexcept MyException as e : pass | Exceptions catching performance in python |
Python | I 've got a DF with columns of different time cycles ( 1/6 , 3/6 , 6/6 etc . ) and would like to `` explode '' all the columns to create a new DF in which each row is a 1/6 cycle.I 'm doing the explode : But the output is not what I want : I would want it to look like this : I am new to Spark and from the start I 've g... | from pyspark import Row from pyspark.sql import SparkSession from pyspark.sql.functions import explode , arrays_zip , colspark = SparkSession.builder \ .appName ( 'DataFrame ' ) \ .master ( 'local [ * ] ' ) \ .getOrCreate ( ) df = spark.createDataFrame ( [ Row ( a=1 , b= [ 1 , 2 , 3 , 4 , 5 , 6 ] , c= [ 11 , 22 , 33 ] ... | How to explode multiple columns , different types and different lengths ? |
Python | How can I fetch the rows for which the second column equals to 4 or 6 ? Apparently , this does not work : | a = np.array ( np.mat ( ' 1 2 ; 3 4 ; 5 6 ; 7 4 ' ) ) b = [ 4,6 ] c = a [ a [ : ,1 ] in b ] | numpy : how to select rows based on a bunch of criteria |
Python | For a website implemented in Django/Python we have the following requirement : On a view page there are 15 messages per web paging shown . When there are more two or more messages from the same source , that follow each other on the view , they should be grouped together . Maybe not clear , but with the following exemp... | Message1 Source1 Message2 Source2 Message3 Source2 Message4 Source1 Message5 Source3 ... Message1 Source1Message2 Source2 ( click here to 1 more message from Source2 ) Message4 Source1Message5 Source3Message6 Source2 | Paging depending on grouping of items in Django |
Python | I have 100 folders with different names and each should be having the same three files inside it , but in some folders all these three files are not present . How I can delete those folders that are empty or containing only one or two files ? These are the three files : | 001.7z002.7z003.7z | Delete the same files inside multiple folders ( python ) |
Python | I really could n't google it . How to transform sparse matrix to ndarray ? Assume , I have sparse matrix t of zeros . Theninstead of [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] Solution : t.toarray ( ) .flatten ( ) | g = t.todense ( ) g [ :10 ] matrix ( [ [ 0 ] , [ 0 ] , [ 0 ] , [ 0 ] , [ 0 ] , [ 0 ] , [ 0 ] , [ 0 ] , [ 0 ] , [ 0 ] ] ) | Numpy : Transform sparse matrix to ndarray |
Python | When I run the above query in the Neo4j web UI , a fell graph of the resulting paths is displayed.However , when I run the same query with the neo4j-python driver , only a Path objects with limited information are returnedHow can I use Cypher and python to get complete path details , including all nodes and the relatio... | MATCH ( u : User { name : $ user } ) , ( target : Group { name : $ group } ) , p=shortestPath ( ( u ) - [ * ] - > ( target ) ) RETURN p < Path start=479557 end=404582 size=1 > | How can I get all the hops in a path of unknown length with neo4j-python ? |
Python | I 'm a beginner to Python and am teaching myself list comprehensions . I 've been doing well with almost all of the for-loop code I 've been translating to list comprehension , but am very stuck on what I thought was a fairly simple loop.So far I 've been trying variations on the following but it 's all getting errors ... | n = 10000def sim ( y ) : count = 0 for i in range ( 10000 ) : if 0.9 < = y [ i ] < = 1.8 : count += 1 probability = count/10000.0 print ( `` P ( a < x < = b ) : { 0:8.4f } '' .format ( probability ) ) print ( `` \t case : \n '' ) , sim ( [ 0.25 if random ( ) < 0.8 else 1.5 for r in range ( n ) ] ) def sim ( y ) : c4 = ... | Python for-loop to list comprehension |
Python | Say you have the following decorator . How can it be modified to say append to some list references to all the functions it decorates ? | def memoize ( obj ) : cache = obj.cache = { } @ functools.wraps ( obj ) def memoizer ( *args , **kwargs ) : if args not in cache : cache [ args ] = obj ( *args , **kwargs ) return cache [ args ] return memoizer @ memoizedef foo ( bar ) : return bar ** 3 | How to register within a decorator all functions it decorates ? |
Python | I am developing a program to process frames from a USB camera on Ubuntu . Currently I 'm using OpenCV in python . When I try to read a frame using a cv2.VideoCapture object I only get partial frames . The camera I 'm using is a Kayeton GS1M2812 USB camera , which claims to be UVC compliant . Most applications ( like ch... | streamer -c /dev/video1 -o capture.jpg import cv2 as cvimport numpy as npimport sysif len ( sys.argv ) ! = 2 : print ( `` invalid arguments '' ) sys.exit ( ) camNo = int ( sys.argv [ 1 ] ) print ( `` opening camera % d '' % camNo ) cap = cv.VideoCapture ( camNo ) print ( `` done '' ) while True : cap.set ( cv.CAP_PROP_... | USB Camera : OpenCV VideoCapture Returns Partial Frames |
Python | The result isBut I ca n't tell their difference . | t0 = [ [ ] ] * 2 t1 = [ [ ] , [ ] ] t0 [ 0 ] .append ( 'hello ' ) print t0 t1 [ 0 ] .append ( 'hello ' ) print t1 [ [ 'hello ' ] , [ 'hello ' ] ] [ [ 'hello ' ] , [ ] ] | what is the difference between [ [ ] , [ ] ] and [ [ ] ] * 2 |
Python | I thought I understood Python slicing operations , but when I tried to update a sliced list , I got confused : Why is n't foo updated after foo [ : ] [ 1 ] = 'two ' ? Update : Maybe I did n't explain my questions clearly . I know when slicing , a new list is created . My doubt is why a slicing assignment updates the li... | > > > foo = [ 1 , 2 , 3 , 4 ] > > > foo [ :1 ] = [ 'one ' ] # OK , foo updated > > > foo [ 'one ' , 2 , 3 , 4 ] > > > foo [ : ] [ 1 ] = 'two ' # why foo not updated ? > > > foo [ 'one ' , 2 , 3 , 4 ] > > > foo [ : ] [ 2 : ] = [ 'three ' , 'four ' ] # Again , foo not updated > > > foo [ 'one ' , 2 , 3 , 4 ] | Updating a sliced list |
Python | Usually Python descriptor are defined as class attributes . But in my case , I want every object instance to have different set descriptors that depends on the input . For example : Each object are have different set of attributes that are decided at instantiation time . Since these are one-off objects , it is not conv... | class MyClass ( object ) : def __init__ ( self , **kwargs ) : for attr , val in kwargs.items ( ) : self.__dict__ [ attr ] = MyDescriptor ( val ) tv = MyClass ( type= '' tv '' , size= '' 30 '' ) smartphone = MyClass ( type= '' phone '' , os= '' android '' ) tv.size # do something smart with the descriptor < property at ... | Create per-instance property descriptor ? |
Python | Given the following data frame : I would like to replace all non-null values with the column name.Desired result : In reality , I have many columns.Thanks in advance ! Update to answer from root : To perform this on a subset of columns : | import pandas as pdd = pd.DataFrame ( { ' a ' : [ 1,2,3 ] , ' b ' : [ np.nan,5,6 ] } ) d a b0 1 NaN1 2 5.02 3 6.0 a b0 a NaN1 a b2 a b d.loc [ : ,d.columns [ 3 : ] ] = np.where ( d.loc [ : ,d.columns [ 3 : ] ] .notnull ( ) , d.loc [ : ,d.columns [ 3 : ] ] .columns , d.loc [ : ,d.columns [ 3 : ] ] ) | Replacing non-null values with column names |
Python | I have approximately 20000 pieces of texts to translate , each of which average around the length of 100 characters . I am using the multiprocessing library to speed up my API calls . And looks like below : The above code unfortunately fails around iteration 2828 +/- 5 every single time ( HTTP Error 503 : Service Unava... | from google.cloud.translate_v2 import Clientfrom time import sleepfrom tqdm.notebook import tqdmimport multiprocessing as mpos.environ [ `` GOOGLE_APPLICATION_CREDENTIALS '' ] = cred_filetranslate_client = Client ( ) def trans ( text , MAX_TRIES=5 ) : res = None sleep_time = 1 for i in range ( MAX_TRIES ) : try : res =... | Google translate api timeout |
Python | I found multiple ( slightly different ) ways to define abstract classes in Python . I read the documentation and also could not find an answer here on stackoverflow . The main difference between the three examples ( see code below ) is : A sets a new metaclass abc.ABCMeta explicitlyB inherits from abc.ABCC inherits fro... | import abcclass A ( metaclass=abc.ABCMeta ) : # Alternatively put __metaclass__ = abc.ABCMeta here @ abc.abstractmethod def foo ( self ) : raise NotImplementedErrorclass B ( abc.ABC ) : @ abc.abstractmethod def foo ( self ) : raise NotImplementedErrorclass C ( object ) : @ abc.abstractmethod def foo ( self ) : raise No... | Differences in three ways to define a abstract class |
Python | I am currently working with GeoPython - Auto GIS . After research on the work flow with conda+python , I have found out how to create and specify the packages in an environment.yml file . But I found no way to specify an optional arguement . An example is as follows , The equivalent of this conda command is the followi... | conda install -y -c conda-forge geopandas name : parkarchannels : - conda-forge- defaultsdependencies : - geopandas conda install -y -c conda-forge basemap=1.0.8.dev0 -- no-deps - basemap=1.0.8.dev0 -- no-deps CondaValueError : invalid package specification : basemap=1.0.8.dev0 -- no-deps - basemap=1.0.8.dev0=np111py35... | How do I set optional arguments in the conda environment.yml file ? |
Python | Is it memory efficient to store big number in list ? Why does the following happens ? Why size of A and B are not equal ? Why size of C and D are equal ? | > > > A = 100**100 > > > sys.getsizeof ( A ) 102 > > > B = [ 100**100 ] > > > sys.getsizeof ( B ) 40 > > > C = [ 1,100**100 ] > > > sys.getsizeof ( C ) 44 > > > D = [ 1000**1000 , 100**100 ] > > > sys.getsizeof ( D ) 44 | Is it better to store big number in list ? |
Python | I am trying to design a C interface which could easily be extended in Python ( using ctypes ) . I 've used the natural idiom in C : It works nicely if I want to extend this interface from C directly : But what I would really like to do , is implement this interface from Python using ctypes . Here is what I have so far ... | struct format { int ( *can_open ) ( const char *filename ) ; struct format * ( *open ) ( const char *filename ) ; void ( *delete ) ( struct format *self ) ; int ( *read ) ( struct format *self , char *buf , size_t len ) ; } ; struct derived /* concrete implementation */ { struct format base ; } ; CANOPENFUNC = ctypes.C... | Self-referencing class : concrete python class from C interface |
Python | In numpy ( 1.8 ) , I want to move this computation out of a Python loop into something more numpy-ish for better performance : base is a ~2000x2000 array , and tool is a 25x25 array . ( Background context : base and tool are height maps , and I 'm trying to figure out the closest approach for tool moved all over base .... | ( width , height ) = base.shape ( toolw , toolh ) = tool.shapefor i in range ( 0 , width-toolw ) : for j in range ( 0 , height-toolh ) : zdiff [ i , j ] = ( tool - base [ i : i+toolw , j : j+toolh ] ) .min ( ) base_view = np.lib.stride_tricks.as_strided ( base , shape= ( 2000 , 2000 , 25 , 25 ) , strides= ( base.stride... | Numpy stride tricks complaining `` array too big '' , why ? |
Python | Is it possible to mark a block in Vim based on the indentation already in place ? Similarly to v { .It would be extremely useful for programming languages with whitespace-sensitive syntax ( like Haskell and Python ) .For example mark everything between the first let and return in this function : http : //en.wikipedia.o... | checkArg ( com : arg ) s d ns | com == `` add-source `` = do let s ' = v ++ s lift $ saveLinks s ' return ( s ' , d ) | com == `` remove-source '' = do let s ' = filter ( not . hasWord str ) s lift $ saveLinks s ' return ( s ' , d ) | Mark block based on indentation level in Vim |
Python | I got two list of listsI would like to iterate over l1 and check if l1 [ 0 ] matches with any l2 [ 2 ] , In this case the output should be [ 1 , l1 [ 0 ] , l2 [ 0 ] ] otherwise output is [ 0 , l1 [ 0 ] , l2 [ 0 ] ] . Output should be a single nested list ( or list of tuples ) with result for each element of l1 . Both l... | l1 = [ [ 1,2,3 ] , [ 4,5,6 ] , [ 7,8,9 ] ] l2 = [ [ ' a ' , ' b',4 ] , [ ' c ' , 'd',1 ] , [ ' e ' , ' f',12 ] , [ ' i ' , ' j',18 ] ] output = list ( ) for i in l1 : matched = 0 for j in l2 : if j [ 2 ] == i [ 0 ] : output.append ( [ 1 , i [ 0 ] , j [ 0 ] ] ) matched = 1 if matched == 0 : output.append ( [ 0 , i [ 0 ]... | Compare elements of one nested list with another nested list |
Python | I have an image that I am uploading using Django Forms , and its available in the variable as InMemoryFile What I want to do is to make it progressive.Code to make an image a progressiveForms.pyThe issue is , I have to save the file in case I want to make it progressive , and open it again to send it to the server . ( ... | img = Image.open ( source ) img.save ( destination , `` JPEG '' , quality=80 , optimize=True , progressive=True ) my_file = pic.pic_url.filephoto = uploader.upload_picture_to_album ( title=title , file_obj=my_file ) my_file=pic.pic_url.file progressive_file = ( my_file ) photo = picasa_api.upload_picture_to_album ( tit... | Python Pillow : Make image progressive before sending to 3rd party server |
Python | For a text classification project ( age ) I 'm making a subset of my data . I 've made 3 lists with filenames , sorted by age . I want to shuffle these lists and then append 5000 filenames from each shuffled list to a new list . The result should be a data subset with 15000 files ( 5000 10s , 5000 20s , 5000 30s ) . Be... | def seed ( ) : return 0.47231099848teens = [ list of files ] tweens = [ list of files ] thirthies = [ list of files ] data = [ ] for categorie in random.shuffle ( [ teens , tweens , thirthies ] , seed ) : data.append ( teens [ :5000 ] ) data.append ( tweens [ :5000 ] ) data.append ( thirthies [ :5000 ] ) | append items from shuffled list to a new list |
Python | I have a domain mapped file , for Wordnet synsets which is linked by offsets , from : - linkThis has two types of databases for different Wordnet versions and other significant differences . The readme says I am using python3.4 with Wordnet version 3 on a linux machine . I could n't seem to find any other version of th... | - `` wn-domains-3.2-20070223 '' contains the mapping between Princeton WordNet 2.0 synsets and their corresponding domains . | How to fetch a specific version of Wordnet when doing nltk.download ( ) |
Python | I am using the python shift function to compare if a value in a Series is equal to the previus value . Basically This is as expected . ( The first comparison is False because we are comparing with the NA of the shifted series ) . Now , I do have Series where I do n't have any value , ie . None , like thisHere the compa... | import pandas as pda = pd.Series ( [ 2 , 2 , 4 , 5 ] ) a == a.shift ( ) Out [ 1 ] : 0 False1 True2 False3 Falsedtype : bool b = pd.Series ( [ None , None , 4 , 5 ] ) b == b.shift ( ) Out [ 3 ] : 0 False1 False2 False3 Falsedtype : bool c = Noned = Nonec == dOut [ 4 ] : True | Compare Series containing None |
Python | Python 's logging functions allow you to pass them multiple arguments that they can interpolate for you . So you have a choice : orBut why choose one over the other ? Is it simply a matter of letting errors happen in the logger as opposed to in the program that 's being logged , or is there something else to it ? | logger.info ( `` Something % s this way comes ! '' % `` wicked '' ) logger.info ( `` Something % s this way comes ! `` , `` wicked '' ) | Why use multiple arguments to log instead of interpolation ? |
Python | I 'm fairly new to Python and I 'm trying to download the feather library but I am getting an error . I have already updated pip and setuptools but I am still getting errors . This is the output I get from PyCharm : =====================Update per Chris Hunt 's Response==========================I am actually receiving ... | Collecting featherUsing cached https : //files.pythonhosted.org/packages/77/d1/073c848713d9987f48d0bc8415646760a069ef3ca80e9b45fdb6b4422133/feather-0.9.1dev.tar.gzComplete output from command python setup.py egg_info : Downloading http : //pypi.python.org/packages/source/d/distribute/distribute-0.6.14.tar.gzTraceback (... | `` Feather '' library installation failing in PyCharm |
Python | I 'm writing a module to load a dataset . I want to keep the interface/API as clean as possible - so I 've made internal functions and variables hidden by prefacing their names with __ . Awesome . My module , however , imports other packages ( e.g . numpy ) which still appear in my module 's namespace , how can I avoid... | import numpy as np__INTERNAL_VAR1 = TrueEXTERNAL_VAR = Truedef loadData ( ) : data = __INTERNAL_FUNC1 ( ) ... return datadef __INTERNAL_FUNC1 ( ) : ... return data > import Loader > Loader . [ TAB ] Loader.EXTERNAL_VAR Loader.loadData Loader.np | avoid sub-modules and external packages in a module 's namespace |
Python | I am using python to download files from a ftp server and i am able to download the files but when i open the files they seem to be corrupted or are not openingFiles like songs or jpgs are working fine but documents , excel sheets , pdfs and text files are not downloading properly.Following is my code : I am able to do... | from ftplib import FTPftp = FTP ( ) ftp.connect ( ip_address , port ) ftp.login ( userid , password ) direc='directory path'ftp.cwd ( direc ) doc='doc.txt ' or xlsx or pdf or jpg etcdownload_path='path to download file on desktop'file=open ( download_path+ doc , 'wb ' ) ftp.retrbinary ( f '' RETR { doc } '' , file.writ... | Downloading files from ftp server using python but files not opening after downloading |
Python | I have created a variable scope in one part of my graph , and later in another part of the graph I want to add OPs to an existing scope . That equates to this distilled example : Which yields : My desired result is : I saw this question which did n't seem to have an answer that addressed the question directly : TensorF... | import tensorflow as tfwith tf.variable_scope ( 'myscope ' ) : tf.Variable ( 1.0 , name='var1 ' ) with tf.variable_scope ( 'myscope ' , reuse=True ) : tf.Variable ( 2.0 , name='var2 ' ) print ( [ n.name for n in tf.get_default_graph ( ) .as_graph_def ( ) .node ] ) [ 'myscope/var1/initial_value ' , 'myscope/var1 ' , 'my... | How can you re-use a variable scope in tensorflow without a new scope being created by default ? |
Python | I 'm trying to port some code from Python 3.6 to Python 3.7 on Windows 10 . I see the multiprocessing code hang when calling .get ( ) on the AsyncResult object . The code in question is much more complicated , but I 've boiled it down to something similar to the following program.This code also runs in Python 2.7 . For... | import multiprocessingdef main ( num_jobs ) : num_processes = max ( multiprocessing.cpu_count ( ) - 1 , 1 ) pool = multiprocessing.Pool ( num_processes ) func_args = [ ] results = [ ] try : for num in range ( num_jobs ) : args = ( 1 , 2 , 3 ) func_args.append ( args ) results.append ( pool.apply_async ( print , args ) ... | Multiprocessing AsyncResult.get ( ) hangs in Python 3.7.2 but not in 3.6 |
Python | I have a nested OrderedDict that I want to extract a value out of . But before I can extract that value I have to make sure a long chain of attributes exist and that their values are n't none.What is the most pythonic way of improving the following code : | if 'first ' in data and \ data [ 'first ' ] and \ 'second ' in data [ 'first ' ] and \ data [ 'first ' ] [ 'second ' ] and \ 'third ' in data [ 'first ' ] [ 'second ' ] and \ data [ 'first ' ] [ 'second ' ] [ 'third ' ] : x = data [ 'first ' ] [ 'second ' ] [ 'third ' ] | Checking if nested attribute exists |
Python | I am trying to learn about bound methods in python and have implemented the code below : When I run this code , the following output is produced : Why is it not possible for me to change p1.draw ( ) after changing it so that it points at draw2 ? | class Point : def __init__ ( self , x , y ) : self.__x=x self.__y=y def draw ( self ) : print ( self.__x , self.__y ) def draw2 ( self ) : print ( `` x '' , self.__x , `` y '' , self.__y ) p1=Point ( 1,2 ) p2=Point ( 3,4 ) p1.draw ( ) p2.draw ( ) p1.draw=draw2p1.draw ( p1 ) 1 23 4Traceback ( most recent call last ) : F... | Python : Change bound method to another method |
Python | I want to generate , in python ( without a dictionary ) , a list of string from aaa-zzz and then output a txtfile such as this ( note , the ... is short for the strings in between ) : The harder challenge is to genrate alternating ( upper and lower ) strings . How to generate these ? Just a bonus question , is there a ... | aaaaabaacaad ... aazabaabbabcabd ... aaz ... zaa ... zzyzzz aaa ... aazaaA ... aaZaba ... abz ... abA ... abZaBa ... aBzaBA ... aBZ ... zzzzzA ... ... zzZzAa ... zAz ... zZa ... zZz ... ... ZZZ | How to generate a continuous string ? |
Python | I 'm working on a piece of software which needs to implement the wiggliness of a set of data . Here 's a sample of the input I would receive , merged with the lightness plot of each vertical pixel strip : It is easy to see that the left margin is really wiggly ( i.e . has a ton of minima/maxima ) , and I want to genera... | def local_maximum ( list , center , delta ) : maximum = [ 0 , 0 ] for i in range ( delta ) : if list [ center + i ] > maximum [ 1 ] : maximum = [ center + i , list [ center + i ] ] if list [ center - i ] > maximum [ 1 ] : maximum = [ center - i , list [ center - i ] ] return maximumdef count_maxima ( list , start , end... | Determine `` wiggliness '' of set of data - Python |
Python | I have spent few recent days to learn how to structure data science project to keep it simple , reusable and pythonic . Sticking to this guideline I have created my_project . You can see it 's structure below.I defined a function that loads data from .data/processed . I want to use this function in other scripts and al... | ├── README.md ├── data│ ├── processed < -- data files│ └── raw ├── notebooks | └── notebook_1 ├── setup.py |├── settings.py < -- settings file └── src ├── __init__.py │ └── data └── get_data.py < -- script def data_sample ( code=None ) : df = pd.read_parquet ( '../../data/processed/my_data ' ) if not code : code = rand... | Elegant way to refer to files in data science project |
Python | I am trying to render a spline chart with PUBNUB EON charting library . I do not understand what is going wrong here . I can see the data in console , but the chart is not rendering , there are only x and y axis lines . I am getting the data from python SDK and subscribing via javascript SDK . There is no error message... | def counterVolume ( data ) : for each in data : y = each.counter_volume data_clean = json.dumps ( y , indent=4 , separators= ( ' , ' , ' : ' ) ) print pubnub.publish ( channel='channel ' , message= data_clean ) counterVolume ( data ) var data ; var pubnub = PUBNUB.init ( { publish_key : 'pub ' , subscribe_key : 'subf '... | PubNub EON chart not Rendering Data |
Python | I have been working on a way to implement HMAC verification in python with flask for the selly.gg merchant website.So selly 's dev documentation give these following examples to verify HMAC signatures ( in PHP and ruby ) : https : //developer.selly.gg/ ? php # signing-validating ( code below : ) PHP : RUBY : So , so fa... | < ? php $ signature = hash_hmac ( 'sha512 ' , json_encode ( $ _POST ) , $ secret ) ; if hash_equals ( $ signature , $ signatureFromHeader ) { // Webhook is valid } ? > signature = OpenSSL : :HMAC.hexdigest ( OpenSSL : :Digest.new ( 'sha512 ' ) , secret , payload.to_json ) is_valid_signature = ActiveSupport : :SecurityU... | Hmac verification with flask in Python ( with reference in PHP and RUBY ) |
Python | Suppose we take np.dot of two 'float32 ' 2D arrays : Numbers . Except , they can change : CASE 1 : slice aResults differ , even though the printed slice derives from the exact same numbers multiplied.CASE 2 : flatten a , take a 1D version of b , then slice a : CASE 3 : stronger control ; set all non-involved entires to... | res = np.dot ( a , b ) # see CASE 1print ( list ( res [ 0 ] ) ) # list shows more digits [ -0.90448684 , -1.1708503 , 0.907136 , 3.5594249 , 1.1374011 , -1.3826287 ] np.random.seed ( 1 ) a = np.random.randn ( 9 , 6 ) .astype ( 'float32 ' ) b = np.random.randn ( 6 , 6 ) .astype ( 'float32 ' ) for i in range ( 1 , len ( ... | Why is np.dot imprecise ? ( n-dim arrays ) |
Python | I want to detect consecutive spans of 1 's in a numpy array . Indeed , I want to first identify whether the element in an array is in a span of a least three 1 's . For example , we have the following array a : Then the following 1 's in bold are the elements satisfy the requirement . [ 1 , 1 , 1 , 0 , 1 , 1 , 1 , 0 , ... | import numpy as np a = np.array ( [ 1 , 1 , 1 , 0 , 1 , 1 , 1 , 0 , 1 , 1 , 0 , 0 , 1 , 1 , 1 , 0 , 0 , 1 , 1 , 1 , 1 , 1 , 0 ] ) [ True , True , True , True , True , True , True , False , False , False , False , False , True , True , True , True , True , True , True , True , True , True , False ] a2 = np.array ( [ 0 ,... | numpy : detect consecutive 1 in an array |
Python | I am working on Project Euler Problem 50 , which states : The prime 41 , can be written as the sum of six consecutive primes : 41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred . The longest sum of consecutive primes below one-thousand that adds to a prime... | primes = tuple ( n for n in range ( 1 , 10**6 ) if is_prime ( n ) ==True ) count_best = 0 # # http : //docs.python.org/release/2.3.5/lib/itertools-example.html : # # Slightly modified ( first for loop ) from itertools import islice def window ( seq ) : for n in range ( 2 , len ( seq ) + 1 ) : it = iter ( seq ) result =... | Calculations on sliding windows and memoization |
Python | I 'm developing a Flask application using Babel . Thanks to Distutils/Setuptools Integration , all the parameters of compile/extract/ ... functions are stored in setup.cfg and compiling the i18n files is as easy as Great . Now I would like this to be done automatically when running In make 's words , that would be lett... | ./setup.py compile_catalog ./setup.py install pip install -r requirements.txt # ! /bin/sh./setup.py compile_catalogpip install -r requirements.txt | compile translation files when calling setup.py install |
Python | I want to make 5 buttons in a loop , and for each buttons bind a commend to print the index . In the following solution it always prints the same index . My code like this : It always prints 5 . How can I fix this ? | for i in range ( 5 ) : make_button = Tkinter.Button ( frame , text = '' make ! `` , command= lambda : makeId ( i ) ) def makeId ( i ) : print ( i ) | How to understand closure in a lambda ? |
Python | Why is there such a large speed difference between the following L2 norm calculations : All three produce identical results as far as I can see.Here 's the source code for numpy.linalg.norm function : EDIT : Someone suggested that one version could be parallelized , but I checked and it 's not the case . All three vers... | a = np.arange ( 1200.0 ) .reshape ( ( -1,3 ) ) % timeit [ np.sqrt ( ( a*a ) .sum ( axis=1 ) ) ] 100000 loops , best of 3 : 12 µs per loop % timeit [ np.sqrt ( np.dot ( x , x ) ) for x in a ] 1000 loops , best of 3 : 814 µs per loop % timeit [ np.linalg.norm ( x ) for x in a ] 100 loops , best of 3 : 2 ms per loop x = a... | Huge speed difference in numpy between similar code |
Python | I have a dataframe df that has the columns [ 'metric_type ' , 'metric_value ' ] . For each row , I want to make sure I have a column with the name equal to 'metric_type ' and a value for that column equal to 'metric_value'.One of my problems is that 'metric_type ' has spurious spaces that I want to get rid of.Consider ... | df = pd.DataFrame ( [ [ ' a ' , 1 ] , [ ' b ' , 2 ] , [ ' c ' , 3 ] ] , columns= [ 'metric_type ' , 'metric_value ' ] ) print ( df ) metric_type metric_value0 a 11 b 22 c 3 def assign_metric_vals ( row ) : row [ row [ 'metric_type ' ] .replace ( `` `` , `` '' ) ] = row [ 'metric_value ' ] return row a b c metric_type m... | More efficient way to clean a column of strings and add a new column |
Python | This is somehow related to question about big strings and PEP8.How can I make my script that has the following line PEP8 compliant ( `` Maximum Line Length '' rule ) ? | pub_key = { ' e ' : 3226833362680126101036263622033066816222202666130162062116461326212012222403311326222666622610430466620224662364142L , ' n ' : 22642100386104124846282622610302260822032824220442268423264033123822023222632161626614624330234268826684628180266266662221386811463226821118622360684662331000666226011046062... | PEP8 - 80 Characters - Big Integers |
Python | I 'm trying to create directory with 777 rights.However what I get is 775I 'm sure that I have appropriate rights because chmod 777 works just fine . | os.mkdir ( Xmldocument.directory , 0777 ) drwxrwxr-x . 2 mwysoki mwysoki 4096 Nov 9 11:38 VeloDBBrowser | os.mkdir 's rights assigning does n't work as expected |
Python | Let 's assume the following function : As you can see , there are two different scenarios depending on par1 . I do not like that line 3 and line 5 are almost identical and do not follow the DRY ( Do n't Repeat Yourself ) principle . How can this code be improved ? | def myfun ( my_list , n , par1= '' ) : if par1 == `` : new_list = [ [ my_fun2 ( i , j ) for j in range ( n ) ] for i in range ( n ) ] else : new_list = [ [ my_fun2 ( i , j ) for j in range ( n ) ] for i in range ( n ) if my_fun2 ( i , n ) == par1 ] return new_list | Pythonic way to use the second condition in list comprehensions |
Python | Suppose I have an object and want one of its methods to be executed when a PyQt signal is emitted . And suppose I want it to do so with a parameter that is not passed by the signal . So I create a lambda as the signal 's slot : Now , normally with PyQt signals and slots , signal connections do n't prevent garbage colle... | class MyClass ( object ) : def __init__ ( self , model ) : model.model_changed_signal.connect ( lambda : self.set_x ( model.x ( ) , silent=True ) ) | Lifetime of object in lambda connected to pyqtSignal |
Python | I was trying to understand why Python is said to be a beautiful language . I was directed to the beauty of PEP 8 ... and it was strange . In fact it says that you can use any convention you want , just be consistent ... and suddenly I found some strange things in the core library : The below functions are new in the Py... | request ( ) getresponse ( ) set_debuglevel ( ) endheaders ( ) http : //docs.python.org/py3k/library/http.client.html popitem ( ) move_to_end ( ) http : //docs.python.org/py3k/library/collections.html | Python Core Library and PEP8 |
Python | I have a projectfolder structure like this : In my settings.py Im trying to import the apps like this : But if I try to migrate one of the app , I get this error : What could be wrong ? This kind of setup used to work with django 1.6 | project applications __init__.py app1 app2 app3 project __init__.py settings.py INSTALLED_APPS = ( 'django.contrib.admin ' , ... 'applications.app1 ' , 'applications.app2 ' , 'applications.app3 ' , ) ./manage.py makemigrations applications.app1App 'applications.app1 ' could not be found . Is it in INSTALLED_APPS ? | Applications in subfolder in 1.7 |
Python | I 'm not aware that I changed anything and am running Ubuntu 10.10 . Mercurial had been working fine and then all of a sudden when I started pushing commits this morning I started receiving the following error : I tried to Google parts of it , but I could n't find anything relevant . Any ideas ? Thanks for looking . : ... | ** unknown exception encountered , details follow** report bug details to http : //mercurial.selenic.com/bts/** or mercurial @ selenic.com** Python 2.6.6 ( r266:84292 , Sep 15 2010 , 15:52:39 ) [ GCC 4.4.5 ] ** Mercurial Distributed SCM ( version 1.6.3 ) ** Extensions loaded : convertTraceback ( most recent call last )... | How can I get Mercurial to push commits again ? |
Python | I 'd like to call some pgcrypto functions from python . Namely px_crypt . I ca n't seem to figure out the right object files to link it seems.Here 's my code : and gcc commands and output : Error is : | # include < Python.h > # include `` postgres.h '' # include `` pgcrypto/px-crypt.h '' static PyObject*pgcrypt ( PyObject* self , PyObject* args ) { const char* key ; const char* setting ; if ( ! PyArg_ParseTuple ( args , `` ss '' , & key , & setting ) ) return NULL ; return Py_BuildValue ( `` s '' , px_crypt ( key , se... | Bind to pgcrypto from python |
Python | I 'm using Keras with a Theano as a backend and I have Sequential neural network model.I wonder is there a difference between following ? and | model.add ( Convolution2D ( 32 , 3 , 3 , activation='relu ' ) ) model.add ( Convolution2D ( 32 , 3 , 3 ) ) model.add ( Activation ( 'relu ' ) ) | What is the difference between these two ways of adding Neural Network layers in Keras ? |
Python | I have two lists of lists . One with maximum values , the other with mínimum values : I want to get a third list with the maximum absolute values and their signs for each related item , that is : Maybe with pandas ? | list_max = [ [ 100 , 10 , 100 ] , [ -50 , 90 , -50 ] ] list_min = [ [ 50 , -90 , -50 ] , [ -100 , -10 , -500 ] ] list_max [ 0 ] [ 0 ] = 100 ; list_min [ 0 ] [ 0 ] = 50 - > list_3 [ 0 ] [ 0 ] = 100list_max [ 0 ] [ 1 ] = 10 ; list_min [ 0 ] [ 1 ] = -90 - > list_3 [ 0 ] [ 1 ] = -90list_3 = [ [ 100 , -90 , 100 ] , [ -100 ,... | Python : Compare two lists and get max and min values with signs |
Python | I take a whole day to debug the code below . It is about multiprocessing . Please take a look.I thought I would get `` QUITTING : printHello '' , `` ENTERING : log_result '' and `` QUITTING : printHello '' among the output lines . What appears strange to me is that , printHello has not yet finished when the main progra... | import numpy as npimport multiprocessing as mpdef printHello ( x ) : print `` ENTERING : printHello '' time.sleep ( 2 ) print `` QUITTING : printHello '' return 'hello '+xdef log_result ( result ) : print `` ENTERING : log_result '' time.sleep ( 2 ) print `` QUITTING : log_result '' def main_multi ( ) : pool = mp.Pool ... | The callback does not call when multiprocessing |
Python | Given the accented unicode word like u'кни́га ' , I need to strip the acute ( u'книга ' ) , and also change the accent format to u'кни+га ' , where '+ ' represents the acute over the preceding letter.What I do now is using a dictionary of acuted and not acuted symbols : I want to do something like this : But of course ... | accented_list = [ u ' я́ ' , u ' и́ ' , u ' ы́ ' , u ' у́ ' , u ' э́ ' , u ' а́ ' , u ' е́ ' , u ' ю́ ' , u ' о́ ' ] regular_list = [ u ' я ' , u ' и ' , u ' ы ' , u ' у ' , u ' э ' , u ' а ' , u ' е ' , u ' ю ' , u ' о ' ] accent_dict = dict ( zip ( accented_list , regular_list ) ) def changeAccentFormat ( word ) : fo... | How do I iterate through unicode symbols , not bytes in python ? |
Python | I 'm using the mutagen module for Python to get the artist of various MP3 files I have.Here 's the code giving the error : The code is working for most of my MP3 files , but there are a select few that continually give the following error : KeyError : 'TPE1'And because of that error , I ca n't see the artist . Note tha... | audio = EasyID3 ( C : \Users\Owner\Music\Music\Blue Öyster Cult\Blue Öyster Cult\Cities on Flame ) print audio [ `` artist '' ] | What is the `` TPE1 '' KeyError ? |
Python | I want to change the value of a particular string index , but unfortunatelyraises a TypeError , because strings are immutable ( `` item assignment is not supported '' ) .So instead I use the rather clumsyIs there a better way of doing this ? | string [ 4 ] = `` a '' string = string [ :4 ] + `` a '' + string [ 4 : ] | Overcoming the `` disadvantages '' of string immutability |
Python | I 'm trying to read in a text file that looks something like this : and this is what I have : I did it this way for a previous file that was very similar to this one , and everything worked fine . However , this file is n't being read in properly . First it gives me an error `` list index out of range '' for closure_st... | Date , StartTime , EndTime 6/8/14 , 1832 , 19036/8/14 , 1912 , 19186/9/14 , 1703 , 17086/9/14 , 1713 , 1750 g = open ( 'Observed_closure_info.txt ' , ' r ' ) closure_date= [ ] closure_starttime= [ ] closure_endtime= [ ] file_data1 = g.readlines ( ) for line in file_data1 [ 1 : ] : data1=line.split ( ' , ' ) closure_dat... | python not properly reading in text file |
Python | I have no idea what I could have done but Pycharm now decides to claim that it does n't know things like TaggedDocument or Doc2Vec although it worked an hour ago.This is my project structure : I ca n't remember doing anything that could have cause this so please tell me how I could fix this.The thing I do n't get it th... | drwxr-sr-x 3 root staff 4096 Oct 23 2015 .drwxr-sr-x 9 root staff 4096 Oct 23 2015 ..-rw-r -- r -- 1 root staff 570651 Oct 23 2015 doc2vec_inner.c-rw-r -- r -- 1 root staff 26872 Oct 23 2015 doc2vec_inner.pyx-rwxr-xr-x 1 root staff 473658 Oct 23 2015 doc2vec_inner.so-rw-r -- r -- 1 root staff 37304 Oct 23 2015 doc2vec.... | Pycharm shows `` Unresolved reference '' all of a sudden |
Python | I am trying to parse out a column by the comma ( also stripping the white space ) and then pivoting all of the origin/destination combinations into new rows . Here is a sample of the data : I am having trouble reproducing the dataframe above using pd.read_clipboard , so here is the dataframe code : The desired output w... | Origin Destination WeightPVG AMS , FRA 10,000CAN , XMN LAX , ORD 25,000 df = pd.DataFrame ( { 'Origin ' : [ 'PVG ' , 'CAN , XMN ' ] , 'Destination ' : [ 'AMS , FRA ' , 'LAX , ORD ' ] , 'Weight ' : [ 10000 , 25000 ] } ) Origin Destination WeightPVG AMS 10,000PVG FRA 10,000CAN LAX 25,000 CAN ORD 25,000XMN LAX 25,000XMN O... | Parse a dataframe column by comma and pivot - python |
Python | Running into a problem with pyinstaller . I 'm trying to ship out an exe/app file using PyInstaller . However , anyone who tries to open my file ends up getting an Illegal Instruction 4 error . This only happens when I try to compile on my machine and send to others . Others who compile using the same process and spec ... | ( veControl ) ahaq-mbp-10028 : asimov-control ahaque $ pyinstaller asimov_gui.spec -- onefile23 WARNING : You are running 64-bit Python : created binaries will only work on Mac OS X 10.6+.If you need 10.4-10.5 compatibility , run Python as a 32-bit binary with this command : VERSIONER_PYTHON_PREFER_32_BIT=yes arch -i38... | Pyinstaller Illegal Instruction 4 ( other computers ) |
Python | In the following code , the mc assigment works fine in Python 2 and 3 . The cc assignment , which uses the same list comprehension within a class , works in Python 2 but fails with Python 3.What explains this behavior ? I get this : Why is the class variable cl2 not defined ? Note that the cc2 assignment works fine , a... | ml1 = `` a b c '' .split ( ) ml2 = `` 1 2 3 '' .split ( ) mc = [ i1 + i2 for i1 in ml1 for i2 in ml2 ] class Foo ( object ) : cl1 = ml1 cl2 = ml2 cc1 = [ i1 for i1 in cl1 ] cc2 = [ i2 for i2 in cl2 ] cc = [ i1 + i2 for i1 in cl1 for i2 in cl2 ] print ( `` mc = `` , mc ) foo = Foo ( ) print ( `` cc = `` , foo.cc ) ( def... | What are list comprehension scoping rules within a Python class ? |
Python | pandas allows for cool slicing on time indexes . For example , I can slice a dataframe df for the months from Janurary 2012 to March 2012 by doing : However , I have a dataframe df with a multiindex where the time index is the second level . It looks like : I can still slice using the method above on any specific level... | df [ '2012-01 ' : '2012-03 ' ] A B C D Ea 2001-01-31 0.864841 0.789273 0.370031 0.448256 0.178515 2001-02-28 0.991861 0.079215 0.900788 0.666178 0.693887 2001-03-31 0.016674 0.855109 0.984115 0.436574 0.480339 2001-04-30 0.120924 0.046013 0.659807 0.210534 0.694029 2001-05-31 0.788149 0.296244 0.478201 0.845042 0.43781... | time slice on second level of multiindex |
Python | Given a 2d matrix , for instance : how can I select NxN window around a given element so that the window is filled with an arbitrary ( e.g . mean ) value if it goes outside the original array ? Example : would yield | A = array ( [ [ 0 , 1 , 2 , 3 ] , [ 4 , 5 , 6 , 7 ] , [ 8 , 9 , 10 , 11 ] , [ 12 , 13 , 14 , 15 ] ] ) neighbors ( A , x=0 , y=0 , N=3 ) array ( [ [ 2.5 , 2.5 , 2.5 ] , [ 2.5 , 0 , 1 ] , [ 2.5 , 4 , 5 ] ] ) | Slicing outside numpy array |
Python | I am trying to simply create a datetime object from the following date : 'Fri Mar 11 15:59:57 EST 2016 ' using the format : ' % a % b % d % H : % M : % S % Z % Y'.Here 's the code.However , this results in a ValueError as shown below.Maybe I am missing something obviously wrong with my format string , but I have checke... | from datetime import datetimedate = datetime.strptime ( 'Fri Mar 11 15:59:57 EST 2016 ' , ' % a % b % d % H : % M : % S % Z % Y ' ) ValueError : time data 'Fri Mar 11 15:59:57 EST 2016 ' does not match format ' % a % b % d % H : % M : % S % Z % Y ' $ localeLANG=en_US.UTF-8LANGUAGE=LC_CTYPE= '' en_US.UTF-8 '' LC_NUMERIC... | ValueError time data 'Fri Mar 11 15:59:57 EST 2016 ' does not match format ' % a % b % d % H : % M : % S % Z % Y ' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.