lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | http : //docs.python.org/2/reference/expressions.html # operator-precedenceMy guess is that it falls into one of the buckets above dict lookups sincedoes the dictionary lookup first.Is there a better chart than my initial link that goes into more detail regarding order of operations in python ? | func ( *mydict [ mykey ] ) | Where does python argument unpacking fall into the order of operations ? |
Python | I have been researching for days trying to figure out a solution to this problem . I would be happy to pay someone for consulting time to solve this if need be . I am currently using Python itertools to generate 6 character permutations of a 32 character alphabet . Via the following command : From the documentation , t... | gen = itertools.permutations ( 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789',6 ) gen2 = itertools.islice ( gen,0,10 ) ( ' A ' , ' B ' , ' C ' , 'D ' , ' E ' , ' F ' ) ( ' A ' , ' B ' , ' C ' , 'D ' , ' E ' , ' G ' ) ( ' A ' , ' B ' , ' C ' , 'D ' , ' E ' , ' H ' ) ( ' A ' , ' B ' , ' C ' , 'D ' , ' E ' , ' J ' ) ( ' A ' , ' B ' ,... | Computing the nth 6 character permutation of an alphabet |
Python | I have a simple test application on Windows - Tornado running a Flask wsgi application . I can start the server just fine and connect through my web browser and that 's just cool.I can run my performance test , and on my machine I get ~900-1000 requests per second . However , after about 20,000 requests , my server sto... | from flask import Flaskapp = Flask ( __name__ ) @ app.route ( `` / '' ) def main ( ) : return `` Hey , it 's working '' if __name__ == `` __main__ '' : app.run ( `` 0.0.0.0 '' , port=5000 , debug=True ) from tornado.wsgi import WSGIContainerfrom tornado.httpserver import HTTPServerfrom tornado.ioloop import IOLoopfrom ... | Why does my Tornado/Flask server choke and die on Windows when hammering it with requests ? |
Python | I wonder if there is a way to catch all exceptions caused in one decorator in another decorator and handle these exceptions.However , before coming up with some sort of convoluted solution to my problem , I figured I would ask the experts and see if there is something I 'm missing . My application looks similar to this... | from random import randintclass RND_ERROR ( Exception ) : def __init__ ( self , ErrNum , *arg , **kwargs ) : self.RND_ERR_NR = int ( ErrNum ) self.RND_ERR_MSG = `` '' if self.RND_ERR_NR == 0x00000000 : self.RND_ERR_MSG = `` NO ERROR '' elif self.RND_ERR_NR == 0x00000001 : self.RND_ERR_MSG = `` RANDOM NUMBER IS ONE '' e... | How to catch multiple exception of same type in decorator |
Python | I have the following string And I would like to extract all parts which are either between the begin of the string and [ or between whitespace and [ . For the given string , these are the parts 'abc ' , 'ijk ' , and 'no'.I have the following expressionBut I can not figure out how to add the beginning of the string as a... | 'abc [ 123 ] defgh ijk [ 456 ] lm no [ 78 ] pq ' exp = re.compile ( r'\s ( .* ? ) \ [ ' ) | Python regex to match begin of string or whitespace |
Python | I am trying to figure out how I can apply cumulative functions to objects . For numbers there are several alternatives like cumsum and cumcount . There is also df.expanding which can be used with apply . But the functions I pass to apply do not work on objects.In the dataframe I have integer values , sets , strings and... | import pandas as pddf = pd.DataFrame ( { `` C1 '' : [ 1 , 2 , 3 , 4 ] , `` C2 '' : [ { `` A '' } , { `` B '' } , { `` C '' } , { `` D '' } ] , `` C3 '' : [ `` A '' , `` B '' , `` C '' , `` D '' ] , `` C4 '' : [ [ `` A '' ] , [ `` B '' ] , [ `` C '' ] , [ `` D '' ] ] } ) dfOut : C1 C2 C3 C40 1 { A } A [ A ] 1 2 { B } B ... | Cumulative operations on dtype objects |
Python | Is there a pythonic way ( I know I can loop using range ( len ( .. ) ) and get an index ) to do the following example : essentially , the nested while loop should be incrementing the for loop.Edit : Not a file handle , confused two things I was working on , it 's a list of strings | for line in list_of_strings : if line [ 0 ] == ' $ ' : while line [ -1 ] == ' # ' : # read in the Next line and do stuff # after quitting out of the while loop , the next iteration of the for loop # should not get any of the lines that the while loop already dealt with | for loops in python |
Python | What do numpy arrays provide when performing time based calculations where state matters . In other words , where what has occurred in earlier or later in a sequence is important.Consider the following time based vectors , Let 's say that an exponential decay in TEMP should be applied once the FLOW falls below 30 witho... | TIME = np.array ( [ 0. , 10. , 20. , 30. , 40. , 50. , 60. , 70. , 80. , 90 . ] ) FLOW = np.array ( [ 100. , 75. , 60. , 20.0 , 60.0 , 50.0 , 20.0 , 30.0 , 20.0 , 10.0 ] ) TEMP = np.array ( [ 300. , 310. , 305. , 300. , 310. , 305. , 310. , 305. , 300. , 295.0 ] ) | Numpy time based vector operations where state of preceding elements matters - are for loops appropriate ? |
Python | Let we have this code : The Python documentation says about def statement : A function definition is an executable statement . Its execution binds the function name ... So , the question is : Does def little_function ( ) execute every time when big_function is invoked ? Question is about def statement exactly , not the... | def big_function ( ) : def little_function ( ) : ... ... . ... ... ... | Function inside function - every time ? |
Python | I have defined data for fitting with one categorical feature `` sex '' : and pipeline for transforming categorical features : When fitting cat_transformers with data directlyI am able to get names of output features created by OneHotEncoder instance : However , if I encapsulate cat_transformers into ColumnTransformer :... | data = pd.DataFrame ( { 'age ' : [ 25,19 , 17 ] , 'sex ' : [ 'female ' , 'male ' , 'female ' ] , 'won_lottery ' : [ False , True , False ] } ) X = data [ [ 'age ' , 'sex ' ] ] y = data [ 'won_lottery ' ] ohe = OneHotEncoder ( handle_unknown='ignore ' ) cat_transformers = Pipeline ( [ ( 'onehot ' , ohe ) ] ) cat_transfo... | Why ColumnTransformer does not call fit on its transformers ? |
Python | It 's a pretty simple exampleoutputWhy is the datatype different for both columns ? Python 3.7.3pandas version : 0.23.4 | import pandasdf = pandas.DataFrame ( ) value_to_be_set = { ' 1 ' } df.loc [ 0 , 'col1 ' ] = value_to_be_setdf [ 'col2 ' ] = Nonedf.loc [ 0 , 'col2 ' ] = value_to_be_setprint ( df.head ( ) ) col1 col20 1 { 1 } | Inconsistent behavior when inserting a set into cells using .loc in pandas |
Python | Supose I have the following DataFrame : And I want to categorize that values in range . Like A : [ 1,10 ] , B : [ 11,20 ] , C ... How can I do it with Pandas ? I tried following code : But `` cut '' command just put range values in DataFrame and I want put the categories names instead of range.EDIT : I tried to pass la... | Area0 14.681 40.542 10.823 2.314 22.3 Area0 B1 D2 C3 A4 C bins = pd.IntervalIndex.from_tuples ( [ ( 0 , 11 ) , ( 11 , 20 ) , ( 20 , 50 ) , ( 50 , 100 ) , ( 100 , 500 ) , ( 500 , np.max ( df [ `` area '' ] ) + 1 ) ] , closed='left ' ) catDf = pd.cut ( df [ `` area '' ] , bins = bins ) | How to categorize a range of values in Pandas DataFrame |
Python | So , I kept returning a Failing test in Django when comparing expected to actual html with form input , so I printed out the result and realized the difference was the rather simple line , caused by my { % csrf_token % } , as follows : So , I expect a simple answer , but I have n't been able to find it : How do I rende... | < input type='hidden ' name='csrfmiddlewaretoken ' value='hrPLKVOlhAIXmxcHI4XaFjqgEAMCTfUa ' / > def test_home_page_returns_correct_html_with_POST ( self ) : request = HttpRequest ( ) request.method = 'POST ' request.POST [ 'item_text ' ] = ' A new list item ' response = home_page ( request ) self.assertIn ( ' A new li... | CRSF Token Interfering With TDD - Is there a variable that stores csrf output ? |
Python | I often see in many Tensorflow tutorials text like : To do this calculation , you need the column means . You would obviously need to compute these in real life , but for this example we 'll just provide them.For small or medium sized CSV datasets computing the mean is as easy as a pandas method on a dataframe or using... | import tensorflow as tfimport tensorflow_transform as tftdef preprocessing_fn ( inputs ) : x = inputs [ ' x ' ] y = inputs [ ' y ' ] s = inputs [ 's ' ] x_centered = x - tft.mean ( x ) y_normalized = tft.scale_to_0_1 ( y ) s_integerized = tft.compute_and_apply_vocabulary ( s ) x_centered_times_y_normalized = x_centered... | Tensorflow Transform : How to find the mean of a variable over the entire dataset |
Python | Let 's say I have this two snippet of code in python : I thought the result of y will be the same in both examples since y point out to x and x become ( 2,3,4,5 ) , BUT it wasn'tThe results were ( 1,2,3,4 ) for 1 and ( 2,3,4,5 ) for 2.After some research I find out that in first exampleYou can find out more about this ... | 1 -- -- -- -- -- -- -- -- -- -- -- -- -- import numpy as npx = np.array ( [ 1,2,3,4 ] ) y = xx = x + np.array ( [ 1,1,1,1 ] ) print y2 -- -- -- -- -- -- -- -- -- -- -- -- -- import numpy as npx = np.array ( [ 1,2,3,4 ] ) y = xx += np.array ( [ 1,1,1,1 ] ) print y # -First example -- -- -- -- -- -- -- -- -- -- -- -- -- ... | Which operator ( + vs += ) should be used for performance ? ( In-place Vs not-in-place ) |
Python | I have a standard financial timeseries of data which has gaps for when the market is closed.The problem is Chaco displays these gaps , I could use a formatter in matplotlib as follows and apply to the x-axis to get around this but I am unsure what I should do about this in Chaco.In matplotlib : What would be the effici... | class MyFormatter ( Formatter ) : def __init__ ( self , dates , fmt= ' % Y- % m- % d % H : % M ' ) : self.dates = dates self.fmt = fmt def __call__ ( self , x , pos=0 ) : 'Return the label for time x at position pos ' ind = int ( round ( x ) ) if ind > =len ( self.dates ) or ind < 0 : return `` return self.dates [ ind ... | Dealing with timeseries gaps in Chaco |
Python | When I developed a package purely for Python 2 , I could use the plain import b syntax to import a relative path without caring about whether the importing file was in a package or not . This had the advantage that I could run an if __name__ == `` __main__ '' : block of any file simply by executing the file , and all i... | Traceback ( most recent call last ) : File `` ./a.py '' , line 2 , in < module > from . import bValueError : Attempted relative import in non-package python -m foo.a foo/foo/__init__.pyfoo/a.py ( imports b ) foo/b.py ( imports c ) foo/c.py import foo.x ( in some file when foo/ is in path ) python [ 23 ] path/to/foo/x.p... | Import structure that works both in packages and out , in both Python 2 and 3 ? |
Python | When a function is called by unpacking arguments , it seems to increase the recursion depth twice . I would like to know why this happens.Normally : With an unpacking call : In theory both should reach about 1000 : This happens on CPython 2.7 and CPython 3.3.On PyPy 2.7 and PyPy 3.3 there is a difference , but it is mu... | depth = 0def f ( ) : global depth depth += 1 f ( ) try : f ( ) except RuntimeError : print ( depth ) # > > > 999 depth = 0def f ( ) : global depth depth += 1 f ( * ( ) ) try : f ( ) except RuntimeError : print ( depth ) # > > > 500 import syssys.getrecursionlimit ( ) # > > > 1000 import dis def f ( ) : f ( ) dis.dis ( ... | Argument Unpacking wastes Stack Frames |
Python | I am using np.random.choice to do sampling without replacement.I would like the following code to choose 0 50 % of the time , 1 30 % of the time , and 2 20 % of the time.How can I correctly choose the parameters for np.random.choice to give me the result that I want ? The numbers I want represent the probability of the... | import numpy as npdraws = [ ] for _ in range ( 10000 ) : draw = np.random.choice ( 3 , size=2 , replace=False , p= [ 0.5 , 0.3 , 0.2 ] ) draws.append ( draw ) result = np.r_ [ draws ] print ( np.any ( result==0 , axis=1 ) .mean ( ) ) # 0.83 , want 0.8print ( np.any ( result==1 , axis=1 ) .mean ( ) ) # 0.68 , want 0.7pr... | Sampling Without Replacement Probabilities |
Python | I have a method ( or function ) which returns a reference to a list of polymorphic objects : How do I expose such a function in boost : :python so that when iterating on the list in python , I would see the different types of As and Bs ? | class A { } ; class B : public A { } ; std : :list < boost : :shared_ptr < A > > & getList ( ) ; | Boost Python : polymorphic container ? |
Python | I was running a simple multiprocessing example in my IPython interpreter ( IPython 7.9.0 , Python 3.8.0 ) on my MacBook and ran into a strange error . Here 's what I typed : However , I received the following error : Furthermore , trying to submit the job again gave me a different error : As a sanity check , I typed th... | [ In [ 1 ] : from concurrent.futures import ProcessPoolExecutor [ In [ 2 ] : executor=ProcessPoolExecutor ( max_workers=1 ) [ In [ 3 ] : def func ( ) : print ( 'Hello ' ) [ In [ 4 ] : future=executor.submit ( func ) Traceback ( most recent call last ) : File `` /Library/Frameworks/Python.framework/Versions/3.8/lib/pyth... | Running a ProcessPoolExecutor in IPython |
Python | Im creating an Autoencoder as part of my full model for a Kaggle competition . Im trying to tie the weighs of the Encoder , transposed to the Decoder . Before the first Epoch the weights are correctly sync , after that , the Decoder weights just freeze , and dont keep up with the Encoder weights that are being updated ... | import tensorflow as tfimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsimport os class DenseTied ( tf.keras.layers.Layer ) : def __init__ ( self , units , activation=None , use_bias=True , kernel_initializer='glorot_uniform ' , bias_initializer='zeros ' , kernel_regularizer=None... | Keras Autoencoder : Tying Weights from Encoder To Decoder not working |
Python | I wrote my own vector class : I want to define that V ( 0,0 ) is an empty vector , such that this would work : ( The first case should return `` Vector is empty '' ) | # ! /usr/bin/env python3class V : `` '' '' Defines a 2D vector '' '' '' def __init__ ( self , x , y ) : self.x = x self.y = y def __add__ ( self , other ) : newx = self.x + other.x newy = self.y + other.y return V ( newx , newy ) def __sub__ ( self , other ) : newx = self.x - other.x newy = self.y - other.y return V ( ... | How to define when a class is empty |
Python | Is there a way I can make class decorators work on Google App Engine , which is limited to Python 2.5 ? Or let me rephrase that : is it possible to alter the behavior of Python 's parser from the same process that it is already executing ? Example : good.py : bad.py : Or is this maybe just plainly impossible.Explanatio... | alter_python_parser ( ) import bad @ decoratedclass Foo ( object ) : pass | Class decorators in Python 2.5 ? |
Python | In IPython 3 interactive shell : Is that because 1 and True get the same interpetation so given that set eliminates duplicates , only one of them ( True ) gets to stay ? How can we keep both ? | In [ 53 ] : set2 = { 1 , 2 , True , `` hello '' } In [ 54 ] : len ( set2 ) Out [ 54 ] : 3In [ 55 ] : set2Out [ 55 ] : { 'hello ' , True , 2 } | Python set interpetation of 1 and True |
Python | I 'm looking to use lime 's explainer within a udf on pyspark . I 've previously trained the tabular explainer , and stored is as a dill model as suggested in linkThis however takes a lot of time , as it appears a lot of the computation happens on the driver . I 've then been trying to use spark broadcast to broadcast ... | loaded_explainer = dill.load ( open ( 'location_to_explainer ' , 'rb ' ) ) def lime_explainer ( *cols ) : selected_cols = np.array ( [ value for value in cols ] ) exp = loaded_explainer.explain_instance ( selected_cols , loaded_model.predict_proba , num_features = 10 ) mapping = exp.as_map ( ) [ 1 ] return str ( mappin... | Using python lime as a udf on spark |
Python | How can I find out the location of the file cursor when iterating over a file in Python3 ? In Python 2.7 it 's trivial , use tell ( ) . In Python3 that same call throws an OSError : My use case is making a progress bar for reading large CSV files . Computing a total line count is too expensive and requires an extra pas... | Traceback ( most recent call last ) : File `` foo.py '' , line 113 , in check_file pos = infile.tell ( ) OSError : telling position disabled by next ( ) call file_size = os.stat ( path ) .st_sizewith open ( path , `` r '' ) as infile : reader = csv.reader ( infile ) for row in reader : pos = infile.tell ( ) # OSError :... | Alternatives to ` tell ( ) ` while iterating over lines of a file in Python3 ? |
Python | I have some trouble with filtering a list of strings . I found a similar question here but is not what i need.The input list is : and the expected result is The order of the items in the result is not importantThe filter function must be fast because the size of list is bigMy current solution isEDITAfter multiple tests... | l = [ 'ab ' , 'xc ' , 'abb ' , 'abed ' , 'sdfdg ' , 'abfdsdg ' , 'xccc ' ] [ 'ab ' , 'xc ' , 'sdfdg ' ] l = [ 'ab ' , 'xc ' , 'abb ' , 'abed ' , 'sdfdg ' , 'abfdsdg ' , 'xccc ' ] for i in range ( 0 , len ( l ) - 1 ) : for j in range ( i + 1 , len ( l ) ) : if l [ j ] .startswith ( l [ i ] ) : l [ j ] = l [ i ] else : i... | Obtain a list containing string elements excluding elements prefixed with any other element from initial list |
Python | I am not able to run with debug option for my Django project after an recent update of PyCharm.The last line of stacktrace gives errorthe first few lines of stacktrace gives errorHere is the full stacktrace - | Process finished with exit code 134 ( interrupted by signal 6 : SIGABRT ) Fatal Python error : Can not recover from stack overflow . pydev debugger : process 21976 is connectingConnected to pydev debugger ( build 181.5087.37 ) Fatal Python error : Can not recover from stack overflow.Thread 0x000070000ee34000 ( most rec... | Debugging not running on PyCharm for my Django project |
Python | My problemSuppose I haveThey are two arrays , of different sizes , containing other arrays ( the inner arrays have same sizes ! ) I want to count how many items of b ( i.e . inner arrays ) are also in a . Notice that I am not considering their position ! How can I do that ? My TryIs there a better way ? Especially in o... | a = np.array ( [ np.array ( [ 1,2 ] ) , np.array ( [ 3,4 ] ) , np.array ( [ 5,6 ] ) , np.array ( [ 7,8 ] ) , np.array ( [ 9,10 ] ) ] ) b = np.array ( [ np.array ( [ 5,6 ] ) , np.array ( [ 1,2 ] ) , np.array ( [ 3,192 ] ) ] ) count = 0for bitem in b : for aitem in a : if aitem==bitem : count+=1 | Check how many numpy array within a numpy array are equal to other numpy arrays within another numpy array of different size |
Python | I 'm new at Django.my project is in DjangoRestFrameworkThis project has a user : models.py : and in views.py I made a function for registeration but for degImage and natImage there is a problem.views.pyserializers.pyIn Postman when i choose a file it 's OK and works fineBut in developing android and iOS they ca n't pos... | class Users ( models.Model ) : name = models.CharField ( max_length=20 , null=True ) lastName = models.CharField ( max_length=50 , null=True ) phone = models.IntegerField ( unique=True , null=False , default='phone ' ) password = models.CharField ( max_length=25 , null=True ) natNum = models.IntegerField ( unique=True ... | Django ImageField in RestFramework |
Python | Assume thatThe first of the following files throwsWhen I do n.encode ( 'utf8 ' ) it works.The second works flawless in both cases.Since in the documentation it is encouraged to use format ( ) instead of the % format operator , I do n't understand why format ( ) seems more `` handicaped '' . Does format ( ) only work wi... | n = u '' Tübingen '' repr ( n ) # ` T\xfcbingen ` # Unicodei = 1 # integer UnicodeEncodeError : 'ascii ' codec ca n't encode character u'\xfc ' in position 82 : ordinal not in range ( 128 ) # Python File 1 # # ! /usr/bin/env python -B # encoding : utf-8print ' { id } , { name } '.format ( id=i , name=n ) # Python File ... | Is there a difference between ` % ` -format operator and ` str.format ( ) ` in python regarding unicode and utf-8 encoding ? |
Python | I 've written this code to calculate the continued fraction expansion of a rational number N using the Euclidean algorithm : If say N is 3.245 the function is never ending as apparently f never equals 0 . The first 10 terms of the expansion are : [ 3.0 , 4.0 , 12.0 , 3.0 , 1.0 , 247777268231.0 , 4.0 , 1.0 , 2.0 , 1.0 ]... | from __future__ import divisiondef contFract ( N ) : while True : yield N//1 f = N - ( N//1 ) if f == 0 : break N = 1/f | Python 2.7 - Continued Fraction Expansion - Understanding the error |
Python | I 'm wondering what is going on with the file open ( ) mode validation ( Python2.7 ) : So , I can not open the file in illegal mode , but I can open it in rock & roll mode . What mode is actually used for opening the file in this case ? Note that on python3 I can not use both illegal and rock & roll : And , this is con... | > > > with open ( 'input.txt ' , 'illegal ' ) as f : ... for line in f : ... print line ... Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > ValueError : mode string must begin with one of ' r ' , ' w ' , ' a ' or ' U ' , not 'illegal ' > > > with open ( 'input.txt ' , 'rock & roll ' ... | Open files in `` rock & roll '' mode |
Python | My code in the view : I do n't want to show this code to the user the second time if he/she refreshes again . How do I go about doing that ? Messages do n't seem to have any sort of expiry setting . There is documentation here : http : //docs.djangoproject.com/en/1.2/ref/contrib/messages/ # expiration-of-messages | from django.contrib import messages messages.add_message ( request , messages.INFO , 'Hello world . ' ) | Django message does n't expire |
Python | Is there any way to extract the auto generated machine learning pipeline in a standalone python script from auto-sklearn ? Here is a sample code using auto-sklearn : It would be nice to have automatic equivalent python code generated somehow.By comparison , when using TPOT we can obtain the standalone pipeline as follo... | import autosklearn.classificationimport sklearn.cross_validationimport sklearn.datasetsimport sklearn.metricsdigits = sklearn.datasets.load_digits ( ) X = digits.datay = digits.targetX_train , X_test , y_train , y_test = sklearn.cross_validation.train_test_split ( X , y , random_state=1 ) automl = autosklearn.classific... | Auto-Machine-Learning python equivalent code |
Python | I recently installed the hg tip version of Ropemacs and I 'd like to use it when editing remote files using TRAMP . Has anyone done this ? When I try to use M-/ to complete a variable name , I am asked to enter the Rope project root folder and I enter : /ssh : myhost : /path/to/myproject/ and it gives me the following ... | Opening [ /ssh : myhost : /path/to/myproject/ ] project ... pymacs-report-error : Python : Traceback ( most recent call last ) : File `` /home/saltycrane/lib/python-environments/default/lib/python2.6/site-packages/Pymacs/pymacs.py '' , line 147 , in loop value = eval ( text ) File `` < string > '' , line 1 , in < modul... | Is it possible to use Ropemacs with TRAMP in Emacs ? |
Python | EDIT : As pointed out by Thierry Lathuille , PEP567 , where ContextVar was introduced , was not designed to address generators ( unlike the withdrawn PEP550 ) . Still , the main question remains . How do I write stateful context managers that behave correctly with multiple threads , generators and asyncio tasks ? I hav... | from contextlib import contextmanagerfrom contextvars import ContextVarMODE = ContextVar ( 'mode ' , default=0 ) @ contextmanagerdef use_mode ( mode ) : t = MODE.set ( mode ) try : yield finally : MODE.reset ( t ) def print_mode ( ) : print ( f'Mode { MODE.get ( ) } ' ) def first ( ) : print ( 'Start first ' ) print_mo... | How do I write consistent stateful context managers ? |
Python | I am using python 2 with requests . This question is more of a curiosity of how I can improve this performance.The issue now is that I must send a cryptographic signature in the header of the request to a HTTPS server . This signature includes a `` nonce '' which must be a timestamp , and ALWAYS must increase ( on the ... | def get_nonce ( self ) : return int ( 1000*time.time ( ) ) def do_post_request ( self , endpoint , parameters ) : with self.lock : url = self.base + endpoint urlpath = endpoint parameters [ 'nonce ' ] = self.get_nonce ( ) postdata = urllib.urlencode ( parameters ) message = urlpath + hashlib.sha256 ( str ( parameters [... | Python - Using nonces with multithreading |
Python | I 've seen How to use a context manager inside a decorator and how to pass an object created in decorator to decorated function as well as python decorators with parameters , and I 'm trying to combine the two..but I 'm struggling to get my head round it.I 'd much rather use the func tools @ wrap decorator to do this i... | def pyro_opener ( func , service , database , port , secret_key ) : def wrapper ( params ) : with Pyro4.Proxy ( `` PYRO : '' +service+ '' @ '' +database+ '' : '' +port ) as obj : obj.set_secret_key ( secret_key ) return obj.func ( params ) return wrapper @ pyro_opener ( output_service , employee_db , port=9876 , secret... | How do I write a decorator to wrap something in a context manager , that takes parameters ? |
Python | Suppose I have two dataframes : I want to remove all rows in df2 that are up to +1 second of the time indices in df1 , so yielding : What 's the most efficient way to do this ? I do n't see anything useful for time range exclusions in the API . | # df1time2016-09-12 13:00:00.017 1.02016-09-12 13:00:03.233 1.02016-09-12 13:00:10.256 1.02016-09-12 13:00:19.605 1.0 # df2time2016-09-12 13:00:00.017 1.02016-09-12 13:00:00.233 0.02016-09-12 13:00:01.016 1.02016-09-12 13:00:01.505 0.02016-09-12 13:00:06.017 1.02016-09-12 13:00:07.233 0.02016-09-12 13:00:08.256 1.02016... | pandas : Remove all rows within time interval of another series 's time index ( i.e . time range exclusion ) |
Python | Is there any way to use somehow use pypy just to compile one function and not for the rest of my python program ? I have a known bottleneck where I spend 99 % of my CPU time ( containing mostly integer shifts and XORs ) and have optimized it as much as I can in Python . I do n't want to have to write and maintain C lib... | def _gf2mulmod ( x , y , m ) : z = 0 while x > 0 : if ( x & 1 ) ! = 0 : z ^= y y < < = 1 y2 = y ^ m if y2 < y : y = y2 x > > = 1 return z Traceback ( most recent call last ) : File `` /Users/jason_s/Documents/python/libgf2/src/libgf2/gf2.py '' , line 440 , in < module > dlog43 = GF2DiscreteLog ( 0x100000000065 ) File `... | Python : JIT for known bottlenecks |
Python | XML Validation fails with error : Element 'CategoryPageUrl ' : 'http : //www.example.com/products ? my_query_parameter [ ] =45 ' is not a valid value of the atomic type 'xs : anyURI'. , line 29Feed looks like this : Appropriate piece of schema looks like this : | < Category > < ExternalId > 1234 < /ExternalId > < Name > Name < /Name > < CategoryPageUrl > http : //www.example.com/products ? my_query_parameter [ ] =45 < /CategoryPageUrl > < /Category > < xs : complexType name= '' CategoryType '' > < xs : all > < xs : element name= '' ExternalId '' type= '' ExternalIdType '' minOc... | Can xs : anyURI contain square brackets in XSD ? |
Python | I am looking for the elegant , Pythonic way of making a Pandas DataFrame columns consistent . Meaning : Ensure all the columns in a master list are present , and if not add in an empty placeholder column.Ensure that the columns are in the same order as the master list.I have the following example that works , but is th... | import pandas as pddf1 = pd.DataFrame ( data= [ { ' a':1 , ' b':32 , ' c':32 } ] ) print df1 a b c0 1 32 32 column_master_list = [ ' b ' , ' c ' , ' e ' , 'd ' , ' a ' ] def get_dataframe_with_consistent_header ( df , headers ) : for col in headers : if col not in df.columns : df [ col ] = pd.np.NaN return df [ headers... | Making columns and ordering consistent in a Pandas DataFrame |
Python | I find this very weird . Can someone tell me whats going on here ? What 's up with the 3 in the end of the output of np.mean ( a ) ? Why is n't it a 6 like the line below it or a 7 ( when rounding off ) ? | > > > a = [ 1,0,1 ] > > > np.mean ( a ) 0.66666666666666663 > > > 2.0/3 0.6666666666666666 | Numpy average function rounding off error |
Python | When embedding Python in my application , and writing an extension type , I can add a signature to the method by using a properly crafted .tp_doc string.When help ( Answer ) is executed , the following is returned ( abbreviated ) : This is good , but I 'm using Python3.6 , which has support for annotations . I 'd like ... | static PyMethodDef Answer_methods [ ] = { { `` ultimate '' , ( PyCFunction ) Answer_ultimate , METH_VARARGS , `` ultimate ( self , question='Life , the universe , everything ! ' ) \n '' `` -- \n '' `` \n '' `` Return the ultimate answer to the given question . '' } , { NULL } } ; class Answer ( builtins.object ) | | ul... | Add a signature , with annotations , to extension methods |
Python | Consider the numpy array aIf I do a bin count , I get integersBut if I add weights to perform the equivalent bin countSame values but float . What is the smartest way to manipulate these to int ? Why does n't numpy assume the same dtype as what was passed as weights ? | a = np.array ( [ 1 , 0 , 2 , 1 , 1 ] ) np.bincount ( a ) array ( [ 1 , 3 , 1 ] ) np.bincount ( a , np.ones_like ( a ) ) array ( [ 1. , 3. , 1 . ] ) | How to get an integer array from numpy.bincount when the weights parameter are integers |
Python | So I understand that : The end of a logical line is represented by the token NEWLINEThis means the way Python 's grammar is defined the only way to end a logical line is with a \n token.The same goes for physical lines ( rather an EOL , which is the EOL of the platform you 're using when writing the file but neverthele... | foo = 'some_value ' # 1 logical line = 1 physical foo , bar , baz = 'their ' , 'corresponding ' , 'values ' # 1 logical line = 1 physicalsome_var , another_var = 10 , 10 ; print ( some_var , another_var ) ; some_fn_call ( ) # the above is still still 1 logical line = 1 physical line # because ; is not a terminator per ... | Python lexical analysis - logical line & compound statements |
Python | I always thought that Python 2.7 functions refer to the scope they were defined in . Consider the following code . Why is the second output not `` calculating : sin '' ? Is there any way to modify the code so it is working as expected ? | import mathmymath = dict ( ) for fun in [ `` sin '' , `` cos '' ] : def _impl ( val ) : print `` calculating : % s '' % fun return getattr ( math , fun ) ( val ) mymath [ fun ] = _impl # calculating : cosprint mymath [ `` cos '' ] ( math.pi ) # calculating : cos < - why ? print mymath [ `` sin '' ] ( math.pi ) | Understanding Python Closures |
Python | I have a python function that has a deterministic result . It takes a long time to run and generates a large output : I modify time_consuming_function from time to time , but I would like to avoid having it run again while it 's unchanged . [ time_consuming_function only depends on functions that are immutable for the ... | def time_consuming_function ( ) : # lots_of_computing_time to come up with the_result return the_result | Hashing a python function to regenerate output when the function is modified |
Python | I have a data source which is best modeled with a dictionary ( it is a collection of key=value pairs ) . For a specific visualization purpose , I need to provide a list-like data access interface ( in addition to the regular dictionary interface ) , meaning that you should be able to do the following : I can not find a... | data [ `` mykey '' ] # returns the associated valuedata [ 12 ] [ 0 ] # returns the 13th key in the dictionarydata [ 12 ] [ 1 ] # returns the 13th value in the dictionary data [ 12 ] = ( `` mykey '' , `` myval '' ) data [ `` mykey '' ] = `` myval '' | Access a dictionary as a list |
Python | Python 3.7 . I 'm trying to fill multidimensional array ( n*m size ) in diagonal-snake pattern : I have a function for n x n size and it works fine for it . But for n x m size it returns : My code : What am I doing wrong ? P.S . Your answer can be in any language . | 1 3 4 10 11 212 5 9 12 20 226 8 13 19 23 307 14 18 24 29 3115 17 25 28 32 3516 26 27 33 34 36 1 3 4 10 142 5 9 15 206 8 16 19 197 17 18 20 21 def method1 ( i , j , n , m ) : num = i+j summ = num * ( num + 1 ) > > 1 s = n * m if num > n-1 : t = 2* ( n-1 ) - ( i+j ) + 1 s -= t* ( t+1 ) > > 1 if num & 1 : if num > n-1 : r... | Diagonal snake filling array |
Python | I 'm trying to run a basic R Markdown document ( that calls python in code chunks ) through Pweave . In the Pweave documentation it states that you can declare code chunks using the style `` ` { python } . However when I try to compile using , for example , pweave -f pandoc FIR_design.mdw the chunks are not run and ins... | < < fig = True , width = '12 cm ' , echo = False > > =from pylab import *plot ( arange ( 10 ) ) show ( ) @ `` ` { python , fig = True , width = '12 cm ' , echo = False } from pylab import *plot ( arange ( 10 ) ) show ( ) `` ` | Using an R Markdown style document ( .Rmd ) as input for Pweave |
Python | The end goal here is to implement indentation based code folding in QScintilla similarly to the way SublimeText3 does.First of all , here 's a little example of how you 'd manually provide folding using QScintilla mechanisms : To know more in depth about it , you can check the official docs : Doc references : QSciScint... | import sysfrom PyQt5.Qsci import QsciScintillafrom PyQt5.Qt import *if __name__ == '__main__ ' : app = QApplication ( sys.argv ) view = QsciScintilla ( ) # http : //www.scintilla.org/ScintillaDoc.html # Folding view.setFolding ( QsciScintilla.BoxedTreeFoldStyle ) lines = [ ( 0 , `` def foo ( ) : '' ) , ( 1 , `` x = 10 ... | How to implement indentation based code folding in QScintilla ? |
Python | What 's the opposite of os.path.commonprefix ? I have two paths and I want the non-overlapping path , e.g . : | > > > p1 = '/Users/foo/something ' > > > p2 = '/Users/foo/something/else/etc ' > > > print somefunction ( [ p1 , p2 ] ) '/else/etc ' | Opposite of os.path.commonprefix |
Python | I 'm new to Rust and PyO3 ( coming from Python ) so this might be obvious to more experienced people.I declared a pyclass struct in PyO3.Then I use Block in a rust function that takes a vector of Block and outputs a vector of int ( signature below ) When I compile using nightly-x86_64-apple-darwin I get the following e... | # [ pyclass ] struct Block { start : i32 , stop : i32 , } # [ pyfunction ] fn from_blocks ( block_list : Vec < Block > ) - > Vec < i32 > # [ pyfunction ] ^^^^^^^^^^^^^ the trait ` pyo3 : :FromPyObject < ' _ > ` is not implemented for ` std : :vec : :Vec < Block > ` # [ pyfunction ] fn to_blocks ( list : Vec < i32 > ) -... | Vector of custom struct in PyO3 |
Python | I have a site that requires the ability for a logged in admin to push a staging database to a live database . The first thing it does is dump the sql and push to the target database . This works fine , but when I go to rsync the folders containing the uploaded material , I get an error . This ONLY occurs when the scrip... | def copy_media ( self , origin_folder , target_folder ) : command_string = `` rsync -a % s % s '' % ( origin_folder , target_folder ) return_code = subprocess.call ( command_string , shell=True ) return return_code | How to rsync to local folders from a Django view |
Python | Why does the second print statement output False ? | > > > item = 2 > > > seq = [ 1,2,3 ] > > > print ( item in seq ) True > > > print ( item in seq is True ) False | Unexpected result from ` in ` operator - Python |
Python | I need to run a function int f ( int i ) with 10_000 parameters and it takes around 1sec to execute due to I/O time.In a language like Python , I can use threads ( or async/await , I know , but I 'll talk about it later ) to parallelize this task.If I want to always have 10 running threads , and to split the task betwe... | def f ( p ) : x = [ ... ] return xp = ThreadPool ( ) xs = p.map ( f , range ( 10_000 ) ) queue = [ `` www.google.com '' , `` www.facebook.com '' ] var f = function ( url ) { http.get ( url , ( e ) = > { const newUrl = queue.pop ( ) ; f ( newUrl ) ; } ) ; } ; for ( var i = 0 ; i < 10 ; i++ ) { f ( queue.pop ( ) ) ; } | How does thread pooling works , and how to implement it in an async/await env like NodeJS ? |
Python | here is a merge sort logic in python : ( this is the first part , ignore the function merge ( ) ) The point in question is converting the recursive logic to a while loop.Code courtesy : Rosettacode Merge SortIs it possible to make it a sort of dynamically in the while loop while each left and right array breaks into tw... | def merge_sort ( m ) : if len ( m ) < = 1 : return m middle = len ( m ) / 2 left = m [ : middle ] right = m [ middle : ] left = merge_sort ( left ) right = merge_sort ( right ) return list ( merge ( left , right ) ) | alternative to recursion based merge sort logic |
Python | Currently I have a list : I need somehow to convert it to Networkx edges , where pairs of words should become nodes of the graph , and integers between become weights : Currently I 'm stuck and have no ideas . Any help would be appreciated ! | [ [ 'Мама мыть ' , 10 , 'рама ' ] , [ 'Мама мыть ' , 10 , 'рама ' , 5 , 'долго ' ] , [ 'Мама мыть ' , 10 , 'рама ' , 3 , 'вчера ' ] , [ 'Мама мыть ' , 10 , 'рама ' , 3 , 'вчера ' , 1 , 'поздно ' ] ] G = nx.Graph ( ) G.add_edge ( 'Мама мыть ' , 'рама ' , weight=10 ) G.add_edge ( 'рама ' , 'долго ' , weight=5 ) G.add_edg... | Transforming Python list to networkx graph |
Python | I build a multilingual web app using Python and webapp2 . I have an object called Tag , which has translations to multiple languages . For this reason , I have created the following models : I would like to ask if this is the correct way to do such task , and how this structure can be used along with WTForms for valida... | class Language ( ndb.Model ) : code = ndb.StringProperty ( ) name = ndb.StringProperty ( indexed=False ) class MultilingualText ( ndb.Model ) : language = ndb.KeyProperty ( kind=Language ) text = ndb.TextProperty ( indexed=False ) class Tag ( ndb.Model ) : translations = ndb.StructuredProperty ( MultilingualText , repe... | How to model multilingual objects in Python using webapp2 |
Python | I 've a python script that uses subprocess.Popen to execute Windows *.exe files . All EXEs except one produce expected output . When printed using print ( ) the output in question includes whitespace between every character of the output.This is how the output looks when executing the EXE in Windows command line : This... | C : \Python27 > autorunsc.exe /accepteulaSysinternals Autoruns v13.51 - Autostart program viewerCopyright ( C ) 2002-2015 Mark RussinovichSysinternals - www.sysinternals.comHKLM\System\CurrentControlSet\Control\Terminal Server\Wds\rdpwd\StartupPrograms rdpclip rdpclip RDP Clip Monitor Microsoft Corporation 6.1.7601.175... | Python subprocess introduces spaces |
Python | Today I profiled a function and I found a ( at least to me ) weird bottleneck : Creating a masked array with mask=None or mask=0 to initialize a mask with all zeros but the same shape as the data is very slow : on the other hand using mask=False or creating the mask by hand is much faster : Why is giving None or 0 almo... | > > > import numpy as np > > > data = np.ones ( ( 100 , 100 , 100 ) ) > > > % timeit ma_array = np.ma.array ( data , mask=None , copy=False ) 1 loop , best of 3 : 803 ms per loop > > > % timeit ma_array = np.ma.array ( data , mask=0 , copy=False ) 1 loop , best of 3 : 807 ms per loop > > > % timeit ma_array = np.ma.arr... | Why is creating a masked numpy array so slow with mask=None or mask=0 |
Python | I use Django 1.8.7 and PostgreSQL and had the following model : The I have added RenameModel operation : Looks that all work OK but sequence name for TemplatePermission.id field still myapp_permission_id_seq : It there right way to rename sequence ? Is it a bug in Django ( I had found very similar bug report and patch ... | class Permission ( models.Model ) : name = models.CharField ( max_length=255 ) template = models.ForeignKey ( Template , related_name='permissions ' ) migrations.RenameModel ( old_name='Permission ' , new_name='TemplatePermission ' , ) , postgres= # \d+ myapp_templatepermission Table `` public.myapp_templatepermission ... | django.db.migrations.RenameModel and AutoField sequence name |
Python | I got a multi-argument function . I simplified the function to map , and here 's my function to test with : And in some case , I just want to hold X , Y as constant and iterate I , J over u_x and u_y , respectively . I write down something below ( while SyntaxError raised ) where the cur.x ( ) and cur.y ( ) are constan... | def _dist ( I , J , X , Y ) : return abs ( I-X ) +abs ( J-Y ) new=map ( _dist ( , ,cur.x ( ) , cur.y ( ) ) , u_x , u_y ) | Python : map ( ) with partial arguments |
Python | I ' v created a script in scrapy to parse the author name of different posts from it 's landing page and then pass it to the parse_page method using meta keyword in order to print the post content along with the author name at the same time . I 've used download_slot within meta keyword which allegedly maskes the scrip... | from scrapy.crawler import CrawlerProcessfrom scrapy import Requestimport scrapyclass ConventionSpider ( scrapy.Spider ) : name = 'stackoverflow ' start_urls = [ 'https : //stackoverflow.com/questions/tagged/web-scraping ' ] def parse ( self , response ) : for link in response.css ( '.summary ' ) : name = link.css ( '.... | How `` download_slot '' works within scrapy |
Python | I 'm working on a simple web scraper in python 3 but when I send a get or a post request , the response is 403 . In python 2 works fine though . I 'm using the same version of requests libraries in both versions . I havealso tried with Verify=False/True but the difference in both versions remains.requests = 2.22.0certi... | from requests import geturl = 'https : //www.gamestop.com/'header = { 'Accept ' : 'text/html , application/xhtml+xml , application/xml ; q=0.9 , */* ; q=0.8 ' , 'Accept-Encoding ' : 'gzip , deflate , br ' , 'Accept-Language ' : 'en-US , en ; q=0.5 ' , 'User-Agent ' : 'Mozilla/5.0 ( Windows NT 10.0 ; WOW64 ; rv:56.0 ) G... | Simple get/post request blocked in python 3 but not in python 2 |
Python | I have added a small debugging aid to my server . It logs a stack trace obtained from traceback.format_stack ( ) It contains few incomplete lines like this : which is not that much helpfull.The source lines 360 and 361 : If only one line can be part of the stack trace , I would say the line 360 with the function name (... | File `` /home/ ... ../base/loop.py '' , line 361 , in run self.outputs.fd_list , ( ) , sleep ) rlist , wlist , unused = select.select ( self.inputs.fd_list , self.outputs.fd_list , ( ) , sleep ) def print_trace ( ) : for fname , lnum , func , line in traceback.extract_stack ( ) [ : -1 ] : print ( 'File `` { } '' , line... | traceback shows only one line of a multiline command |
Python | I want to plot stacked areas with Python , and find out this Pandas ' function : However , the result is weirdly antialiased , mixing together the colors , as shown on those 2 plots : The same problem occurs in the example provided in the documentation.Do you know how to remove this anti-aliasing ? ( Or another mean to... | df = pd.DataFrame ( np.random.rand ( 10 , 4 ) , columns= [ ' a ' , ' b ' , ' c ' , 'd ' ] ) df.plot.area ( ) ; | Remove anti-aliasing for pandas plot.area |
Python | I have a pandas dataframe as follows : Is there a simple way to split the dataframe into multiple dataframes based on non-null values ? | a b c 0 1.0 NaN NaN 1 NaN 7.0 5.0 2 3.0 8.0 3.0 3 4.0 9.0 2.0 4 5.0 0.0 NaN a 0 1.0 b c 1 7.0 5.0 a b c 2 3.0 8.0 3.0 3 4.0 9.0 2.0 a b 4 5.0 0.0 | Split pandas dataframe into multiple dataframes based on null columns |
Python | I am reading McKinney 's Data Analysis book , and he has shared 150MB file . Although this topic has been discussed extensively at Progress Bar while download file over http with Requests , I am finding that the code in accepted answer is throwing an error . I am a beginner , so I am unable to resolve this . I want to ... | https : //raw.githubusercontent.com/wesm/pydata-book/2nd-edition/datasets/fec/P00000001-ALL.csv DATA_PATH='./Data'filename = `` P00000001-ALL.csv '' url_without_filename = `` https : //raw.githubusercontent.com/wesm/pydata-book/2nd-edition/datasets/fec '' url_with_filename = url_without_filename + `` / '' + filenameloc... | Progress for downloading large CSV files from Internet using Python |
Python | The following function returns None : So I was not surprised by this output : Ok , this makes sense . But now , consider the following function : g does not use None , so why is it in co_consts ? | In [ 5 ] : def f ( ) : ... : pass In [ 8 ] : dis.dis ( f ) 2 0 LOAD_CONST 0 ( None ) 3 RETURN_VALUE In [ 10 ] : f.__code__.co_constsOut [ 10 ] : ( None , ) In [ 11 ] : def g ( ) : ... . : return 1In [ 12 ] : dis.dis ( g ) 2 0 LOAD_CONST 1 ( 1 ) 3 RETURN_VALUE In [ 13 ] : g.__code__.co_constsOut [ 13 ] : ( None , 1 ) | What is None doing in the code object 's co_consts attribute ? |
Python | I have created a dialog box in browser ( this Happens when an error occurs in user input details ) . What I need is to wait until the user clicks on the dialog box before preceding with automatic execution ( only for testing ) . Here is what I haveI tried to search online but only got an answer when a user clicks on a ... | # driver is a chrome web driverdriver.execute_script ( `` alert ( 'qwer ' ) ; '' ) wait = WebDriverWait ( driver , 10 ) element = wait.until ( EC.alert_is_present ( ) ) | Selenium Wait for user to click on alert dialog box in python |
Python | The child class inherits from the parent class . Inside the constructor of child I am initializing a list-type member variablexs by repeatedly calling the member function foo ( ) defined in parent . It turns out that if I initialize xs by explicitly looping and appending each value returned by foo ( ) , everything work... | class parent ( object ) : def __init__ ( self ) : self.x = 5 def foo ( self , a ) : return self.xclass child ( parent ) : def __init__ ( self ) : super ( ) .__init__ ( ) self.xs = [ ] for i in range ( 9 ) : self.xs.append ( super ( ) .foo ( i ) ) mychild = child ( ) class child ( parent ) : def __init__ ( self ) : supe... | Ca n't call parent 's method in list comprehension in child 's initializer , but explicit loop works |
Python | Say I haveThen , I want to create an abstract subclass B of A , which itself is concrete . Should I use multi-inheritance for this purpose ? If so , should I import ABC first , as in , or should I import it last , as in | class A : # Some code class B ( ABC , A ) : @ abstractmethod def some_method ( ) : pass class B ( A , ABC ) : @ abstractmethod def some_method ( ) : pass | How to create an abstract subclass of a concrete superclass in Python 3 ? |
Python | I 'm on Windows 7.I can not connect to my iPad with a simple Python script : The errors I have is `` getaddrinfo returns an empty list '' and the `` can not reach ... '' message ... Can not solve it ... I tried to FTP with several programs on the iPad without success . If I FTP via DOS box or using a FTP software it wo... | HOST = '192.168.1.122'try : f = ftplib.FTP ( HOST ) except ( socket.error , socket.gaierror ) , e : MessageBox.Show ( 'ERROR : can not reach `` % s '' ' % HOST ) return try : f.connect ( HOST,2121 ) f.login ( ) except ftplib.error_perm : MessageBox.Show ( 'ERROR : can not login anonymously ' ) f.quit ( ) return | Python FTP to iPad |
Python | yihui gives an example of using the cache option for the different engines https : //github.com/yihui/knitr-examples/blob/master/023-engine-python.RmdI ca n't seem to get it to work for python.The following worksBut this does n't workAnyone have an idea ? | `` ` { r , engine='python ' , cache=TRUE } x=10print x `` ` `` ` { r , engine='python ' , cache=TRUE } x = 10 `` `` `` { r , engine='python ' , cache=TRUE } print x `` ` | knitr - Python engine cache option not working |
Python | While studying C # I found it really strange , that dynamically typed Python will rise an error in the following code : whereas statically typed C # will normally proceed the similar code : I would expect other way around ( in python I would be able to do this without any casting , but C # would require me to cast int ... | i = 5print i + `` `` int i = 5 ; Console.Write ( i + `` `` ) ; | Why is `` int + string '' possible in statically-typed C # but not in dynamically-typed Python ? |
Python | In python : Is there an equivalent way - i.e . dir ( ) function - to do this with instances in the scala REPL ? | > > > s = `` abc '' > > > dir ( s ) [ '__add__ ' , '__class__ ' , '__contains__ ' , '__delattr__ ' , ... | What command to use to introspect instances in scala REPL ? |
Python | Below is a simple test . repr seems to work fine . yet len and x for x in does n't seem to divide the unicode text correctly in Python 2.6 and 2.7 : Good news is Python 3.3 does the right thing ™.Is there any hope for Python 2.x series ? | In [ 1 ] : u '' '' Out [ 1 ] : u'\U0002f920\U0002f921'In [ 2 ] : [ x for x in u '' '' ] Out [ 2 ] : [ u'\ud87e ' , u'\udd20 ' , u'\ud87e ' , u'\udd21 ' ] | Does python support unicode beyond basic multilingual plane ? |
Python | I 've tried to understand when Python strings are identical ( aka sharing the same memory location ) . However during my tests , there seems to be no obvious explanation when two string variables that are equal share the same memory : Strings are immutable , and as far as I know Python tries to re-use existing immutabl... | import sysprint ( sys.version ) # 3.4.3 # Example 1s1 = `` Hello '' s2 = `` Hello '' print ( id ( s1 ) == id ( s2 ) ) # True # Example 2s1 = `` Hello '' * 3s2 = `` Hello '' * 3print ( id ( s1 ) == id ( s2 ) ) # True # Example 3i = 3s1 = `` Hello '' * is2 = `` Hello '' * iprint ( id ( s1 ) == id ( s2 ) ) # False # Examp... | How does Python determine if two strings are identical |
Python | I have an n-dimensional numpy array , and I 'd like to get the i-th slice of the k-th dimension . There must be something better than | # ... elif k == 5 : b = a [ : , : , : , : , : , i , ... ] # ... | get the i-th slice of the k-th dimension in a numpy array |
Python | In reading the specifications for the with statement ( link ) , I have some things I 'd like to play around with . This is n't for any production code or anything , I 'm just exploring , so please do n't be too harsh if this is a bad idea.What I 'd like to do is grab the piece called `` BLOCK '' in the linked docs abov... | with MyNameSpace ( some_object ) : print a # Should print some_object.a x = 4 # Should set some_object.x=4 my_dict = { ' a':3 , ' b':2 } with MyNameSpace ( my_dict ) : print a # Should print 3 x = 5 # When the block finishes , my_dict [ ' x ' ] should now be 5 my_dict = { ' a':1 , ' b':2 } m = locals ( ) print m [ `` m... | Getting the block of commands that are to be executed in the with statement |
Python | I just discovered that it 's legal in Python to compare arbitrary functions using the operators > , < , > = and < = . This seems a bit silly ; I half expected such a comparison to always be False ( or throw an exception ) , but the docs say : `` Most other objects of built-in types compare unequal unless they are the s... | > > > def g ( ) : pass > > > def y ( ) : pass > > > g > yFalse > > > y > gTrue > > > def r ( ) : pass > > > g > rFalse > > > r > gTrue > > > y > rFalse > > > r > yTrue > > > def barfoo ( ) : pass > > > barfoo > r > y > gTrue > > > unicode > super > object > type > tuple > str > basestring > slice > frozenset > set > xr... | When does Python 2 consider one function `` greater than '' or `` less than '' another function ? |
Python | I have this task that I 've been working on , but am having extreme misgivings about my methodology.So the problem is that I have a ton of excel files that are formatted strangely ( and not consistently ) and I need to extract certain fields for each entry . An example data set isMy original approach was this : Export ... | # This file takes a tax CSV file as input # and separates it into counties # then appends each county 's entries onto # the end of the master out.csv # which will contain everything including # taxes , bonds , etc from all years # import the data csvimport sysimport reimport csvdef cleancommas ( x ) : toggle=False for ... | Data analysis for inconsistent string formatting |
Python | I am trying to populate a new column in my pandas dataframe by considering the values of the previous n rows . If the current value is not equal to any of the past n values in that column , it should populate `` N '' , else `` Y '' .Please let me know what would be a good way to achieve this.Here 's my input data : Inp... | testdata = { 'col1 ' : [ 'car ' , 'car ' , 'car ' , 'bus ' , 'bus ' , 'bus ' , 'car ' ] } df = pd.DataFrame.from_dict ( testdata ) col10 car1 car2 car3 bus4 bus5 car 6 car col1 Result0 car 1 car 2 car Y 3 bus N 4 bus Y 5 bus Y 6 car N | Compare the previous N rows to the current row in a pandas column |
Python | If you know exactly how you want to filter a dataframe , the solution is trivial : df [ ( df.A == 1 ) & ( df.B == 1 ) ] But what if you are accepting user input and do not know beforehand how many criteria the user wants to use ? For example , the user wants a filtered data frame where columns [ A , B , C ] == 1 . Is i... | def filterIt ( *args , value ) : return df [ ( df . *args == value ) ] df [ ( df.A == 1 ) & ( df.B == 1 ) & ( df.C == 1 ) ] | pandas : Is it possible to filter a dataframe with arbitrarily long boolean criteria ? |
Python | When I run this command : It gives this error : Aside from the error , html.py files are created for each html file . For example : for index.html , an index.html.py is created with it in the template folder . These html.py files contains just ' X ' and ' B ' characters with some text to translate . For example : I alr... | django-admin makemessages -l ar Traceback ( most recent call last ) : File `` c : \users\ahmed\appdata\local\programs\python\python36-32\lib\site-packages\django\utils\encoding.py '' , line 65 , in force_texts = str ( s , encoding , errors ) UnicodeDecodeError : 'utf-8 ' codec ca n't decode byte 0xe9 in position 3107 :... | makemessages command results in html.py files and a UnicodeDecodeError |
Python | I have a question regarding garbage collection in Python . After reading some insightful articles on why one might prefer to run a Python program with disabled garbage collection* , I decided to search and remove all circular references in my code to allow objects to be destroyed through ref-counting alone.For finding ... | import gcgc.disable ( ) def bar ( ) : class Foo ( object ) : passbar ( ) print ( gc.collect ( ) ) # prints 6 import gcgc.disable ( ) def bar ( ) : type ( `` Foo '' , ( object , ) , { } ) bar ( ) print ( gc.collect ( ) ) # prints 6 again import gcgc.disable ( ) import weakrefdef bar ( ) : weakref.ref ( type ( `` Foo '' ... | Are dynamically created classes always `` unreachable '' for gc in Python ? |
Python | I 'm trying to use the timeit module in Python ( EDIT : We are using Python 3 ) to decide between a couple of different code flows . In our code , we have a series of if-statements that test for the existence of a character code in a string , and if it 's there replace it like this : We do this a number of times for di... | if `` < substring > '' in str_var : str_var = str_var.replace ( `` < substring > '' , `` < new_substring > '' ) str_var = str_var.replace ( `` < substring > '' , `` < new_substring > '' ) str_var = ' < string > < substring > < more_string > ' , timeit.timeit ( stmt=stmt1 , setup=setup ) timeit.timeit ( stmt=stmt2 , set... | Python timeit module execution confusion |
Python | When I use Python to generate a base64 string that will be used in the raw key { 'raw ' : value } GMAIL API , sending the email occurs perfectly.But when I use Dart to generate the same base64 string , the string is not the same as python and because of that I can not send the email because the GMAIL API tells me messa... | var message = `` ' < html > < meta http-equiv= '' content-type '' content= '' text/html ; charset=utf-8 '' / > < head > < /head > < body > Test < /body > < /html > ' '' import base64e = base64.urlsafe_b64encode ( `` ' < html > < meta http-equiv= '' content-type '' content= '' text/html ; charset=utf-8 '' / > < head > <... | Dart - Base64 string is not equal to python |
Python | I 'm attempting to run 2to3 on Windows machine where *.py files has Unix-style end-line characters . Running 2to3 modifies newline characters in output file.MCVE : print2.py content beforeExecuted command : print2.py content afterExpected content : Is it possible to keep old newline characters when 2to3 conversion is p... | print `` Hello , world ! `` \n 2to3 print2.py -w -n print ( `` Hello , world ! `` ) \r\n print ( `` Hello , world ! `` ) \n | 2to3 - how to keep newline characters from input file ? |
Python | I see a warning like this in my logs : This message does not help very much.I would like to see the stacktrace where this happens.Please do n't look into the content of this warning . This question is not about Beautiful Soup : - ) An easy solution would be to modify the third party code ( bs4/__init__.py at line 219 )... | py.warnings.__init__ : WARNING ... /bs4/__init__.py:219 : UserWarning : `` foo '' looks like a filename , not markup . You should probably open this file and pass the filehandle into Beautiful Soup import tracebacklogger.warn ( 'Exc at ... \n % s ' % `` .join ( traceback.format_stack ( ) ) ) | Stacktrace for UserWarning |
Python | Initial question : Why ca n't I get math.pi back ? I thought import would import all the defined variables and functions to the current scope . And if a variable name already exists in current scope , then it would replace it . Yes , it does replace it : Then I thought maybe the math.pi = 3 assignment actually changed ... | > > > import math > > > math.pi3.141592653589793 > > > math.pi = 3 > > > math.pi3 > > > import math > > > math.pi3 > > > pi = 3 > > > from math import * > > > pi3.141592653589793 > > > import math > > > math.pi3.141592653589793 > > > math.pi = 3 > > > from math import * > > > pi3 | Why is `` import '' implemented this way ? |
Python | I have two lists available_points = [ [ 2,3 ] , [ 4,5 ] , [ 1,2 ] , [ 6,8 ] , [ 5,9 ] , [ 51,35 ] ] andsolution = [ [ 3,5 ] , [ 2,1 ] ] I 'm trying to pop a point in available_points and append it to solution for which the sum of euclidean distances from that point , to all points in the solution is the greatest.So , I... | import numpy as npfrom scipy.spatial.distance import pdist , squareformavailable_points = np.array ( [ [ 2,3 ] , [ 4,5 ] , [ 1,2 ] , [ 6,8 ] , [ 5,9 ] , [ 51,35 ] ] ) D = squareform ( pdist ( available_points ) I_row , I_col = np.unravel_index ( np.argmax ( D ) , D.shape ) solution = available_points [ [ I_row , I_col ... | Sum of distances from a point to all other points |
Python | Generic question regarding Python-code . How can I most effectively locate the worst parts of my Python-code with respect to memory usage ? See e.g . this small exampleHow can I in an automated way tell that a2 is much larger that a1 in size ? And how can I - still automated - root this back towards my_func1 ( ) and my... | def my_func ( ) : a = [ 1 ] * ( 12 ** 4 ) return adef my_func2 ( ) : b = [ 2 ] * ( 10 ** 7 ) return bif __name__ == '__main__ ' : a1 = my_func ( ) a2 = my_func2 ( ) | Who ate my Python memory ? |
Python | Considering that I have two lists like : and I need to create a dictionary where the keys are those element from second list that are found in the first and values are lists of elements found between `` keys '' like : What 's a more pythonic way to do this ? Currently I 'm doing this : But I 'm quite positive that this... | l1 = [ ' a ' , ' c ' , ' b ' , ' e ' , ' f ' , 'd ' ] l2 = [ ' x ' , ' q ' , 'we ' , 'da ' , 'po ' , ' a ' , 'el1 ' , 'el2 ' , 'el3 ' , 'el4 ' , ' b ' , 'some_other_el_1 ' , 'some_other_el_2 ' , ' c ' , 'another_element_1 ' , 'another_element_2 ' , 'd ' , `` , `` , 'another_element_3 ' , 'd4 ' ] result = { ' a ' : [ 'e... | Pythonic way to create a dictionary from a list where the keys are the elements that are found in another list and values are elements between keys |
Python | On Python 3.7 ( tested on Windows 64 bits ) , the replacement of a string using the RegEx . * gives the input string repeated twice ! On Python 3.7.2 : On Python 3.6.4 : On Python 2.7.5 ( 32 bits ) : What is wrong ? How to fix that ? | > > > import re > > > re.sub ( `` . * '' , `` ( replacement ) '' , `` sample text '' ) ' ( replacement ) ( replacement ) ' > > > import re > > > re.sub ( `` . * '' , `` ( replacement ) '' , `` sample text '' ) ' ( replacement ) ' > > > import re > > > re.sub ( `` . * '' , `` ( replacement ) '' , `` sample text '' ) ' (... | re.sub ( `` . * '' , `` , `` ( replacement ) '' , `` text '' ) doubles replacement on Python 3.7 |
Python | Let 's say I want to paralelize some intensive computation ( not I/O bound ) .Naturally , I do not want to run more processes than available processors or I would start paying for context switching ( and cache misses ) .Mentally , I would expect that as I increased n in multiprocessing.Pool ( n ) , total time would beh... | # ! /usr/bin/env pythonfrom math import factorialdef pi ( n ) : t = 0 pi = 0 deno = 0 k = 0 for k in range ( n ) : t = ( ( -1 ) **k ) * ( factorial ( 6*k ) ) * ( 13591409+545140134*k ) deno = factorial ( 3*k ) * ( factorial ( k ) **3 ) * ( 640320** ( 3*k ) ) pi += t/deno pi = pi * 12/ ( 640320** ( 1.5 ) ) pi = 1/pi ret... | python multiprocessing : no diminishing returns ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.