lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Python
Here 's an example of what I mean : Do I need to decorate the actual class ?
class MyDecorator ( object ) : def __call__ ( self , func ) : # At which point would I be able to access the decorated method 's parent class 's instance ? # In the below example , I would want to access from here : myinstance def wrapper ( *args , **kwargs ) : return func ( *args , **kwargs ) return wrapperclass SomeC...
Python : How do I access an decorated class 's instance from inside a class decorator ?
Python
Here is the data - Rows 1,3 have duplicate values in Account_Number . So do rows 4,7 . I need to replace the duplicate values in Account_Number with the same values in Dummy_Account . So for 1050080713252 , both rows 1,3 should have same dummy values ACC0000000000001 . But instead of replacing directly , I want to keep...
Account_Number Dummy_Account1050080713252 ACC00000000000011050223213427 ACC00000000000021050080713252 ACC00000001695321105113502309 ACC00000001230051100043521537 ACC00000000000041100045301840 ACC00000000000051105113502309 ACC0000000000040 Account_Number_Map Dummy_Account_OriginalACC0000000000001 ACC0000000000001ACC0000...
Replace other columns of duplicate rows with first unique value and create lookup
Python
I need a way to find the dependencies for each of my Python package 's sub-modules at runtime so I can initialize them in a proper order ( see my current [ EDIT : former ] solution here , which does n't work to well ) , so at first I used the standard Python module modulefinder , but that was way too slow ( ~1-2 second...
# File my_package/module3.pyimport my_package.module1 # Some misc . moduleimport my_package.module2 # Some other misc . moduleimport my_package.dependency_analyzermy_package.dependency_analyzer.gendeps ( )
Python dependency analyzer library
Python
I 'd like to be able to do this : This seems like a problem that should have a simple solution , but I ca n't think of or find one .
class A ( object ) : @ staticandinstancemethod def B ( self=None , x , y ) : print self is None and `` static '' or `` instance '' A.B ( 1,2 ) A ( ) .B ( 1,2 )
Can a method be used as either a staticmethod or instance method ?
Python
I am quite new to programming and do n't understand a lot of concepts . Can someone explain to me the syntax of line 2 and how it works ? Is there no indentation required ? And also , where I can learn all this from ?
string = # extremely large numbernum = [ int ( c ) for c in string if not c.isspace ( ) ]
Complex syntax- Python
Python
SolutionThis solved all issues with my Perl code ( plus extra implementation code ... . : - ) ) In conlusion both Perl and Python are equally awesome . Thanks to ALL who responded , very much appreciated . EditIt appears that the Perl code I am using is spending the majority of its time performing the http get , for ex...
use WWW : :Curl : :Easy ; my $ start_time = gettimeofday ; $ request = HTTP : :Request- > new ( 'GET ' , 'http : //localhost:8080/data.json ' ) ; $ response = $ ua- > request ( $ request ) ; $ page = $ response- > content ; my $ end_time = gettimeofday ; print `` Time taken @ { [ $ end_time - $ start_time ] } seconds.\...
Python vs perl sort performance
Python
I have a pandas Series like this : and a numpy array like this : How can I do a lookup from the values in the numpy array to the indices in the series to get this :
measure0 0.36 0.69 0.211 0.314 0.017 0.123 0.9 array ( [ [ 0 , 0 , 9 , 11 ] , [ 6 , 14 , 6 , 17 ] ] ) array ( [ [ 0.3 , 0.3 , 0.2 , 0.3 ] , [ 0.6 , 0.0 , 0.6 , 0.1 ] ] )
How to apply a Pandas lookup table to a numpy array ?
Python
I am writing a python script which calculates various quantities based on two parameters , the long radius and short radius of a spheroid . It occurred to me that I could write a spheroid class to do this . However , I 'm new to object oriented design and wonder if you more experienced chaps can help me . An instance i...
class Spheroid : def __init__ ( self , a , b ) : self.longax = a self.shortax = b def Volume ( self ) : return 4*pi/3 * self.longax * self.shortax * self.shortax self.volume = 4*pi/3 * self.longax * self.shortax * self.shortax class Spheroid : def __init__ ( self , a , b ) : self.longax = a self.shortax = b self.volume...
Attribute or Method ?
Python
In python , you can concatenate boolean values , and it would return an integer . Example : Why ? Why does this make sense ? I understand that True is often represented as 1 , whereas False is represented as 0 , but that still does not explain how adding two values together of the same type returns a completely differe...
> > > TrueTrue > > > True + True2 > > > True + False1 > > > True + True + True3 > > > True + True + False2 > > > False + False0
Why does concatenating a boolean value return an integer ?
Python
In flask-restplus , I want to render API authentication view for my minimal flask API , where whenever when I make a request to the server , the first API should pop up a protective view for asking the user to provide customized token value before using API call . I came up my solution to make API authentication pop vi...
from functools import wrapsimport requests , json , psycopg2 , datetimefrom time import timefrom flask import Flask , requestfrom flask_sqlalchemy import SQLAlchemyfrom flask_restplus import Resource , Api , abort , fields , inputs , reqparsefrom itsdangerous import SignatureExpired , JSONWebSignatureSerializer , BadSi...
flask : how to bridge front-end with back-end service to render api authentication ?
Python
OverviewSo , I ’ m in the middle of refactoring a project , and I ’ m separating out a bunch of parsing code . The code I ’ m concerned with is pyparsing . I have a very poor understanding of pyparsing , even after spending a lot of time reading through the official documentation . I ’ m having trouble because ( 1 ) py...
def test_multiline_command_ends ( self , topic ) : output = parsed_input ( 'multiline command ends\n\n ' , topic ) expect ( output ) .to_equal ( r '' ' [ 'multiline ' , 'command ends ' , '\n ' , '\n ' ] - args : command ends- multiline_command : multiline- statement : [ 'multiline ' , 'command ends ' , '\n ' , '\n ' ] ...
Can ’ t fix pyparsing error…
Python
I have a list of lists in Python and I want to ( as fastly as possible : very important ... ) append to each sublist the number of time it appear into the nested list.I have done that with some pandas data-frame , but this seems to be very slow and I need to run this lines on very very large scale . I am completely wil...
l = [ [ 1 , 3 , 2 ] , [ 1 , 3 , 2 ] , [ 1 , 3 , 5 ] ] res = [ [ 1 , 3 , 2 , 2 ] , [ 1 , 3 , 5 , 1 ] ]
What is the faster way to count occurrences of equal sublists in a nested list ?
Python
My models are ... My fixture for District model is ... .In fact , the fixture is generated by django 's 'dumpdata ' itself.But , while trying to load the fixture , I am getting the following error ... Where am I doing wrong ?
class StateManager ( models.Manager ) : def get_by_natural_key ( self , name ) : return self.get ( name=name ) class DistrictManager ( models.Manager ) : def get_by_natural_key ( self , name , state ) : return self.get ( name=name , state=state ) class State ( models.Model ) : class Meta : verbose_name = `` State '' ve...
django : loading fixtures with natural foreignkey fails with 'ValueError : invalid literal for int ( ) with base 10 '
Python
I was trying set comprehension for 2.6 , and came across the following two ways . I thought the first method would be faster than the second , timeit suggested otherwise . Why is the second method faster even though the second method has got an extra list instantiation followed by a set instantiation ? Method 1 : Metho...
In [ 16 ] : % timeit set ( node [ 0 ] for node in pwnodes if node [ 1 ] .get ( 'pm ' ) ) 1000000 loops , best of 3 : 568 ns per loop In [ 17 ] : % timeit set ( [ node [ 0 ] for node in pwnodes if node [ 1 ] .get ( 'pm ' ) ] ) 1000000 loops , best of 3 : 469 ns per loop
python set comprehension for 2.6
Python
Using django-cacheops , I want to test that my views are getting cached as I intend them to be . In my test case I 'm connecting cacheops cache_read signal to a handler that should increment a value in the cache for hits or misses . However , the signal is never fired . Does anyone know the correct way to connect a dja...
from cacheops.signals import cache_readcache.set ( 'test_cache_hits ' , 0 ) cache.set ( 'test_cache_misses ' , 0 ) def cache_log ( sender , func , hit , **kwargs ) : # never called if hit : cache.incr ( 'test_cache_hits ' ) else : cache.incr ( 'test_cache_misses ' ) class BootstrapTests ( TestCase ) : @ classmethod def...
Connecting django signal handlers in tests
Python
I would like to extend the Decimal class to add some helpful methods to it , specially for handling money.The problem when I go do this : It throws an exception : This is because of the way Decimal does arithmetic , it always returns a new Decimal object , by literally calling Decimal ( new value ) at the end of the co...
from decimal import Decimalclass NewDecimal ( Decimal ) : def new_str ( self ) : return `` $ { } '' .format ( self ) d1 = NewDecimal ( 1 ) print d1.new_str ( ) # prints ' $ 1'd2 = NewDecimal ( 2 ) d3 = NewDecimal ( 3 ) d5 = d2 + d3print d5.new_str ( ) # exception happens here AttributeError : 'Decimal ' object has no a...
Python , How to extend Decimal class to add helpful methods
Python
I would like to build a multilevel dropdown hierarchy in Django using Models.And informations should be updates dynamicaly without reloading the page.I know that i should use Ajax , but is it possible to generate a template from the following models : It it possible to generate that model from django model forms or I s...
class Pays ( models.Model ) : nom_pays=models.CharField ( max_length=45 ) def__str__ ( self ) : return self.nom_paysclass Province ( models.Model ) : nom_province=models.CharField ( max_length=100 ) pays=models.ForeignKey ( Pays , on_delete=models.CASCADE ) def__str__ ( self ) : return self.nom_provinceclass Ville ( mo...
I would like to generate 4 levels dropdown form using django model forms
Python
When submitting an event , using the Google Analytics Measurement Protocol ... GA is classifying the events as bot traffic . I can determine this by configuring two views in GA , one with bot filtering on , and one with bot filtering disabled . The events show up consistently in the view with bot filtering disabled.We ...
payload = { ' v ' : 1 , 't ' : 'event ' , 'tid ' : tracking_id , 'ec ' : category , 'ea ' : action , 'el ' : label } if value and type ( value ) is int : payload [ 'ev ' ] = valueif user_id : payload [ 'uid ' ] = user_idelse : payload [ 'cid ' ] = str ( uuid4 ( ) ) requests.post ( 'https : //www.google-analytics.com/co...
Google Analytics , Server-Side Tracking & Bot Filter
Python
I 'm working with a data set of accelerations using python 2.7 , in order to find the angle , I 'm using arctan2 ( y , x ) . My problem is that , while my data can rotate beyond pi , the output of arctan2 ( y , x ) is bounded between pi and -pi . This means any time I go above pi , I suddenly have a dramatic jump in my...
for index in range ( 1 , ( len ( x_data ) ) ) : new_angle = math.atan2 ( ( y_data [ index ] ) , ( x_data [ index ] ) ) if ( new_angle - angle [ index-1 ] ) > 5 : new_angle = new_angle - 6.28 if ( new_angle - angle [ index-1 ] ) < -5 : new_angle = new_angle + 6.28 angle.append ( new_angle )
Making arctan2 ( ) continuous beyond 2pi
Python
I am trying to write a closure in Ruby . This is the code written in Python : Is there a `` nonlocal '' equivalent in Ruby so I can access and make changes to the variable x from inside increment ?
def counter ( ) : x = 0 def increment ( y ) : nonlocal x x += y print ( x ) return increment
Ruby equivalent of python nonlocal
Python
I did some LDA using scikit-learn 's LDA function and I noticed in my resulting plots that there is a non-zero correlation between LDs . This is very concerning , so I went back and used the Iris data set as reference . I also found in the scikit documentation the same non-zero correlation LDA plot , which I could repr...
from sklearn.lda import LDAsklearn_lda = LDA ( n_components=2 ) transf_lda = sklearn_lda.fit_transform ( X , y )
Bug in scikit-learns LDA function - plots shows non-zero correlation
Python
I have a large gzipped file ( 5000 columns × 1M lines ) consisting of 0 's and 1 's : I want to transpose it , but using numpy or other methods just loads the whole table on the RAM , and I just have at my disposal 6GB.For this reason , I wanted to use a method that writes each transposed line to an open file , instead...
0 1 1 0 0 0 1 1 1 ... . ( ×5000 ) 0 0 0 1 0 1 1 0 0 ... . ( ×1M ) import gzipwith open ( `` output.txt '' , `` w '' ) as out : with gzip.open ( `` file.txt '' , `` rt '' ) as file : number_of_columns = len ( file.readline ( ) .split ( ) ) # iterate over number of columns ( ~5000 ) for column in range ( number_of_column...
Transpose a large array without loading into memory
Python
With `` pip freeze '' I 'll get a list of package names . e.g . : Is there any way to receive a list of actual names to import ? e.g . instead of djangorestframework = > rest_framework
Django==1.9.7psycopg2==2.6.1djangorestframework==3.3.3djangorestframework-jwt==1.8.0django-rest-swagger==0.3.7django-environ==0.4.0python-dateutil==2.5.3django-sendfile==0.3.10
List of actuals import names in python
Python
Code : With both CPython and PyPy , I am getting a segmentation fault . Why ? CPython bug reportPyPy bug reportAbstract Syntax Trees documentation
import astglobalsDict = { } fAst = ast.FunctionDef ( name= '' foo '' , args=ast.arguments ( args= [ ] , vararg=None , kwarg=None , defaults= [ ] ) , body= [ ] , decorator_list= [ ] ) exprAst = ast.Interactive ( body= [ fAst ] ) ast.fix_missing_locations ( exprAst ) compiled = compile ( exprAst , `` < foo > '' , `` sing...
Python : getting segmentation fault when using compile/eval
Python
The work here is to scrape an API a site that starts from https : //xxx.xxx.xxx/xxx/1.json to https : //xxx.xxx.xxx/xxx/1417749.json and write it exactly to mongodb . For that I have the following code : But it is taking lot of time to do the task . Question here is how can I speed up this process .
client = pymongo.MongoClient ( `` mongodb : //127.0.0.1:27017 '' ) db = client [ `` thread1 '' ] com = db [ `` threadcol '' ] start_time = time.time ( ) write_log = open ( `` logging.log '' , `` a '' ) min = 1max = 1417749for n in range ( min , max ) : response = requests.get ( `` https : /xx.xxx.xxx/ { } .json '' .for...
How can I scrape faster
Python
Context : I am developping a simple Python application using a PySide2 GUI . It currently works fine in Windows , Linux and Mac . On Windows , I could use PyInstaller and InnoSetup to build a simple installer . Then I tried to do the same thing on Mac . It soon broke , because the system refused to start the command or...
python setup.py py2app -A from PySide3.QtWidgets import *import sysclass MainWindow ( QMainWindow ) : def __init__ ( self ) : super ( ) .__init__ ( ) hello = QLabel ( 'Hello ' , self ) hello.move ( 50 , 50 ) def run ( args ) : app = QApplication ( args ) main = MainWindow ( ) main.show ( ) sys.exit ( app.exec_ ( ) ) if...
How to build an mac os app from a python script having a PySide2 GUI ?
Python
I want to remove those tuples which had same values at index 0 except the first occurance . I looked at other similar questions but did not get a particular answer I am looking for . Can somebody please help me ? Below is what I tried.my expected output : [ ( 1,2,3 ) , ( 2,3,4 ) , ( 0,2,0 ) , ( 5,4,3 ) ]
from itertools import groupbyimport randomNewlist = [ ] abc = [ ( 1,2,3 ) , ( 2,3,4 ) , ( 1,0,3 ) , ( 0,2,0 ) , ( 2,4,5 ) , ( 5,4,3 ) , ( 0,4,1 ) ] Newlist = [ random.choice ( tuple ( g ) ) for _ , g in groupby ( abc , key=lambda x : x [ 0 ] ) ] print Newlist
How can I remove duplicate tuples from a list based on index value of tuple while maintaining the order of tuple ?
Python
I have been doing research for a very important personal project . I would like to create a Flask Search Application that allows me to search for content across 100 Plus PDF files . I have found Some information around A ElasticSearch Lib that works well with flask. -- -- -- Progress -- -- -- I now have a working solut...
# ! /usr/bin/env python3 # -*- coding : utf-8 -*- # import libraries to help read and create PDFimport PyPDF2from fpdf import FPDFimport base64import jsonfrom flask import Flask , jsonify , request , render_template , jsonfrom datetime import datetimeimport pandas as pd # import the Elasticsearch low-level client libra...
How do I Make a PDF searchable for a flask search application ?
Python
I have the following recursive function , and I 'm having trouble figuring out how python handles variables in recursive functions . Will it create a copy of the addresses variable for every recursion , or will it overwrite the variable and create a horrible mess ?
def get_matches ( ) : addresses = get_addresses ( ) # do stuff for addr in addresses : # do stuff if some_condition : get_matches ( ) else : return
python recursive variables referenced or copied ?
Python
This is what I have so far : I want to be able to eventually scan a document and have it pick out 3 letter words but I ca n't get this portion to work . I am new to coding in general and python is the first language I 've learned so I am probably making a big stupid mistake .
alphabet = `` a '' or `` b '' or `` c '' or `` d '' or `` e '' or `` f '' or \ `` g '' or `` h '' or `` i '' or `` j '' or `` k '' or `` l '' or \ `` m '' or `` n '' or `` o '' or `` p '' or `` q '' or `` r '' or \ `` s '' or `` t '' or `` u '' or `` v '' or `` w '' or `` x '' or \ `` y '' or `` z '' letter_word_3 = an...
Defining the alphabet to any letter string to then later use to check if a word has a certain amount of characters
Python
Suppose we are given two 2D numpy arrays a and b with the same number of rows . Assume furthermore that we know that each row i of a and b has at most one element in common , though this element may occur multiple times . How can we find this element as efficiently as possible ? An example : It is easy to come up with ...
import numpy as npa = np.array ( [ [ 1 , 2 , 3 ] , [ 2 , 5 , 2 ] , [ 5 , 4 , 4 ] , [ 2 , 1 , 3 ] ] ) b = np.array ( [ [ 4 , 5 ] , [ 3 , 2 ] , [ 1 , 5 ] , [ 0 , 5 ] ] ) desiredResult = np.array ( [ [ np.nan ] , [ 2 ] , [ 5 ] , [ np.nan ] ] ) from intertools import starmapdesiredResult = np.array ( list ( starmap ( np.in...
Numpy : find row-wise common element efficiently
Python
Let 's have a small dataframe : df = pd.DataFrame ( { 'CID ' : [ 1,2,3,4,12345 , 6 ] } ) When I search for membership the speed is vastly different based on whether I ask to search in df.CID or in df [ 'CID ' ] . Why is that ?
In [ 25 ] : % timeit 12345 in df.CIDOut [ 25 ] :89.8 µs ± 254 ns per loop ( mean ± std . dev . of 7 runs , 10000 loops each ) In [ 26 ] : % timeit 12345 in df [ 'CID ' ] Out [ 26 ] :42.3 µs ± 334 ns per loop ( mean ± std . dev . of 7 runs , 10000 loops each ) In [ 27 ] : type ( df.CID ) Out [ 27 ] : pandas.core.series....
Speed difference between bracket notation and dot notation for accessing columns in pandas
Python
I have a program that works fine , but when I make it into an executable via PyInstaller , I have problems . I traced this down to a weird behavior that demonstrates the problem . In main ( ) , I place the following statement : When I run my normal Python script , it prints '1e-07 ' as expected.When I run my PyInstalle...
print float ( '1e-07 ' ) def main ( ) : print float ( '1e-07 ' ) if __name__ == '__main__ ' : main ( ) import tracebackimport sysprint `` test '' try : print float ( `` 1e-07 '' ) except : traceback.print_exc ( file=sys.stdout ) pyinstaller test.py 156 INFO : PyInstaller : 3.2 156 INFO : Python : 2.7.3 156 INFO : Platf...
converting a Python string to float only fails with PyInstaller
Python
I have a dataset of events ( tweets to be specific ) that I am trying to bin / discretize . The following code seems to work fine so far ( assuming 100 bins ) : But then , I came across this fateful line at python docs 'This makes possible an idiom for clustering a data series into n-length groups using zip ( * [ iter ...
HOUR = timedelta ( hours=1 ) start = datetime.datetime ( 2009,01,01 ) z = [ dt + x*HOUR for x in xrange ( 1 , 100 ) ]
Binning into timeslots - Is there a better way than using list comp ?
Python
Suppose I have an object model A with a one-to-many relationship with B in Peewee using an sqlite backend . I want to fetch some set of A and join each with their most recent B . Is their a way to do this without looping ? The naive way would be to call order_by and limit ( 1 ) , but that would apply to the entire quer...
class A ( Model ) : some_field = CharField ( ) class B ( Model ) : a = ForeignKeyField ( A ) date = DateTimeField ( default=datetime.datetime.now ) q = A.select ( ) .join ( B ) .order_by ( B.date.desc ( ) ) .limit ( 1 ) q = B.select ( ) .order_by ( B.date.desc ( ) ) .limit ( 1 ) .join ( A ) q1 = A.select ( ) q2 = B.sel...
Fetching most recent related object for set of objects in Peewee
Python
There are two numeric columns in a data file . I need to calculate the average of the second column by intervals ( such as 100 ) of the first column.I can program this task in R , but my R code is really slow for a relatively large data file ( millions of rows , with the value of first column changing between 1 to 3313...
5380 30.07383\n5390 30.87\n5393 0.07383\n5404 6\n5428 30.07383\n5437 1\n5440 9\n5443 30.07383\n5459 6\n5463 30.07383\n5480 7\n5521 30.07383\n5538 0\n5584 20\n5673 30.07383\n5720 30.07383\n5841 3\n5880 30.07383\n5913 4\n5958 30.07383\n intervals_of_first_columns , average_of_2nd column_by_the_interval100 , 0\n200 , 0\n3...
Efficiently average the second column by intervals defined by the first column
Python
SummarySee the toy example Azure notebook hosted at this link . The notebook can be cloned and run , or downloaded and run locally , from there , but all of the code is also below for convenience.When all the cells are run , the javascript console reports these errors ( abbreviated ) in the final cell , and the final e...
Error : Could not create a view for model id 91700d0eb745433eaee98bca2d9f3fc8 at promiseRejection ( utils.js:119 ) Error : Could not create view at promiseRejection ( utils.js:119 ) Uncaught ( in promise ) TypeError : Can not read property 'then ' of undefinedUncaught ( in promise ) TypeError : Can not read property 't...
Child widget creation in ipywidgets produces an error using ViewList and create_child_view
Python
I 've seen following code in the python standard library /usr/lib/python2.7/multiprocessing/dummy/__init__.py : What does this idiom mean ? My best guess is : `` let 's check if dict and list exist '' .Is it just legacy code from the ancient times without list and dict in the __builtins__ ? And I have another mad guess...
list = listdict = dict
What is the effect of `` list=list '' in Python modules ?
Python
Why the mixture of lowercase and UpperCamelCase ? Why collections instead of Collections ? I sometimes do this for example : by mistake . What rule of thumb can I use to avoid such mistakes in the future ?
namedtupledeque Counter OrderedDictdefaultdict from collections import default_dict
Naming convention in Collections : why are some lowercase and others CapWords ?
Python
I am trying to figure out what 's special about March 16th , 1984 . On a virtual machine I am using ( nothing special about it ) , Python ( as well as PyPy ) crashes when trying to use mktime with what seems to be a perfectly reasonable time struct . Why and what can be done to avoid this issue ? Although the problem d...
$ pypyPython 2.7.3 ( f66246c46ca30b26a5c73e4cc95dd6235c966b8f , Jul 30 2013 , 09:27:06 ) [ PyPy 2.0.2 with GCC 4.4.7 20120313 ( Red Hat 4.4.7-3 ) ] on linux2Type `` help '' , `` copyright '' , `` credits '' or `` license '' for more information. > > > > import time > > > > time.mktime ( ( 1984,3,16,0,0,0,0,0,0 ) ) Trac...
What happened on March 16th 1984 ?
Python
I have a queue from which I need to get chunks of 10 entries and put them in a list , which is then processed further . The code below works ( the `` processed further '' is , in the example , just print the list out ) .This code is ugly . I do not see how to improve it - I read some time ago how to use iter with a sen...
import multiprocessing # this is an example of the actual queueq = multiprocessing.Queue ( ) for i in range ( 22 ) : q.put ( i ) q.put ( `` END '' ) counter = 0mylist = list ( ) while True : v = q.get ( ) if v == `` END '' : # outputs the incomplete ( < 10 elements ) list print ( mylist ) break else : mylist.append ( v...
How to get chunks of elements from a queue ?
Python
I 'm trying to use Django 1.6 transactions to avoid race conditions on a game I 'm developing . The game server has one simple goal : to pair two players.My current approach is : User wants to playThe server checks if there is anyone else waiting to play.If there is not , it creates a GameConnection object ( that has a...
# data [ 'nickname ' ] = user 's choicegames = GameConnection.objects.all ( ) if not games : game = GameConnection.objects.create ( connection=unicode ( uuid.uuid4 ( ) ) ) game.nick1 = data [ `` nickname '' ] game.save ( ) response = HttpResponse ( json.dumps ( { 'connectionId ' : game.connection , 'whoAmI ' : 1 , 'nic...
Django 1.6 transactions to avoid race conditions
Python
I am using django 1.27 with python 2.7.2.I want a message to be translated to an empty string.For example if i have this in my django.po file : So i want it to not show the 'word ' when translating the page.I have tried putting a space instead of `` '' but that did not help and i still get the original 'word ' displaye...
# .\path\file.pymsgid `` word '' msgstr `` ''
How do i translate a message to an empty string with django
Python
I am using an external program to compute a matrix that is written in C++ and is interfaced with python through boost : :python . I would like to pass this C array to numpy , and according to the authors this ability is already implemented with numpy 's obj.__array_interface__ . If I call this in a python script and as...
print X # < sprint.Matrix object at 0x107c5c320 > print X.__array_interface__ # < bound method Matrix.__array_interface__ of < sprint.Matrix object at 0x107c5c320 > > print X.__array_interface__ ( ) # { 'shape ' : ( 5 , 5 ) , 'data ' : ( 4416696960 , True ) , 'typestr ' : ' < f8 ' } print np.array ( X ) # Traceback ( m...
Numpy 's __array_interface__ not returning dict
Python
I have some GAE apps which I am thinking to separate into three modules : default ( www ) , mobile and api but I am having some difficulties understanding Modules and how to organize the code.According to the image found here this is how an app should look like.This is the simplifed structure I came up with so far : Th...
gae-app/├── modules│ ├── api│ │ ├── app.yaml│ │ └── src│ │ └── main.py│ ├── mobile│ │ ├── app.yaml│ │ └── src│ │ └── index.html│ └── www│ ├── app.yaml│ └── src│ ├── main.py│ └── templates├── cron.yaml├── index.yaml└── queue.yaml
How to organize GAE Modules app structure and code ?
Python
I have dataframe i.e. , I need to replace the `` Nan '' in `` school '' and `` city '' when a value in `` class '' and `` section '' column matches . The resultant outcome suppose to be , Input DataframeCan anyone help me out in this ?
Input Dataframe class section sub marks school city0 I A Eng 80 jghss salem1 I A Mat 90 jghss salem 2 I A Eng 50 Nan salem 3 III A Eng 80 gphss Nan4 III A Mat 45 Nan salem5 III A Eng 40 gphss Nan6 III A Eng 20 gphss salem7 III A Mat 55 gphss Nan class section sub marks school city0 I A Eng 80 jghss salem1 I A Mat 90 jg...
Pandas Dataframe replace Nan from a row when a column value matches
Python
I 'd like to test the default behavior of a function . I have the following : Output is hello ; not what I wanted.One solution is to pass the default value explicitly : app.foo.bar ( text=app.foo.DEFAULT_VALUE ) .But I find it interesting that this does n't seem to be an issue when defaulting to the global scope : Outp...
# app/foo.pyDEFAULT_VALUE = 'hello'def bar ( text=DEFAULT_VALUE ) : print ( text ) # test/test_app.pyimport appdef test_app ( monkeypatch ) : monkeypatch.setattr ( 'app.foo.DEFAULT_VALUE ' , 'patched ' ) app.foo.bar ( ) assert 0 # app/foo.pyDEFAULT_VALUE = 'hello'def bar ( ) : print ( DEFAULT_VALUE )
pytest - monkeypatch keyword argument default
Python
For example , the digits of 123431 and 4577852 increase and then decrease . I wrote a code that breaks the numbers into a list and is able to tell if all of the digits increase or if all of the digits decrease , but I do n't know how to check for digits increasing then decreasing . How do I extend this ?
x = int ( input ( `` Please enter a number : `` ) ) y = [ int ( d ) for d in str ( x ) ] def isDecreasing ( y ) : for i in range ( len ( y ) - 1 ) : if y [ i ] < y [ i + 1 ] : return False return Trueif isDecreasing ( y ) == True or sorted ( y ) == y : print ( `` Yes '' )
How can I determine if the numbers in a list initially increase ( or stay the same ) and then decrease ( or stay the same ) with Python ?
Python
Presumably dict_keys are supposed to behave as a set-like object , but they are lacking the difference method and the subtraction behaviour seems to diverge.Why does dict_keys class try to iterate an integer here ? Does n't that violate duck-typing ?
> > > d = { 0 : 'zero ' , 1 : 'one ' , 2 : 'two ' , 3 : 'three ' } > > > d.keys ( ) - [ 0 , 2 ] { 1 , 3 } > > > d.keys ( ) - ( 0 , 2 ) TypeError : 'int ' object is not iterable > > > dict.fromkeys ( [ ' 0 ' , ' 1 ' , '01 ' ] ) .keys ( ) - ( '01 ' , ) { '01 ' } > > > dict.fromkeys ( [ ' 0 ' , ' 1 ' , '01 ' ] ) .keys ( )...
Why do dict keys support list subtraction but not tuple subtraction ?
Python
How to check if a given link ( url ) is to file or another webpage ? I mean : page : https : //stackoverflow.com/questions/page : https : //www.w3schools.com/html/default.aspfile : https : //www.python.org/ftp/python/3.7.2/python-3.7.2.exefile : http : //jmlr.org/papers/volume19/16-534/16-534.pdf # page=15Currently I a...
import redef check_file ( url ) : try : sub_domain = re.split ( '\/+ ' , url ) [ 2 ] # part after '2nd slash ( es ) '' except : return False # nothing = main page , no file if not re.search ( '\ . ' , sub_domain ) : return False # no dot , no file if re.search ( '\.htm [ l ] { 0,1 } $ |\.php $ |\.asp $ ' , sub_domain )...
Regex check if link is to a file
Python
See MWE below : While text1 and text2 which use \ , and \ ; spacing will work without issues , text3 which uses \ : ( ie : the horizontal spacing located between the previous two ) fails with a ValueError : Why is this LaTeX spacing not recognized ?
import matplotlib.pyplot as pltimport matplotlib.offsetbox as offsetboxfig = plt.figure ( ) ax = fig.add_subplot ( 111 ) text1 = r ' $ a\ , =\ , { } \pm { } $ '.format ( 0.01 , 0.002 ) # Works.text2 = r ' $ a\ ; =\ , { } \pm { } $ '.format ( 0.01 , 0.002 ) # Works.text3 = r ' $ a\ : =\ , { } \pm { } $ '.format ( 0.01 ,...
ValueError in matplotlib when using \ : LaTeX horizontal spacing
Python
The code pasted below does the following : creates an import hookcreates a context manager which sets the meta_path and cleans on exit.dumps all the imports done by a program passed in input in imports.logNow I was wondering if using a context manager is a good idea in this case , because actually I do n't have the sta...
with CollectorContext ( cl , sys.argv , 'imports.log ' ) as cc : from __future__ import with_statementimport osimport sysclass CollectImports ( object ) : `` '' '' Import hook , adds each import request to the loaded set and dumps them to file `` '' '' def __init__ ( self ) : self.loaded = set ( ) def __str__ ( self ) ...
Is a context manager right for this job ?
Python
In Perl , one can do the followingI would like to be able to do the equivalent in Python , that is to skip a block if it has been executed once .
for ( @ foo ) { # do something next if $ seen { $ _ } ++ ; }
What is the python equivalent of the Perl pattern to track if something has already been seen ?
Python
What is the difference between int and int* ?
reveal_type ( 1 ) # Revealed type is 'builtins.int'bla = [ 1,2,3 ] reveal_type ( bla [ 0 ] ) # Revealed type is 'builtins.int*'reveal_type ( bla [ 0 ] * 2 ) # Revealed type is 'builtins.int '
What does the asterisk in the output of ` reveal_type ` mean ?
Python
I 'm trying to get my Sphinx documentation build correctly and have cross-references ( including those from inherited relations ) work right.In my project , I have a situation which is depicted in the example below , which I replicated for convenience on this github repo : In a.b.__init__ , I declare classes A and B . ...
$ tree ..├── a│ ├── b│ │ └── __init__.py│ └── __init__.py├── conf.py├── index.rst└── README.md WARNING : py : class reference target not found : a.b.A
Sphinx cross referencing breaks for inherited objects imported and documented in a parent module
Python
I 've got a loop that wants to execute to exhaustion or until some user specified limit is reached . I 've got a construct that looks bad yet I ca n't seem to find a more elegant way to express it ; is there one ? Holy nesting ! There has to be a better way . For purposes of a working example , xrange is used where I n...
def ello_bruce ( limit=None ) : for i in xrange ( 10**5 ) : if predicate ( i ) : if not limit is None : limit -= 1 if limit < = 0 : breakdef predicate ( i ) : # lengthy computation return True
a more pythonic way to express conditionally bounded loop ?
Python
I need to examine a python module to find simple data as well as `` user defined objects '' . Here , I mean objects ( or functions or classes ) that are not builtin , but defined with a class/def statement or dynamically loaded/generated.Note there are similar questions , but they ask about `` new style user defined cl...
> > > a=0. > > > dir ( a ) [ '__abs__ ' , '__add__ ' , '__and__ ' , '__bool__ ' , '__ceil__ ' , '__class__ ' ... > > > type ( a ) < class 'float ' >
How to check if a python class or object is user defined ( not a builtin ) ?
Python
Later Edit : I uploaded here a sample of my original data . It 's actually a segmentation image in the DICOM format . The volume of this structure as it is it 's ~ 16 mL , so I assume the inner ellipsoid volume should be smaller than that . to extract the points from the DICOM image I used the following code : I have a...
import osimport numpy as npimport SimpleITK as sitkdef get_volume_ml ( image ) : x_spacing , y_spacing , z_spacing = image.GetSpacing ( ) image_nda = sitk.GetArrayFromImage ( image ) imageSegm_nda_NonZero = image_nda.nonzero ( ) num_voxels = len ( list ( zip ( imageSegm_nda_NonZero [ 0 ] , imageSegm_nda_NonZero [ 1 ] ,...
Maximum volume inscribed ellipsoid in a polytope/set of points
Python
Is there a way to do what classmethod does in Python in C # ? That is , a static function that would get a Type object as an ( implicit ) parameter according to whichever subclass it 's used from.An example of what I want , approximately , isthe expected output being ( same code on codepad here . )
class Base : @ classmethod def get ( cls , id ) : print `` Would instantiate a new % r with ID % d . `` % ( cls , id ) class Puppy ( Base ) : passclass Kitten ( Base ) : passp = Puppy.get ( 1 ) k = Kitten.get ( 1 ) Would instantiate a new < class __main__.Puppy at 0x403533ec > with ID 1.Would instantiate a new < class ...
Python-style classmethod for C # ?
Python
For example in this code : I found this code , but I need to be able to explain each and every part of it .
def product ( list ) : p =1 for i in list : p *= i return p
What does *= mean in python ?
Python
My aim is to have a custom QSlider with tickmarks and tick labels in Python 3 using PySide2 module . In order to do so I edit the default paintEvent of the QSlider class in a derived class . However , it turns out that that the printable area is limited and the top/bottom labels I placed are cropped ( see screenshot ) ...
import sysfrom PySide2.QtCore import *from PySide2.QtWidgets import *from PySide2.QtGui import *slider_x = 150slider_y = 450slider_step = [ 0.01 , 0.1 , 1 , 10 , 100 ] # in micronsclass MySlider ( QSlider ) : def __init__ ( self , type , parent=None ) : super ( MySlider , self ) .__init__ ( parent ) self.Type = type de...
Is it possible to expand the drawable area around the QSlider
Python
Sorry for the vague title , but it 's hard to explain concisely.Basically , imagine I have a list ( in Python ) that looks like this : From that , I want to get this : One way I was thinking of doing this was using reduce like so : But I do n't think this is very efficient , since it does n't take advantage of the fact...
[ ' a ' , ' b ' , ' c\nd ' , ' e ' , ' f\ng ' , ' h ' , ' i ' ] [ ' a ' , ' b ' , ' c ' , 'd ' , ' e ' , ' f ' , ' g ' , ' h ' , ' i ' ] reduce ( lambda x , y : x + y.split ( '\n ' ) , lst , [ ] ) Ignorable lineField name 1|Field name 2|Field name 3|Field name 4Value 1|Value 2|Value 3|Value 4Value 1|Value 2|Value 3|Val...
Best way to split every nth string element and merge into array ?
Python
I am trying to store the output of a cmd command as a variable in python . To achieve this i am using os.system ( ) but os.system ( ) just runs the process , it does n't capture the output . Then i tried to use the subprocess module.I am getting the following error FileNotFoundError : [ WinError 2 ] The system can not ...
import osPlatformName = os.system ( `` adb shell getprop | grep -e 'bt.name ' '' ) DeviceName = os.system ( `` adb shell getprop | grep -e '.product.brand ' '' ) DeviceID = os.system ( `` adb shell getprop | grep -e 'serialno ' '' ) Version = os.system ( `` adb shell getprop | grep -e 'version.release ' '' ) print ( Pl...
Store filtered output of cmd command in a variable
Python
I 'm trying to write a custom exporter for Blender in Python . However , I 'm having some trouble figuring out how I could use Python 's native sort implementation to sort my vertices in the way I need.Basically , I need to export the vertices in such a way where they can form a grid like this , assuming that V is a do...
V V V V VV V V V VV V V V VV V V V V # ! BPY '' '' '' Name : 'VaV Export'Blender : 269Group : 'Export'Tooltip : 'Export to VaV file format ' '' '' '' import Blenderimport bpyclass Coordinate : def __init__ ( self , posX , posY ) : self.posX = posX self.posY = posY def sortX ( self , other ) : if posX < other.posX : ret...
Multisort Python
Python
Let 's say I have these parsers : parse_foo and parse_bar are both generators that yield rows one by one . If I wish to create a single dispatch function , I would do this : The yield from syntax allows me to tunnel information easily up and down the generators.Is there any way to maintain the tunneling while modifying...
parsers = { `` .foo '' : parse_foo , `` .bar '' , parse_bar } def parse ( ext ) : yield from parsers [ ext ] ( ) def parse ( ext ) : for result in parsers [ ext ] ( ) : # Add the extension to the result result.ext = ext yield result
Modifying yield from 's return value
Python
I use Poetry to build tar.gz and whl files for my example package ( https : //github.com/iamishalkin/cyrtd ) and then try to install package inside pipenv environment . tar.gz installation fails and this is a piece of logs : Cython is installed and is callable from virtual interpreter . Even in logs it is written , tha...
$ poetry build ... $ pip install dist/cyrtd-0.1.0.tar.gzProcessing c : \work2\cyrtd\dist\cyrtd-0.1.0.tar.gz Installing build dependencies ... done Getting requirements to build wheel ... done Preparing wheel metadata ... doneRequirement already satisfied : cython < 0.30.0 , > =0.29.13 in c : \users\ivan.mishalkin\.virt...
No module named 'Cython ' with pip installation of tar.gz
Python
I might seem stupid here . However , I was writing some python code , and this thing struck me . In python there are things called decorators which are denoted by @ and used `` around '' functions like : I also know slivers of design patterns and I know there are patterns called decorators . Then once I thought , `` He...
class PlotABC ( metaclass=ABCMeta ) : @ property def figure ( self ) : if self._figure is None : self.__create_figure ( ) return self._figure @ abstractmethod def _prepare_series ( self ) : pass
Is python @ decorator related to the decorator design pattern ?
Python
I want a string such as 'ddxxx ' to be returned as ( 'd ' : 2 , ' x ' : 3 ) . So far I 've attemptedwhere s is the string , however I keep getting a KeyError . E.g . if I put s as 'hello ' the error returned is :
result = { } for i in s : if i in s : result [ i ] += 1 else : result [ i ] = 1return result result [ i ] += 1KeyError : ' h '
How do I create a dictionary from a string returning the number of characters
Python
I 'm trying to package my Kivy app for Windows , but I 'm having some issues.Following the instructions in the kivy docs , I created and edited the spec file . I do n't use neither pygame nor SDL2 ( I mean I do n't import them directly to run my program ) , but in the Kivy log I see pygame still provides my window : I ...
[ INFO ] [ Text ] Provider : pygame [ INFO ] [ Window ] Provider : pygame ( ... ) 202 WARNING : stderr : File `` C : \Program Files\Python Kivy-1.9.0-py3.4-win32-x86\kivy34\kivy\tools\packaging\pyinstaller_hooks\__init__.py '' , line 13 , in install_hooks sym [ 'rthooks ' ] [ 'kivy ' ] = [ join ( curdir , 'rt-hook-kivy...
Kivy 1.9.0 Windows package KeyError : 'rthooks '
Python
I 'm trying to remove the parenthesis areas of these strings below , but I ca n't get a regex working : ( Data : Regex tried : Regex101 : http : //regex101.com/r/bD8fE2Example code
x ( LOC ) ds ds ( 32C ) d'ds ds ( LeC ) ds-d da ( LOQ ) 12345 ( deC ) [ \ ( \w+\ ) ] items = [ `` x ( LOC ) '' , `` ds ds ( 32C ) '' , `` d'ds ds ( LeC ) '' , `` ds-d da ( LOQ ) '' , `` 12345 ( deC ) '' ] for item in items : item = re.sub ( r '' [ \ ( \w+\ ) ] '' , `` '' , item ) print item
Regex for removing data in parenthesis
Python
I 've written a script in python scrapy to download some images from a website . When i run my script , I can see the link of images ( all of them are in .jpg format ) in the console . However , when I open the folder in which the images are supposed to be saved when the downloading is done , I get nothing in there . W...
import scrapyfrom scrapy.crawler import CrawlerProcessclass YifyTorrentSpider ( scrapy.Spider ) : name = `` yifytorrent '' start_urls= [ 'https : //www.yify-torrent.org/search/1080p/ ' ] def parse ( self , response ) : for q in response.css ( `` article.img-item .poster-thumb '' ) : image = response.urljoin ( q.css ( `...
Trouble downloading images using scrapy
Python
note : this question is indeed a duplicate of Split pandas dataframe string entry to separate rows , but the answer provided here is more generic and informative , so with all respect due , I chose not to delete the threadI have a 'dataset ' with the following format : and I would like to normalize it by duplicating al...
id | value | ... -- -- -- -- | -- -- -- -| -- -- -- a | 156 | ... b , c | 457 | ... e , g , f , h | 346 | ... ... | ... | ... id | value | ... -- -- -- -- | -- -- -- -| -- -- -- a | 156 | ... b | 457 | ... c | 457 | ... e | 346 | ... g | 346 | ... f | 346 | ... h | 346 | ... ... | ... | ... df [ 'count_ids ' ] = df [ '...
normalizing data by duplication
Python
I 'm using openpyxl to open an .xlsx file , update some values in it and save it as a different .xlsx file . I am trying to add a footer with new lines in it : But when I open newly created file and look at the footer , \n gets replaced in a weird way : I have also noticed that if I try to convert it to PDF with a help...
# example codewb = openpyxl.load_workbook ( 'file.xlsx ' ) sheet = wb.get_sheet_by_name ( 'Sheet1 ' ) sheet.header_footer.left_footer.font_size = 7sheet.header_footer.left_footer.text = ' & BSome text & B\nMore text\nEven more'sheet.header_footer.right_footer.font_size = 7sheet.header_footer.right_footer.text = 'Page &...
Rendering out new line properly in openpyxl generated XLSX file
Python
So I am trying to fade my screen out and back in after completing a level using PyGame . My problem is that only the fadeout ( ) works and not the fadein ( ) . When calling the fadein ( ) the screen turns black for a few seconds then suddenly shows the next level . I ca n't find the problem , any ideas ?
def fadeout ( ) : fadeout = pg.Surface ( ( screen_width , screen_height ) ) fadeout = fadeout.convert ( ) fadeout.fill ( black ) for i in range ( 255 ) : fadeout.set_alpha ( i ) screen.blit ( fadeout , ( 0 , 0 ) ) pg.display.update ( ) def fadein ( ) : fadein = pg.Surface ( ( screen_width , screen_height ) ) fadein = f...
How to fade the screen out and back in using PyGame ?
Python
I was told that list ( [ ] ) == [ ] . So why is this code doingoldChain = list ( chain ) instead of oldChain = chainit 's the same thing so it does not matter either way to do it ?
from cs1graphics import *from math import sqrtnumLinks = 50restingLength = 20.0totalSeparation = 630.0elasticityConstant = 0.005gravityConstant = 0.110epsilon = 0.001def combine ( A , B , C= ( 0,0 ) ) : return ( A [ 0 ] + B [ 0 ] + C [ 0 ] , A [ 1 ] + B [ 1 ] + C [ 1 ] ) def calcForce ( A , B ) : dX = ( B [ 0 ] - A [ 0...
Python list ( [ ] ) and [ ]
Python
I 'm wondering if it 's possible for a closure in Python to manipulate variables in its namespace . You might call this side-effects because the state is being changed outside the closure itself . I 'd like to do something like thisObviously what I hope to do is more complicated , but this example illustrates what I 'm...
def closureMaker ( ) : x = 0 def closure ( ) : x+=1 print x return closurea = closureMaker ( ) a ( ) 1a ( ) 2
Python closure with side-effects
Python
Let 's say I have two set ( ) s : Now , what I want to do is to find the set difference b \ a but ignoring the last element from every tuple . So it 's just like doing something like this : Expected output : b \ a = { ( ' 1 ' , ' 2 ' , ' 6 ' , ' b ' ) } Is there any obvious / pythonic way of achieving this without havi...
a = { ( ' 1 ' , ' 2 ' , ' 3 ' , ' a ' ) , ( ' 1 ' , ' 2 ' , ' 4 ' , ' a ' ) , ( ' 1 ' , ' 2 ' , ' 5 ' , ' b ' ) } b = { ( ' 1 ' , ' 2 ' , ' 3 ' , ' b ' ) , ( ' 1 ' , ' 2 ' , ' 4 ' , ' b ' ) , ( ' 1 ' , ' 2 ' , ' 6 ' , ' b ' ) } a = { ( ' 1 ' , ' 2 ' , ' 3 ' ) , ( ' 1 ' , ' 2 ' , ' 4 ' ) , ( ' 1 ' , ' 2 ' , ' 5 ' ) } b ...
Pythonic way of ignoring the last element when doing set difference
Python
I 'm trying to create a login form for my site but when I use cleaned_data in my views.py I do n't get the right data . here is my code : views.py forms.pylogin.htmland here is what I get when I fill username and password field and click on submit . print ( form.cleaned_data ) shows there is data in url fields that I w...
def login_page ( request ) : form = LoginForm ( request.POST or None ) context = { 'form ' : form } if form.is_valid ( ) : print ( form.cleaned_data ) username = form.cleaned_form.get ( `` username '' ) password = form.cleaned_form.get ( `` password '' ) user = authenticate ( request , username=username , password=pass...
why I do n't get clean data when i use cleaned_data
Python
In previous astropy versions it was possible to handle propagation of uncertainties along the following lines : Changes to NDData seem to have removed this capability . I get `` AttributeError : 'NDData ' object has no attribute 'add ' '' , and I ca n't find any useful advice in the documentation . How is error propaga...
from astropy.nddata import NDData , StdDevUncertaintyx = NDData ( 16.0 , uncertainty=StdDevUncertainty ( 4.0 ) ) y = NDData ( 361.0 , uncertainty=StdDevUncertainty ( 19.0 ) ) print x.add ( y )
Propagation of uncertainties with Astropy
Python
How do I convert this string which is a list into a proper list ? I tired this but its not what I was expecting : I 'd like it like this : Thanks
mylist = `` [ 'KYS_Q5Aa8 ' , 'KYS_Q5Aa9 ' ] '' print mylist.split ( ) [ `` [ 'KYS_Q5Aa8 ' , '' , `` 'KYS_Q5Aa9 ' ] '' ] [ 'KYS_Q5Aa8 ' , 'KYS_Q5Aa9 ' ]
covert a string which is a list into a proper list python
Python
I am trying to generate the same signature from http : //docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html using python , But my signature is cb0b0ec487fd5e01382c9c3b6b6a6dfa170da312ddab58a4b18869e7413951be and expected signature is 46503978d3596de22955b4b18d6dfb1d54e8c5958727d5bdcd02cc1119c60fc9Where am ...
DateKey = hmac.new ( b'AWS4wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY ' , b'20151229 ' , hashlib.sha256 ) .digest ( ) DateRegionKey = hmac.new ( DateKey , b'us-east-1 ' , hashlib.sha256 ) .digest ( ) DateRegionServiceKey = hmac.new ( DateRegionKey , b's3 ' , hashlib.sha256 ) .digest ( ) SigningKey = hmac.new ( DateRegion...
sigv4-post-example using python
Python
I have disassembled the following python code and the resulting bytecode What do the ' > > ' symbols in the above bytecode stand for ?
def factorial ( n ) : if n < = 1 : return 1 elif n == 2 : return 2 elif n ==4 : print ( 'hi ' ) return n * 2 2 0 LOAD_FAST 0 ( n ) 3 LOAD_CONST 1 ( 1 ) 6 COMPARE_OP 1 ( < = ) 9 POP_JUMP_IF_FALSE 163 12 LOAD_CONST 1 ( 1 ) 15 RETURN_VALUE 4 > > 16 LOAD_FAST 0 ( n ) 19 LOAD_CONST 2 ( 2 ) 22 COMPARE_OP 2 ( == ) 25 POP_JUMP...
Meaning of ' > > ' in Python byte code
Python
I have a csv that contains 3 columns , count_id , AMV and time.I am using pandas and have read this in as a data frame . First , I am sorting the data frame first for count_id and then for AMV . This gives I now want to perform some normalisation on the data so that I can ultimately plot it on the same plot . What I wi...
results= pd.read_csv ( './output.csv ' ) results_sorted = results.sort_index ( by= [ 'count_id ' , 'AMV ' ] , ascending= [ True , True ] ) count_id AMV Hour0 16012E 4004 141 16012E 4026 122 16012E 4099 153 16012E 4167 114 16012E 4239 105 16012E 4324 136 16012E 4941 167 16012E 5088 178 16012E 5283 99 16012E 5620 810 160...
Pandas data frame - lambda calculus and minimum value per series
Python
I have a short bash script foo.shWhen I run it directly from the shell , it runs fine , exiting when it is donebut when I run it from Pythonit outputs the line but then just hangs forever . What is causing this discrepancy ?
# ! /bin/bashcat /dev/urandom | tr -dc ' a-z1-9 ' | fold -w 4 | head -n 1 $ ./foo.sh m1un $ $ python -c `` import subprocess ; subprocess.call ( [ './foo.sh ' ] ) '' ygs9
Script works differently when ran from the terminal and ran from Python
Python
I have trying to visualize my data from pandas column as 3D scatter plot . I am facing the problem to adjust the color bar match to the exact size of my z axis.My code : My Result I want my color bar height to be adjusted with z axis height .
import matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Ds = pd.read_csv ( 'FahrerVP8.out_1.csv ' , index_col=0 ) ax = plt.figure ( ) three_d = ax.gca ( projection='3d ' ) three_d1 = three_d.scatter ( s [ 'Latitude ' ] , s [ 'Longitude ' ] , s [ 'Mean_ VehicleSpeed ' ] , c =s [ 'Mean_ VehicleSpeed ' ] ) th...
How to make 3D scatter plot color bar adjust to the Z axis size ?
Python
For example , I have a blog based on Django and I already have several functions for users : login、edit_profile、share.But now I need to implement a mission system.User logins , reward 10 score per dayUser completes his profile , reward 20 scoreUser shares my blogs , reward 30 scoreI do n't want to mix reward code with ...
@ login_requireddef edit_profile ( request ) : user = request.user nickname = ... desc = ... user.save ( ... ) action.send ( sender='edit_profile ' , payload= { 'user_id ' : user.id } ) return Response ( ... ) @ receiver ( 'edit_profile ' ) def edit_profile_reward ( payload ) : user_id = payload [ 'user_id ' ] user = U...
What is the proper way to process the user-trigger events in Django ?
Python
How do I convert an unsigned integer ( representing a user ID ) to a random looking but actually a deterministically repeatable choice ? The choice must be selected with equal probability ( irrespective of the distribution of the the input integers ) . For example , if I have 3 choices , i.e . [ 0 , 1 , 2 ] , the user ...
> > > num_choices = 3 > > > id_num = 123 > > > int ( hashlib.sha256 ( str ( id_num ) .encode ( ) ) .hexdigest ( ) , 16 ) % num_choices2
Convert integer to a random but deterministically repeatable choice
Python
I have a program which deals with nested data structures where the underlying type usually ends up being a decimal . e.g . Is there a simple pythonic way to print such a variable but rounding all floats to ( say ) 3dp and not assuming a particular configuration of lists and dictionaries ? e.g.I 'm thinking something li...
x= { ' a ' : [ 1.05600000001,2.34581736481 , [ 1.1111111112,9.999990111111 ] ] , ... } { ' a ' : [ 1.056,2.346 , [ 1.111,10.000 ] , ... } pformat ( x , conversions= { 'float ' : lambda x : `` % .3g '' % x } )
Rounding decimals in nested data structures in Python
Python
I 'm learning Python ( 2.7 ) at the moment , and an exercise says to write a program which counts how many coins you need to pay a specific sum.My solution is this : This is nearly working , but when I input e.g . 17,79 it gives me the coins for 17,78.Why ? Has this something to do with round ?
sum = input ( `` Bitte gebe einen Euro Betrag ein : `` ) coins = [ ] euro = [ 20,10,5,2,1,0.5,0.2,0.1,0.05,0.02,0.01 ] for i in euro : while sum > = i : sum -= i coins.append ( i ) print coins Bitte gebe einen Euro Betrag ein : 17.79 [ 10 , 5 , 2 , 0.5 , 0.2 , 0.05 , 0.02 , 0.01 ]
Python counting through a number with > =
Python
I 'm attempting to keep my code to 80 chars or less nowadays as I think it looks more aesthetically pleasing , for the most part . Sometimes , though , the code ends up looking worse if I have to put line breaks in weird places . One thing I have n't figured out how to handle very nicely yet is long strings . For examp...
# 0 ... ... ... 1 ... ... ..2 ... ... ..3 ... ... ..4 ... ... ... 5 ... ... ... 6 ... ... ... 7 ... ... ... 8xxxxxxxxx9xxxxxxdef foo ( ) : if conditional ( ) : logger.info ( `` < Conditional 's meaning > happened , so we 're not setting up the interface . '' ) return # ... .. # 0 ... ... ... 1 ... ... ..2 ... ... ..3 ....
How to cleanly keep below 80-char width with long strings ?
Python
I 'd like to resample a pandas object using a specific date ( or month ) as the edge of the first bin . For instance , in the following snippet I 'd like my first index value to be 2020-02-29 and I 'd be happy specifying start=2 or start= '' 2020-02-29 '' .So far this is the cleanest I can come up with uses pd.cut and ...
> > > dates = pd.date_range ( `` 2020-01-29 '' , `` 2021-07-04 '' ) > > > s = pd.Series ( range ( len ( dates ) ) , index=dates ) > > > s.resample ( '4M ' ) .count ( ) 2020-01-31 32020-05-31 1212020-09-30 1222021-01-31 1232021-05-31 1202021-09-30 34Freq : 4M , dtype : int64 > > > rule = `` 4M '' > > > start = pd.Timest...
Pandas resample with start date
Python
I 'm working on a game ( writing my own physics engine ) , and trying to follow good design in writing it . Recently , I 've been running into many hard-to-find bugs , and in order to catch these bugs easier , I 've been trying to write unit-tests . This has been difficult to do , due to the fact that a lot of my compo...
class Entity : @ property def position ( self ) : `` '' '' Interpolate the position from the last known position from that time . '' '' '' # Here , the game class instance is referenced directly , creating coupling . dt = game.game_time - self._last_valid_time # x_f = x_i + v_i*t + 1/2 at^2 return self._position + self...
Eliminating coupling and global state in the `` Game '' singleton
Python
I have a decorator @ pure that registers a function as pure , for example : Next , I want to identify a newly defined pure functionObviously house_area is pure , since it only calls pure functions.How can I discover all pure functions automatically ( perhaps by using ast )
@ puredef rectangle_area ( a , b ) : return a*b @ puredef triangle_area ( a , b , c ) : return ( ( a+ ( b+c ) ) ( c- ( a-b ) ) ( c+ ( a-b ) ) ( a+ ( b-c ) ) ) **0.5/4 def house_area ( a , b , c ) : return rectangle_area ( a , b ) + triangle_area ( a , b , c )
Identifying pure functions in python
Python
I 'm using Python 2.7.9 in Windows.I have a UTF-8-encoded python script file with the following contents : I get a curious failure when I run the doctest : I see this same failure output whether I launch the doctests through the IDE I usually use ( IDEA IntelliJ ) , or from the command line : I copied the lines under E...
# coding=utf-8def test_func ( ) : u '' '' '' > > > test_func ( ) u'☃ ' `` '' '' return u'☃ ' Failed example : test_func ( ) Expected : u'\u2603'Got : u'\u2603 ' > x : \my_virtualenv\Scripts\python.exe -m doctest -v hello.py > x : \my_virtualenv\Scripts\python.exe -m doctest -v hello.py > out.txt Failed example : test_f...
How can a python 2 doctest fail and yet have no difference in the values in the failure message ?
Python
I have a function that its called recursively . When I run it I get the error `` maximum recursion depth exceeded while calling a Python object '' How can increase the limit on mac ? If I use the following , I get the error `` can not increase the limit on mac ''
resource.setrlimit ( resource.RLIMIT_STACK , ( 2**24 , -1 ) ) sys.setrecursionlimit ( 10**6 )
Python - Increase recursion limit in mac osx
Python
i have a dataframei want to group by id and add row before 1st row and after last row of every group such that my dataframe looks : i am adding row with value 0Now for every group of id , i want to add sequence column such that : the last part is easy but i am looking for how to add rows before and after every group ?
value id100 1200 1300 1500 2600 2700 3 value id0 1100 1200 1300 10 10 2500 2600 20 20 3700 30 3 value id sequence0 1 1100 1 2200 1 3300 1 40 1 50 2 1500 2 2600 2 30 2 40 3 1700 3 20 3 3
Add row before first and after last position of every group in pandas
Python
Python 3 seems to have some arbitrary limit to Decimal sizes that Python 2 does not . The following code works on Python 2 : But on Python 3 I get : Increasing the precision does not help . Why is this happening ? Is there something I can do about it ?
Decimal ( '1e+100000000000000000000 ' ) decimal.InvalidOperation : [ < class 'decimal.InvalidOperation ' > ]
How can I create a Decimal with a large exponent in Python 3 ?
Python
In my test code , my doctest fails but the script exits with a zero return value , which causes the CI run to pass , which is not intended.Is this the correct behavior of doctest module ? My script ends with : The output is like :
if __name__ == '__main__ ' : import doctest doctest.testmod ( ) **********************************************************************File `` test/test.py '' , line 7 , in __main__Failed example : f ( 1,0 ) Expected : -- -- - type : < type 'exceptions.ZeroDivisionError ' > value : integer division or modulo by zero x -...
Doctest failed with zero exit code
Python
I would like to count the number of 2d arrays with only 1 and 0 entries that have a disjoint pair of disjoint pairs of rows that have equal vector sums . For a 4 by 4 matrix the following code achieves this by just iterating over all of them and testing each one in turn.The output is 3136.The problem with this is that ...
import numpy as npfrom itertools import combinationsn = 4nxn = np.arange ( n*n ) .reshape ( n , -1 ) count = 0for i in xrange ( 2** ( n*n ) ) : A = ( i > > nxn ) % 2 p = 1 for firstpair in combinations ( range ( n ) , 2 ) : for secondpair in combinations ( range ( n ) , 2 ) : if firstpair < secondpair and not set ( fir...
Finding a better way to count matrices
Python
The examples given in the docs all seem to be the cases where the first callable argument in defaultdict is a `` constant '' function , like int , list , or lambda : const etc . I do n't know if defaultdict is just supposed to take constant functions as its callabe argument , but if not , I want the callable to be depe...
toy = collections.defaultdict ( lambda x : len ( x ) , { 'foo ' : 3 } ) toy [ 'barr ' ] TypeError : < lambda > ( ) missing 1 required positional argument : ' x '
Can defaultdict accept callables dependent on the given missing key ?