lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Python
Say I want to debug a simple class with an attribute myattribute . I create a repr method like this : It feels a bit redundant , so I would prefer to use format directly : ... but that fails with an IndexError : tuple index out of range . I understand it that format can not access the self argument , but I do not see w...
class SimpleClass : def __repr__ ( self ) : return `` { 0.myattribute } '' .format ( self ) class SimpleClass : __repr__ = `` { 0.myattribute } '' .format
How can I use ` str.format ` directly as ` __repr__ ` ?
Python
I have following DataFrame : I want to transform following Dataframe : into dataframe of rows : The products are known ahead.Any idea how to do so ?
data = { 'year ' : [ 2010 , 2010 , 2011 , 2012 , 2011 , 2012 , 2010 , 2011 , 2012 , 2013 ] , 'store_number ' : [ '1944 ' , '1945 ' , '1946 ' , '1947 ' , '1948 ' , '1949 ' , '1947 ' , '1948 ' , '1949 ' , '1947 ' ] , 'retailer_name ' : [ 'Walmart ' , 'Walmart ' , 'CRV ' , 'CRV ' , 'CRV ' , 'Walmart ' , 'Walmart ' , 'CRV ...
Transforming Dataframe columns into Dataframe of rows
Python
If I try to print the class variable which is a list , I get a Python object . ( These are examples I found on stackoverflow ) .But in this more simple example , it actually prints : I figured this line is the culprit : Contact.all_contacts.append ( self ) in the first sample code . But I 'm not exactly sure whats goin...
class Contacts : all_contacts = [ ] def __init__ ( self , name , email ) : self.name = name self.email = email Contacts.all_contacts.append ( self ) def __str__ ( self ) : return ' % s , < % s > ' % ( self.name , self.email ) c1 = Contacts ( `` Grace '' , `` something @ hotmail.com '' ) print ( c1.all_contacts ) [ < __...
How do I print this class variable ?
Python
Suppose you find yourself in the unfortunate position of having a dependency on a poorly behaved library . Your code needs to call FlakyClient.call ( ) , but sometimes that function ends up hanging for an unacceptable amount of time.As shown below , one way around this is to wrap the call in its own Process , and use t...
from multiprocessing import Processfrom flaky.library import FlakyClientTIMEOUT_IN_SECS = 10def make_flaky_call ( ) : result = FlakyClient.call ( ) proc = Process ( target=make_flaky_call ) proc.start ( ) proc.join ( TIMEOUT_IN_SECS ) if proc.is_alive ( ) : proc.terminate ( ) raise Exception ( `` Timeout during call to...
How can you safeguard yourself from a flaky library call that might hang indefinitely ?
Python
Is there a better way to do this ? I feel like I am doing something wrong by being too repetitive .
O = viz.pick ( 1 , viz.WORLD ) BackSetts = [ `` set_b1b '' , `` set_b2a '' , `` set_b1a '' , `` set_b2b '' ] LeftSetts = [ `` set_l1a '' , `` set_l1b '' , `` set_l2a '' , `` set_l1b '' ] NormSetts = [ `` set_nr_a '' , `` set_nr_b '' ] Maps = [ `` MapA '' , '' MapB '' ] if O.name in BackSetts : for i in set ( BackSetts ...
Is there a better way to write this ?
Python
I want to split array into array with mask and indexlike below into can I do this without loop ? Edit : More examples ... Say , we have an array a with shape [ 10 , 10 , 10 ] where a [ x , y , : ] = [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] Now given the mask b = [ 0 , 3 , 7 ] I want the output to be an array c with sh...
a = array ( [ 0 , 1 , 2 , 3 , 4 , 5 ] ) ) b = [ 0,2,3 ] c = array ( [ [ 0 , 2 , 3 ] , [ 1 , 3 , 4 ] , [ 2 , 4 , 5 ] ] )
can I split numpy array with mask ?
Python
Thanks in advance for helping.I have a csv file with the following structure : I need a nested JSON for use in D3 or amcharts . With the python script on this page ( https : //github.com/hettmett/csv_to_json ) I could create a nested JSON . The results looks like this : However it is not exactly what I need . The probl...
group1 , group2 , group3 , name , infoGeneral , Nation , ,Phil , info1General , Nation , ,Karen , info2General , Municipality , ,Bill , info3General , Municipality , ,Paul , info4Specific , Province , ,Patrick , info5Specific , Province , ,Maikel , info6Specific , Province , Governance , Mike , info7Specific , Province...
Problem creating nested JSON with python from csv with columns without value
Python
I 'm learning a bit of python coding and I 'm following this youtube video too to make some practice.Now here is what I 'm running.The strange thing is that for a few buses , the program somehow mixes longitude , latitude and direction for no apparent reason.For example , this is what I 've got right now : I know the c...
import urllibimport operatorfrom xml.etree.ElementTree import parseimport webbrowserfrom showmap import showmapdef getbuses ( ) : u = urllib.urlopen ( 'http : //ctabustracker.com/bustime/map/getBusesForRoute.jsp ? route=22 ' ) data = u.read ( ) f = open ( 'rt22.xml ' , 'wb ' ) f.write ( data ) f.close ( ) doc = parse (...
Ca n't spot a bug in my python code
Python
I came across a strange result while playing around with Pandas and I am not sure why this would work like this . Wondering if it is a bug.This gives `` 15.0 '' as result.This gives as result a Series : type ( df1.loc [ ' b ' , 'mvl ' ] ) - > pandas.core.series.Seriestype ( df.loc [ ' b ' , 'mvl ' ] ) - > numpy.float64...
cf = pd.DataFrame ( { 'sc ' : [ ' b ' , ' b ' , ' c ' , 'd ' ] , 'nn ' : [ 1 , 2 , 3 , 4 ] , 'mvl ' : [ 10 , 20 , 30 , 40 ] } ) df = cf.groupby ( 'sc ' ) .mean ( ) df.loc [ ' b ' , 'mvl ' ] cf1 = cfcf1 [ 'sc ' ] = cf1 [ 'sc ' ] .astype ( 'category ' , categories= [ ' b ' , ' c ' , 'd ' ] , ordered = True ) df1 = cf1.gr...
Pandas - Category variable and group by - is this a bug ?
Python
If I write : I get : Why is it coercing them into ints ? It does the same thing in reverse.Output is : Can this be disabled ? Is it a bug ?
d = { 0 : ' a ' , 1 : ' b ' } d [ False ] = ' c 'd [ True ] = 'd'print ( d ) { 0 : ' c ' , 1 : 'd ' } d = { False : ' a ' , True : ' b ' } d [ 0 ] = ' c 'd [ 1 ] = 'd'print ( d ) { False : ' c ' , True : 'd ' }
Dictionary coercion intentional or no ?
Python
I 've read various `` there is no truly private data in Python instances '' posts , but we 're all aware of using closures in Perl and JavaScript to effectively achieve private data . So why not in Python ? For example : Now we do : What can you do to the instance thing to get read access to the original string ( ignor...
import codecsclass Secret : def __private ( ) : secret_data = None def __init__ ( self , string ) : nonlocal secret_data if secret_data is None : secret_data = string def getSecret ( self ) : return codecs.encode ( secret_data , 'rot_13 ' ) return __init__ , getSecret __init__ , getSecret = __private ( ) > > > thing = ...
Python private instance data revisited
Python
When inputting 1000 for the range of this code , many ellipse shapes are created , some of which are hard to see . This seems to only happen with the Fibonacci sequence and no other chains of long numbers . Why is this ?
in_range = int ( input ( `` range : `` ) ) fibo_list = [ ] a = 0b = 1count = 0if in_range < 0 : print ( `` faulty '' ) elif in_range == 0 : print ( `` faulty '' ) else : while count < in_range : c = a + b a = b b = c count += 1 fibo_list.append ( a ) print ( fibo_list )
Why do very large Fibonacci numbers create an ellipse-type shape ?
Python
so far my dataframe looks like this : I would like to replace the area ' Q ' with ' P ' for every row where the Stage is equal to ' X'.So the result should look like : I tried : It does not work . Help is appreciated ! : )
ID Area Stage1 P X2 Q X3 P X4 Q Y ID Area Stage1 P X2 P X3 P X4 Q Y data.query ( 'Stage in [ `` X '' ] ' ) [ 'Area ' ] =data.query ( 'Stage in [ `` X '' ] ' ) [ 'Area ' ] .replace ( ' Q ' , ' P ' )
Replace column value based on value in other column
Python
I have two dataframes with the same columns : Dataframe 1 : Dataframe 2 : I want to generate a correlation and p-value dataframe of all posible combinations , this would be the result : The problem is that the cartesian product generates more than 3 million tuples . Taking minutes to finish . This is my code , I 've wr...
attr_1 attr_77 ... attr_8userID John 1.2501 2.4196 ... 1.7610Charles 0.0000 1.0618 ... 1.4813Genarito 2.7037 4.6707 ... 5.3583Mark 9.2775 6.7638 ... 6.0071 attr_1 attr_77 ... attr_8petID Firulais 1.2501 2.4196 ... 1.7610Connie 0.0000 1.0618 ... 1.4813PopCorn 2.7037 4.6707 ... 5.3583 userId petID Correlation p-value0 Jo...
Optimizing cartesian product between two Pandas Dataframe
Python
Somewhat of a python/programming newbie here ... I am trying to come up with a regex that can handle extracting sentences from a line in a text file , and then appending them to a list . The code : Printed Output as per last 5 lines of above code : The contents of 'sample.txt ' : I have been playing around with the reg...
import retxt_list = [ ] with open ( 'sample.txt ' , ' r ' ) as txt : patt = r'.* } [ . ! ? ] \s ? \n ? |.* } .+ [ . ! ? ] \s ? \n ? ' read_txt = txt.readlines ( ) for line in read_txt : if line == `` \n '' : txt_list.append ( `` \n '' ) else : found = re.findall ( patt , line ) for f in found : txt_list.append ( f ) fo...
Python : Extracting Sentences From Line - Regex Needed Based on Criteria
Python
I am trying to match strings in a column of a data frame with the strings in a column of another data frame and map the corresponding values . The number of rows are different for both data framesExpected output
df1 = data.frame ( name = c ( `` ( CKMB ) Creatinine Kinase Muscle & Brain '' , `` 24 Hours Urine for Sodium '' , `` Antistreptolysin O Titer '' , `` Blood group O '' , lonic_code = c ( `` 27816-8-O '' , `` 27816-8-B '' , `` 1869-7 '' , `` 33914-3 '' ) df2 = data.frame ( Testcomponents = c ( `` creatinine '' , `` blood...
Matching strings in a column of a data frame with the strings in a column of another data frame using R or Python
Python
I am a newbie to JavaScript , but I am familiar with Python . I am trying to figure out the differences between the Dictionary in Python and the Object in JS.As far as I know , the key in a dictionary in Python needs to be defined in advance , but it could be undefined in an object in JS . However , I am confused about...
var n = 'name ' ; var n2 = n ; var person = { n : 'mike ' } ; person.n # 'mike'person [ ' n ' ] # 'mike'person [ n2 ] # undefinedperson.n2 # undefinedperson [ 'name ' ] # undefinedperson . 'name ' # undefined n = 'name'n2 = nperson = { n : 'mike ' } person [ n ] # 'mike'person [ n2 ] # 'mike'person [ 'name ' ] # 'mike ...
I am so confused about Object in JavaScript
Python
This is homework , so I do n't expect the answer , just a point in the right direction.In python I have a dictionary that is like so : For example 'Racing Bike ' is the product name and the list of pairs is ( part , amount required ) , respectively.I have to write a function that , given the above dictionary and the pr...
{ 'bike101 ' : ( 'Road Bike ' , [ ( 'WH139 ' , 2 ) , ( 'TR102 ' , 2 ) , ( 'TU177 ' , 2 ) , ( 'FR101 ' , 1 ) , ( 'FB101 ' , 1 ) , ( 'BB101 ' , 1 ) , ( 'GS101 ' , 1 ) ] ) , 'bike201 ' : ( 'Mountain Bike ' , [ ( 'WH239 ' , 2 ) , ( 'TR202 ' , 2 ) , ( 'TU277 ' , 2 ) , ( 'FR201 ' , 1 ) , ( 'FB201 ' , 1 ) , ( 'BB201 ' , 1 ) ,...
Finding an element of a list when the list is in a dictionary ?
Python
So I have a line of code : That throws me this error : But magically fixes itself if I take out the `` input '' : Here is the function specification in the PyTorch docs : https : //pytorch.org/docs/stable/_modules/torch/nn/utils/rnn.html # pack_padded_sequenceI 'm using Python3 and PyTorch 0.4 . Am I missing something ...
packed_embeddings = pack_padded_sequence ( input=embeddings , lengths=lengths , batch_first=True ) File `` /Users/kwj/anaconda3/lib/python3.6/site-packages/torch/onnx/__init__.py '' , line 130 , in might_trace first_arg = args [ 0 ] IndexError : tuple index out of range packed_embeddings = pack_padded_sequence ( embedd...
Is `` input '' a keyword that causes errors when used as a parameter name ( in PyTorch ) ?
Python
This is n't a practical problem - I 'm just curious about some strange behavior I 've observed , and wondering if I understand the `` is '' operator correctly.Here 's some predictable Python interpreter output : Now let 's define a variable called True : The interpreter will still return `` True '' for boolean operatio...
> > > True is TrueTrue > > > ( 1==1 ) is TrueTrue > > > True = 'abc ' > > > True == 'abc'True > > > True is 'abc'True > > > ( 1==1 ) True > > > ( 1==1 ) is 'abc'False > > > ( 1==1 ) is TrueFalse
Strange behavior when defining a value for True in Python
Python
for some reason , any mouse event that happens with my program does n't make the image in the window disappear nor reappear , although my on_key_press ( ) function works.I 've tried state flags and declaring a new image resource , but it does n't change anything in the window.Is there a way to make this work ? Should I...
import pygletwindow = pyglet.window.Window ( ) image = pyglet.resource.image ( 'test.png ' ) image.anchor_x = image.width // 2image.anchor_y = image.height // 2state = True @ window.eventdef on_draw ( ) : print ( 'on_draw ( ) called ' ) window.clear ( ) if state : image.blit ( window.width // 2 , window.height // 2 ) @...
Python Pyglet mouse events do n't call on_draw ( ) nor make changes in window
Python
I am writing code to read data from a CSV file to a pandas dataframe and to get the unique values and concatenate them as a string . The problem is that one of the columns contains the values True and False . So while concatenating the values I am getting the errorI want python to treat True as string rather than boole...
sequence item 0 : expected str instance , bool found import pandas as pddf=pd.read_csv ( ' C : /Users/jaiveeru/Downloads/run_test1.csv ' ) cols=df.columns.tolist ( ) for i in cols : lst=df [ i ] .unique ( ) .tolist ( ) str1 = ' , '.join ( lst ) lst2= [ str1 ] -- -- > 5 str1 = ' , '.join ( lst ) TypeError : sequence ite...
String Join treats True as Boolean rather than string
Python
I think I 'm overlooking something simple , but I ca n't seem to figure out what exactly . Please consider the following code : I expected that both for-loops would produce the same result , so 4 5 . However , the for-loop that prints the generator exp prints 4 5 6 7 8 9 . I think it has something to do with the declar...
a = [ 2 , 3 , 4 , 5 ] lc = [ x for x in a if x > = 4 ] # List comprehensionlg = ( x for x in a if x > = 4 ) # Generator expressiona.extend ( [ 6,7,8,9 ] ) for i in lc : print ( `` { } `` .format ( i ) , end= '' '' ) for i in lg : print ( `` { } `` .format ( i ) , end= '' '' )
Unexpected results when comparing list comprehension with generator expression
Python
I was just trying to learn K-ary tree implementation in Python and came across this link : http : //www.quesucede.com/page/show/id/python-3-tree-implementationIn the tree.py file , there is a section of code like this : What is self [ identifier ] ? Is it a list ? This is really confusing.Can someone explain and/or poi...
class Tree : def __init__ ( self ) : self.__nodes = { } @ property def nodes ( self ) : return self.__nodes def add_node ( self , identifier , parent=None ) : node = Node ( identifier ) self [ identifier ] = node if parent is not None : self [ parent ] .add_child ( identifier ) return node # ... ... def __getitem__ ( s...
What does self [ identifier ] = some_value do in this code ?
Python
I have a question about this on testing the following code:1,2 , The file object closed when the file_close_test exits because no reference to it.After the exception raised , the file object not closed.so i think the related stack data not released.After exception_wrapper exit , the file closed automatically.can you ex...
def file_close_test ( ) : f = open ( '/tmp/test ' , ' w+ ' ) if __name__ == '__main__ ' : file_close_test ( ) # wait to see whether file closed . import time time.sleep ( 30 ) def file_close_on_exc_test ( ) : f = open ( '/tmp/test ' , ' w+ ' ) raise Exception ( ) def exception_wrapper ( ) : try : file_close_on_exc_test...
when to release function stack data in python ?
Python
This is actually in a job posting on SO and being a newbie I thought it was interesting . So you get output like the following : To me this is already confusing because I thought izip_longest ( * ( [ iter ( iterable ) ] * n ) ) would run the izip_longest function on a list of n identical iterators so I would have expec...
def partition ( n , iterable ) : p = izip_longest ( * ( [ iter ( iterable ) ] * n ) ) r = [ ] for x in p : print ( x ) # I added this s = set ( x ) s.discard ( None ) r.append ( list ( s ) ) return r partition ( 5 , L ) ( 1 , 2 , 3 , 4 , None ) Out [ 86 ] : [ [ 1 , 2 , 3 , 4 ] ] p = izip_longest ( * ( [ iter ( iterable...
What does this function do ? ( Python iterators )
Python
I have two images , an analysis image and an ROI Mask image ( the ROI Mask image is below ) .What I want to do is to measure the RGB mean value in an area of the analysis image selected by the ROI Mask image . I am doing this by using a for loop but it takes too long.Is there any way to make this simpler ?
import cv2import numpy as npfrom statistics import meanimg=cv2.imread ( `` Analysis.jpg '' , 1 ) mask=cv2.imread ( `` ROI_Mask.jpg '' , 0 ) height = im.shape [ 0 ] width = im.shape [ 1 ] R_value= [ ] G_value= [ ] B_value= [ ] for x in range ( width ) : for y in range ( height ) : if mask [ y ] [ x ] ! =0 : b , g , r=im...
How do I measure RGB mean in a unique ROI ?
Python
For some reason , I need to be able to delete all the children ( in some sense ) that were originated by some method of the class . Here is an example : What I want is somehow to append generated class B from gen_b to A ( ) .children so that : Additionally , I need this for cython ( I use cdef classes ) , so maybe ther...
class A ( ) : def __init__ ( self ) : self.a_val = 56 self.children = list ( ) def __del__ ( self ) : del self.children def gen_b ( self ) : return B ( self.a_val ) class B ( ) : def __init__ ( self , val ) : self.a_val = val self.b_val = 87 a_class = A ( ) b_generated = a_class.gen_b ( ) del a_class # b_generated is a...
Delete all variables ( classes ) generated by class method python
Python
Consider the following operation in the limit of low length iterables , Setting as a list is 25 % faster than using a generator expression ? Why is this the case as setting as a list is an extra operation.Note : In both runs I obtained the warning : The slowest run took 6.42 times longer than the fastest . This could m...
d = ( 3 , slice ( None , None , None ) , slice ( None , None , None ) ) In [ 215 ] : % timeit any ( [ type ( i ) == slice for i in d ] ) 1000000 loops , best of 3 : 695 ns per loopIn [ 214 ] : % timeit any ( type ( i ) == slice for i in d ) 1000000 loops , best of 3 : 929 ns per loop import timeit , pylab , multiproces...
Is it faster to iterate a small list within an any ( ) statement ?
Python
I am having a dataset with dates and company names . I only want to keep rows such that the combination of the company name and the date appeared in the dataset at least twice . To illustrate the problem , let us assume I have the following dataframe : My desired output would be : I would know how to drop the rows base...
df1 = pd.DataFrame ( np.array ( [ [ '28/02/2017 ' , 'Apple ' ] , [ '28/02/2017 ' , 'Apple ' ] , [ '31/03/2017 ' , 'Apple ' ] , [ '28/02/2017 ' , 'IBM ' ] , [ '28/02/2017 ' , 'WalMart ' ] , [ '28/02/2017 ' , 'WalMart ' ] , [ '03/07/2017 ' , 'WalMart ' ] ] ) , columns= [ 'date ' , 'keyword ' ] ) df2 = pd.DataFrame ( np.a...
Drop rows in pandas if records in two columns do not appear together at least twice in the dataset
Python
I am working on a project where very specific scheduling is needed ( and why I am not using a library ) . It works , but I am trying to find a faster solution to the following problem : We have employees requesting hours every week . They input their total availability for the week ( ex : 8-1 M , W , R ) . They all mus...
# let availability be the string of availability availability = `` 8,9,10,11 ; 8,9 ; ; 8,9,10,11 ; '' poss_times = availability.split ( `` ; '' ) # where I put into one array with each day letter in front sched= [ ] sched.extend ( [ `` m '' + day for day in list ( filter ( None , poss_times [ 0 ] .split ( `` , '' ) ) )...
How to efficiently and quickly find valid combinations out of an array of string elements for employee scheduling ?
Python
I wrote a simple prime sieve ( an unbounded sieve of Eratosthenes ) using Python , but for some reason , it is n't working correctly . Here is the sieve : Unfortunately , this is n't working . Instead , it just returns the same values as the count ( 2 ) iterator would.For comparison , this : will print : while the siev...
from itertools import countdef sieve ( ) : nums = count ( 2 ) while True : n = next ( nums ) nums = filter ( lambda k : k % n ! = 0 , nums ) yield n nums = count ( 2 ) print ( next ( nums ) ) nums = filter ( lambda k : k % 2 ! = 0 , nums ) print ( next ( nums ) ) nums = filter ( lambda k : k % 2 ! = 0 , nums ) print ( ...
Creating a simple prime sieve in Python
Python
Ok , this might be a very stupid question and it might not be possible , or I am thinking in a twisted way . So , consider this : Ok , here we have two classes : MyClass is just something very ordinary and nothing special . It has two instance attributes : x and y.MyList , on the other hand , should be a class which de...
class MyClass : def __init__ ( self , x ) : self.x = x self.y = self.x ** 2class MyList : def __init__ ( self , list ) : self.list = list def __iter__ ( self ) : return iter ( self.list ) foo = [ MyClass ( x=1 ) , MyClass ( x=2 ) ] bar = MyList ( list=foo ) for i in bar : print ( i.x , i.y )
Define what class contains
Python
I have two 1-dimensional numpy.ndarray objects , and want to work out which elements in the first array are within dx of any element in the second.What I have currently is which returns a timeit result as followsWhat 's the best way to optimise the find_all_close function , especially if a and b are guaranteed to be fl...
# setupnumpy.random.seed ( 1 ) a = numpy.random.random ( 1000 ) # create one arraynumpy.random.seed ( 2 ) b = numpy.random.random ( 1000 ) # create second arraydx = 1e-4 # close-ness parameter # function I want to optimisedef find_all_close ( a , b ) : # compare one number to all elements of b def _is_coincident ( t ) ...
What 's the most efficient way to find which elements of one array are close to any element in another ?
Python
I am currently writing a program to model Dijkstra 's algorithm , however I am having some trouble the graph in its current form below : I want to get the graph in the form such as the one belowWould this be possible ?
G = [ [ ' a ' , ' b ' , ' c ' , 'd ' , ' e ' , ' f ' , ' g ' , ' h ' , ' i ' , ' j ' ] , [ ( { ' a ' , ' b ' } , 4 ) , ( { ' a ' , ' c ' } , 6 ) , ( { ' a ' , 'd ' } , 8 ) , ( { ' b ' , ' e ' } , 1 ) , ( { ' b ' , ' f ' } , 9 ) , ( { ' c ' , ' f ' } , 2 ) , ( { 'd ' , ' g ' } , 7 ) , ( { 'd ' , ' h ' } , 1 ) , ( { ' e ...
Converting a graph into dictionary form
Python
Does Python support conditional structure in regex ? If yes , why I ca n't have the following ( using lookahead in the ifpart ) right ? Any way to make Python support it ? Using backreference as the if part works , however : http : //www.regular-expressions.info/conditional.html says Conditionals are supported by the J...
> > > p = re.compile ( r ' ( ? ( ? =regex ) then|else ) ' ) Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > File `` /usr/lib/python2.7/re.py '' , line 190 , in compile return _compile ( pattern , flags ) File `` /usr/lib/python2.7/re.py '' , line 242 , in _compile raise error , v # i...
Does Python support conditional structure in regex ?
Python
I have a YAML file that goes as ( just an example ) : I want to read this file , and do some stuff with bs and cs . The problem is that I ca n't read this file as a dictionary using yaml.load ( ) , since it will only give me { ' a ' : { ' b ' : 3 } } . Instead , I want to read it as a list of dictionaries , i.e , I wan...
a : b : 1 a : b : 2 c : 1a : b : 3 [ { ' a ' : { ' b ' : 1 } } , { ' a ' : { ' b ' : 2 , ' c ' : 1 } } , { ' a ' : { ' b ' : 3 } } ]
Read YAML file as list
Python
I am using the Flask-Mail library for my Flask application to send a default welcome email to the user when they sign up to be added to the newsletter . After debugging the library I found that it can only handle one connection at a time to send a message and will then automatically close the connection . If the backen...
import osimport redisfrom rq import Worker , Queue , Connectionlisten = [ 'high ' , 'default ' , 'low ' ] redis_url = os.environ.get ( 'REDISTOGO_URL ' ) conn = redis.from_url ( redis_url ) if __name__ == '__main__ ' : with Connection ( conn ) : worker = Worker ( map ( Queue , listen ) ) worker.work ( ) from flask impo...
Flask-Mail queue messages to be sent to different emails
Python
I am working on a leetcode problem `` wordLadder '' Given two words ( beginWord and endWord ) , and a dictionary 's word list , find the length of shortest transformation sequence from beginWord to endWord , such that : Only one letter can be changed at a time . Each transformed word must exist in the word list . Note ...
Input : beginWord = `` hit '' , endWord = `` cog '' , wordList = [ `` hot '' , '' dot '' , '' dog '' , '' lot '' , '' log '' , '' cog '' ] Output : 5Explanation : As one shortest transformation is `` hit '' - > `` hot '' - > `` dot '' - > `` dog '' - > `` cog '' , return its length 5 . Input : beginWord = `` hit '' end...
Exhaustively get all the possible combinations of a word of three lettters
Python
I was just looking at the implementation of functools.lru_cache , when I stumbled across this snippet : I am familiar with circular and doubly linked lists . I am also aware that new_list = my_list [ : ] creates a copy of my_list.When looking for slice assignments or other implementations of circular doubly linked list...
root = [ ] # root of the circular doubly linked listroot [ : ] = [ root , root , None , None ] # initialize by pointing to self
What is happening when I assign a list with self references to a list copy with the slice syntax ` mylist [ : ] = [ mylist , mylist , ... ] ` ?
Python
I have the following dictionary : And for this dictionary I want write a function that returns the three key-value pairs that have the highest values ( So in this case key 18 , 19 , 20 ) .I came up with the following : This gives me a list of the max-values I want to lookup . But how do I proceed from here ? Is there a...
' { 0 : 0 , 1 : 11 , 2 : 26 , 3 : 43 , 4 : 14 , 5 : 29 , 6 : 34 , 7 : 49 , 8 : 49 , 9 : 108 , 10 : 124 , 11 : 108 , 12 : 361 , 13 : 290 , 14 : 2118 , 15 : 5408 , 16 : 43473 , 17 : 109462 , 18 : 111490 , 19 : 244675 , 20 : 115878 , 21 : 6960 } ' cachedict = nr_of_objects_per_century ( ) # Dictionary mentioned abovedef t...
Returning the three maximal values in a dictionary
Python
I 've run into this problem a few times in different situations but my setup is the following : I have two Django models files . One that contains User models and CouponCodes that a user can use to sign up for a Course . Those are both in the account/models.py file . Course and the related many-to-many field are in a d...
from account import models as amodclass Course ( ExtendedModel ) : stuff = stuff class CouponCode ( ExtendedModel ) : assigned_course = UniqueIDForeignKey ( `` course.Course '' , blank=True , null=True , related_name='assigned_coupon_code_set ' ) ... ... @ staticmethod def assign_batch ( c , upper_limit ) : import cour...
Python/Django : Why does importing a module right before using it prevent a circular import ?
Python
When I had a list that was in format of I could use However now lets say I have multiple values such as I have no idea how to go about creating a dict so that it would show the first name as the key and the following values as the value.Thanks in advance
list1 = [ [ James,24 ] , [ Ryan,21 ] , [ Tim,32 ] ... etc ] dic1 =dict ( list1 ) list1 = [ [ James,24 , Canada , Blue , Tall ] , [ Ryan,21 , U.S. , Green , Short [ Tim,32 , Mexico , Yellow , Average ] ... etc ]
Converting List to Dict
Python
I am wanting to check if a list has a specific sequence of elements . I have sorted the list which contains 7 elements , I now want to check of the first 4 are the same as each other and the last 3 are the same as each other . For what I want to achieve to be True the list would be like this : I hope this makes what I ...
list = [ ' 1 ' , ' 1 ' , ' 1 ' , ' 1 ' , ' 2 ' , ' 2 ' , ' 2 ' ]
Checking a List for a Sequence
Python
In the following data , I am trying to run a simple markov model.Say I have a data with following structure : Block M represents data from one set of catergories , so does block S.The data are the strings which are made by connecting letter along the position line . So , the string value for M1 is A-T-C-G , and so is f...
pos M1 M2 M3 M4 M5 M6 M7 M8 hybrid_block S1 S2 S3 S4 S5 S6 S7 S81 A T T A A G A C A|C C G C T T A G A2 T G C T G T T G T|A A T A T C A A T3 C A A C A G T C C|G G A C G C G C G4 G T G T A T C T G|T C T T T A T C T
How to read two lines from a file and create dynamics keys in a for-loop ?
Python
I have the following list of strings : I want to obtain a list that has , say , these same elements repeated n times . If n=3 I 'd get : What I am trying is this : But what I obtain is this : If I try this : I obtain : What am I missing ?
l1 = [ 'one ' , 'two ' , 'three ' ] l2 = [ 'one ' , 'one ' , 'one ' , 'two ' , 'two ' , 'two ' , 'three ' , 'three ' , 'three ' ] l2 = [ 3*i for i in l1 ] l2 = [ 'oneoneone ' , 'twotwotwo ' , 'threethreethree ' ] l2 = [ 3* ( str ( i ) + '' , '' ) for i in l1 ] l2 = [ 'one , one , one ' , 'two , two , two ' , 'three , t...
Python : expand list of strings by adding n elements for each original element
Python
I am implementing an array-like object that should be interoperable with standard numpy arrays . I just hit an annoying problem that narrows down to the following : This yields the following output : Clearly , rather than calling MyArray ( ) .__rmul__ ( array ( [ 1,2,3 ] ) ) as I had hoped , __rmul__ is called for ever...
class MyArray ( object ) : def __rmul__ ( self , other ) : return MyArray ( ) # value not important for current purposefrom numpy import arrayprint array ( [ 1,2,3 ] ) * MyArray ( ) [ < __main__.MyArray instance at 0x91903ec > < __main__.MyArray instance at 0x919038c > < __main__.MyArray instance at 0x919042c > ]
numpy coercion problem for left-sided binary operator
Python
I 'm creating an application with python to calculate duct-tape overlapping ( modeling a dispenser applies a product on a rotating drum ) .I have a program that works correctly , but is really slow . I 'm looking for a solution to optimize a for loop used to fill a numpy array . Could someone help me vectorize the code...
import numpy as npimport matplotlib.pyplot as plt # Some parameterswidth = 264bbddiam = 940accuracy = 4 # 2 points per pixeldrum = np.zeros ( accuracy**2 * width * bbddiam ) .reshape ( ( bbddiam * accuracy , width * accuracy ) ) # The `` slow '' functiondef line_mask ( drum , coef , intercept , upper=True , accuracy=ac...
Vectorize a for loop in numpy to calculate duct-tape overlaping
Python
I understand there are at least 3 kinds of methods in Python having different first arguments : instance method - instance , i.e . selfclass method - class , i.e . clsstatic method - nothingThese classic methods are implemented in the Test class below including an usual method : In Python 3 , the unknown_mthd can be ca...
class Test ( ) : def __init__ ( self ) : pass def instance_mthd ( self ) : print ( `` Instance method . '' ) @ classmethod def class_mthd ( cls ) : print ( `` Class method . '' ) @ staticmethod def static_mthd ( ) : print ( `` Static method . '' ) def unknown_mthd ( ) : # No decoration -- > instance method , but # No s...
Are there more than three types of methods in Python ?
Python
I am working on an interactive plotting script using matplotlib version 3.2.2 and tkinter.When the script is run , the first window looks like this : Furthermore , the rcParams are updated and plotted once the Plot figure button is clicked : If I now hit the button Change plot settings and change for instance the marke...
`` `` '' This is a script for interactively plotting a scatterplot and changing the plot params . `` `` '' import numpy as npimport matplotlib as mplimport matplotlib.styleimport randommpl.use ( 'TkAgg ' ) import numpy as npfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAggfrom matplotlib.figure import Fig...
Matplotlib rcParams ignored when plotting
Python
I 'm using the Mirametrix S2 gaze tracking device . In the API docs ( v1.1 ) , it says that the ENABLE_SEND_GPI command allows a tracking client to insert data into the gaze stream . Copying some of the example code , I tried the following : I get the following in response : I 've tried many different combinations of i...
sock.send ( ' < SET ID= '' ENABLE_SEND_GPI '' STATE= '' 1 '' / > \r\n ' ) sock.send ( ' < SET ID= '' GPI_NUMBER '' VALUE= '' 1 '' / > \r\n ' ) sock.send ( ' < SET ID= '' GPI1 '' VALUE= '' INTERVAL '' / > \r\n ' ) < ACK ID= '' ENABLE_SEND_GPI '' STATE= '' 1 '' / > < ACK ID= '' GPI_NUMBER '' VALUE= '' 1 '' / > < ACK ID= ...
Mirametrix S2 gaze tracker : Sending general purpose input ( GPI ) values always fails
Python
What 's the rationale behind not allowing * in relative imports ? e.g.or doing a relative import directly :
from ..new_tool import * import ..new_tool
python : What 's the rationale behind not allowing * in relative imports ?
Python
The intended objective of function foo is to add the number provided as argument to the list and , in case it is 0 , reset the list . First I wrote this program : output : but it looks like bar = [ ] is ignored . Then I changed bar = [ ] with bar.clear ( ) and it works as I thought : output : I have n't understood why ...
def foo ( n , bar = [ ] ) : if n == 0 : bar = [ ] print ( `` list empty '' ) else : bar.append ( n ) for y in bar : print ( y , end= ' , ' ) print ( ) foo ( 5 ) foo ( 3 ) foo ( 0 ) foo ( 6 ) 5 , 5 , 3 , list empty5 , 3 , 6 , def foo ( n , bar = [ ] ) : if n == 0 : bar.clear ( ) print ( `` list empty '' ) else : bar.app...
How is list.clear ( ) different from list = [ ] ?
Python
I am trying to create a custom estimator based on scikit learn . I have written the below dummy code to explain my problem . In the score method , I am trying to access mean_ calulated in fit . But I am unable to . What I am doing wrong ? I have tried many things and have done this referring three four articles . But d...
import numpy as npfrom sklearn.model_selection import cross_val_scoreclass FilterElems : def __init__ ( self , thres ) : self.thres = thres def fit ( self , X , y=None , **kwargs ) : self.mean_ = np.mean ( X ) self.std_ = np.std ( X ) return self def predict ( self , X ) : # return sign ( self.predict ( inputs ) ) X = ...
Custom scikit-learn scorer ca n't access mean after fit
Python
I want to use Keras Resnet50 model using OpenCV for reading and resizing the input image.I 'm using the same preprocessing code from Keras ( with OpenCV I need to convert to RGB since this is the format expected by preprocess_input ( ) ) .I get slightly different predictions using OpenCV and Keras image loading . I do ...
import numpy as npimport jsonfrom tensorflow.keras.applications.resnet50 import ResNet50from tensorflow.keras.preprocessing import imagefrom tensorflow.keras.applications.resnet50 import preprocess_input , decode_predictionsimport cv2model = ResNet50 ( weights='imagenet ' ) img_path = '/home/me/squirle.jpg ' # Keras pr...
Resnet50 produces different prediction when image loading and resizing is done with OpenCV
Python
I want to be able to do something like : In other words , is there a hashable equivalent for Counter ? Note that I ca n't use frozenset since I have repeated elements that I want to keep in the key.Edit : In my actual application , the objects in foo may not be comparable with each other so the list can not be sorted .
foo = Counter ( [ 'bar ' , 'shoo ' , 'bar ' ] ) tmp = { } tmp [ foo ] = 5
Unordered list as dict key
Python
I have 2 models that look like this : models.pyThen in the admin , I have inlined the related models to make it easy to make changes regardless of the object type you have open.admin.pyHowever , if you add a Client to a Deal and then open the Client detail page , the corresponding deal does not appear . Is there someth...
class Client ( models.Model ) : deal = models.ManyToManyField ( 'Deal ' , related_name= '' clients '' ) class Deal ( models.Model ) : client = models.ManyToManyField ( Client , related_name= '' deals '' ) class ClientInline ( admin.TabularInline ) : model = Deal.client.throughclass DealAdmin ( admin.ModelAdmin ) : inli...
Django related model not updating related object in admin
Python
I am trying to implement a series of statistical operations , and I need help vectorizing my code.The idea is to extract NxN patches from two images , the compute a distance metric between these two patches.To do this , first I construct the patches with the following loops : This takes about 10 seconds to complete , a...
params = [ ] for i in range ( 0 , patch1.shape [ 0 ] ,1 ) : for j in range ( 0 , patch1.shape [ 1 ] ,1 ) : window1 = np.copy ( imga [ i : i+N , j : j+N ] ) .flatten ( ) window2 = np.copy ( imgb [ i : i+N , j : j+N ] ) .flatten ( ) params.append ( ( window1 , window2 ) ) print ( f '' We took { time ( ) - t0:2.2f } secon...
Advice on vectorizing block-wise operations in Numpy
Python
This one has me entirely baffled.This code works perfectly with the collections line commented out . However , when I comment out the row = dict line and remove the comment from the collections line things get very strange . There are about 4 million of these rows being generated and appended to asset_hist.So , when I ...
asset_hist = [ ] for key_host , val_hist_list in am_output.asset_history.items ( ) : for index , hist_item in enumerate ( val_hist_list ) : # row = collections.OrderedDict ( [ ( `` computer_name '' , key_host ) , ( `` id '' , index ) , ( `` hist_item '' , hist_item ) ] ) row = { `` computer_name '' : key_host , `` id '...
Python OrderDict sputtering as compared to dict ( )
Python
It is well known , that small bytes-objects are automatically `` interned '' by CPython ( similar to the intern-function for strings ) . Correction : As explained by @ abarnert it is more like the integer-pool than the interned strings.Is it possible to restore the interned bytes-objects after they have been corrupted ...
% % cythondef do_bad_things ( ) : cdef bytes b=b ' a ' cdef const unsigned char [ : ] safe=b cdef char *unsafe= < char * > & safe [ 0 ] # who needs const and type-safety anyway ? unsafe [ 0 ] =98 # replace through ` b ` import ctypesimport sysdef do_bad_things ( ) : b = b ' a ' ; ( ctypes.c_ubyte * sys.getsizeof ( b ) ...
Is it possible to restore corrupted “ interned ” bytes-objects
Python
Here is some code I wrote for parallelizing the creation of a dictionaryparallelize.pyHere is the output for size 1 mil with threshold 1 milHere is output for size = 10mil with threshold 1 milHere is the output for size 100 mil with threshold 10 mil , the worst part here is even before the combining , the map_async sti...
if __name__ == `` __main__ '' : import time from multiprocessing import Pool def assign_dict ( alist ) : return { x : x for x in alist } my_dict = { } size = 10000000 threshold=10000000 my_list=list ( range ( size ) ) start=time.time ( ) my_dict=assign_dict ( my_list ) end=time.time ( ) print ( `` check seq '' , end-st...
Python3 parallel code via multiprocessing.pool is slower than sequential code
Python
I am building a Python utility that will involve mapping integers to word strings , where many integers might map to the same string . From my understanding , Python interns short strings and most hard-coded strings by default , saving memory overhead as a result by keeping a `` canonical '' version of the string in a ...
import systop = 10000non1 = [ ] non2 = [ ] for i in range ( top ) : s1 = ' { :010d } '.format ( i ) s2 = ' { :010d } '.format ( i ) non1.append ( s1 ) non2.append ( s2 ) same = Truefor i in range ( top ) : same = same and ( non1 [ i ] is non2 [ i ] ) print ( `` non : `` , same ) # prints Falsedel non1 [ : ] del non2 [ ...
In Python , why do separate dictionary string values pass `` in '' equality checks ? ( string Interning Experiment )
Python
Suppose you use a transaction to process a Stripe payment and update a user entity : It is possible that the Stripe API call succeeds but that the put fails because of contention . The user would then be charged , but his account would n't reflect the payment.You could pull the Stripe API call out of the transaction an...
@ ndb.transactionaldef process_payment ( user_key , amount ) : user = user_key.get ( ) user.stripe_payment ( amount ) # API call to Stripe user.balance += amount user.put ( )
GAE/P : Transaction safety with API calls
Python
Given a list [ 2,8,13,15,24,30 ] , all the elements of which are supposed to be in range ( 31 ) . Now I want to slice it into 3 lists , first list with numbers from 0 to 10 , the second one with numbers from 11 to 20 , and the others into the rest.Here is my ugly code : I do n't think this is a good way to do it . Any ...
numbers = [ 2,8,13,15,24,30 ] mylist = [ [ ] , [ ] , [ ] ] # I hate this the most ... for i in numbers : if i < = 10 : mylist [ 0 ] .append ( i ) elif i > 10 and i < = 20 : mylist [ 1 ] .append ( i ) else : mylist [ 2 ] .append ( i ) print mylist
Elegant way to slice a list with a condition
Python
Consider the following session . How are the differences explained ? I thought that a += b is a syntactical sugar of ( and thus equivalent to ) a = a + b . Obviously I 'm wrong.Thank you
> > > import numpy as np > > > a = np.arange ( 24 . ) .reshape ( 4,6 ) > > > print a [ [ 0 . 1 . 2 . 3 . 4 . 5 . ] [ 6 . 7 . 8 . 9 . 10 . 11 . ] [ 12 . 13 . 14 . 15 . 16 . 17 . ] [ 18 . 19 . 20 . 21 . 22 . 23 . ] ] > > > for line in a : ... line += 100 ... > > > print a # a has been changed [ [ 100 . 101 . 102 . 103 . ...
Processing data by reference or by value in python
Python
For example : But os.__dict__ shows there is a __dict__ attribute .
> > > import os > > > '__dict__ ' in dir ( os ) False
Why does dir of a module show no __dict__ ? ( python )
Python
given two general numpy 1-d arrays ( no guarantees about values whatsoever ) , I need to check if one is a sub-array of the other.It 's short and easy to do by casting to strings , but probably not the most efficient : is there an efficient builtin/native numpy way to do this ?
import numpy as npdef is_sub_arr ( a1 , a2 ) : return str ( a2 ) .strip ( ' [ ] ' ) in str ( a1 ) .strip ( ' [ ] ' ) arr1 = np.array ( [ 9 , 1 , 3 , 2 , 7 , 2 , 7 , 2 , 8 , 5 ] ) arr2 = np.array ( [ 3 , 2 , 7 , 2 ] ) arr3 = np.array ( [ 1,3,7 ] ) print ( is_sub_arr ( arr1 , arr2 ) ) # Trueprint ( is_sub_arr ( arr1 , ar...
Numpy : check if 1-d array is sub-array of another
Python
I look up online and know that list.pop ( ) has O ( 1 ) time complexity but list.pop ( i ) has O ( n ) time complexity . While I am writing leetcode , many people use pop ( i ) in a for loop and they say it is O ( n ) time complexity and in fact it is faster than my code , which only uses one loop but many lines in tha...
class Solution ( object ) : def removeDuplicates ( self , nums ) : `` '' '' : type nums : List [ int ] : rtype : int `` '' '' left , right = 0 , 0 count = 1 while right < len ( nums ) -1 : if nums [ right ] == nums [ right+1 ] : right += 1 else : nums [ left+1 ] =nums [ right+1 ] left += 1 right += 1 count += 1 return ...
Python list.pop ( i ) time complexity ?
Python
I want to use a function f ( x ) in python . Something like ax^2 + bx + c ( polynomials ) . I want to do that using a for loop and a list . This is what I have so far : for example : when I fill in f ( [ 5,2,3 ] ,5 ) I have to get:3*5^0 + 2*5^1 + 5*5^2 . Does somebody know how I can change my code so the output will be...
def f ( a , x ) : for i in range ( 0 , len ( a ) ) : i = ( [ a ] *x**i ) print ( i )
Using a normal function f ( x ) in python
Python
I am using django-haystack and I am trying to implement a way to append the page number to a pdf link in order to open it in the specific page . My goal is to open the pdf in the page where the first hit is found . I know the position of the hit in my document and the position where the page changes . For example i kno...
from django.shortcuts import renderfrom haystack.utils.highlighting import Highlighterdef getPage ( request ) : pos = Highlighter.getPos ( ) print ( pos ) return render ( request , 'search/_result_object.html ' , { 'pos ' : pos } ) < ul > { % for element in pos % } < li > { { element } } < /li > { % endfor % } < /ul >
Django pass Haystack highlighter result to a view
Python
I understand that the python builtin id ( ) returns an ID that is unique for the lifetime of an object . Objects with non-overlapping lifetimes , I understand , can end up with the same ID . However , I am trying to understand this rather confusing behavior : And in fact across multiple interpreter instances , the beha...
> > > id ( matplotlib.image.BboxImage.set_cmap ) 4424372944 > > > id ( numpy.ma.core.MaskedArray.sum ) 4424372944 Mac : ~ $ python2.7 -c `` import matplotlib.image ; import numpy ; print id ( matplotlib.image.BboxImage.set_cmap ) , id ( numpy.ma.core.MaskedArray.sum ) '' 4343186208 4343186208Mac : ~ $ python2.7 -c `` i...
Repeatable id clashes on python objects
Python
I 'm trying to convert numbers to excel column letters.Code : Desired output : Actual output :
def num2col ( num ) : letters = `` while num : mod = num % 26 num = num // 26 letters += chr ( mod + 64 ) return `` .join ( reversed ( letters ) ) print num2col ( 25 ) , num2col ( 26 ) , num2col ( 27 ) print num2col ( 51 ) , num2col ( 52 ) , num2col ( 53 ) print num2col ( 77 ) , num2col ( 78 ) , num2col ( 79 ) Y Z AAAY...
Python character function , where is the `` Z '' ?
Python
I 've got some code ( that someone else wrote ) : which I think could be re-written as : This would of course fail if someone passed in attrs=None , but is that something to be expected ? Is there a penalty for the attrs= { } ( extra wasted dict creation ? ) I 'm still too new to python to answer these questions , but ...
def render ( self , name , value , attrs=None ) : if not attrs : attrs = { } attrs.update ( { 'class ' : 'ui-autocomplete-input ' } ) def render ( self , name , value , attrs= { } ) : attrs.update ( { 'class ' : 'ui-autocomplete-input ' } ) > > > def x ( attrs= { } ) : ... attrs.update ( { ' a ' : ' b ' } ) ... print a...
Best way to deal with default params in Python ?
Python
I try to concatenate the following strings to a pathleads to To get to the desired outcome I need to remove the first forward slash in the variable lpIs there a more elegant to do it as I do not want to parse all identifiers for a forwarding slash in the beginning ?
mr = `` /mapr '' cn = `` 12.12.12 '' lp = `` /data/dir/ '' vin = `` var '' os.path.join ( mr , cn , lp , vin ) '/data/dir/var ' lp = `` data/dir/ '' os.path.join ( mr , cn , lp , vin ) '/mapr/12.12.12/data/dir/var '
connecting multiple strings to path in python with slashes
Python
I have a dictionary that needs to be sorted . I understand that a dictionary can not be sorted , so I am building a list to perform a sort based upon the index . The problem I am having is that there are duplicate values across multiple keys ; also , the values can be multiple lists.Dictionary : I need to be able to so...
my_dict = { ' 1 ' : [ 'Red ' , 'McDonald\'s ' ] , ' 2 ' : [ [ 'Orange ' , 'Wendy\'s ' ] , [ 'Purple ' , 'Cookout ' ] ] , ' 3 ' : [ 'Yellow ' , 'Longhorn ' ] , ' 4 ' : [ 'Green ' , 'Subway ' ] , ' 5 ' : [ 'Blue ' , 'Chipotle ' ] , ' 6 ' : [ 'Indigo ' , 'Taco Bell ' ] , ' 7 ' : [ [ 'Violet ' , 'Steak n Shake ' ] , [ 'Dar...
Sorting a dictionary with multiple sized values
Python
I have a greyscale image in numpy array format ( standard OpenCV format ) . Normal image , uint8 , all values between 0 and 255 . When I run : I get : But when I run : I get : And what 's really weird is that if I resize the pyplot image window , those line artifacts change in width . What 's up with this ? I have no i...
import cv2cv2.imshow ( `` , image ) from matplotlib import pyplotpyplot.imshow ( image , cmap= '' gray '' ) pyplot.show ( )
Artifacts in PyPlot vs. OpenCV imshow
Python
How can I append or insert a class attribute into its sub-elements , but only for direct children and then to repeat it for the next class and sub-elements.In the docs it is referenced here pyquery manipulatingSampleSo for each race classappend it into its sub-elements called nomination as raceid so nomination becomesT...
> > > d = pq ( ' < html > < body > < div id= '' test '' > < a href= '' http : //python.org '' > python < /a > ! < /div > < /body > < /html > ' ) > > > p.prependTo ( d ( ' # test ' ) ) [ < p # hello.hello > ] > > > d ( ' # test ' ) .html ( ) u ' < p class= '' hello '' .. < meeting id= '' 42499 '' barriertrial= '' 0 '' v...
PyQuery How do I append and rename an element into each of its subelements
Python
The Python Language Reference specifies object.__await__ as follows : object.__await__ ( self ) Must return an iterator . Should be used to implement awaitable objects . For instance , asyncio.Future implements this method to be compatible with the await expression.That 's it . I find this specification very vague and ...
import asyncioclass Spam : def __await__ ( self ) : yield from range ( 10 ) async def main ( ) : await Spam ( ) asyncio.run ( main ( ) ) RuntimeError : Task got bad yield : 0
Precise specification of __await__
Python
For example I get following input : And I need to get following list : Here is my code , but I do n't know how to deal with minuses.warning : I can not use any libraries except re and math .
-9x+5x-2-4x+5 [ '-9x ' , '5x ' , '-2 ' , '-4x ' , ' 5 ' ] import retext = '-3x-5x+2=9x-9'text = re.split ( r'\W ' , text ) print ( text )
How to split algebraic expressions in a string using python ?
Python
I have a table with keywords associated with articles , looks like this : I need to get a sort of a pivot table : It means , that the pair ( A , B ) occurs in two articles ( # 1 and # 2 ) , the pair ( A , C ) occurs in just one article ( # 1 ) , etc.What is the most Pythonic way to do that ? I tried Pandas pivot tables...
article_id keyword1 A1 B1 C2 A2 B2 D3 E3 F3 D A B C D E FA - 2 1 1 0 0B - - 1 1 0 0C - - - 0 0 0D - - - - 1 1E - - - - - 1F - - - - - -
Cross tabulate counts between pairs of keywords per group with pandas
Python
I would like to vectorize this NumPy operation : where idx contains axis-0 index to an x slice . Is there some simple way to do this ?
for j in range ( yt ) : for i in range ( xt ) : y [ j , i ] = x [ idx [ j , i ] , j , i ]
NumPy : Evaulate index array during vectorized assignment
Python
I am trying to calculate the # of days between failures . I 'd like to know on each day in the series the # of days passed since the last failure where failure = 1 . There may be anywhere from 1 to 1500 devices.For Example , Id like my dataframe to look like this ( please pull data from url in the second code block . T...
date device failure elapsed 10/01/2015 S1F0KYCR 1 0 10/07/2015 S1F0KYCR 1 7 10/08/2015 S1F0KYCR 0 0 10/09/2015 S1F0KYCR 0 0 10/17/2015 S1F0KYCR 1 11 10/31/2015 S1F0KYCR 0 0 10/01/2015 S8KLM011 1 0 10/02/2015 S8KLM011 1 2 10/07/2015 S8KLM011 0 010/09/2015 S8KLM011 0 010/11/2015 S8KLM011 0 010/21/2015 S8KLM011 1 20 url =...
Date Difference Between Two Device Failures
Python
Just curious if there is a way to both print and return within one function without assigning the output to variable ? Consider this code : Is there a way to reference that variable stored for the purpose of return statement ?
def secret_number ( secret_number_range ) : return random.randrange ( 1 , secret_number_range + 1 )
Returning and printing without assigning to variable ?
Python
I have an array , given number of items in a group and number of groups , I need to print the array cyclically in a loop.Array- [ 1,2,3,4,5,6 ] Group- 4Iterations- 7Output should be :
[ ' 1 ' , ' 2 ' , ' 3 ' , ' 4 ' ] [ ' 5 ' , ' 6 ' , ' 1 ' , ' 2 ' ] [ ' 3 ' , ' 4 ' , ' 5 ' , ' 6 ' ] [ ' 1 ' , ' 2 ' , ' 3 ' , ' 4 ' ] [ ' 5 ' , ' 6 ' , ' 1 ' , ' 2 ' ] [ ' 3 ' , ' 4 ' , ' 5 ' , ' 6 ' ] [ ' 1 ' , ' 2 ' , ' 3 ' , ' 4 ' ]
Display grouped list of items from python list cyclically
Python
Input data is a 2D array ( timestamp , value ) pairs , ordered by timestamp : I want to find time windows where the value exceeds a threshold ( eg . > =4 ) . Seems I can do the threshold part with a boolean condition , and map back to the timestamps with np.extract ( ) : But from that I need the first and last timestam...
np.array ( [ [ 50 , 51 , 52 , 53 , 54 , 55 , 56 , 57 , 58 , 59 , 60 , 61 , 62 , 63 , 64 , 65 , 66 ] , [ 2 , 3 , 5 , 6 , 4 , 2 , 1 , 2 , 3 , 4 , 5 , 4 , 3 , 2 , 1 , 2 , 3 ] ] ) > > > a [ 1 ] > = 4array ( [ False , False , True , True , True , False , False , False , False , True , True , True , False , False , False , F...
Threshold numpy array , find windows
Python
I have defined the following class : And the following code works : with output : But this does not : It gives the following error : Which is because the point class is being fed into the int mul function , I 'm assuming . How can I keep the definition of point contained in the Point class and still have 3*y return the...
class Point ( object ) : def __repr__ ( self ) : return `` ( `` +str ( self.x ) + '' , '' +str ( self.y ) + '' ) '' def __init__ ( self , x , y ) : self.x = x self.y = y def __add__ ( self , point ) : return Point ( self.x+point.x , self.y+point.y ) def __sub__ ( self , point ) : return Point ( self.x-point.x , self.y-...
Overiding __mul__ in two dimensional vector class to preserve commutivity
Python
Can I implement a generic descriptor in Python in a way it will support/respect/understand inheritance hierarchy of his owners ? It should be more clear in the code : gist - almost the same code snippet on gist
from typing import ( Generic , Optional , TYPE_CHECKING , Type , TypeVar , Union , overload , ) T = TypeVar ( `` T '' , bound= '' A '' ) # noqaclass Descr ( Generic [ T ] ) : @ overload def __get__ ( self : `` Descr [ T ] '' , instance : None , owner : Type [ T ] ) - > `` Descr [ T ] '' : ... @ overload def __get__ ( s...
typing : How to bind owner class to generic descriptor ?
Python
Running : Books.referTable being a data descriptor is not shadowed by book.__dict__ [ 'referTable ' ] : The property ( ) function is implemented as a data descriptor . Accordingly , instances can not override the behavior of a property.To shadow it , instead of property built-in descriptor i must use my own descriptor ...
class Books ( ) : def __init__ ( self ) : self.__dict__ [ 'referTable ' ] = 1 @ property def referTable ( self ) : return 2book = Books ( ) print ( book.referTable ) print ( book.__dict__ [ 'referTable ' ] ) vic @ ubuntu : ~/Desktop $ python3 test.py 21
Built-in non-data version of property ?
Python
The problem is a list of room numbers and guest details I ripped straight from a txt file that needs to be put into a dictionary with the room number as the keys and the details as the values.The guest list is literally a list , each item represents room number , guest name , arrival , departure dates . Rooms without a...
nlist = [ [ '101 ' ] , [ '102 ' ] , [ '103 ' ] , [ '201 ' , ' John Cleese ' , ' 5/5/12 ' , ' 5/7/12 ' ] , [ '202 ' ] , [ '203 ' , ' Eric Idle ' , ' 7/5/12 ' , ' 8/7/12 ' ] , [ '301 ' ] , [ '302 ' ] , [ '303 ' ] ] guests = { } for i in nlist : if len ( i ) == 1 : key = i [ 0 ] guests [ key ] = None else : key = i [ 0 ] ...
How do I sort a dictionary ?
Python
This code works but I was wondering if there is a more pythonic way for writing it.word_frequency is a dictionary of lists , e.g . : Is there a more elegant way of writing this loop ?
word_frequency = { 'dogs ' : [ 1234 , 4321 ] , 'are ' : [ 9999 , 0000 ] , 'fun ' : [ 4389 , 3234 ] } vocab_frequency = [ 0 , 0 ] # stores the total times all the words used in each classfor word in word_frequency : # that is not the most elegant solution , but it works ! vocab_frequency [ 0 ] += word_frequency [ word ]...
Pythonic way of executing a loop on a dictionary of lists
Python
I have the following directory structurewith main_code.py just importing mylib : and mylib.py just importing time : Now it turns out that mylib.py imports libs/time.py and not the built-in standard library time . Is there any way to get the 'normal ' behavior , i.e . that mylib.py imports the built-in standard library ...
main_code.pylibs/ __init__.py mylib.py time.py from libs import mylib import timeprint time
How to import standard library instead of same-named module in module path
Python
I have an enum for which some of the members are deprecated : How do it get the following behavior : When somebody writes Foo.BAR , everything behaves normallyWhen somebody writes Foo.BAZ , a DeprecationWarning is issued using warnings.warn ( `` BAZ is deprecated '' , DeprecationWarning ) . Afterwards everything behave...
from enum import Enumclass Foo ( Enum ) : BAR = `` bar '' BAZ = `` baz '' # deprecated
How do I detect and invoke a function when a python enum member is accessed
Python
Can someone please explain this behaviour :
> > > a = { 'hello ' : 'world ' , 'good ' : 'food ' } > > > b = [ 1,2 ] > > > b = b + aTraceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > TypeError : can only concatenate list ( not `` dict '' ) to list > > > b += a > > > b [ 1 , 2 , 'good ' , 'hello ' ] < -- - Why do the keys get added...
Why does += operator work differently than + and assign operator for python dictionary ?
Python
Suppose I have a dataframe of which one column is a list ( of a unknown values and length ) for example : I came across this solution but it isnt what I am looking for.How best to extract a Pandas column containing lists or tuples into multiple columnsin theory the resulting df would look likeSee above
df = pd.DataFrame ( { 'messageLabels ' : [ [ 'Good ' , 'Other ' , 'Bad ' ] , [ 'Bad ' , 'Terrible ' ] ] } ) messageLabels | Good| Other| Bad| Terrible -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [ 'Good ' , 'Other ' , 'Bad ' ] | True| True |True| False -- -- -- -- -- -- -- -- -- ...
How do I perform One Hot Encoding on lists in a pandas column ?
Python
In Python the symbol int is used both as a type and a built-in function . But when I use int in the REPL , or ask for its type , the REPL tells me it is a type.This is fine , but int is also a built-in function : it is listed in the table of built-in functions right in the Python documentation.Other built-in functions ...
> > > int < type 'int ' > > > > type ( int ) < type 'type ' > > > > abs < built-in function abs > > > > type ( abs ) < type 'builtin_function_or_method ' > > > > map ( int , [ `` 4 '' , `` 2 '' ] ) [ 4 , 2 ] id ( int )
Does Python assume a symbol is a type before trying to see if it is a function ?
Python
Now , when I enter : I get : which does n't make a whole lot of sense to me . Can anybody explain that simply ?
two_d = np.array ( [ [ 0 , 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 , 9 ] , [ 10 , 11 , 12 , 13 , 14 ] , [ 15 , 16 , 17 , 18 , 19 ] , [ 20 , 21 , 22 , 23 , 24 ] ] ) first = np.array ( ( True , True , False , False , False ) ) second = np.array ( ( False , False , False , True , True ) ) two_d [ first , second ] array ( [ 3,9 ...
Unexpected behaviour when indexing a 2D np.array with two boolean arrays
Python
In the code below , I import a saved sparse numpy matrix , created with python , densify it , add a masking , batchnorm and dense ouptput layer to a many to one SimpleRNN . The keras sequential model works fine , however , I am unable to use shap . This is run in Jupyter lab from Winpython 3830 on a Windows 10 desktop ...
from sklearn.model_selection import train_test_splitimport tensorflow as tffrom tensorflow.keras.models import Sequentialimport tensorflow.keras.backend as Kbfrom tensorflow.keras import layersfrom tensorflow.keras.layers import BatchNormalizationfrom tensorflow import keras as Kimport numpy as npimport shapimport rand...
Error using shap with SimpleRNN sequential model
Python
How can I write a function `` fmap '' , with this properties : ( I search a kind of `` fmap '' in haskell , but in python3 ) .I have a very ugly solution , but there is certainly a solution more pythonic and generic ? :
> > > l = [ 1 , 2 ] ; fmap ( lambda x : 2*x , l ) [ 2 , 4 ] > > > l = ( 1 , 2 ) ; fmap ( lambda x : 2*x , l ) ( 2 , 4 ) > > > l = { 1 , 2 } ; fmap ( lambda x : 2*x , l ) { 2 , 4 } def fmap ( f , container ) : t = container.__class__.__name__ g = map ( f , container ) return eval ( f '' { t } ( g ) '' )
How can I write a function fmap that returns the same type of iterable that was inputted ?
Python
I have a mercurial hook like so : with the code looking like this : but this hook runs on commands that use the commit logic to do something else , in my case hg shelve . is there a way to get the command that the user has input to avoid running the hook on that command ? perhaps something like this :
[ hooks ] pretxncommit.myhook = python : path/to/file : myhook def myhook ( ui , repo , **kwargs ) : # do some stuff def myhook ( ui , repo , command , **kwargs ) : if command is `` hg shelve '' return 0 # do some stuff
ignore certain mercurial commands in mercurial hook
Python
When i changed two words in a string with other two words using re.sub i got the output . But when i tried that with numbers output is not coming correctlyi do n't know why this happens could u please tel me how to use this Thanks in advance
> > > import re > > > a='this is the string i want to change ' > > > re.sub ( ' ( .* ) is ( .* ) want ( . * ) ' , '\\1 % s\\2 % s\\3 ' % ( 'was ' , 'wanted ' ) , a ) 'this was the string i wanted to change ' > > > re.sub ( ' ( .* ) is ( .* ) want ( . * ) ' , '\\1 % s\\2 % s\\3 ' % ( 'was ' , '12345 ' ) , a ) 'this was\...
Multiple substitutions of numbers in string using regex python