lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | I want to perform a specific operation . Namely , from a matrix : To the followingOr in words : multiply every entry by the identity matrix and keep the same order.Now I have accomplished this by using numpy , using the following code . Here N and M are the dimensions of the starting matrix , and the dimension of the i... | A = np.array ( [ [ 1,2 ] , [ 3,4 ] ] ) B = np.array ( [ [ 1 , 0 , 0 , 2 , 0 , 0 ] , [ 0 , 1 , 0 , 0 , 2 , 0 ] , [ 0 , 0 , 1 , 0 , 0 , 2 ] , [ 3 , 0 , 0 , 4 , 0 , 0 ] , [ 0 , 3 , 0 , 0 , 4 , 0 ] , [ 0 , 0 , 3 , 0 , 0 , 4 ] ] ) l_slice = 3n_slice = 2A = np.reshape ( np.arange ( 1 , 1+N ** 2 ) , ( N , N ) ) B = np.array (... | Modifying ( keras/tensorflow ) Tensors using numpy methods |
Python | I 'm trying to use my local s3ninja with s3cmd.Every command like : s3cmd ls s3 : //test throws the same exceptions.The s3cfg seems to be ok and the called endpoints are correct.Was anyone able to use s3ninja with s3cmd ? PS : I know S3 is n't costly and there are many better ways to test against S3 . I need S3 Ninja f... | DEBUG : ConfigParser : Reading file '/Users/daniel/.s3cfg'DEBUG : ConfigParser : access_key- > AK ... 17_chars ... EDEBUG : ConfigParser : access_token- > DEBUG : ConfigParser : add_encoding_exts- > DEBUG : ConfigParser : add_headers- > DEBUG : ConfigParser : bucket_location- > USDEBUG : ConfigParser : ca_certs_file- >... | S3Cmd does n't work with S3 Ninja |
Python | I need to transform some text files into HTML code . I 'm stuck in transforming a list into an HTML unordered list . Example source : some text in the document * item 1 * item 2 * item 3 some other textThe output should be : Currently , I have this : which creates an HTML list without < ul > tags.How can I identify the... | some text in the document < ul > < li > item 1 < /li > < li > item 2 < /li > < li > item 3 < /li > < /ul > some other text r = re.compile ( r'\* ( . * ) \n ' ) r.sub ( ' < li > \1 < /li > ' , the_text_document ) | Python Regex - Identifying the first and last items in a list |
Python | In Python , if I want to get the first n characters of a string minus the last character , I do : What 's the Ruby equivalent ? | output = 'stackoverflow'print output [ : -1 ] | What 's the Ruby equivalent of Python 's output [ : -1 ] ? |
Python | I 'm trying to figure out how to setup Test Driven Development for GAE.I start the tests with : I keep getting the error : The datastore does n't exist until I create it in the setUp ( ) , but I 'm still getting an error that the entities already exists ? I 'm using the code from the GAE tutorial . Here is my testing c... | nosetests -v -- with-gae InternalError : table `` dev~guestbook ! ! Entities '' already exists import sys , os , subprocess , time , unittest , shlex sys.path.append ( `` /usr/local/google_appengine '' ) sys.path.append ( `` /usr/local/google_appengine/lib/yaml/lib '' ) sys.path.append ( `` /usr/local/google_appengine/... | How am I getting 'InternalError : table `` dev~guestbook ! ! Entities '' already exists ' when I just created datastore ? |
Python | Let 's say I have the following code : This generates the following list : Then I want to modify the first element in the first list : I expected only the first element of the list to be modified , but actually the first element of each list was changed : I managed to find another way to represent my data to avoid this... | a_list = [ [ 0 ] *10 ] *10 [ [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0... | Python list confusion |
Python | Assume the following code structure : I run python inside 1/ and do import hhh.foo.baz . It fails : Now I replace baz.py with : and again do import hhh.foo.baz . Now it works , although I ’ m loading the same module , only binding a different name.Does this mean that the distinction between import module and from modul... | # # # # 1/hhh/__init__.py : empty # # # # 1/hhh/foo/__init__.py : from hhh.foo.baz import * # # # # 1/hhh/foo/bar.py : xyzzy = 4 # # # # 1/hhh/foo/baz.py : import hhh.foo.bar as barqux = bar.xyzzy + 10 Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > File `` hhh/foo/__init__.py '' , l... | Why do these two Python imports work differently ? |
Python | I got some working code using einsum function . But as einsum is currently still like black voodoo for me . I was wondering , what this code actually is doing and if it can be somehow optimized using np.dotMy data looks likes thisAnd my existing functions einsum functions looks like thisBut what does it really do ? I g... | n , p , q = 40000 , 8 , 4a = np.random.rand ( n , p , q ) b = np.random.rand ( n , p ) f1 = np.einsum ( `` ijx , ijy- > ixy '' , a , a ) f2 = np.einsum ( `` ijx , ij- > ix '' , a , b ) | Black voodoo of NumPy Einsum |
Python | For example , I am now learning wxPython , specifically a class ' init function : As a matter of good programming practice , should I memorize the order of the parameters , or just the keywords and call the function using the keywords everytime ? Is it better to do the latter for readability ? | __init__ ( self , parent , id=-1 , label=EmptyString , pos=DefaultPosition , size=DefaultSize , style=0 , name=StaticTextNameStr ) | Should I memorize the order of function arguments when learning a new module ? |
Python | I 'm new to tensorflow . I have the following problem : input : list of floats ( or a dynamic array . In python list is the datatype to be used ) Output : is a 2-d array of size len ( input ) × len ( input ) Example1 : Input : Output : I tried to create the function using while loop and calculating each row independent... | [ 1.0 , 2.0 , 3.0 ] [ [ 0.09003057 , 0.24472847 , 0.66524096 ] , [ 0.26894142 , 0.73105858 , 0.0 ] , [ 1.0 , 0.0 , 0.0 ] ] | Tensorflow : Regarding tensorflow functions |
Python | This is not homework.I saw this article praising Linq library and how great it is for doing combinatorics stuff , and I thought to myself : Python can do it in a more readable fashion.After half hour of dabbing with Python I failed . Please finish where I left off . Also , do it in the most Pythonic and efficient way p... | from itertools import permutationsfrom operator import mulfrom functools import reduceglob_lst = [ ] def divisible ( n ) : return ( sum ( j*10^i for i , j in enumerate ( reversed ( glob_lst ) ) ) % n == 0 ) oneToNine = list ( range ( 1 , 10 ) ) twoToNine = oneToNine [ 1 : ] for perm in permutations ( oneToNine , 9 ) : ... | Help me finish this Python 3.x self-challenge |
Python | I have a Python utility that goes over a tar.xz file and processes each of the individual files . This is a 15MB compressed file , with 740MB of uncompressed data.On one specific server with very limited memory , the program crashes because it runs out of memory . I used objgraph to see which objects are created . It t... | with tarfile.open ( ... ) as tar : while True : next = tar.next ( ) stream = tar.extractfile ( next ) process_stream ( ) iter+=1 if not iter % 1000 : objgraph.show_growth ( limit=10 ) TarInfo 2040 +1000TarInfo 3040 +1000TarInfo 4040 +1000TarInfo 5040 +1000TarInfo 6040 +1000TarInfo 7040 +1000TarInfo 8040 +1000TarInfo 90... | Leaking TarInfo objects |
Python | I have a list with points ( centroids ) and some of them have to be removed.How can I do this without loops ? I 've tried the answer given here but this error is shown : My lists look like this : And I want to remove the elements in index . The final result would be : | list indices must be integers , not list centroids = [ [ 320 , 240 ] , [ 400 , 200 ] , [ 450 , 600 ] ] index = [ 0,2 ] centroids = [ [ 400 , 200 ] ] | Remove list of indices from a list in Python |
Python | the file contains 2000000 rows : each row contains 208 columns , separated by comma , like this : The program read this file to a numpy narray , I expected it will consume about ( 2000000 * 208 * 8B ) = 3.2GB memory . However , when the program read this file , I found the program consumes about 20GB memory . I am conf... | 0.0863314058048,0.0208767447842,0.03358010485,0.0,1.0,0.0,0.314285714286,0.336293217457,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,... | why numpy narray read from file consumes so much memory ? |
Python | I suddenly ca n't load newly upgraded modules modules , e.g scikit-learn , zope , but I can find other packages . Even though the path links from the import points to the correct anaconda folder , which contains all the code . Any ideas what might be wrong and how to fix it ? | Python 2.7.13 |Anaconda custom ( 64-bit ) | ( default , Dec 20 2016 , 23:09:15 ) [ GCC 4.4.7 20120313 ( Red Hat 4.4.7-1 ) ] on linux2 > > > import sklearn > > > from os import listdir > > > print ( dir ( sklearn ) ) [ '_ASSUME_FINITE ' , '__SKLEARN_SETUP__ ' , '__all__ ' , '__builtins__ ' , '__check_build ' , '__doc__ ... | Suddenly I ca n't load some newly upgraded modules in Python |
Python | I 'm running Python 2.5 ( r25:51908 , Sep 19 2006 , 09:52:17 ) [ MSC v.1310 32 bit ( Intel ) ] on win 32When I 'm asking PythonThat 's fine . When I askThat 's fine , too . But when I ask So according Python `` u11-Phrase 100.wav '' comes before `` u11-Phrase 1000.wav '' but `` u11-Phrase 101.wav '' comes after `` u11-... | > > > `` u11-Phrase 099.wav '' < `` u11-Phrase 1000.wav '' True > > > `` u11-Phrase 100.wav '' < `` u11-Phrase 1000.wav '' True > > > `` u11-Phrase 101.wav '' < `` u11-Phrase 1000.wav '' False > > > `` u11-Phrase 0101.wav '' < `` u11-Phrase 1000.wav '' True files = glob.glob ( '*.wav ' ) files.sort ( ) for file in file... | Python sorts `` u11-Phrase 1000.wav '' before `` u11-Phrase 101.wav '' ; how can I overcome this ? |
Python | I have a small project I want to try porting to Python 3 - how do I go about this ? I have made made the code run without warnings using python2.6 -3 ( mostly removing .has_key ( ) calls ) , but I am not sure of the best way to use the 2to3 tool . Use the 2to3 tool to convert this source code to 3.0 syntax . Do not man... | 2to3 something.pypython3.0 something.pymv something.py.bak something.pyvim something.py # repeat mv something.py py2.6_something.py # once2to3 py2.6_something.py -- write-file something.pyvim py2.6_something.py # repeat | Python 3 porting workflow ? |
Python | Is the following code for generating primes pythonic ? Note that next ( next_p ) will eventually throw a StopIteration error which somehow ends the function get_primes . Is that bad ? Also note that next_p is a generator which iterates over primes , however primes changes during iteration . Is that bad style ? adding t... | def get_primes ( n ) : primes= [ False , False ] + [ True ] * ( n-1 ) next_p= ( i for i , j in enumerate ( primes ) if j ) while True : p=next ( next_p ) yield p primes [ p*p : :p ] = [ False ] * ( ( n-p*p ) //p+1 ) if p*p < =n : primes [ p*p : :p ] = [ False ] * ( ( n-p*p ) //p+1 ) | is this primes generator pythonic |
Python | So I 've trying to model a small user-group relationship in Neo4j with Django . I am currently employing the Neo4django python package seen here . Now , I have nodes representing my users , and nodes representing my groups , and relationships that link them indicating membership . What I 'm hoping to also do in the nea... | class User ( models.NodeModel ) : friends = models.Relationship ( 'User ' , rel_type=Outgoing.FRIEND , related_single=False , related_name='friends ' ) groups = models.Relationship ( 'Group ' , rel_type=Outgoing.USER_GROUPS , related_single=False , related_name='groups ' ) user_name = models.StringProperty ( max_length... | Neo4django Relationship properties |
Python | I 'm wondering if anyone has a sort of hacky / cool solution to this problem . I have a text file like so : So I have some blocks that all contain lines that can be split into a dict , and some that can not . How can I take lines without the : character and join them to the previous line ? Here 's what I 'm currently d... | NAME : nameID : idPERSON : personLOCATION : locationNAME : namemorenamestuffID : idPERSON : personLOCATION : locationJUNK # loop through chunk # the first element of dat is a Title , so skip that key_map = dict ( x.split ( ' : ' ) for x in dat [ 1 : ] ) # there will be a key_map for each chunk of datakey_map [ 'NAME ' ... | Python iterate over list and join lines without a special character to the previous item |
Python | I 'm currently trying to implement a siamese-net in Keras where I have to implement the following loss function : detailed description of loss function from paperWhere KL is the Kullback-Leibler divergence and HL is the Hinge-loss.During training , I label same-speaker pairs as 1 , different speakers as 0 . The goal is... | loss ( p ∥ q ) = Is · KL ( p ∥ q ) + Ids · HL ( p ∥ q ) def kullback_leibler_divergence ( vects ) : x , y = vects x = ks.backend.clip ( x , ks.backend.epsilon ( ) , 1 ) y = ks.backend.clip ( y , ks.backend.epsilon ( ) , 1 ) return ks.backend.sum ( x * ks.backend.log ( x / y ) , axis=-1 ) def kullback_leibler_shape ( sh... | Custom combined hinge/kb-divergence loss function in siamese-net fails to generate meaningful speaker-embeddings |
Python | I would like to match strings , using Pythons regex module.In my case I want to verify that strings start , end and consist of upper case letters combined by `` _ '' . As an example , the following string is valid : `` MY_HERO2 '' . The following strings are not valid : `` _MY_HREO2 '' , `` MY HERO2 '' , `` MY_HERO2_ '... | import remy_string = `` MY_HERO '' p = re.compile ( `` ^ ( [ A-Z,0-9 ] +_ ? ? ) + [ A-Z,0-9 ] $ '' ) if p.match ( my_string ) : print `` validated '' MY_HERO2 -- > 53 msMY_SUPER_GREAT_UNBELIEVABLE_HERO -- > 69 microsecondsMY_SUPER_GREAT_UNBELIEVABLE HERO -- > 223576 microsecondsMY_SUPER_GREAT_UNBELIEVABLE_STRONG_HERO -... | Python regex slow when whitespace in string |
Python | I am trying to read one short and long from a binary file using python struct . But the which is wrong , It should have been 2 bytes for short and 8 bytes for long . I am not sure i am using the struct module the wrong way . When i print the value for each it is Is there a way to force python to maintain the precision ... | print ( struct.calcsize ( `` hl '' ) ) # o/p 16 print ( struct.calcsize ( `` h '' ) ) # o/p 2print ( struct.calcsize ( `` l '' ) ) # o/p 8 | Python struct calsize different from actual |
Python | I 've been using the sys.settrace function to write a tracer for my program , which is working great except that it does n't seem to get called for built-in functions , like open ( 'filename.txt ' ) . This behavior does n't seem to be documented , so I 'm not sure if I 'm doing something wrong or if this is the expecte... | import traceback , __builtin__def wrapped_open ( *arg , **kw ) : print 'open called ' traceback.print_stack ( ) f = __builtin__.open ( *arg , **kw ) return f open = wrapped_open | python 's sys.settrace wo n't trace builtin functions |
Python | I have the following code in C++ : I wrapped it in boost : :python in this way : When I try to call person.GetGender ( ) from Python I get the following exception : How can I tell the GetGender function what type to return explicitly ? | class Person { public : enum Gender { Male , Female } ; Gender GetGender ( ) const ; } BOOST_PYTHON_MODULE ( TestPython ) { scope the_scope = class_ < Person > ( `` Person '' ) .def ( `` GetGender '' , & Person : :GetGender ) ; enum_ < Person : :Gender > ( `` Gender '' ) .value ( Male , Person : :Male ) .value ( Female... | Namespaces mixed up when returning scoped enum from class method |
Python | My task is to reproduce the plot below : It comes from this journal ( pg 137-145 ) In this article , the authors describe a kleptographic attack called SETUP against Diffie-Hellman keys exchange . In particular , they write this algorithm : Now , in 2 the authors thought `` Maybe we can implement honest DHKE and malici... | import timeit # used to measure the running time of functionsimport matplotlib.pyplot as plt # plot the resultsimport randomimport numpy as npimport pyDH # library for Diffie-Hellman key exchangeX= pyDH.DiffieHellman ( ) # Eve 's private keyY= X.gen_public_key ( ) # Eve 's public key # The three integers a , b , W embe... | Implementation of kleptography in Python ( SETUP attack ) |
Python | Question about Python internals . If I execute import abc then Python reads the module into a new namespace and binds the variable abc in the global namespace to point to the new namespace.If I execute from abc import xyz then it reads the entire module abc into some new namespace and then binds the variable xyz in the... | from abc import xyzfrom abc import fgh | Executing ` from abc import xyz ` where does the module ` abc ` go ? |
Python | I want to write this statement : however np.where can not write & ( and ) logic . How do I write this case when logic in the np.where in python . Thanks | def custom_asymmetric_train ( y_true , y_pred ) : residual = ( y_true - y_pred ) .astype ( `` float '' ) grad = np.where ( residual > 0 , -2*10.0*residual , -2*residual ) hess = np.where ( residual > 0 , 2*10.0 , 2.0 ) return grad , hess case when residual > =0 and residual < =0.5 then -2*1.2*residual when residual > =... | How to write a case when like statement in numpy array |
Python | I have a pd.Series with duplicated indices , and each index containing a set of booleans : What I 'm trying to do for each different index in an efficient way , is to keep only as True the first and last True values of the sequence , and set the rest to False . There can also be False values between those that are True... | FA155 FalseFA155 FalseFA155 FalseFA155 TrueFA155 TrueFA155 TrueFA155 TrueFA155 TrueFA155 False FA155 FalseFA155 FalseFA155 FalseFA155 TrueFA155 FalseFA155 FalseFA155 FalseFA155 TrueFA155 False | Groupby search first and last True values |
Python | I would like to implement a function , that would multiply all elements in list by two . However my problem is that lists can have different amount of dimensions.Is there a general way to loop/iterate multidimensional list and for example multiply each value by two ? EDIT1 : Thanks for the fast answers . For this case ... | # 2x3 dimensional listmultidim_list = [ [ 1,2,3 ] , [ 4,5,6 ] , ] # 2x3x2 dimensional listmultidim_list2 = [ [ [ 1,2,3 ] , [ 4,5,6 ] , ] , [ [ 7,8,9 ] , [ 10,11,12 ] , ] ] def multiply_list ( list ) : ... | Python : Iterating lists with different amount of dimensions , is there a generic way ? |
Python | I tried to reflect an existing oracle database into sqlalchemy metadata : This returns the following : I have tried to import native types and also the types from dialect oracle usingbut it seems it does not recognize BINARY_DOUBLE typeI am using SQLAlchemy , version ' 1.2.1 ' | from sqlalchemy import create_enginefrom sqlalchemy import MetaDatafrom sqlalchemy import Tabledb_uri = 'oracle : //USER : PASS @ MYDBTNSNAME'engine = create_engine ( db_uri ) # create a MetaData instancemetadata = MetaData ( ) # reflect db schema to MetaDatametadata.reflect ( bind=engine ) SAWarning : Did not recogniz... | How to reflect an oracle database with BINARY_DOUBLE type columns |
Python | Huh , for some reason I ca n't seem to get F working properly even on the simplest of models . Here on Django 1.9.x.In the simplest form , TestAccountBut according to this : https : //docs.djangoproject.com/en/1.9/ref/models/instances/ # updating-attributes-based-on-existing-fields it should work ... Why F is n't being... | class TestAccount ( models.Model ) : decimal = models.DecimalField ( max_digits=5 , decimal_places=2 ) integer = models.IntegerField ( ) In [ 1 ] : ta = TestAccount ( ) In [ 2 ] : ta.integer = 1In [ 3 ] : ta.decimal = 1In [ 4 ] : ta.save ( ) In [ 5 ] : In [ 5 ] : In [ 5 ] : taOut [ 5 ] : < TestAccount : TestAccount obj... | Django F does n't seem to work ? |
Python | I have an input dataframe which can be generated from the code given belowThe input dataframe looks like as shown belowThis is what I didThough it works , I am afraid that this may not be the best approach . As we might have more than 200 columns and 50k RECORDS . Any help to improve my code further is very helpful . I... | df = pd.DataFrame ( { 'subjectID ' : [ 1,1,2,2 ] , 'keys ' : [ 'H1Date ' , 'H1 ' , 'H2Date ' , 'H2 ' ] , 'Values ' : [ '10/30/2006',4 , ' 8/21/2006',6.4 ] } ) s1 = df.set_index ( 'subjectID ' ) .stack ( ) .reset_index ( ) s1.rename ( columns= { 0 : 'values ' } , inplace=True ) d1 = s1 [ s1 [ 'level_1 ' ] .str.contains ... | Create a new column based on previous row value and delete the current row |
Python | I have a process that is essentially just an infinite loop and I have a second process that is a timer . How can I kill the loop process once the timer is done ? I want the python script to end once the timer is done . | def action ( ) : x = 0 while True : if x < 1000000 : x = x + 1 else : x = 0def timer ( time ) : time.sleep ( time ) exit ( ) loop_process = multiprocessing.Process ( target=action ) loop_process.start ( ) timer_process = multiprocessing.Process ( target=timer , args= ( time , ) ) timer_process.start ( ) | How to kill a process using the multiprocessing module ? |
Python | I have two classes A and B , each one storing references to objects of the other class in lists : Now , my app builds two lists , one of objects of A , one of objects of B , having cross references.Obviously , if I call json.dumps ( ) on either list_of_ ... , I get a circular reference error.What I want to do to circum... | class A : def __init__ ( self , name ) : self.name = name self.my_Bs = [ ] def registerB ( self , b ) : self.my_Bs.append ( b ) class B : def __init__ ( self , name ) : self.name = name self.my_As = [ ] def registerA ( self , a ) : self.my_As.append ( a ) # a list of As , a list of Bslist_of_As = [ A ( 'firstA ' ) , A ... | What would be the pythonic way to go to prevent circular loop while writing JSON ? |
Python | I 'm trying to have a mutually exclusive group between different groups : I have the arguments -a , -b , -c , and I want to have a conflict with -a and -b together , or -a and -c together . The help should show something like [ -a | ( [ -b ] [ -c ] ) ] .The following code does not seem to do have mutually exclusive opt... | import argparseparser = argparse.ArgumentParser ( description='My desc ' ) main_group = parser.add_mutually_exclusive_group ( ) mysub_group = main_group.add_argument_group ( ) main_group.add_argument ( `` -a '' , dest= ' a ' , action='store_true ' , default=False , help= ' a help ' ) mysub_group.add_argument ( `` -b ''... | Using mutually exclusive between groups |
Python | I have to check a lot of worlds if they are in string ... code looks like : how to make it more readable and more clear ? | if `` string_1 '' in var_string or `` string_2 '' in var_string or `` string_3 '' in var_string or `` string_n '' in var_string : do_something ( ) | How to make it shorter ( Pythonic ) ? |
Python | I need a list-like object that will `` autogrow '' whenever a slot number greater or equal to its length is accessed , filling up all the newly created slots with some pre-specified default value . E.g. : Thanks ! PS . I know it is not hard to implement a class like this , but I avoid wheel-reinvention as much as possi... | # hypothetical DefaultList classx = DefaultList ( list ( 'abc ' ) , default='* ' ) x [ 6 ] = ' g'print x [ 2 ] , x [ 4 ] , x [ 6 ] , x [ 8 ] # should print ' c * g * ' | Autogrowing list in Python ? |
Python | I have the following python3 code : and when I run it on Python 3.6.3 ( v3.6.3:2c5fed8 , Oct 3 2017 , 18:11:49 ) [ MSC v.1900 64 bit ( AMD64 ) ] on win32 I get the following outputWhy is n't it outputting doing instance check ? The documentation says the __instancecheck__ method needs to be defined on the metaclass and... | class BaseTypeClass ( type ) : def __new__ ( cls , name , bases , namespace , **kwd ) : result = type.__new__ ( cls , name , bases , namespace ) print ( `` creating class ' { } ' '' .format ( name ) ) return result def __instancecheck__ ( self , other ) : print ( `` doing instance check '' ) print ( self ) print ( othe... | Why is n't __instancecheck__ being called ? |
Python | Right now , I have this code : I have used Boost here and then but I could n't really remember any simple way to write it somewhat like I would maybe write it in Python , e.g . : Is there any construct in STL/Boost to write it more or less like this ? Or maybe an equivalent to this Python Code : Mostly I am wondering i... | bool isAnyTrue ( ) { for ( std : :list < boost : :shared_ptr < Foo > > : :iterator i = mylist.begin ( ) ; i ! = mylist.end ( ) ; ++i ) { if ( ( *i ) - > isTrue ( ) ) return true ; } return false ; } def isAnyTrue ( ) : return any ( o.isTrue ( ) for o in mylist ) def isAnyTrue ( ) : return any ( map ( mylist , lambda o ... | simplify simple C++ code -- something like Pythons any |
Python | I am trying to find all the nearest neighbors which are within 1 KM radius . Here is my script to construct tree and search the nearest points , From what I read in pysal page , it says - kd-tree built on top of kd-tree functionality in scipy . If using scipy 0.12 or greater uses the scipy.spatial.cKDTree , otherwise u... | from pysal.cg.kdtree import KDTreedef construct_tree ( s ) : data_geopoints = [ tuple ( x ) for x in s [ [ 'longitude ' , 'latitude ' ] ] .to_records ( index=False ) ] tree = KDTree ( data_geopoints , distance_metric='Arc ' , radius=pysal.cg.RADIUS_EARTH_KM ) return treedef get_neighbors ( s , tree ) : indices = tree.q... | Optimize scipy nearest neighbor search |
Python | I 'm trying to multiply two 2D arrays that were transformed with fftpack_rfft2d ( ) ( SciPy 's FFTPACK RFFT ) and the result is not compatible with what I get from scipy_rfft2d ( ) ( SciPy 's FFT RFFT ) .The image below shares the output of the script , which displays : The initialization values of both input arrays ; ... | import numpy as npfrom scipy import fftpack as scipy_fftpackfrom scipy import fft as scipy_fft # SCIPY RFFT 2Ddef scipy_rfft2d ( matrix ) : fftRows = [ scipy_fft.rfft ( row ) for row in matrix ] return np.transpose ( [ scipy_fft.fft ( row ) for row in np.transpose ( fftRows ) ] ) # SCIPY IRFFT 2Ddef scipy_irfft2d ( mat... | How to multiply two 2D RFFT arrays ( FFTPACK ) to be compatible with NumPy 's FFT ? |
Python | I 'm trying to use a generator with a Python class that works somewhat similarly to a linked list . Here is a really simple example of what I mean : Of course this is just an example , but it 's enough to illustrate the point.Now , I was expecting to be able to invoke something like : And have the cycle stop when it re... | class GeneratorTest ( ) : def __init__ ( self , list ) : if list : self.elem = list [ 0 ] if list [ 1 : ] : self.n = GeneratorTest ( list [ 1 : ] ) else : self.n = None def __iter__ ( self ) : return self def next ( self ) : my_next = self while my_next is not None : yield my_next my_next = my_next.n g = GeneratorTest ... | Yield on recursive data structure |
Python | I have a df which has 1 columnI have other dataframe df2which has 2 columnsI want to replace such words in my df , which occurs in original column of my df2and replace with corresponding words in correct column.and store the new strings in other dataframe df_newIs it possible without using loops and iteration , and onl... | List 0 What are you trying to achieve 1 What is your purpose right here 2 When students don ’ t have a proper foundation 3 I am going to DESCRIBE a sunset original correct0 are were1 sunset sunrise2 I we3 right correct4 is was List 0 What were you trying to achieve 1 What was your purpose correct here 2 When students d... | Replace rows of strings in dataframe with corresponding words in other dataframe pandas |
Python | How do you have a multiple line statement in either a list comprehension or eval ? I was trying to turn this code : Into a lambda function like so : In both x is a string such as 'onomatopoeia ' and y is a list such as [ ' o ' , ' a ' , ' o ' ] .But for some reason , it returns a syntax error . Can anyone explain this ... | def f ( x , y , b= '' ) : for i in x : if i in y : y.remove ( i ) i *= 2 b += i return b j=lambda x , y : ''.join ( eval ( ' y.remove ( i ) ; i*2 ' ) if i in y else i for i in x ) | Python 2 list comprehension and eval |
Python | ProblemGiven a list of string find the strings from the list that appear in the given text . Example 'red ' because it has 'shared ' has 'red ' as a substringThis is very similar to this question except that the word we need to look for can be substring as well . The list is pretty large and increases with increase in ... | list = [ 'red ' , 'hello ' , 'how are you ' , 'hey ' , 'deployed ' ] text = 'hello , This is shared right ? how are you doing tonight'result = [ 'red ' , 'how are you ' , 'hello ' ] def FindWord ( trie , text , word_so_far , index ) : index > len ( text ) return //Check if the word_so_far is a prefix of a key ; if not ... | Given a list of words and a sentence find all words that appear in the sentence either in whole or as a substring |
Python | I noticed a strange performance hit from a minor refactoring that replaced a loop with a call to the builtin max inside a recursive function.Here 's the simplest reproduction I could produce : Both f1 and f2 calculate factorial using the standard recursion but with an unnecessary maximization added in ( just so I get t... | import timedef f1 ( n ) : if n < = 1 : return 1 best = 0 for k in ( 1 , 2 ) : current = f1 ( n-k ) *n if current > best : best = current return bestdef f2 ( n ) : if n < = 1 : return 1 return max ( f2 ( n-k ) *n for k in ( 1 , 2 ) ) t = time.perf_counter ( ) result1 = f1 ( 30 ) print ( 'loop : ' , time.perf_counter ( )... | Why does max ( iterable ) perform much slower than an equivalent loop ? |
Python | I have a program set up so that it displays a FileChooserDialog all by itself ( no main Gtk window , just the dialog ) .The problem I 'm having is that the dialog does n't disappear , even after the user has selected the file and the program has seemingly continued executing.Here 's a snippet that showcases this issue ... | from gi.repository import Gtkclass FileChooser ( ) : def __init__ ( self ) : global path dia = Gtk.FileChooserDialog ( `` Please choose a file '' , None , Gtk.FileChooserAction.OPEN , ( Gtk.STOCK_CANCEL , Gtk.ResponseType.CANCEL , Gtk.STOCK_OPEN , Gtk.ResponseType.OK ) ) self.add_filters ( dia ) response = dia.run ( ) ... | How to hide a Gtk+ FileChooserDialog in Python 3.4 ? |
Python | I have list like this : I count item from that list : then I get : I want to get key from counter , so i do this : and I get sorted list like this : but I need an output like this ( not sorted ) : Sorry for my bad english . | Pasang = [ 0 , 4 , 4 , 5 , 1 , 7 , 6 , 7 , 5 , 7 , 4 , 9 , 0 , 10 , 1 , 10 , ... . , 23 , 9 , 23 , 7 , 23 ] satuan = Counter ( pasang ) Counter ( { 5 : 10 , 6 : 7 , 0 : 5 , 1 : 5 , 7 : 5 , 10 : 4 , 11 : 4 , 15 : 4 , ... ,14 : 1 , 21 : 1 } ) satu = satuan.keys ( ) [ 0 , 1 , 2 , 4 , 5 , ... ,21 , 22 , 23 ] [ 5 , 6 , 0 , ... | Counter list python 2.7 |
Python | Is there a construct in java that does something like this ( here implemented in python ) : Today I 'm using something like : And to me the first way looks a bit smarter . | [ ] = [ item for item in oldList if item.getInt ( ) > 5 ] ItemType newList = new ArrayList ( ) ; for ( ItemType item : oldList ) { if ( item.getInt > 5 ) { newList.add ( item ) ; } } | Java oneliner for list cleanup |
Python | I need to retrieve the definition of an acronym based on the number of letters enclosed in parentheses . For the data I 'm dealing with , the number of letters in parentheses corresponds to the number of words to retrieve . I know this is n't a reliable method for getting abbreviations , but in my case it will be . For... | import re a = 'Although family health history ( FHH ) is commonly accepted as an important risk factor for common , chronic diseases , it is rarely considered by a nurse practitioner ( NP ) . ' x2 = re.findall ( ' ( \ ( . * ? \ ) ) ' , a ) for x in x2 : length = len ( x ) print ( x , length ) | Retrieve definition for parenthesized abbreviation , based on letter count |
Python | Given a list of slices , how do I separate a sequence based on them ? I have long amino-acid strings that I would like to split based on start-stop values in a list . An example is probably the most clear way of explaining it : The extra parentheses are to show which elements were selected from the split_points list . ... | str = `` MSEPAGDVRQNPCGSKAC '' split_points = [ [ 1,3 ] , [ 7,10 ] , [ 12,13 ] ] output > > [ 'M ' , ' ( SEP ) ' , 'AGD ' , ' ( VRQN ) ' , ' P ' , ' ( CG ) ' , 'SKAC ' ] | Given a list of slices , how do I split a sequence by them ? |
Python | Lets 's say I have an enumerator , is it possible to get the property that follows ? So if I had today=Days.Sunday would I be able to do something like tomorrow=today.next ( ) ? example : I know I could use tuples ( like below ) to do something like tomorrow=today [ 1 ] , but I was hoping there was something built in o... | class Days ( Enum ) : Sunday = 'S ' Monday = 'M ' ... Saturday = 'Sa ' class Days ( Enum ) : Sunday = ( 'S ' , 'Monday ' ) Monday = ( 'M ' , 'Tuesday ' ) ... Saturday = ( 'Sa ' , 'Sunday ' ) | Get next enumerator constant/property |
Python | The default SQLAlchemy behavior for compiling in_ expressions is pathological for very large lists , and I want to create a custom , faster , compiler for the operator . It does n't matter to the application if the solution is a new operator ( i.e . : in_list_ ) or if it overrides the default compiler for in_ . However... | from sqlalchemy.types import TypeEngineclass in_list_ ( TypeEngine.Comparator ) : pass @ compiles ( in_list_ ) def in_list_impl ( element , compiler , **kwargs ) : return `` IN ( 'Now ' , ' I ' , 'can ' , 'inline ' , 'the ' , 'list ' ) '' select ( [ mytable.c.x , mytable.c.y ] ) .where ( mytable.c.x.in_list_ ( long_lis... | New/override SQLAlchemy operator compiler output |
Python | I have a dataframe and perform a groupby with unique after filtering via a mask . My grouper series is categorical . I am using Python 3.6.0 / Pandas 0.19.2.This works as expected . Now with nunique I would expect [ 1 , 2 , 0 ] .But instead I see [ 1 , 1 , 0 ] : If I omit conversion to categorical , the result is as ex... | df1 = pd.DataFrame ( { 'sku ' : [ 'A0 ' , 'A0 ' , 'A2 ' , 'A2 ' , 'A3 ' , 'A3 ' ] , 'ID ' : [ '10 ' , 'T1 ' , 'T1 ' , 'T2 ' , '10 ' , '20 ' ] } ) df1 [ 'sku ' ] = df1 [ 'sku ' ] .astype ( 'category ' ) res = df1 [ df1 [ 'ID ' ] .str [ 0 ] == 'T ' ] .groupby ( 'sku ' ) [ 'ID ' ] .unique ( ) skuA0 [ T1 ] A2 [ T1 , T2 ] A... | Groupby nunique versus unique with categorical data |
Python | Why does list ( next ( iter ( ( ) ) ) for _ in range ( 1 ) ) return an empty list rather than raising StopIteration ? The same thing happens with a custom function that explicitly raises StopIteration : | > > > next ( iter ( ( ) ) ) Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > StopIteration > > > [ next ( iter ( ( ) ) ) for _ in range ( 1 ) ] Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > StopIteration > > > list ( next ( iter ( ( ) ) ) for _ in... | Why does list ( next ( iter ( ( ) ) ) for _ in range ( 1 ) ) == [ ] ? |
Python | I want to create an indicator variable that will propagate to all rows with the same customer-period value pair as the indicator . Specifically , if baz is yes , I want all rows of that same customer and period email to show my indicator.I 've triedwhich returnsBut this is the desired output : I 'm not sure how to go a... | df Customer Period Question Score A 1 foo 2 A 1 bar 3 A 1 baz yes A 1 biz 1 B 1 bar 2 B 1 baz no B 1 qux 3 A 2 foo 5 A 2 baz yes B 2 baz yes B 2 biz 2 df [ 'Indicator ' ] = np.where ( ( df.Question.str.contains ( 'baz ' ) & ( df.Score == 'yes ' ) ) , 1 , 0 ) Customer Period Question Score Indicator A 1 foo 2 0 A 1 bar ... | propagate conditional column value in pandas |
Python | Given a single integer and the number of bins , how to split the integer into as equal parts as possible ? E.g . the sum of the outputs should be equals to the input integerAnother e.g . I 've tried this : It works but there must be a simpler/better way , maybe using bisect or numpy ? Using numpy from https : //stackov... | [ in ] : x = 20 , num_bins = 3 [ out ] : ( 7 , 7 , 6 ) [ in ] : x = 20 , num_bins = 6 [ out ] : ( 4 , 4 , 3 , 3 , 3 , 3 ) x = 20num_bins = 3y = [ int ( x/num_bins ) ] * num_binsfor i in range ( x % num_bins ) : y [ i ] += 1 list ( map ( len , np.array_split ( range ( x ) , num_bins ) ) ) | Split an integer into bins |
Python | In Python3 , returns False , butreturns True . So I would assume based on this example alone , == has precedence over is.However , returns True . Andreturns True . Butreturns False . In this case , it would seem as if is has precedence over ==.To give another example , and this expression is n't meant to do anything , ... | a = b = 3a is None == b is None ( a is None ) == ( b is None ) a = b = Nonea is None == b is None ( a is None ) == ( b is None ) a is ( None == b ) is None None is None == None None is ( None == None ) ( None is None ) == None | Python is , == operator precedence |
Python | I would like to make a module that makes it very simple to build click commands that share a lot of options . Those options would be distilled into a single object that is passed into the command . As an illustrative example : The total command would then have many -- magic- ... options that go into the magic object pa... | from magic import magic_commandimport click @ magic_command ( 'Colored ' ) @ click.option ( ' -- color ' ) def cmd ( magic , color ) : pass def magic_command ( name ) : def decorator ( func ) : @ click.option ( ' -- magic-foo ' ) @ click.option ( ' -- magic-bar ' ) def wrapper ( magic_foo , magic_bar , **kwargs ) : pri... | Commands with multiple common options going into one argument using custom decorator |
Python | I 'm trying to mimic the WWII Enigma machine in Python code , following some reading in Wikipedia and other dedicated sources . Currently , I got a machine that scrambles input text and can revert the scrambled output back to input if the configuration is reset . But the problem is the code is not yielding the expected... | With the rotors I , II and III ( from left to right ) , wide B-reflector , all ringsettings in A-position , and start position AAA , typing AAAAA will produce theencoded sequence BDZGO . | Enigma replica not yielding expected result |
Python | In Python , __init__ used to initialize a class : what 's the equivalent method of init in Perl 6 ? Is the method new ? | class Auth ( object ) : def __init__ ( self , oauth_consumer , oauth_token=None , callback=None ) : self.oauth_consumer = oauth_consumer self.oauth_token = oauth_token or { } self.callback = callback or 'http : //localhost:8080/callback ' def HMAC_SHA1 ( ) : pass | what 's the equivalent method of __init__ in Perl 6 ? |
Python | i am coding on a dataset [ 23,25,28,28,32,33,35 ] according to wiki and scipy docIQR = Q3 − Q1 = 33 - 25 = 8when I run IQR on a dataset , the result ( 6 ) is not as expected ( 8 ) .I tried another method in https : //stackoverflow.com/a/23229224 , and the result is 6.here is my codewhat leads to the problem ? | import numpy as npfrom scipy.stats import iqrx = np.array ( [ 23,25,28,28,32,33,35 ] ) print ( iqr ( x , axis=0 ) ) | Is scipy.stats doing wrong calculation for iqr ? |
Python | my Python class has some variables that require work to calculate the first time they are called . Subsequent calls should just return the precomputed value.I do n't want to waste time doing this work unless they are actually needed by the user.So is there a clean Pythonic way to implement this use case ? My initial th... | class myclass ( object ) : def get_age ( self ) : self.age = 21 # raise an AttributeError here return self.age age = property ( get_age ) | Pythonic way to only do work first time a variable is called |
Python | I 've built a neural network with keras using the mnist dataset and now I 'm trying to use it on photos of actual handwritten digits . Of course I do n't expect the results to be perfect but the results I currently get have a lot of room for improvement.For starters I test it with some photos of individual digits writt... | result : 3 . probabilities : [ 1.9963557196245318e-10 , 7.241294497362105e-07 , 0.02658148668706417 , 0.9726449251174927 , 2.5416460047722467e-08 , 2.6078915027483163e-08 , 0.00019745019380934536 , 4.8302300825753264e-08 , 0.0005754049634560943 , 2.8358477788259506e-09 ] result : 3 . probabilities : [ 1.090986676000049... | Improve real-life results of neural network trained with mnist dataset |
Python | At the risk of being a bit off-topic , I want to show a simple solution for loading large csv files in a dask dataframe where the option sorted=True can be applied and save a significant time of processing.I found the option of doing set_index within dask unworkable for the size of the toy cluster I am using for learni... | export LC_ALL=Czcat BigFat.csv.gz |fgrep -v ( have headers ? ? take them away ) |sort -key=1,1 -t `` , '' ( fancy multi field sorting/index ? -key=3,3 -key=4,4 ) |split -l 10000000 ( partitions ? ? ) ddf=dd.read_csv ( ... .. ) ddf.set_index ( ddf.mykey , sorted=True ) | dask set_index from large unordered csv file |
Python | I 'm trying to shade the marker of an errorbar plot , without shading the error bar lines.Here 's a MWE : Also , how do I get rid of the marker edges without changing the capsize ? If I put markeredgewidth = 0 the capsize gets reset.Updated code : | import matplotlib.pyplot as pltx = [ 1 , 2 , 3 , 4 ] y = [ 1 , 2 , 3 , 4 ] dx = 0.1dy = 0.1plt.errorbar ( x , y , xerr = dx , yerr = dy , marker = ' . ' , linestyle = ' ' , color = 'black ' , capsize = 2 , elinewidth = 0.5 , capthick = 0.4 , alpha = 0.8 ) plt.savefig ( 'MWE.pdf ' ) plt.show ( ) import matplotlib.pyplot... | Shade error bar marker without shading error bar line |
Python | When implementing a custom equality function for a class , does it make sense to check for identity first ? An example : This interesting is for cases when the other criteria may be more expensive ( e.g . comparing some long strings ) . | def __eq__ ( self , other ) : return ( self is other ) or ( other criteria ) | Does it make sense to check for identity in __eq__ ? |
Python | In my Django model , I defined a @ property which worked nicely and the property can be shown in the admin list_display without any problems . I need this property not only in admin but in my code logic in other places as well , so it makes sense to have it as property for my model . Now I wanted to make the column of ... | class De ( models.Model ) : fr = models.BooleanField ( `` [ ... ] '' ) de = models.SmallIntegerField ( `` [ ... ] '' ) gd = models.SmallIntegerField ( `` [ ... ] '' ) na = models.SmallIntegerField ( `` [ ... ] '' ) # [ several_attributes , Meta , __str__ ( ) removed for readability ] @ property def s_d ( self ) : if se... | How to implement sorting in Django Admin for calculated model properties without writing the logic twice ? |
Python | This only happens on Linux ( possible OS X also , ca n't test atm ) , works fine on Windows.I have a wx.ProgressDialog that is spawned with the main thread . I send the work off to another thread , and it periodically calls back to a callback function in the main thread that will update the ProgressDialog or , at the e... | import wxversionwxversion.select ( `` 2.8 '' ) import wximport sysimport threadingMAX_COUNT = 100 # # This class is in a different area of the codebase andclass WorkerThread ( threading.Thread ) : def __init__ ( self , callback ) : threading.Thread.__init__ ( self ) self.callback = callback def run ( self ) : # simulat... | wx.ProgressDialog causing seg fault and/or GTK_IS_WINDOW failure when being destroyed |
Python | I have a data frame that looks like the following I was wondering if there exist a fastest way to create a python dict in pandas that would hold data like followingHere the keys are users ids and the values are uniques list of dates.This can be done early in core python but was wondering if there is a pandas or numpy b... | table = { 2 : [ 4 , 5 , 6 , 7 , 8 ... ] , 4 : [ 1 , 2 , 3 , 4 , ... ] } levels = pd.DataFrame ( { k : df.index.get_level_values ( k ) for k in range ( 2 ) } ) table = levels.drop_duplicates ( ) \ .groupby ( 0 ) [ 1 ] .apply ( list ) \ .to_dict ( ) print ( table ) res.reset_index ( ) .drop_duplicates ( [ 'user_id ' , 'd... | How to get dict of first two indexes for multi index data frame |
Python | I 'm developing an app using a Python library urllib and it is sometimes rising exceptions due to not being able to access an URL.However , the exception is raised almost 6 levels into the standard library stack : I usually run the code in ipython3 with the % pdb magic turned on so in case there is an exception I can i... | /home/user/Workspace/application/main.py in call ( path ) 11 headers= { 'content-type ' : 'application/json ' } , 12 data=b '' ) -- - > 13 resp = urllib.request.urlopen ( req ) # # # # # # # THIS IS MY CODE 14 return json.loads ( resp.read ( ) .decode ( 'utf-8 ' ) ) /usr/lib/python3.4/urllib/request.py in urlopen ( url... | Stop at exception in my , not library code |
Python | EDIT : I 'm redoing the question entirely . The issue has nothing to do with time.time ( ) Here 's a program : This program , when saved as a file and run with IDLE in Python 3.4 , takes about 10 seconds , even though 0.0 is printed out from time.time ( ) . The issue is very clearly with IDLE , because when run from th... | import timestart=time.time ( ) a=9 < < ( 1 < < 26 ) # The line that makes it take a whileprint ( time.time ( ) -start ) def f ( ) : a = 9 < < ( 1 < < 26 ) | Why does IDLE 3.4 take so long on this program ? |
Python | I 'm using previous demand to predict future demand , using 3 variables , but whenever I run the code my Y axis shows errorIf I use only one variable on the Y axis separately it has no error.Example : DATASETSCRIPTOUTPUTGitHub : repository | demandaY = bike_data [ [ 'cnt ' ] ] n_steps = 20for time_step in range ( 1 , n_steps+1 ) : demandaY [ 'cnt'+str ( time_step ) ] = demandaY [ [ 'cnt ' ] ] .shift ( -time_step ) .valuesy = demandaY.iloc [ : , 1 : ] .valuesy = np.reshape ( y , ( y.shape [ 0 ] , n_steps , 1 ) ) features = [ 'cnt ' , 'temp ' , 'hum ' ] dema... | Recurrent neural networks for Time Series with Multiple Variables - TensorFlow |
Python | I 'd like to solve y = ( x+1 ) **3 - 2 for x in sympy to find its inverse function.I tried using solve , but I did n't get what I expected . Here 's what I wrote in IPython console in cmd ( sympy 1.0 on Python 3.5.2 ) : I was looking at the last element in the list in Out [ 4 ] , but it does n't equal x = ( y+2 ) ** ( ... | In [ 1 ] : from sympy import *In [ 2 ] : x , y = symbols ( ' x y ' ) In [ 3 ] : n = Eq ( y , ( x+1 ) **3 - 2 ) In [ 4 ] : solve ( n , x ) Out [ 4 ] : [ - ( -1/2 - sqrt ( 3 ) *I/2 ) * ( -27*y/2 + sqrt ( ( -27*y - 54 ) **2 ) /2 - 27 ) ** ( 1/3 ) /3 - 1 , - ( -1/2 + sqrt ( 3 ) *I/2 ) * ( -27*y/2 + sqrt ( ( -27*y - 54 ) **... | How can I solve y = ( x+1 ) **3 -2 for x in sympy ? |
Python | I have some Python / Numpy code that is running slow and I think it is because of the use of a double for loop . Here is the code.I am trying to remove the double for loop and vectorize Z . Here is my attempt . This does n't work - I get the following error : So somewhere in trying to vectorize Z , I messed up . Can yo... | def heat ( D , u0 , q , tdim ) : xdim = np.size ( u0 ) Z = np.zeros ( [ xdim , tdim ] ) Z [ : ,0 ] =u0 ; for i in range ( 1 , tdim ) : for j in range ( 1 , xdim-1 ) : Z [ j , i ] =Z [ j , i-1 ] +D*q* ( Z [ j-1 , i-1 ] -2*Z [ j , i-1 ] +Z [ j+1 , i-1 ] ) return Z def heat ( D , u0 , q , tdim ) : xdim = np.size ( u0 ) Z ... | How do I vectorize this double for loop in Numpy ? |
Python | I 'm trying to get rid of explicit binding between my models . Thus instead of using ForeignKey , I 'll use IntegerField to just store the primary key of target model as a field . Thus I 'll handle the relationship manually at code level . This is because , I 'll have to move my some schemas to different database insta... | 17 class Customer ( models.Model ) : 18 id = models.UUIDField ( primary_key=True , default=uuid.uuid4 , editable=False ) 19 phone_no = models.CharField ( max_length=15 , unique=True ) 47 class CustomerAddress ( models.Model ) : 48 # customer = models.ForeignKey ( Customer , related_name='cust_addresses ' ) 49 customer_... | Using nested serializers with explicit ForeignKey binding replaced with raw IntegerField |
Python | I have a regular expression like this : What I am trying to do is to replace each occurrence with an associated replacement word from a list so that the end sentence would look like this : I tried using re.sub inside a for loop enumerating over replacement but it looks like re.sub returns all occurrences . Can someone ... | findthe = re.compile ( r '' the `` ) replacement = [ `` firstthe '' , `` secondthe '' ] sentence = `` This is the first sentence in the whole universe ! '' > > > print sentenceThis is firstthe first sentence in secondthe whole universe | Replacing each match with a different word |
Python | Given are two python lists with strings in them ( names of persons ) : I want a mapping of the names , that are most similar.Is there a neat way to do this in python ? The lists contain in average 5 or 6 Names . Sometimes more , but this is seldom . Sometimes it is just one name in every list , which could be spelled s... | list_1 = [ ' J . Payne ' , 'George Bush ' , 'Billy Idol ' , 'M Stuart ' , 'Luc van den Bergen ' ] list_2 = [ 'John Payne ' , 'George W. Bush ' , 'Billy Idol ' , 'M . Stuart ' , 'Luc Bergen ' ] ' J . Payne ' - > 'John Payne '' George Bush ' - > 'George W. Bush '' Billy Idol ' - > 'Billy Idol '' M Stuart ' - > 'M . Stuar... | Given two python lists of same length . How to return the best matches of similar values ? |
Python | Largest product in a gridProblem 11In the 20×20 grid below , four numbers along a diagonal line have been marked in red . The product of these numbers is 26 × 63 × 78 × 14 = 1788696.What is the greatest product of four adjacent numbers in the same direction ( up , down , left , right , or diagonally ) in the 20×20 grid... | x = '' '08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 0849 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 0081 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 6552 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 9122 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 8024 47 32 60 99 03... | Project Euler # 11 Numpy way |
Python | How would you iterate through a list of lists , such as : and construct a new list by grabbing the first item of each list , then the second , etc . So the above becomes this : | [ [ 1,2,3,4 ] , [ 5,6 ] , [ 7,8,9 ] ] [ 1 , 5 , 7 , 2 , 6 , 8 , 3 , 9 , 4 ] | Python Iterate through list of list to make a new list in index sequence |
Python | I encounter the following small annoying dilemma over and over again in Python : Option 1 : cleaner but slower ( ? ) if called many times since a_list get re-created for each call of do_something ( ) Option 2 : Uglier but more efficient ( spare the a_list creation all over again ) What do you think ? | def do_something ( ) : a_list = [ `` any '' , `` think '' , `` whatever '' ] # read something from a_list a_list = [ `` any '' , `` think '' , `` whatever '' ] def do_something ( ) : # read something from a_list | Python : How expensive is to create a small list many times ? |
Python | i can silence and restore sys.stdout this way : i know i 'd better be using contextlib.redirect_stdout which probably does something similar but my question is : why does the above code work ? i 'd have assumed python would call things like sys.stdout.write ( ) so whatever i replace sys.stdout with should have a write ... | import syssys.stdout = Noneprint ( 'hello ' ) # does not write to stdoutsys.stdout = sys.__stdout__print ( 'hello ' ) # writes to stdout | why does sys.stdout = None work ? |
Python | I need to know WHY this fails : When I run the code , i receive the following msg : < snip > ConfigurationError.py '' , line 7 , in __init__self.args [ 0 ] =self.__prettyfi ( self.args [ 0 ] ) TypeError : 'tuple ' object does not support item assignmentI edited the line no . to match this code sample.I do not understan... | class ConfigurationError ( Exception ) : def __init__ ( self , *args ) : super ( ConfigurationError , self ) .__init__ ( self , args ) self.args = list ( args ) # Do some formatting on the message string stored in self.args [ 0 ] self.args [ 0 ] =self.__prettyfi ( self.args [ 0 ] ) def __prettyfi ( self , arg ) : pass ... | python tuples and lists . A tuple that refuses to convert |
Python | How to get the month of maximum runoffI want to get the month of maximum runoff for each year , and for the time series as a whole . The idea is to characterise global seasonality by looking at the month of max runoff . I then want to try and consider whether each pixel has a unimodal or bimodal regime.I want to create... | # get the dataimport subprocesscommand = `` '' '' wget -O grun.nc https : //www.research-collection.ethz.ch/bitstream/handle/20.500.11850/324386/GRUN_v1_GSWP3_WGS84_05_1902_2014.nc ? sequence=1 & isAllowed=y '' '' '' import osif not os.path.exists ( 'grun.nc ' ) : process = subprocess.Popen ( command.split ( ) , stdout... | python get month of maximum value xarray |
Python | Python functions have a descriptors . I believe that in most cases I should n't use this directly but I want to know how works this feature ? I tried a couple of manipulations with such an objects : What is the obj and what is the type ? Sure that I ca n't do this trick with functions which take no arguments . Is it re... | def a ( ) : return ' x ' a.__get__.__doc__'descr.__get__ ( obj [ , type ] ) - > value ' > > > a.__get__ ( ) TypeError : expected at least 1 arguments , got 0 > > > a.__get__ ( 's ' ) < bound method ? .a of 's ' > > > > a.__get__ ( 's ' ) ( ) TypeError : a ( ) takes no arguments ( 1 given ) > > > def d ( arg1 , arg2 , a... | How work pre-defined descriptors in functions ? |
Python | I would like to ask what is the cheapest data type ( in term of memory consumption and cost to hold/process it ) to be used as dummy value in python dict ( only key of the dict matters to me , values are just placeholder ) For examples : Here only keys ( 1 , 2 , 3 ) are useful to me , the values are not so they can be ... | d1 = { 1 : None , 2 : None , 3 : None } d2 = { 1 : -1 , 2 : -1 , 3 : -1 } d3 = { 1 : False , 2 : False , 3 : False } | Python - What is the cheapest data type to be used as `` dummy value '' in dict |
Python | Sometime , I ca n't identify when or what 's causing it , pdb will not help you with code like : You end up with the usual prompt , but trying to access e will lead to : It 's not all the time of course , and it happens on linux , windows , my machine , my colleague machine ... | try : foo ( ) except Exception as e : import pdb ; pdb.set_trace ( ) ( pdb ) e*** NameError : name ' e ' is not defined . | Why ca n't pdb access a variable containing an exception ? |
Python | Background : I 'm a very experienced Python programmer who is completely clueless about the new coroutines/async/await features . I ca n't write an async `` hello world '' to save my life.My question is : I am given an arbitrary coroutine function f. I want to write a coroutine function g that will wrap f , i.e . I wil... | def generator_wrapper ( _ , *args , **kwargs ) : gen = function ( *args , **kwargs ) method , incoming = gen.send , None while True : with self : outgoing = method ( incoming ) try : method , incoming = gen.send , ( yield outgoing ) except Exception as e : method , incoming = gen.throw , e | Python coroutines : Release context manager when pausing |
Python | Update : not sure if this is possible without some form of a loop , but np.where will not work here . If the answer is , `` you ca n't '' , then so be it . If it can be done , it may use something from scipy.signal.I 'd like to vectorize the loop in the code below , but unsure as to how , due to the recursive nature of... | dist = 5000.v0 = float ( 1e6 ) r = pd.Series ( np.random.rand ( 12 ) * .01 , index=pd.date_range ( '2017 ' , freq= 'M ' , periods=12 ) ) value = pd.Series ( np.empty_like ( r ) , index=r.index ) from pandas.tseries import offsetsvalue = ( value.append ( Series ( v0 , index= [ value.index [ 0 ] - offsets.MonthEnd ( 1 ) ... | Recursion : account value with distributions |
Python | I 'm experiencing an odd issue with a SWIG-generated Python wrapper to a C++ class , wherein I can not seem to use the standard accessor functions of std : :map when it is wrapped as a std : :shared_ptr type . I managed to produce a MWE that reproduces the odd behavior I am observing.TestMap.hAnd then my SWIG interface... | # include < iostream > # include < map > # include < memory > class fooType { public : fooType ( ) { } ; ~fooType ( ) { } ; void printFoo ( ) { std : :cerr < < `` FOO ! '' < < std : :endl ; } static std : :shared_ptr < fooType > make_shared ( ) { return std : :shared_ptr < fooType > ( new fooType ( ) ) ; } } ; class te... | SWIG : Using std : :map accessors with a shared_ptr ? |
Python | This article describes how Python looks up an attribute on an object when it executes o.a . The priority order is interesting - it looks for : A class attribute that is a data-descriptor ( most commonly a property ) An instance attributeAny other class attributeWe can confirm this using the code below , which creates a... | class C : def __init__ ( self ) : self.__dict__ [ ' a ' ] = 1 @ property def a ( self ) : return 2o = C ( ) print ( o.a ) # Prints 2 | In Python , why do properties take priority over instance attributes ? |
Python | I have the following Python code and output : When I run this in R , the results do not match : I know the differences are pretty minor , but this is a bit of an issue with my application . Also of note , the R results match Stata 's results too.Note : I 'm using Python 2.7.2 , NumpPy 1.6.1 , R 2.15.2 GUI 1.53 Leopard ... | > > > import numpy as np > > > s = [ 12.40265325 , -1.3362417499999921 , 6.8768662500000062 , 25.673127166666703 , 19.733372250000002 , 21.649556250000003 , 7.1676752500000021 , -0.85349583333329804 , 23.130314250000012 , 20.074925250000007 , -0.29701574999999281 , 17.078694250000012 , 3.3652611666666985 , 19.491246250... | Any ideas why R and Python 's NumPy scaling of vectors is not matching ? |
Python | Why does doing the above operation in two steps result in the transpose of doing it in one step ? | import numpy as npx = np.random.randn ( 2 , 3 , 4 ) mask = np.array ( [ 1 , 0 , 1 , 0 ] , dtype=np.bool ) y = x [ 0 , : , mask ] z = x [ 0 , : , : ] [ : , mask ] print ( y ) print ( z ) print ( y.T ) | Numpy 3D array transposed when indexed in single step vs two steps |
Python | In a related question I learned that if I have an array of shape MxMxN , and I want to select based on a boolean matrix of shape MxM , I can simply do and be done with it . Unfortunately , now I have my data in a different order : For each element in data indexed i0 , i1 , i2 , it should be selected , if select [ i0 , ... | data [ select , ... ] import numpy as npdata = np.arange ( 36 ) .reshape ( ( 3 , 4 , 3 ) ) select = np.random.choice ( [ 0 , 1 ] , size=9 ) .reshape ( ( 3 , 3 ) ) .astype ( bool ) data.flatten ( ) [ np.repeat ( select [ : , None , : ] , 4 , axis=1 ) .flatten ( ) ] | 2d boolean selection in 3d matrix |
Python | I 'm trying to format a list of integers with Python and I 'm having a few difficulties achieving what I 'd like . Input is a sorted list of Integers : I would like it the output to be a String looking like this : So far all I managed to achieve is this : I 'm having trouble to tell my code to ignore a Int if it was al... | list = [ 1 , 2 , 3 , 6 , 8 , 9 ] outputString = `` 1-3 , 6 , 8-9 '' outputString = `` 1-2-3 , 6 , 8-9 '' def format ( l ) : i = 0 outputString = str ( l [ i ] ) for x in range ( len ( l ) -1 ) : if l [ i + 1 ] == l [ i ] +1 : outputString += '- ' + str ( l [ i+1 ] ) else : outputString += ' , ' + str ( l [ i+1 ] ) i = ... | Formatting consecutive numbers |
Python | While my startup is in dark mode I want all access except access to / to go to a screener page where users have enter a password given to them by a representative . I 've come up with the following simple middleware to perform the task . Just to be clear , this is intended to ensure that users agree to keep the site in... | from django.http import HttpResponseRedirectfrom django.core.urlresolvers import reverseimport reclass LicenceScreener ( object ) : SCREENER_PATH = reverse ( `` licence '' ) INDEX_PATH = reverse ( `` index '' ) LICENCE_KEY = `` commercial_licence '' def process_request ( self , request ) : `` '' '' Redirect any access ... | Security issues with a middleware screener page |
Python | I 'm pip-installing my module like so : When I later import the module from within Python , can I somehow detect if the module is installed in this editable mode ? Right now , I 'm just checking if there 's a .git folder in os.path.dirname ( mymodule.__file__ ) ) which , well , only works if there 's actually a .git fo... | cd my_working_dirpip install -e . | How to detect if module is installed in `` editable mode '' ? |
Python | What algorithm can I use to find the set of all positive integer values of n1 , n2 , ... , n7 for which the the following inequalities holds true.For example one set n1= 2 , n2 = n3 = ... = n7 =0 makes the inequality true . How do I find out all other set of values ? The similar question has been posted in M.SE.ADDED :... | 97n1 + 89n2 + 42n3 + 20n4 + 16n5 + 11n6 + 2n7 - 185 > 0-98n1 - 90n2 - 43n3 - 21n4 - 17n5 - 12n6 - 3n7 + 205 > 0n1 > = 0 , n2 > = 0 , n3 > =0 . n4 > =0 , n5 > =0 , n6 > =0 , n7 > = 0 97n1 + 89n2 + 42n3 + 20n4 + 16n5 + 11n6 + 6n7 + 2n8 - 185 > 0-98n1 - 90n2 - 43n3 - 21n4 - 17n5 - 12n6 - 7 - 3n8 + 205 > 0n1 > = 0 , n2 > =... | find the set of integers for which two linear equalities holds true |
Python | I have a dataframe like the following : I am trying to clean my dataframe in the following way : For every row having more value than 1.5 times the previous row value or less than 0.5 times the previous row value , drop it.But If the previous row is a to-drop row , comparison must be made with the immediate previous NO... | A1 10002 10003 10014 10015 106 10007 10108 99 1010 611 99912 1011013 1011114 1000 A1 10002 10003 10014 10016 10007 101011 99914 1000 | Filtering rows from dataframe based on the values of the previous rows |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.