lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | I often find that I need to assign some member variables temporarily , e.g.but I wish I could simply writeor evenCan Python 's decorators or other language features enable this kind of pattern ? ( I could modify c 's class as needed ) | old_x = c.xold_y = c.y # keep c.z unchangedc.x = new_xc.y = new_ydo_something ( c ) c.x = old_xc.y = old_y with c.x = new_x ; c.y = new_y : do_something ( c ) do_something ( c with x = new_x ; y = new_y ) | How to assign member variables temporarily ? |
Python | After upgrading to the new google-api-python-client 1.8.1 I 'm receiving this error . Do we know if python 3.8 breaks the latest google-api-core ? And whether there 's a solutionHere are my dependencies : | Traceback ( most recent call last ) : File `` /usr/local/lib/python3.8/site-packages/gunicorn/arbiter.py '' , line 583 , in spawn_worker worker.init_process ( ) File `` /usr/local/lib/python3.8/site-packages/gunicorn/workers/base.py '' , line 129 , in init_process self.load_wsgi ( ) File `` /usr/local/lib/python3.8/sit... | Breaking change for google-api-python-client 1.8.1 - AttributeError : module 'googleapiclient ' has no attribute '__version__ ' |
Python | I have this for example this characters : which i stored in a list I used this to store it in the chars : Now the problem is i want to turn all of the dots between letters L into # but vertically , so like this : I have been trying for a few hours now and i ca n't think of anything . Help much appreciated.EDIT : I used... | ... ..U ... ... L ... L. # # # # # # .S ... . # ... ... ... L ... ... . chars = [ ' ... ..U ... ... ' , ' L ... L. # # # # # # ' , '.S ... . # ... .. ' , ' ... .L ... ... . ' ] for x in range ( 0 , N ) : g = input ( ) chars.append ( g ) ... ..U ... ... L ... L. # # # # # # .S.. # . # ... ... ... L ... ... . while y ! =... | Python , connecting vertical lists |
Python | I think that I know how variables and generators work in Python well.However , the following code makes me confused.When run the code (Python 2 ) , it says : In Python 3 , it says NameError : name ' x ' is not definedbut , when I run : The code does n't work in Python 3 , but it does in Python 2 , or in a function like... | from __future__ import print_functionclass A ( object ) : x = 4 gen = ( x for _ in range ( 3 ) ) a = A ( ) print ( list ( a.gen ) ) Traceback ( most recent call last ) : File `` Untitled 8.py '' , line 10 , in < module > print ( list ( a.gen ) ) File `` Untitled 8.py '' , line 6 , in < genexpr > gen = ( x for _ in rang... | Variable Scope In Generators In Classes |
Python | I have a very a very large 2D numpy array that contains 2x2 subsets that I need to take the average of . I am looking for a way to vectorize this operation . For example , given x : I need to end up with a 2x3 array which are the averages of each 2x2 sub array , i.e . : so element [ 0,0 ] is calculated as the average o... | # |- col 0 -| |- col 1 -| |- col 2 -| x = np.array ( [ [ 0.0 , 1.0 , 2.0 , 3.0 , 4.0 , 5.0 ] , # row 0 [ 6.0 , 7.0 , 8.0 , 9.0 , 10.0 , 11.0 ] , # row 0 [ 12.0 , 13.0 , 14.0 , 15.0 , 16.0 , 17.0 ] , # row 1 [ 18.0 , 19.0 , 20.0 , 21.0 , 22.0 , 23.0 ] ] ) # row 1 result = np.array ( [ [ 3.5 , 5.5 , 7.5 ] , [ 15.5 , 17.5... | How can I vectorize the averaging of 2x2 sub-arrays of numpy array ? |
Python | I was wondering how I can split words in a nested list into their individual letters such thatbecomes | [ [ 'ANTT ' ] , [ 'XSOB ' ] ] [ [ ' A ' , ' N ' , 'T ' , 'T ' ] , [ ' X ' , 'S ' , ' O ' , ' B ' ] ] | Split words in a nested list into letters |
Python | using the itertools tool , I have all the possible permutations of a given list of numbers , but if the list is as follows : itertools does not `` know '' that iterating the zeros is wasted work , for example the following iterations will appear in the results : they are the same but itertools just takes the first zero... | List= [ 0,0,0,0,3,6,0,0,5,0,0 ] List= [ 0,3,0,0,0,6,0,0,5,0,0 ] List= [ 0,3,0,0,0,6,0,0,5,0,0 ] | How to generate permutations of a list without “ moving ” zeros . in Python |
Python | I 've been reading this documentation on how to update custom attributes for users . From how this is written , it seems as though I would be able to do the following : However , I am thrown the error : https : //www.googleapis.com/admin/directory/v1/users/test % 40test.com ? alt=json returned `` Not Authorized to acce... | email = `` a @ a.com '' results = service.users ( ) .list ( domain= '' a.com '' , projection= '' full '' , query='email= { 0 } '.format ( email ) ) .execute ( ) if len ( results [ `` users '' ] ) == 1 : user = results [ `` users '' ] [ 0 ] user [ `` customSchemas '' ] [ `` TEST '' ] = `` TEST '' try : userResponse = se... | Creating and setting custom attributes for Google Admin SDK |
Python | I recently had to complete an assignment that used a lot of coordinate operations . Thinking to save time and simplify my code , I defined a class to encapsulate the behaviour of a coordinate pair . The class looked like this : This allowed me to write code like this ( for example ) : But my application was terribly sl... | class Vector ( tuple ) : def __init__ ( self , value ) : tuple.__init__ ( self , value ) def __add__ ( self , other ) : return Vector ( ( self [ 0 ] + other [ 0 ] , self [ 1 ] + other [ 1 ] ) ) def translate ( pointList , displacement ) : return [ point + displacement for point in pointList ] v = Vector ( ( 0 , 0 ) ) d... | Extremely slow object instantiation in Python 2.7 |
Python | In Python , there 's a dir ( ) and __builtin__ list of built-in objects.Is there a dir ( ) function that can probe objects in Julia ? Is there also a list of __builtin__ objects in Julia ? | > > > dir ( __builtins__ ) [ 'ArithmeticError ' , 'AssertionError ' , 'AttributeError ' , 'BaseException ' , 'BufferError ' , 'BytesWarning ' , 'DeprecationWarning ' , 'EOFError ' , 'Ellipsis ' , 'EnvironmentError ' , 'Exception ' , 'False ' , 'FloatingPointError ' , 'FutureWarning ' , 'GeneratorExit ' , 'IOError ' , '... | Python 's dir ( object ) and __builtin__ equivalent in Julia |
Python | Let 's say we have a request made in Django which renders my_template.html and the context of { foo : bar } Now based on the user activity foo and bar change . Let 's say if a user has made his first request . Django will return the template and the corresponding { foo : bar } based on user activity . Let 's say if the... | return render ( request , `` my_template.html '' , { foo : bar } ) | Do Django templates get cached in browser ? |
Python | I 've a query on the results given by the PyEphem module relating to Observer ( ) queries , and the effects of elevation . I understand from a couple of sources ( such as http : //curious.astro.cornell.edu/question.php ? number=388 ) that the elevation of the observer has a marked effect on sunset time . However in the... | import ephememphemObj = ephem.Observer ( ) emphemObj.date = '2011/08/09'emphemObj.lat = '53.4167'emphemObj.long = '-3'emphemObj.elevation = 0ephemResult = ephem.Sun ( ) ephemResult.compute ( emphemObj ) print `` Sunset time @ 0m : `` + str ( emphemObj.previous_rising ( ephemResult ) ) emphemObj.elevation = 10000ephemRe... | Results for Observer ( ) seemingly not accounting for elevation effects in PyEphem |
Python | I have a huge dataframe with many columns , many of which are of type datetime.datetime . The problem is that many also have mixed types , including for instance datetime.datetime values and None values ( and potentially other invalid values ) : Hence resulting in an object type column . This can be solved with df.colx... | 0 2017-07-06 00:00:001 2018-02-27 21:30:052 2017-04-12 00:00:003 2017-05-21 22:05:004 2018-01-22 00:00:00 ... 352867 2019-10-04 00:00:00352868 None352869 some_stringName : colx , Length : 352872 , dtype : object | Infer which columns are datetime |
Python | I 'm trying to create a non-detached signature on python3 . I currently have code that does this on python2 with m2crypto , but m2crypto is n't available for python3.I 've been trying rsa , pycrypto and openssl , but have n't seen to find how.Here 's the equivalent OpenSSL command : It 's the nodetach option that I ca ... | openssl smime -sign -signer $ CRTFILE -inkey $ KEYFILE -outformDER -nodetach | Non-detached PKCS # 7 SHA1+RSA signature without M2Crypto |
Python | I have an Azure Function written in Python that has an Service Bus ( Topic ) output binding . The function is triggered by another queue , we process some files from a blobl storage and then put another message in a queue.My function.json file looks like that : In my function , I can send a message to another queue lik... | { `` bindings '' : [ { `` type '' : `` serviceBus '' , `` connection '' : `` Omnibus_Input_Send_Servicebus '' , `` name '' : `` outputMessage '' , `` queueName '' : `` validation-output-queue '' , `` accessRights '' : `` send '' , `` direction '' : `` out '' } ] , '' disabled '' : false } with open ( os.environ [ 'outp... | Azure Function - Python - ServiceBus Output Binding - Setting Custom Properties |
Python | I am trying to patch python ’ s built-in str in order to track the count of all str allocations . I am running into some issues and was wondering if anyone could see what I ’ m doing wrong , or if this is even possible natively through monkey patching in python3 ? ( the following works fine in python 2.7.12 ) I first n... | $ pythonPython 3.5.2 ( default , Nov 23 2017 , 16:37:01 ) [ GCC 5.4.0 20160609 ] on linux def patch_str_allocations ( ) : old_str = str def mystr ( *args , **kwargs ) : return old_str ( *args , **kwargs ) builtins.str = mystrdef test ( ) : logger = logging.getLogger ( __name__ ) patch_str_allocations ( ) logger.debug (... | Is it possible to fully Monkey Patch builtin ` str ` in python3 |
Python | I 'm trying to use a cached property decorator that can take arguments.I looked at this implementation : http : //www.daniweb.com/software-development/python/code/217241/a-cached-property-decoratorBut the problem I have is that I can not call the decorator with the @ syntax if I want to use the parameter : How to use t... | from functools import update_wrapper def cachedProperty ( func , name =None ) : if name is None : name =func .__name__ def _get ( self ) : try : return self .__dict__ [ name ] except KeyError : value =func ( self ) self .__dict__ [ name ] =value return value update_wrapper ( _get , func ) def _del ( self ) : self .__di... | python decorator arguments with @ syntax |
Python | I just noticed that the zeros function of numpy has a strange behavior : On the other hand , ones seems to have a normal behavior.Is anybody know why initializing a small numpy array with the zeros function takes more time than for a large array ? ( Python 3.5 , numpy 1.11 ) | % timeit np.zeros ( ( 1000 , 1000 ) ) 1.06 ms ± 29.8 µs per loop ( mean ± std . dev . of 7 runs , 1000 loops each ) % timeit np.zeros ( ( 5000 , 5000 ) ) 4 µs ± 66 ns per loop ( mean ± std . dev . of 7 runs , 100000 loops each ) | Performance of zeros function in Numpy |
Python | I have a user environment where most python packages are installed on a network share and are made available via the PYTHONPATH environment variable . Python itself is still installed locally . Some of those packages need to register setuptools Entry Points . Normally , this would happen by running the setup.py file fo... | setup ( ... entry_points= { 'xx_plugin ' : [ 'value = package.module : func ' ] , } ) | How to register Entry Points for network python package installs ? |
Python | I need to implement a function for summing the elements of an array with a variable section length.So , I attempted an implementation in cython here : https : //gist.github.com/2784725for performance I am comparing to the pure numpy solution for the case where the section_lengths are all the same : would you have any s... | a = np.arange ( 10 ) section_lengths = np.array ( [ 3 , 2 , 4 ] ) out = accumulate ( a , section_lengths ) print outarray ( [ 3. , 7. , 35 . ] ) LEN = 10000b = np.ones ( LEN , dtype=np.int ) * 2000a = np.arange ( np.sum ( b ) , dtype=np.double ) out = np.zeros ( LEN , dtype=np.double ) % timeit np.sum ( a.reshape ( -1,... | cython numpy accumulate function |
Python | This question has nothing to do with the warnings SSE AVX etc.. I 've included the output for completeness . The issue is the fail on some cuda libs , I think , at the end , the machine has a NVIDA 1070 card and has the Cuda libs that are used earlier in the process but something is missing at the end ? I pip installed... | ( py36 ) tom @ tomServal : ~/Documents/LearningRepos/Working $ python Minst_with_summaries.pyI tensorflow/stream_executor/dso_loader.cc:135 ] successfully opened CUDA library libcublas.so.8.0 locallyI tensorflow/stream_executor/dso_loader.cc:135 ] successfully opened CUDA library libcudnn.so.5 locallyI tensorflow/strea... | Cuda issue in TensorFlow 1.0 tutorial looks like TF ca n't find CUPTI/lib64 ? |
Python | I was going through the Documentation of exceptions in python : - ( https : //docs.python.org/2/tutorial/classes.html # exceptions-are-classes-too ) I ca n't seem to find how this code works Output : -What 's `` pass '' doing in the classes ? Just by going over the documentation all i can get is objects of all the clas... | class B : passclass C ( B ) : passclass D ( C ) : pass for c in [ B , C , D ] : try : raise c ( ) except D : print `` D '' except C : print `` C '' except B : print `` B '' BCD class B : passclass C ( B ) : passclass D ( C ) : pass for c in [ B , C , D ] : try : raise c ( ) except B : print `` B '' except C : print `` ... | Classes with exception |
Python | I 'd like to generate an animation pixel by pixel programmatically . Preferably in Hi-Def , in Python or in Ruby . I thought about using PIL to make each frame and then convert the frames into video . Is there a better way to do this ? EDIT : Clarification , this is 2D and I need the pixels to be precise . EDITEDIT : S... | frame = Frame ( ) frame.draw ( 0 , 0 , 'red ' ) frame.draw ( 0 , 1 , 'blue ' ) ... frame = Frame ( ) ... | generate video pixel by pixel , programmatically |
Python | I want to have : How do I do that ? Putting __repr__ inside hehe function does not work.EDIT : In case you guys are wondering why I want to do this : I just do n't like the way it shows here . | > > > def hehe ( ) : ... return `` spam '' ... > > > repr ( hehe ) ' < function hehe at 0x7fe5624e29b0 > ' > > > repr ( hehe ) 'hehe function created by awesome programmer ' > > > defaultdict ( hehe ) defaultdict ( < function hehe at 0x7f0e0e252280 > , { } ) | How do I change the representation of a Python function ? |
Python | If I understand correctlygives the same result asso I guess it 's more elegant.I seem to remember seeing this kind of short-circuit assignment statement in JavaScript code . But is it considered good style in Python to use short-circuiting in assignment statements ? | myvar = a and b or c if a : if b : myvar = b else : myvar = celse : myvar = c | Is short-circuiting in assignment statements considered good style ? |
Python | I am trying to implement a unranked boolean retrieval . For this , I need to construct a tree and perform a DFS to retrieve documents . I have the leaf nodes but I am having difficulty to construct the tree . Eg : query = OR ( AND ( maria sharapova ) tennis ) Result : I traverse the tree using DFS and calculate the boo... | OR | | AND tennis | | maria sharapova | Constructing a tree using Python |
Python | I 've been trying to learn about metaclasses in Python . I get the main idea , but I ca n't seem to activate the mechanism . As I understand it , you can specify M to be as the metaclass when constructing a class K by setting __metaclass__ to M at the global or class level . To test this out , I wrote the following pro... | p = printclass M ( type ) : def __init__ ( *args ) : type.__init__ ( *args ) print ( `` The rain in Spain '' ) p ( 1 ) class ClassMeta : __metaclass__ = Mp ( 2 ) __metaclass__ = Mclass GlobalMeta : passp ( 3 ) M ( 'NotMeta2 ' , ( ) , { } ) p ( 4 ) C : \Documents and Settings\Daniel Wong\Desktop > python -- versionPytho... | Should n't __metaclass__ force the use of a metaclass in Python ? |
Python | Below are two simple python functions . First tries to connect to test.com domain on 666 ( host name is valid but port is not ) . Second tries to connect to imap.mail.outlook.com on port 993 ( host name is valid , but looks like not for public use/access ) .And here are execution time for that function with different t... | def fn_outlook ( timeout ) : try : socket.create_connection ( ( `` imap.mail.outlook.com '' , 993 ) , timeout=timeout ) except socket.timeout : passdef fn_test ( timeout ) : try : socket.create_connection ( ( `` test.com '' , 666 ) , timeout=timeout ) except socket.timeout : pass In [ 14 ] : % time fn_test ( 1 ) CPU ti... | Python 's 2.7 socket.timeout behavior |
Python | A picture paints a thousand words ... : In my Python 2.7 application I have a button which when clicked pops up a menu.In some circumstances this list is larger than the screen size.In Ubuntu 12.04 ( uses Gtk 3.4.2 ) this is OK because you get scroll-arrows ( as shown on the right of the picture ) .In Ubuntu 12.10/13.0... | # -*- Mode : python ; coding : utf-8 ; tab-width : 4 ; indent-tabs-mode : nil ; -*- # ! /usr/bin/env pythonfrom gi.repository import Gtkdef popupclick ( self , *args ) : popup.popup ( None , None , None , None , 0 , Gtk.get_current_event_time ( ) ) window = Gtk.Window ( ) window.connect ( 'delete_event ' , Gtk.main_qui... | What is the correct method to display a large popup menu ? |
Python | I 'm working on a CMS in Python that uses reStructuredText ( via docutils ) to format content . Alot of my content is imported from other sources and usually comes in the form of unformatted text documents . reST works great for this because it makes everything look pretty sane by default.One problem I am having , howe... | from docutils import coreimport reSTpygmentsdef reST2HTML ( str ) : parts = core.publish_parts ( source = str , writer_name = 'html ' ) return parts [ 'body_pre_docinfo ' ] + parts [ 'fragment ' ] | How Do I Suppress or Disable Warnings in reSTructuredText ? |
Python | What 's the best Python idiom for this C construct ? I do n't have the ability to recode next ( ) .update : and the answer from seems to be : | while ( ( x = next ( ) ) ! = END ) { ... . } for x in iter ( next , END ) : ... . | Most Pythonic way equivalent for : while ( ( x = next ( ) ) ! = END ) |
Python | I 'm trying to use the struct.pack functionand it gives me this output : while the python docs say : so len ( ) should be 2 + 4 = 6 , and I need bytes with size = 6Any ideas ? I 'm using Python 3.6 on Windows 10 | import structvalues = ( 0 , 44 ) s = struct.Struct ( 'HI ' ) b = s.pack ( *values ) print ( b ) print ( str ( len ( b ) ) ) b'\x00\x00\x00\x00 , \x00\x00\x00 ' 8 Format - C Type - Python type - Standard size - NotesH - unsigned short - integer - 2 - ( 3 ) I - unsigned int - integer - 4 - ( 3 ) | struct pack return is too long |
Python | I was fiddling around with Python 's generators and iterable class , just for fun . Basically I wanted test out something that I 've never been too sure about : that classes in Pythons have some significant overhead and it 's better to rely on methods that implement yield instead of classes that implement an iterator p... | # ! /usr/bin/env pythonimport time x = 0def create_generator ( num ) : mylist = range ( num ) for i in mylist : yield it = time.time ( ) gen = create_generator ( 100000 ) for i in gen : x = x + iprint `` % .3f '' % ( time.time ( ) - t ) # ! /usr/bin/env pythonimport timex = 0class Generator ( object ) : def __init__ ( ... | Overhead on looping over an iterable class |
Python | I have a DataFrame , which I group.I would like to add another column to the data frame , that is a result of function diff , per group . Something like : I would like to get per each group the differnece of column D , and have a DF that include a new column with the diff calculation . | df = pd.DataFrame ( { ' A ' : [ 'foo ' , 'bar ' , 'foo ' , 'bar ' , 'foo ' , 'bar ' , 'foo ' , 'foo ' ] , ' B ' : [ 'one ' , 'one ' , 'two ' , 'three ' , 'two ' , 'two ' , 'one ' , 'three ' ] , ' C ' : np.random.randn ( 8 ) , 'D ' : np.random.randn ( 8 ) } ) df_grouped = df.groupby ( ' B ' ) for name , group in df_grou... | Modify pandas group |
Python | I 'm having trouble assigning unicode strings as names for a namedtuple . This works : and this does n't : I get the errorWhy is that the case ? The documentation says , `` Python 3 also supports using Unicode characters in identifiers , '' and the key is valid unicode ? | a = collections.namedtuple ( `` test '' , `` value '' ) b = collections.namedtuple ( `` βαδιζόντων '' , `` value '' ) Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > File `` /usr/lib64/python3.4/collections/__init__.py '' , line 370 , in namedtuple result = namespace [ typename ] Key... | namedtuple with unicode string as name |
Python | We are aware that the standard method of setting a single cell is using at or iat . However , I noticed some interesting behaviour I was wondering if anyone could rationalise . In solving this question , I come across some weird behaviour of loc.To set cell ( 1 , ' B ' ) , it suffices to do this with at , like df.at [ ... | # Setup.pd.__version__ # ' 0.24.0rc1'df = pd.DataFrame ( { ' A ' : [ 12 , 23 ] , ' B ' : [ [ ' a ' , ' b ' ] , [ ' c ' , 'd ' ] ] } ) df A B0 12 [ a , b ] 1 23 [ c , d ] df.loc [ 1 , ' B ' ] = [ 'm ' , ' n ' , ' o ' , ' p ' ] # ValueError : Must have equal len keys and value when setting with an iterable df.loc [ 1 , '... | Inserting list into a cell - why does loc ACTUALLY work here ? |
Python | Is there a more concise syntax for using sqlalchemy joinedload to eager load items from more than one table that only relates to the query table by way of another intermediate table ( or is there an alternative load syntax that is better for what I am trying to do ) ? For example , using the familiar data structure of ... | from sqlalchemy.orm import joinedloadresult = session.query ( Question ) .\ options ( joinedload ( Question.answers ) . joinedload ( Answer.comments ) ) .\ options ( joinedload ( Question.answers ) . joinedload ( Answer.votes ) ) .\ filter ( Question.id == ' 1 ' ) .\ first ( ) result = session.query ( Question ) .\ opt... | sqlalchemy joinedload : syntax to load multiple relationships more than 1 degree separated from query table ? |
Python | I have a dataframe like thisThe mission is to get a list like thisAny ideas , thanks in advance . | A B C D E 0 0.0 1.0 0.0 0.0 1.0 1 0.0 0.0 1.0 0.0 0.0 2 0.0 1.0 1.0 1.0 0.0 3 1.0 0.0 0.0 0.0 1.0 4 0.0 0.0 0.0 1.0 0.0 0 B , E1 C2 B , C , D3 A , E4 D | Boolean values to column names in one list , dataframe pandas python |
Python | I 'm looking at creating a Dataframe that is the combination of two unrelated series.If we take two dataframes : I 'm looking for this output : One way could be to have loops on the lists direclty and create the DataFrame but there must be a better way . I 'm sure I 'm missing something from the pandas documentation.Ul... | A = [ ' a ' , ' b ' , ' c ' ] B = [ 1,2,3,4 ] dfA = pd.DataFrame ( A ) dfB = pd.DataFrame ( B ) A B0 a 11 a 22 a 33 a 44 b 15 b 26 b 37 b 48 c 19 c 210 c 311 c 4 result = [ ] for i in A : for j in B : result.append ( [ i , j ] ) result_DF = pd.DataFrame ( result , columns= [ ' A ' , ' B ' ] ) from datetime import datet... | What is the most efficient way to create a DataFrame from two unrelated series ? |
Python | I use requests.api lib to send post request . What I want is to send multidimensional POST data and I always come up short with this code : On the receiving end i get a POST with `` requestData '' = > `` someKey3 '' instead of `` requestData '' = > [ `` someKey3 '' = > 'someData3 ' ] How do I send the correct POST ? | import requestsurl = 'http : //someurl.com ' ; request_data = { } request_data [ 'someKey ' ] = 'someData'request_data [ 'someKeytwo ' ] = 'someData2'request_data [ 'requestData ' ] = { 'someKey3 ' : 'someData3 ' } login = requests.post ( url , data=login_data ) | How to send multidimensional POST in Python |
Python | In my Django project I get below error when I query my data : django.db.utils.OperationalError : ( 1052 , `` Column 'name ' in field list is ambiguous '' ) using : but if I use : It will work fine.my ListAPIView code : my serializer code : my model of PhysicalServer : EDIT-1My Switches Model : and my SwitchesPort model... | http : //localhost:8000/api/physicalserver/list/ ? switchesport__bandwidth=10 http : //localhost:8000/api/physicalserver/list/ ? switches__id=xxx class PhysicalServerListAPIView ( ListAPIView ) : serializer_class = PhysicalServerListSerializer permission_classes = [ AllowAny ] pagination_class = CommonPagination def ge... | django.db.utils.OperationalError : ( 1052 , `` Column 'name ' in field list is ambiguous '' ) |
Python | For example if I have a list like this : | List1 = [ 7,6,9 ] List1 = List1.sort ( ) | Can anyone explain why this sorting wo n't work ? |
Python | This is my first attempt at threads in Python ... And it failed miserably : ) I wanted to implement a basic critical zone problem , and found that this code actually does n't present a problem.The question : why do n't I have problems with the counter increment ? Should n't the counter have random values after a run ? ... | import threadingimport timeturnstile_names = [ `` N '' , `` E '' , `` S '' , `` W '' ] count = 0class Counter ( threading.Thread ) : def __init__ ( self , id ) : threading.Thread.__init__ ( self ) self.id = id def run ( self ) : global count for i in range ( 20 ) : # self.sem.acquire ( ) count = count + 1 # self.sem.re... | Threading in Python - What am I missing ? |
Python | I can see similar questions have been asked before but those are running multi processors and not executors . Therefore I am unsure how to fix this.the GitHub issue also say its resolved in 4.1 https : //github.com/celery/celery/issues/1709 I am usingMy script as as follows , ive tried to cut it down to show relevant c... | celery==4.1.1django-celery==3.2.1django-celery-beat==1.0.1django-celery-results==1.0.1 @ asyncio.coroutinedef snmp_get ( ip , oid , snmp_user , snmp_auth , snmp_priv ) : results= [ ] snmpEngine = SnmpEngine ( ) errorIndication , errorStatus , errorIndex , varBinds = yield from getCmd ( ... ) ... for varBind in varBinds... | Django celery - asyncio - daemonic process are not allowed to have children |
Python | Suppose I have a dataset like the followingI often want to perform a groupby-aggregate operation where I group by multiple columns and apply multiple functions to one column . Furthermore , I usually do n't want a multi-indexed , multi-level table . To accomplish this , it 's taking me three lines of code which seems e... | df = pd.DataFrame ( { 'x1 ' : [ ' a ' , ' a ' , ' b ' , ' b ' ] , 'x2 ' : [ True , True , True , False ] , 'x3 ' : [ 1,1,1,1 ] } ) df x1 x2 x30 a True 11 a True 12 b True 13 b False 1 bg = df.groupby ( [ 'x1 ' , 'x2 ' ] ) .agg ( { 'x3 ' : { 'my_sum ' : np.sum , 'my_mean ' : np.mean } } ) bg.columns = bg.columns.droplev... | A better way to aggregate data and keep table structure and column names with Pandas |
Python | I 've got a bunch of dates i 'm trying to OCR using tesseract.However , a lot of the digits in the dates merge with the lines in the date boxes as so : Also , here 's a good image that i can tesseract well with : And here 's my code : The output from the good image attached is so : Tesseracting this image does give me ... | import osimport cv2from matplotlib import pyplot as pltimport subprocessimport numpy as npfrom PIL import Imagedef show ( img ) : plt.figure ( figsize= ( 20,20 ) ) plt.imshow ( img , cmap='gray ' ) plt.show ( ) def sort_contours ( cnts , method= '' left-to-right '' ) : # initialize the reverse flag and sort index rever... | OpenCV digits merging into surrounding boxes |
Python | i use the following codes to read data from csv using read_csv , but after i print the result and found the first column name is circled by double quote , but other column names are normal , The output is here | import pandas as pdimport numpy as npimport csvpath1 = `` C : \\Users\\IBM_ADMIN\\Desktop\\ml- 1m\\SELECT_FROM_HRAP2P3_SAAS_ZTXDMPARAM_201611291745.csv '' frame1 = pd.read_csv ( path1 , encoding='utf8 ' , dtype = { 'COMPANY_ORGANIZATION ' : str } ) frame1 | first column name is circled by double quote after reading from csv |
Python | I can parse out the paths to the files of a Python traceback , and I can then send those on to Vim using -p on the command line , so that they are opened one file per tab . So I end up with a command like , for exampleThat opens each file in a new tab , but I would like them opened in a new tab , at the correct line nu... | vim -p main.py module.py another.py vim -p main.py +10 module.py +20 another.py +30 vim -p main.py+10 module.py+20 another.py+30vim -p main.py\ +10 `` module.py +20 '' another.py @ 30 | How can I send line number from Python traceback into vim ? |
Python | I 'd like to associate positional arguments with the `` argument state '' which exists when they occur . For example , the following command line : Should produce the following associations : Can this be done with the argparse module ? | script.py -m 1 foo -r 2 bar -r 7 baz -m 6 quux foo : m=1 , r=0 ( default value for r ) bar : m=1 , r=2baz : m=1 , r=7quux : m=6 , r=7 | Can argparse associate positional arguments with named arguments ? |
Python | I have an open source python software ( GridCal ) that has a GUI made with PyQt5 . The program is pip-installable pip3 install GridCal.I would like to know what do I have to do so that when someone pip-installs my program , it appears on the system menus like when one installs Spyder ( The python IDE ) So far , all I c... | from distutils.core import setupimport sysimport osname = `` GridCal '' # Python 2.4 or later neededif sys.version_info < ( 3 , 5 , 0 , 'final ' , 0 ) : raise ( SystemExit , 'Python 3.5 or later is required ! ' ) # Build a list of all project modulespackages = [ ] for dirname , dirnames , filenames in os.walk ( name ) ... | Package a python app like spyder does |
Python | I found this as one of the ways to run ( using exec ( ) method ) python script from java . I have one simple print statement in python file . However , my program is doing nothing when I run it . It neither prints the statement written in python file nor throws an exception . The program just terminates doing nothing :... | Process p = Runtime.getRuntime ( ) .exec ( `` C : \\Python\\Python36-32\\python.exe C : \\test2.py '' ) ; Process p = Runtime.getRuntime ( ) .exec ( `` C : \\Python\\Python36-32\\python.exe C : \\test2.py output.txt 2 > & 1 '' ) ; | Issue in calling Python code from Java ( without using jython ) |
Python | I just wrote a class decorator like below , tried to add debug support for every method in the target class : Run above code , the result is : You can find that 'TestMethod2 ' printed twice.Is there problem ? Is my understanding right for the decorator in python ? Is there any workaround ? BTW , i do n't want add decor... | import unittestimport inspectdef Debug ( targetCls ) : for name , func in inspect.getmembers ( targetCls , inspect.ismethod ) : def wrapper ( *args , **kwargs ) : print ( `` Start debug support for % s. % s ( ) '' % ( targetCls.__name__ , name ) ) ; result = func ( *args , **kwargs ) return result setattr ( targetCls ,... | How to Write a valid Class Decorator in Python ? |
Python | I am using heapq to get nlargest elements from list of lists . The program I wrote is below.I just want the top 20 elements . So Instead of sorting I thought of using a heap . The error I am getting is , Can I know why I am getting the error and how to resolve it . Is there any property of using heapq I am missing . | import csvimport heapqf = open ( `` E : /output.csv '' , '' r '' ) read = csv.reader ( f ) allrows = [ row for row in read ] for i in xrange ( 0,2 ) : print allrows [ i ] allrows.sort ( key=lambda x : x [ 2 ] ) # this is working properlyit=heapq.nlargest ( 20 , enumerate ( allrows ) , key=lambda x : x [ 2 ] ) # error T... | How can I get n largest lists from a list of lists in python |
Python | I have the following resource defined : When I try to query using the objectid , I get empty list.5834987589b0dc353b72c27d is the valid _id for the element.If I move the data relation out of the embedded document I can query it as expectedIs there anyway to do this with an embedded data relation ? | item = { 'wrapper ' : { 'type ' : 'dict ' , 'schema ' : { 'element ' : { 'type ' : 'objectid ' , 'data_relation ' : { 'resource ' : 'code ' , 'field ' : '_id ' , 'embeddable ' : True , } , } , } , } , } http : //127.0.0.1:5000/item ? where= { `` wrapper.element '' : '' 5834987589b0dc353b72c27d '' } | Python Eve - Query Embedded Data Relation |
Python | Some time ago I thought that the tuple 's constructor was a pair of parentheses ( ) .Example : But now I know that it is the comma , .So , doing the same as above : But if I do : This makes sense to me , but : And finally : Here 's the question : why are parenthesis needed in the final case if the tuple is just 1,2,3 ? | > > > ( 1 , ) ( 1 , ) > > > type ( ( 1 , ) ) < type 'tuple ' > > > > t = ( 1 , ) > > > type ( t ) < type 'tuple ' > > > > 1 , ( 1 , ) > > > type ( 1 , ) < type 'int ' > # Why ? > > > 1,2,3 ( 1,2,3 ) > > > type ( 1,2,3 ) Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > TypeError : type... | Why parenthesis are needed in tuples ? |
Python | I had a question about equality comparison with numpy and arrays of strings.Say I define the following array : Then I can test for equality with other strings and it does element wise comparison with the single string ( following , I think , the broadcasting rules here : http : //docs.scipy.org/doc/numpy-1.10.1/user/ba... | x = np.array ( [ 'yes ' , 'no ' , 'maybe ' ] ) 'yes ' == x # op : array ( [ True , False , False ] , dtype=bool ) x == 'yes ' # op : array ( [ True , False , False ] , dtype=bool ) x == u'yes ' # op : array ( [ True , False , False ] , dtype=bool ) u'yes ' == x # op : False | Unicode elementwise string comparison in numpy |
Python | Example data can be found here in CSV format.Given the following code : I obtain the following figure : Why is pandas inserting gaps in the figure ? The values range from 0 to 7 , and are all represented , so I see no reason why this should happen.Thanks very much in advance ! | figure ( ) grp.vis.plot ( kind='hist ' , alpha=.5 , normed=True ) show ( ) | Why is pandas inserting spaces in my histogram ? |
Python | I would like to understand which items can be tested for set membership in Python . In general , set membership testing works like list membership testing in Python.However , sets are different from lists in that they can not contain unhashable objects , for example nested sets.List , okay : Set , does not work because... | > > > 1 in { 1,2,3 } True > > > 0 in { 1,2,3 } False > > > > > > [ 1,2 , { 1,2 } ] [ 1 , 2 , { 1 , 2 } ] > > > > > > { 1,2 , { 1,2 } } Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > TypeError : unhashable type : 'set ' > > > > > > { 1 } in { 1,2,3 } False > > > { 1,2 } in { 1,2,3 } ... | What makes an element eligible for a set membership test in Python ? |
Python | I have a web application timeout issue , and I 'm suspecting the error is in the database . The query is running too long . How do I increase the allowed-running-time for my setup ? I am using a DB pool by using sqlalchemy and psycopg2 . My database is a Postgres database . | import psycopg2 import sqlalchemy.pool as pool def generate_conn_string ( db_name ) : db_name = db_name.upper ( ) conn_string = `` host= ' { } ' port= ' { } ' dbname= ' { } ' user= ' { } ' password= ' { } ' `` .format ( os.environ.get ( 'DB_HOST_ ' + db_name ) , os.environ.get ( 'DB_PORT_ ' + db_name ) , os.environ.get... | sqlalchemy.pool + psycopg2 timeout issue |
Python | My question is an extension to another question where the OP has a dictionary , the one below , and wants to sort main keys based on the sub-dictionary keysThe proposed ( quoted below ) solution works perfectly . However this solution does sorting in ascending order for all ( sorting in descending order is straightforw... | myDict = { 'SER12346 ' : { 'serial_num ' : 'SER12346 ' , 'site_location ' : 'North America ' } , 'ABC12345 ' : { 'serial_num ' : 'ABC12345 ' , 'site_location ' : 'South America ' } , 'SER12345 ' : { 'serial_num ' : 'SER12345 ' , 'site_location ' : 'North America ' } , 'SER12347 ' : { 'serial_num ' : 'SER12347 ' , 'site... | Sort python dictionary keys based on sub-dictionary keys by defining sorting order |
Python | Create a zip file from a generator in Python ? describes a solution for writing a .zip to disk from a bunch of files.I have a similar problem in the opposite direction . I am being given a generator : and I would love to pipe it to a tar gunzip file-like object : But I ca n't : I can solve this in the shell like so : H... | stream = attachment.iter_bytes ( ) print type ( stream ) b = io.BytesIO ( stream ) f = tarfile.open ( mode= ' r : gz ' , fileobj = b ) f.list ( ) < type 'generator ' > Error : 'generator ' does not have the buffer interface $ curl -- options http : //URL | tar zxf - ./path/to/interesting_file | How do I read a tarfile from a generator ? |
Python | I am sure there is an answer to this but I can not seem to find it . Also , important to note that I am very new to Python.I recently cloned this repo which uses python and wsgi https : //github.com/hypothesis/via for routing . What I want is to have a param in the url path ( no query string ) as such : How can I achie... | meow.com/cat_articles/ : article_id # i.e . meow.com/cat_articles/677 | How to include a variable in URL path using wsgi ? ( not query string ) |
Python | I am trying to get average merged image to show up using the following code : The following code adds the two images and result is same as whats shown in the course . But a simple addition avg=img1+img2 doesnt work.Two images added together without any modification - washout areas are due to addition being over 255 for... | import numpy as npimport cv2import matplotlib.pyplot as pltdolphin=cv2.imread ( 'dolphin.png',0 ) # Also tried without the 0bicycle=cv2.imread ( 'bicycle.png',0 ) sumimg=cv2.add ( dolphin , bicycle ) cv2.imshow ( 'Sum image ' , sumimg ) cv2.waitKey ( 0 ) cv2.destroyAllWindows ( ) avgimg=cv2.add ( dolphin/2 , bicycle/2 ... | OpenCV python image washout |
Python | Is there any way I can get ctags to somehow support the built-in functions provided by PHP/Python ( Or whatever I 'm working with at that moment ) , so that I can also use those in Source Explorer in vim and alike ? Update : Okay so with python I can just run ctags on the source folder to get a tags file with the built... | /* { { { proto resource mysql_connect ( [ string hostname [ : port ] [ : /path/to/socket ] [ , string username [ , string password [ , bool new [ , int flags ] ] ] ] ] ) -- regex-C='/\/\* \ { \ { \ { proto ( [ ^ ] + ) ( [ ^ ( ] * ) /\2/f/ ' | ctags info for built-in functions in PHP/Python/Etc |
Python | For example , y=Axwhere A is an diagonal matrix , with its trainable weights ( w1 , w2 , w3 ) on the diagonal . How to create such trainable A in Tensorflow or Keras ? If I try A = tf.Variable ( np.eye ( 3 ) ) , the total number of trainable weights would be 3*3=9 , not 3 . Because I only want to update ( w1 , w2 , w3 ... | A = [ w1 ... ... ... w2 ... ... ... w3 ] | Tensorflow , Keras : How to create a trainable variable that only update in specific positions ? |
Python | How to reduce a data with the longest string under pandas framework ? I tried the following code , but get ValueError : invalid number of arguments.Ex . InputOutput : | def f1 ( s ) : return max ( s , key=len ) data.groupby ( 'id ' ) .agg ( { 'name ' : ( lambda s : f1 ( s ) ) } ) id nameGB `` United Kingdom '' GB EnglandUS `` United States '' US America id nameGB `` United Kingdom '' US `` United States '' | How to reduce a data with the longest string under pandas framework ? |
Python | I have an application where I need to measure the week-number of the year , and I want all weeks to have 7 days , regardless of whether the days are in separate years.For example , I want all the days from Dec 30 , 2012 to Jan 5 , 2013 to be in the same week.But this is not straight forward to do in python , because as... | % U Week number of the year ( Sunday as the first day of the week ) as a decimal number [ 00,53 ] . All days in a new year preceding the first Sunday are considered to be in week 0. import datetime datetime.date ( 2012 , 12 , 31 ) .strftime ( ' % Y- % U ' ) > > > 2012-53 import datetime datetime.date ( 2013 , 01 , 01 )... | Python Week Numbers where all weeks have 7 days , regardless of year rollover |
Python | I tested list ( x for x in a ) with three different CPython versions . On a = [ 0 ] it 's significantly faster than on a = [ ] : With tuple instead of list , it 's the expected other way around : So why is list faster when it ( and the underlying generator iterator ) has to do more ? Tested on Windows 10 Pro 2004 64-bi... | 3.9.0 64-bit 3.9.0 32-bit 3.7.8 64-bita = [ ] a = [ 0 ] a = [ ] a = [ 0 ] a = [ ] a = [ 0 ] 465 ns 412 ns 543 ns 515 ns 513 ns 457 ns 450 ns 406 ns 544 ns 515 ns 506 ns 491 ns 456 ns 408 ns 551 ns 513 ns 515 ns 487 ns 455 ns 413 ns 548 ns 516 ns 513 ns 491 ns 452 ns 404 ns 549 ns 511 ns 508 ns 486 ns 3.9.0 64-bit 3.9.0... | Why is list ( x for x in a ) faster for a= [ 0 ] than for a= [ ] ? |
Python | There is a pandas dataframe like this : I would like to round the index to the hour like this : I am trying the following code : but returns a serie instead of a dataframe with the modified index column | index2018-06-01 02:50:00 R 45.48 -2.8 2018-06-01 07:13:00 R 45.85 -2.0 ... 2018-06-01 08:37:00 R 45.87 -2.7 index2018-06-01 02:00:00 R 45.48 -2.8 2018-06-01 07:00:00 R 45.85 -2.0 ... 2018-06-01 08:00:00 R 45.87 -2.7 df = df.date_time.apply ( lambda x : x.round ( ' H ' ) ) | How to round date time index in a pandas data frame ? |
Python | I have been trying to use python 's numpy.where function to determine the location of a specific value , but for some reason it incorrectly determines False where the value is actually found . Thereby returning an empty array . See below : Does anyone know why this is happening ? I 've tried many different variants , e... | > > > lbpoly=numpy.array ( [ 5.45 5.5 5.55 5.6 5.65 5.7 5.75 5.8 5.85 5.9 5.95 6.6.05 6.1 6.15 6.2 6.25 6.3 6.35 6.4 6.45 6.5 6.55 6.66.65 6.7 6.75 6.8 6.85 6.9 6.95 7 . ] ) > > > cpah=numpy.where ( lbpoly==6.2 ) > > > print cpah > > > ( array ( [ ] , dtype=int32 ) , ) | Numpy.where function not finding values within array ... Anyone know why ? |
Python | There is an Activation layer in Keras.Seems this code : and this one : produces the same result.What is the purpose of this additional Activation layer ? [ Upgr : 2017-04-10 ] Is there a difference in performance with above two scenarios ? | model.add ( Convolution2D ( 64 , 3 , 3 ) ) model.add ( Activation ( 'relu ' ) ) model.add ( Convolution2D ( 64 , 3 , 3 , activation='relu ' ) ) | keras usage of the Activation layer instead of activation parameter |
Python | If I specify the character encoding ( as suggested by PEP 263 ) in the `` magic line '' or shebang of a python module likecan I retrieve this encoding from within that module ? ( Working on Windows 7 x64 with Python 2.7.9 ) I tried ( without success ) to retrieve the default encoding or shebangwill yield : sys.getdefau... | # -*- coding : utf-8 -*- # -*- coding : utf-8 -*-import sysfrom shebang import shebangprint `` sys.getdefaultencoding ( ) : '' , sys.getdefaultencoding ( ) print `` shebang : '' , shebang ( __file__.rstrip ( `` oc '' ) ) | get encoding specified in magic line / shebang ( from within module ) |
Python | Python 's documentation on the methods related to the in-place operators like += and *= ( or , as it calls them , the augmented arithmetic assignments ) has the following to say : These methods should attempt to do the operation in-place ( modifying self ) and return the result ( which could be , but does not have to b... | > > > x = 5 > > > x.__iadd__Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > AttributeError : 'int ' object has no attribute '__iadd__ ' > > > list1 = [ ] > > > list2 = list1 > > > list1 += [ 1,2,3 ] > > > list1 is list2True | Why return anything but ` self ` from ` __iadd__ ` ? |
Python | Suppose I have a python file named file.py.Normally to run this file from the command-line I would do : My question is , is it possible to do this without having the python before the file path like so : Or , if I have the path to file.py in my Environment Variables , simply just : I suppose it 's worth noting I want t... | python path\to\file\file.py path\to\file\file.py file.py | How to run a python file ( .py ) from the windows command-line without having to type python first ? |
Python | Supposing I have an XPath function I 'm calling from an XSL transform using lxml ( with libxml and libxslt ) , eg : From this function , I 'd like to return an XML fragment that consists the following : The python function my_func is set-up correctly using lxml to be available via the XSL stylesheet , and used lxml.htm... | < xsl : template match= '' / '' > < xsl : variable name= '' result '' select= '' myns : my-func ( ./* ) '' / > ... < /xsl : template > some sample < em > text < /em > | How can I return a text fragment from an XPath function ? |
Python | I would like to store a PNG image in Python where the RGB values are given by the list ( row , column , RGB triple ) , together with a default value of [ 255 , 255 , 255 ] and the information about the total dimensions of the image.Using PIL , I could of course translate entries into a dense m-by-n-by-3 matrix , but th... | entries = [ [ 1 , 2 , [ 255 , 255 , 0 ] ] , [ 1 , 5 , [ 255 , 100 , 0 ] ] , [ 2 , 5 , [ 0 , 255 , 110 ] ] , # ... ] | create PNG image from sparse data |
Python | I 'd like to define a new word which includes count values from two ( or more ) different words . For example : I would like to define mother as mom + mother : This is a way to alternative define group of words having some meaning ( at least for my purpose ) .Any suggestion would be appreciated . | Words Frequency0 mom 2501 2020 1512 the 1243 19 824 mother 81 ... ... ... 10 London 611 life 612 something 6 Words Frequency0 mother 3311 2020 1512 the 1243 19 82 ... ... ... 9 London 610 life 611 something 6 | Merge related words in NLP |
Python | Given the target ( ' b ' , ' a ' ) and the inputs : The aim is to find the location of the continuous ( ' b ' , ' a ' ) element and get the output : Using the pairwise recipe : I could do this to get the desired output : But that would require me to loop through all pairs of characters till I find the first instance . ... | x0 = ( ' b ' , ' a ' , ' z ' , ' z ' ) x1 = ( ' b ' , ' a ' , ' z ' , ' z ' ) x2 = ( ' z ' , ' z ' , ' a ' , ' a ' ) x3 = ( ' z ' , ' b ' , ' a ' , ' a ' ) > > > find_ba ( x0 ) 0 > > > find_ba ( x1 ) 0 > > > find_ba ( x2 ) None > > > find_ba ( x3 ) 1 from itertools import teedef pairwise ( iterable ) : `` s - > ( s0 , ... | Finding index of pairwise elements |
Python | Why am i getting this error ? and here is how i call the streaming API . Probably cause by GAE does n't allowed the socket , i 'm not sure how to apply the query term to get specific filtered streaming tweets . My purpose with this portion of code is to getting live stream with designate keywords . If there any alterna... | import tweepyimport syscreds = json.loads ( open ( 'credential.json ' ) .read ( ) ) tw_consumer_key = creds [ 'tw_consumer_key ' ] tw_consumer_secret = creds [ 'tw_consumer_secret ' ] tw_access_token = creds [ 'tw_access_token ' ] tw_access_token_secret = creds [ 'tw_access_token_secret ' ] try : auth = tweepy.OAuthHan... | Twitter Streaming on GAE |
Python | I am doing the Tango with Django tutorial and I have completed the tutorials successfully however I noticed in the official Django Polls tutorial , the following : The part to notice here is the `` Always return an HttpResponseRedirect after successfully dealing with POST data . '' However , in the Tango with Django tu... | def vote ( request , question_id ) : p = get_object_or_404 ( Question , pk=question_id ) try : selected_choice = p.choice_set.get ( pk=request.POST [ 'choice ' ] ) except ( KeyError , Choice.DoesNotExist ) : # Redisplay the question voting form . return render ( request , 'polls/detail.html ' , { 'question ' : p , 'err... | Should I use HttpResponseRedirect here ? |
Python | I 've found that len ( arr ) is almost twice as fast as arr.shape [ 0 ] and am wondering why.I am using Python 3.5.2 , Numpy 1.14.2 , IPython 6.3.1The below code demonstrates this : I 've also done some more tests for comparison : So I have two questions:1 ) Why does len ( arr ) works faster than arr.shape [ 0 ] ? ( I ... | arr = np.random.randint ( 1 , 11 , size= ( 3 , 4 , 5 ) ) % timeit len ( arr ) # 62.6 ns ± 0.239 ns per loop ( mean ± std . dev . of 7 runs , 10000000 loops each ) % timeit arr.shape [ 0 ] # 102 ns ± 0.163 ns per loop ( mean ± std . dev . of 7 runs , 10000000 loops each ) class Foo ( ) : def __init__ ( self ) : self.sha... | Numpy performance gap between len ( arr ) and arr.shape [ 0 ] |
Python | First off , i have searched online and this website for solutions and the ones i have tried are not working so i decided to post my individual question and code . This program was created using Python 3.2.2 and the corresponding compatible version of pygame . I also realize a more efficient method would be to use sprit... | import pygameimport randomimport mathpygame.init ( ) height = 550width = 750screen = pygame.display.set_mode ( ( width , height ) ) background = pygame.image.load ( `` Planet.jpg '' ) Clock = pygame.time.Clock ( ) class asteroid ( pygame.sprite.Sprite ) : def __init__ ( self , x , y , size ) : pygame.sprite.Sprite.__in... | Software Design and Development Major : Pygame Smudge Trails |
Python | I read about List comprehension without [ ] in Python so now I know thatis faster thanbecause `` list comprehensions are highly optimized '' So I suppose that the optimization relies on the parsing of the for expression , sees mylist , computes its length , and uses it to pre-allocate the exact array size , which saves... | ''.join ( [ str ( x ) for x in mylist ] ) `` .join ( str ( x ) for x in mylist ) mylist = [ 1,2,5,6,3,4,5 ] ''.join ( [ str ( x ) for x in mylist if x < 4 ] ) import timeitprint ( timeit.timeit ( `` ''.join ( [ str ( x ) for x in [ 1,5,6,3,5,23,334,23234 ] ] ) '' ) ) print ( timeit.timeit ( `` ''.join ( str ( x ) for x... | How does python optimize conditional list comprehensions |
Python | I have a situation where I need to find a specific folder in S3 to pass onto a PythonOperator in an Airflow script . I am doing this using another PythonOperator that finds the correct directory . I can successfully either xcom.push ( ) or Variable.set ( ) and read it back within the PythonOperator . The problem is , I... | def check_for_done_file ( **kwargs ) : # # # This function does a bunch of stuff to find the correct S3 path to # # # populate target_dir , this has been verified and works Variable.set ( `` target_dir '' , done_file_list.pop ( ) ) test = Variable.get ( `` target_dir '' ) print ( `` TEST : `` , test ) # # # # END OF ME... | Can I get ( ) or xcom.pull ( ) a variable in the MAIN part of an Airflow script ( outside a PythonOperator ) ? |
Python | I want to use the FileUpload widget in jupyter lab.I have the following lines of codes in my notebook cell : In jupyter notebook , the output of the cell is a clickable button that I can use to upload a file . In jupyter lab , the output is the following : Here 's the info on the uploader object : Is it possible to mak... | uploader = widgets.FileUpload ( ) uploader FileUpload ( value= { } , description='Upload ' ) Type : FileUploadString form : FileUpload ( value= { } , description='Upload ' ) File : ~/miniconda3/envs/fastai2/lib/python3.7/site-packages/ipywidgets/widgets/widget_upload.py | How to use FileUpload widget in jupyter lab ? |
Python | I 'm using a lot of 3D memoryviews in Cython , e.g.I often want to loop over all elements of a. I can do this using a triple loop likeIf I do not care about the indices i , j and k , it is more efficient to do a flat loop , likeHere I need to know the number of elements ( size ) in the array . This is given by the prod... | cython.declare ( a='double [ : , : , : :1 ] ' ) a = np.empty ( ( 10 , 20 , 30 ) , dtype='double ' ) for i in range ( a.shape [ 0 ] ) : for j in range ( a.shape [ 1 ] ) : for k in range ( a.shape [ 2 ] ) : a [ i , j , k ] = ... cython.declare ( a_ptr='double* ' ) a_ptr = cython.address ( a [ 0 , 0 , 0 ] ) for i in range... | Cython : size attribute of memoryviews |
Python | I 'm trying to make a simple image classifier using PyTorch.This is how I load the data into a dataset and dataLoader : I want to print out the number of images in each class in training and test data separately , something like this : In train data : shoes : 20shirts : 14In test data : shoes : 4shirts : 3I tried this ... | batch_size = 64validation_split = 0.2data_dir = PROJECT_PATH+ '' /categorized_products '' transform = transforms.Compose ( [ transforms.Grayscale ( ) , CustomToTensor ( ) ] ) dataset = ImageFolder ( data_dir , transform=transform ) indices = list ( range ( len ( dataset ) ) ) train_indices = indices [ : int ( len ( ind... | Number of instances per class in pytorch dataset |
Python | When I tried to search the optimal C and gamma in rbf kernel SVM by : It returns the error says C is not the parameter of OneVsRestClassifier . What is the proper way to achieve the grid search on the parameters with multiclass SVM then ? | params = dict ( C = C_range , gamma = gamma_range ) clf = GridSearchCV ( OneVsRestClassifier ( SVC ( ) ) , params , cv = 5 ) | OneVsRestClassification with GridSearchCV in Sklearn |
Python | I 'm taking user input from the console but it will only accept 4096 bytes ( 4kb ) of input . Since that is such a specific number is it something that is built into the language/is there a way around it ? The code I 'm using : | message = input ( `` Enter Message : `` ) | String from input is limited ? |
Python | I have written a package for Mathematica called MathOO . In short , it allows you to use object orientation in Mathematica just like you do in Python . Please read the following article in Voofie/MathOO for details : MathOO : Adding Python style Object Orientation to Mathematica with MathOO ( 1.0 beta launch ) [ Altern... | NewClass [ Object1 ] Object1. $ init $ [ self_ ] : = Return [ ] ; object1 = new [ Object1 ] [ ] Out : object $ 13 In : y = Module [ { x } , x [ 1 ] = 2 ; x ] Out : x $ 117In : FullDefinition [ y ] Out : y = x $ 117 Attributes [ x $ 117 ] = { Temporary } x $ 117 [ 1 ] = 2 In : y = 1 ; In : Definition [ x $ 117 ] Out : A... | Temporary variables in Mathematica |
Python | I 'm building a database library for my application using sqlite3 as the base . I want to structure it like so : So I would do this in Python : I 'm suffering analysis paralysis ( oh no ! ) about how to handle the database connection . I do n't really want to use classes in these modules , it does n't really seem appro... | db/ __init__.py users.py blah.py etc.py import dbdb.users.create ( 'username ' , 'password ' ) # users.pyfrom db_stuff import connection | How should I build a simple database package for my python application ? |
Python | Here 's a code snippet from Pandas Issue # 13966Fails : Per the issue linked above , this seems to be a bug . Does anyone have a good workaround ? | dates = pd.date_range ( start='2016-01-01 09:30:00 ' , periods=20 , freq='s ' ) df = pd.DataFrame ( { ' A ' : [ 1 ] * 20 + [ 2 ] * 12 + [ 3 ] * 8 , ' B ' : np.concatenate ( ( dates , dates ) ) , ' C ' : np.arange ( 40 ) } ) df.groupby ( ' A ' ) .rolling ( '4s ' , on= ' B ' ) .C.mean ( ) ValueError : B must be monotonic | Time-based .rolling ( ) fails with group by |
Python | I was looking up how to create a function that removes duplicate characters from a string in python and found this on stack overflow : It works , but how ? I 've searched what OrderedDict and fromkeys mean but I ca n't find anything that explains how it works in this context . | from collections import OrderedDict def remove_duplicates ( foo ) : print `` `` .join ( OrderedDict.fromkeys ( foo ) ) | How does this function to remove duplicate characters from a string in python work ? |
Python | I am getting the flake 8 error of E712 at the line `` added_parts = new_part_set [ ( new_part_set [ `` duplicate '' ] == False ) & ( new_part_set [ `` version '' ] == `` target '' ) ] '' **Following is snippet of code which we used for spreadsheet comparisonAre there any other ways of how this can be avoided , Unsure o... | source_df = pd.read_excel ( self.source , sheet ) .fillna ( 'NA ' ) target_df = pd.read_excel ( self.target , sheet ) .fillna ( 'NA ' ) file_path = os.path.dirname ( self.source ) column_list = source_df.columns.tolist ( ) source_df [ 'version ' ] = `` source '' target_df [ 'version ' ] = `` target '' source_df.sort_va... | how to fix the flake 8 error `` E712 comparison to False should be 'if cond is False : ' or 'if not cond : ' '' in pandas dataframe |
Python | I am relatively new to Python development , and in reading through the language documentation , I came across a line that read : It is illegal to unbind a name that is referenced by an enclosing scope ; the compiler will report a SyntaxError.So in a learning exercise , I am trying to create this error in the interactiv... | def outer ( ) : a=5 def inner ( ) : nonlocal a print ( a ) del a | Python variable naming/binding confusion |
Python | I 'm using an object 's __del__ ( ) to unsubscribe it from an event ( using an event scheme similar to this ) : Oddly I received the following error at the end of the program 's run : How could this be possible ? ! my_environment is a module I imported , how come it could be None ? ( events is a global object in it wit... | import my_enviromentclass MyClass ( ) : def __del__ ( self ) : my_environment.events.my_event -= self.event_handler_func Exception AttributeError : `` 'NoneType ' object has no attribute 'events ' '' in < bound method MyClass.__del__ of < myclass.MyClass instance at 0x04C54580 > > ignored | Unable to reference an imported module in __del__ ( ) |
Python | Python 3.x 's sorted ( ) function can not be relied on to sort heterogeneous sequences , because most pairs of distinct types are unorderable ( numeric types like int , float , decimal.Decimal etc . being an exception ) : In contrast , comparisons between objects that have no natural order are arbitrary but consistent ... | Python 3.4.2 ( default , Oct 8 2014 , 08:07:42 ) [ GCC 4.8.2 ] on linuxType `` help '' , `` copyright '' , `` credits '' or `` license '' for more information. > > > sorted ( [ `` one '' , 2.3 , `` four '' , -5 ] ) Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > TypeError : unorderab... | Why does this key class for sorting heterogeneous sequences behave oddly ? |
Python | My code looks like this : I want it to print that statement at the top to the screen first , then do the function , and then print the `` Done '' line . Currently it waits until the `` Done '' line is executed before it prints the top part with it.In other words , I want the pausing to occur with `` Doing Something ...... | print `` Doing Something ... '' , do_some_function_that_takes_a_long_time ( ) print `` Done '' | printing to the screen on the same line at different times |
Python | I 'm trying to get server messages pushed out to the end user that 's logged into our flask website.I 've done some research and it seems that the best solution is to use socket-io.My attempts at this do n't seem to be working , I must also indicate that my knowledge of javascript is very basic.Any assistance / guidanc... | from flask_socketio import SocketIO , emitfrom flask import Flask , render_template , url_for , requestfrom time import sleepapp = Flask ( __name__ ) app.config [ 'SECRET_KEY ' ] = 'secret'app.config [ 'DEBUG ' ] = True # turn the flask app into a socketio appsocketio = SocketIO ( app , async_mode=None , logger=True , ... | Asynchronous server messages with python flask |
Python | I am trying to use timeit.timeit in order to find how much time it takes to exectute a specific line of code.The problem is that this line includes variables and I need to import them somehow , so my question is how ? In order to be more clear , the code looks something like this : If I were trying to execture this cod... | def func ( ) : var1 = 'aaa ' var2 = 'aab ' t1 = timeit.timeit ( 'var1==var2 ' , 'from __main__ import ___ ' , number = 10**4 ) # here I 'm missing what to put after the import | timeit.timeit variable importing in python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.