lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | I 'm wondering what techniques people use for simplifying the 'size ' of code used for unit testing . For example I was trying to marshal an object of the class and testing the marshal'ed object ( but this presumes marshal is working correctly ) .Consider the classand then the marshaling based , list based , and normal... | import unittestclass Nums ( object ) : def __init__ ( self , n1_ , n2_ , n3_ ) : self.n1 , self.n2 , self.n3 = n1_ , n2_ , n3_def marshal ( self ) : return `` n1 % g , n2 % g , n3 % g '' % ( self.n1 , self.n2 , self.n3 ) class NumsTests ( unittest.TestCase ) : def setUp ( self ) : self.nu = Nums ( 10,20,30 ) def test_i... | Is there a minimal style for unittests in Python ? |
Python | On my machine , the values from PYTHONPATH appear to get inserted in sys.path : beginning at index 1order preservedde-duplicatedFor example , with PYTHONPATH=/spam : /eggs : /spam and then checking in python -m site , I get a result like : It seems to be the same behaviour on Python 2 and Python 3 . The question is , h... | sys.path = [ something , '/spam ' , '/eggs ' , more , stuff , after ] | Is it reliable and documented how PYTHONPATH populates the sys.path ? |
Python | I need to build a generator and I was looking for a way to shorten this for loop into a single line . I tried enumerate but that did not work . | counter=0for element in string : if function ( element ) : counter+=1 yield counter else : yield counter | Is there any way to shorten this Python generator expression ? |
Python | This code gives shp== ( 5,4,4,3 ) I do n't understand why . How can a larger array be output ? makes no sense to me and would love an explanation . | a = np.zeros ( ( 5,4,3 ) ) v = np.ones ( ( 5 , 4 ) , dtype=int ) data = a [ v ] shp = data.shape | Indexing numpy array with index array of lower dim yields array of higher dim than both |
Python | I have a list which contains many lists and in those there 4 tuples.I want them in two separate lists like : my attempt was using the map function for this.but this is giving me an error : | my_list = [ [ ( 12 , 1 ) , ( 10 , 3 ) , ( 4 , 0 ) , ( 2 , 0 ) ] , [ ( 110 , 1 ) , ( 34 , 2 ) , ( 12 , 1 ) , ( 55 , 3 ) ] ] my_list2 = [ 12,10,4,2,110,34,12,55 ] my_list3 = [ 1,3,0,0,1,2,1,3 ] my_list2 , my_list3 = map ( list , zip ( *my_list ) ) ValueError : too many values to unpack ( expected 2 ) | How to make two lists out of two-elements tuples that are stored in a list of lists of tuples |
Python | models.pymy forms.pyOn my code above my form look like this : Hovewer that not what I want since possible multiple name , and I know that value come from def __str__ on my model.How to add another str so on my field will be : Its contain id + name on dropdown , or also other information . | class User ( models.Model ) : id = models.CharField ( max_length=255 ) name = models.CharField ( max_length=255 ) desc = models.TextField ( ) created_at = models.DateTimeField ( auto_now=True ) updated_at = models.DateTimeField ( auto_now_add=True , null=True ) def __str__ ( self ) : return self.user.name class PostsFo... | Django Multi value on ModelMultipleChoiceField |
Python | I need to make a connection to an API using a complicated authentication process that I do n't understand.I know it involves multiple steps and I have tried to mimic it , but I find the documentation to be very confusing ... The idea is that I make a request to an endpoint which will return a token to me that I need to... | import time , base64 , hashlib , hmac , urllib.request , jsonapi_nonce = bytes ( str ( int ( time.time ( ) *1000 ) ) , `` utf-8 '' ) api_request = urllib.request.Request ( `` https : //www.website.com/getToken '' , b '' nonce= % s '' % api_nonce ) api_request.add_header ( `` API-Key '' , `` API_PUBLIC_KEY '' ) api_requ... | Authentication with hashing |
Python | I have a df as I am looking for a pattern `` ABD followed by CDE without having event B in between them `` For example , The output of this df will be : This pattern can be followed multiple times for a single ID and I want find the list of all those IDs and their respective count ( if possible ) . | Id Event SeqNo 1 A 1 1 B 2 1 C 3 1 ABD 4 1 A 5 1 C 6 1 A 7 1 CDE 8 1 D 9 1 B 10 1 ABD 11 1 D 12 1 B 13 1 CDE 14 1 A 15 Id Event SeqNo 1 ABD 4 1 A 5 1 C 6 1 A 7 1 CDE 8 | Looking for a sequential pattern with condition |
Python | I am having an issue where my bullets dont look like they are coming out of my gun they look like they are coming out of the players body VIDEO as you can see in the video it shoots somewhere else or its the gun its the same thing for the left side it shoots good going up but it shoots bad going down VIDEOI tried angel... | class projectile ( object ) : def __init__ ( self , x , y , dirx , diry , color ) : self.x = x self.y = y self.dirx = dirx self.diry = diry self.slash = pygame.image.load ( `` round.png '' ) self.slash = pygame.transform.scale ( self.slash , ( self.slash.get_width ( ) //2 , self.slash.get_height ( ) //2 ) ) self.rect =... | How Can I Make My Bullets Look LIke They Are Comming Out Of My Guns Tip ? |
Python | in this code : the output is `` function inner at 0x107dea668 '' if i change i to other letter , for example : the output is `` 4 '' Answeri : function inner at 0x101344d70in loop : 4315172208in inner:4315172208in inner:4315172208in inner:4315172208call : function inner at 0x101344d70 i : function inner at 0x101344de8i... | results = [ ] for i in [ 1 , 2 , 3 , 4 ] : def inner ( y ) : return i results.append ( inner ) for i in results : print i ( None ) results = [ ] for i in [ 1 , 2 , 3 , 4 ] : def inner ( y ) : return i results.append ( inner ) for j in results : print j ( None ) results = [ ] for i in [ 1 , 2 , 3 , 4 ] : def inner ( y )... | Why do different variable names get different results(python2.7) ? |
Python | Given that we can easily convert between product of items in list with sum of logarithm of items in list if there are no 0 in the list , e.g : How should we handle cases where there are 0s in the list and in Python ( in a programatically and mathematically correct way ) ? More specifically , how should we handle cases ... | > > > from operator import mul > > > pn = [ 0.4 , 0.3 , 0.2 , 0.1 ] > > > math.pow ( reduce ( mul , pn , 1 ) , 1./len ( pn ) ) 0.22133638394006433 > > > math.exp ( sum ( 0.25 * math.log ( p ) for p in pn ) ) 0.22133638394006436 > > > pn = [ 0.4 , 0.3 , 0 , 0 ] > > > math.pow ( reduce ( mul , pn , 1 ) , 1./len ( pn ) ) ... | Resolving Zeros in Product of items in list |
Python | How can I change every element in a DataFrame with hierarchical indexing ? For example , maybe I want to convert strings into floats : I tried this : As you can see , it changes the hierarchical indexing quite a bit . How can I avoid this ? Or maybe there is a better way.Thanks | from pandas import DataFramef = DataFrame ( { ' a ' : [ ' 1,000 ' , ' 2,000 ' , ' 3,000 ' ] , ' b ' : [ ' 2,000 ' , ' 3,000 ' , ' 4,000 ' ] } ) f.columns = [ [ 'level1 ' , 'level1 ' ] , [ 'item1 ' , 'item2 ' ] ] fOut [ 152 ] : level1 item1 item20 1,000 2,0001 2,000 3,0002 3,000 4,000 def clean ( group ) : group = group... | Changing data in a dataframe with hierarchical indexing |
Python | I noticed a strange behavior of Python 2.7 logic expressions : and with True in place of FalseAre there any rules when Python convert logical statement to integer ? Why does it show sometimes 0 insted of False and 1 insted of True ? What is more , why does it return this ? | > > > 0 and False0 > > > False and 0False > > > 1 and FalseFalse > > > False and 1False > > > 0 and True0 > > > True and 00 > > > 1 and TrueTrue > > > True and 11 > > > '' test '' or `` test '' 'test ' | Strange conversion in Python logic expressions |
Python | I am trying to create a directed graph upon this dataset : To create an undirected graph with my data above , I did : I would like to add date information in the graph , in order to create a directed graph : the ID who has the earliest date is the source.So for example : Julie and Mirk are linked together : a directed ... | ID Link_to Label Date Size0 mary NaN 0 2020-01-23 11 Julie Mirk 1 2020-02-27 121 Julie Mark 1 2020-02-27 121 Julie Sarah 1 2020-02-27 121 Chris Mirk 1 2020-01-26 12 ... ... ... ... ... ... ... 50 Mirk Chris 0 2020-04-29 451 Mark NaN 0 2020-04-29 352 Greg NaN 0 2020-04-27 253 Luke Matt 0 2020-04-08 154 Sarah James 0 202... | How to create a directed graph ? |
Python | I am trying to write a program in Python , but I am stuck in this piece of code : It gives me value 1 instead of 5 . Actually the function I am trying to write is a little bit more complicated , but the problem is actually the same , it does n't give me the right result.v is a list of values smaller than 1 and b has an... | def function ( ) : a= [ 3,4,5,2,4 ] b=1 c=0 for x in range ( 5 ) : if a [ x-1 ] > b : c=c+1 return cprint ( function ( ) ) def result ( ) : r= [ 0 ] *len ( y ) a=2 b=an_integer while b > 0 : for x in range ( len ( y ) ) : if y [ x-1 ] > 1/a and b > 0 : r [ x-1 ] =r [ x-1 ] +1 b=b-1 a=a+1 return r print ( result ( ) ) | Python programming beginner difficulties |
Python | I have to find the best way to create a new Dataframe using existing DataFrame.Look at this link to have full code : jdoodle.com/a/xKPI have this kind of DataFrame : And need to have this result : Currently , I create a function who return DataFrame with one stat : After I make an .append with the function like this : ... | df = pd.DataFrame ( { 'length ' : [ 112 , 214 , 52,88 ] , 'views ' : [ 10000 , 50000 , 25000,5000 ] , 'click ' : [ 55 , 64 , 85,9 ] } , index = [ 'id1 ' , 'id2 ' , 'id3 ' , 'id4 ' ] ) click length viewsid1 55 112 10000id2 64 214 50000id3 85 52 25000id4 9 88 5000 type_stat statid1 click 55id2 click 64id3 click 85id4 cli... | Best way to add pandas DataFrame column to row |
Python | Python Shell - shell.appspot.com is acting weird ? or am I missing something ? But the below result is expectedAnd also same with the dictionary data type.Thanks , Abhinay | Google App Engine/1.3.0Python 2.5.2 ( r252:60911 , Apr 7 2009 , 17:42:26 ) [ GCC 4.1.0 ] > > > mycolors = [ 'red ' , 'green ' , 'blue ' ] > > > mycolors.append ( 'black ' ) > > > print mycolors [ 'red ' , 'green ' , 'blue ' ] [ 'red ' , 'green ' , 'blue ' , 'black ' ] | is something wrong with Python Shell ( Google App ) ? |
Python | Given a module containing : How can I define a function get_defined_objects so that I can do : Right now the only solution I can imagine is to read the original module file , extract defined names with re.search ( r'^ ( ? : def|class ) ? ( \w+ ) ( ? : \s*= ) ? ' then import the module , and find the intersection with _... | import stufffrom foo import Foofrom bar import *CST = Truedef func ( ) : pass print ( get_defined_objects ( 'path.to.module ' ) ) { 'CST ' : True , 'func ' , < function path.to.module.func > } | How to get a list of all non imported names in a Python module ? |
Python | I 'm running Python 2.7.10 on a 16GB , 2.7GHz i5 , OSX 10.11.5 machine . I 've observed this phenomenon many times in many different types of examples , so the example below , though a bit contrived , is representative . It 's just what I happened to be working on earlier today when my curiosity finally piqued . You 'l... | > > > timeit ( 'unicodedata.category ( chr ) ' , setup = 'import unicodedata , random ; chr=unichr ( random.randint ( 0,50000 ) ) ' , number=100 ) 3.790855407714844e-05 > > > timeit ( 'unicodedata.category ( chr ) ' , setup = 'import unicodedata , random ; chr=unichr ( random.randint ( 0,50000 ) ) ' , number=1000 ) 0.0... | python 's ` timeit ` does n't always scale linearly with number ? |
Python | I have an image that looks equivalent to this image : . It is a series of circles on a page in a curvy line , and the line is different every time.After importing it , I was wondering if there was a way of distinguishing the colours . For the example this might be : The line has no pattern to it , and is several thousa... | from PIL import Imageim = Image.open ( `` bride.jpg '' ) [ Purple , Cyan , Purple , Cyan , Purple Cyan ... ] | Colour picking from a curvy line |
Python | I wrote a metaclass that I 'm using for logging purposes in my python project . It makes every class automatically log all activity . The only issue is that I do n't want to go into every file and have to add in : Is there a way to set the metaclass in the top level folder so that all the files underneath use that meta... | __metaclass__ = myMeta | Python : Setting the metaclass for all files in a folder |
Python | I just stumbled over what seems to be a flaw in the python syntax -- or else I 'm missing something.See this : But this is a syntax error : If you have an else clause , you have to write : But this is a syntax error : What am I missing ? Why is this so inconsistent ? | [ x for x in range ( 30 ) if x % 2 == 0 ] [ x for x in range ( 30 ) if x % 2 == 0 else 5 ] [ x if x % 2 == 0 else 5 for x in range ( 30 ) ] [ x if x % 2 == 0 for x in range ( 30 ) ] | Inconsistent comprehension syntax ? |
Python | I 'm writing a view generator for my Django project . I have a large number of models from a legacy application ( ~150 models ) , that all need the same basic CRUD operations ( providing Admin access is n't enough apparently ) .So I 'm writing a generator that returns 5 Views for each model , and of course each view ca... | def generate_views ( model_class , **kwargs ) : `` '' '' For a given model , returns a dict of generic class-based views `` '' '' # # # # Forms # Optionally generate form classes if not already provided # # # # Append these fields with either `` create_ '' or `` update_ '' to have them only # apply to that specific typ... | Defining an API for complex View generator function ( with many configurables ) |
Python | Why are the following indexing forms produce differently shaped outputs ? Almost certain I 'm missing something obvious . | a = np.zeros ( ( 5 , 5 , 5 , 5 ) ) print ( a [ : , : , [ 1 , 2 ] , [ 3 , 4 ] ] .shape ) # ( 5 , 5 , 2 ) print ( a [ : , : , 1:3 , [ 3 , 4 ] ] .shape ) # ( 5 , 5 , 2 , 2 ) | Inconsistent advanced indexing in NumPy |
Python | I have a slight problem understanding the behaviour of lists.My exercise question is : Draw a memory model showing the effect of the following statements : My thinking was that executing these statements will change the list to something like this [ 0 , [ 0 , 1 , 2 ] , 3 ] , in other words second statement will append ... | values = [ 0 , 1 , 2 ] values [ 1 ] = values [ 0 , [ ... ] , 2 ] | Assigning list to one value in that list |
Python | I had seen this test question on Pluralsight : Given these sets : What is the value of x | y ^ z ? The expected answer is : Combines the sets ( automatically discarding duplicates ) , and orders them from lowest to greatest.My questions are : What is this expression called ? Why do I get 3 different results from 3 diff... | x = { ' a ' , ' b ' , ' c ' , 'd ' } y = { ' c ' , ' e ' , ' f ' } z = { ' a ' , ' g ' , ' h ' , ' i ' } { ' a ' , ' b ' , ' c ' , 'd ' , ' e ' , ' f ' , ' g ' , ' h ' , ' i ' } { ' c ' , ' h ' , ' f ' , 'd ' , ' b ' , ' i ' , ' g ' , ' a ' , ' e ' } set ( [ ' a ' , ' c ' , ' b ' , ' e ' , 'd ' , ' g ' , ' f ' , ' i ' ... | What are these set operations , and why do they give different results ? |
Python | I have a dictionary , with this value : I would like to rename the key b to B , without it losing its second place . In Python 3.7 and higher , dictionaries preserve insertion order , so the order of the keys can be counted on and might mean something . The end result I 'm looking for is : The obvious code would be to ... | { `` a '' : 1 , `` b '' : 2 , `` c '' : 3 } { `` a '' : 1 , `` B '' : 2 , `` c '' : 3 } > > > dictionary [ `` B '' ] = dictionary.pop ( `` b '' ) { ' a ' : 1 , ' c ' : 3 , ' B ' : 2 } | How do I rename a key while preserving order in dictionaries ( Python 3.7+ ) ? |
Python | I am trying to understand the internal working of the in command and index ( ) of the list data structure.When I say : Is it traversing the whole list internally , similar to a for loop or does it use , better approaches like hashtables etc.Also the index ( ) in lists , gives an error if the item is not present in the ... | if something not in some_list : print `` do something '' | in and index function of list [ Python ] |
Python | I have a table that looks like this : Using A as the key , I 'd like to remove duplicates such that that dataframe becomes:1 is duplicated three times , the value cat occurs the most so it is recorded . there is no majority for 2 so it is considered ambiguous and removed completely . 3 remains as it has no duplicate . | A B1 cat1 cat1 dog2 illama2 alpaca3 donkey A B1 cat3 donkey | Drop duplicates based on majority rule |
Python | Inside my custom loss function I need to call a pure python function passing in the computed TD errors and some indexes . The function does n't need to return anything or be differentiated . Here 's the function I want to call : I 've tried using tf.py_function to call a wrapper function but it only gets called if it '... | def update_priorities ( self , traces_idxs , td_errors ) : `` '' '' Updates the priorities of the traces with specified indexes . '' '' '' self.priorities [ traces_idxs ] = td_errors + eps def masked_q_loss ( data , y_pred ) : `` '' '' Computes the MSE between the Q-values of the actions that were taken and the cumulat... | How to trigger a python function inside a tf.keras custom loss function ? |
Python | So , I notice that calling array [ : -1 ] is going to clone the array.Say I have a large array with like 3000 elements in it . I do n't want it to be cloned as I iterate over it ! I just want to iterate to the 2nd last one.So do I have to resort to a counter variable , or is there way to make/will array [ : -1 ] syntax... | for item in array [ : -1 ] : # do something with the item for c in range ( 0 , len ( array ) - 1 ) : # do something with array [ c ] | Python loop to [ : -1 ] |
Python | I have a list of dictionaries like in this example : I know that 'name ' exists in each dictionary ( as well as the other keys ) and that it is unique and does not occur in any of the other dictionaries in the list.I would like a nice way to access the values of 'two ' and 'one ' by using the key 'name ' . I guess a di... | listofdict = [ { 'name ' : 'Foo ' , 'two ' : 'Baz ' , 'one ' : 'Bar ' } , { 'name ' : 'FooFoo ' , 'two ' : 'BazBaz ' , 'one ' : 'BarBar ' } ] { 'Foo ' : { 'two ' : 'Baz ' , 'one ' : 'Bar ' } , 'FooFoo ' : { 'two ' : 'BazBaz ' , 'one ' : 'BarBar ' } } | Elegant way to transform a list of dict into a dict of dicts |
Python | I would like to do things like this with a for in a single line , can i do it or i have to use a filter ? | not 0 < = n < = 255 for n in [ -1 , 256 , 23 ] # True0 < = n < = 255 for n in [ 0 , 255 , 256 ] # False0 < = n < = 255 for n in [ 0 , 24 , 255 ] # True | Python3 - using for loop in a if condition |
Python | i have several nested lists , which are all permutations of each other within sublists : I want to select only those , which comply with this requirement : if sublists contains element 'd ' or ' b ' in it , it must have index 0 in that sublist.So among lists in x only must be selected , because 'd ' has index 0 in its ... | x = [ [ ' a ' , [ [ ' b ' , ' c ' , [ [ ' e ' , 'd ' ] ] ] ] ] , [ ' a ' , [ [ ' b ' , [ [ ' e ' , 'd ' ] ] , ' c ' ] ] ] , [ [ [ ' b ' , ' c ' , [ [ ' e ' , 'd ' ] ] ] ] , ' a ' ] , [ ' a ' , [ [ [ [ 'd ' , ' e ' ] ] , ' c ' , ' b ' ] ] ] , [ ' a ' , [ [ ' b ' , [ [ 'd ' , ' e ' ] ] , ' c ' ] ] ] ] [ ' a ' , [ [ ' b '... | How to specify index of specific elements in every sublist of nested list ? |
Python | Python 3.8 ( or CPython 3.8 ? ) added the warningfor the code 0 is 0.I understand the warning , and I know the difference between is and ==.However , I also know that CPython caches the object for small integers and shares it in other cases as well . ( Out of curiosity , I just checked the code ( header ) again.Small i... | SyntaxWarning : `` is '' with a literal . Did you mean `` == '' ? def sum1a ( *args ) : y = 0 for x in args : if y is 0 : y = x else : y = y + x return y def sum1b ( *args ) : y = 0 for x in args : if y == 0 : y = x else : y = y + x return y def sum1c ( *args ) : y = None for x in args : if y is None : y = x else : y =... | Is ` 0 is 0 ` always ` True ` in Python ? |
Python | My real task is to recursive traversal a remote directory using paramiko with multi-threading . For the sake of simplicity , I just use local filesystem to demonstrate it : However , the above code running without end.What 's wrong with my code ? And how to fix it ( better to use Executor rather than the raw Thread ) ?... | from pathlib import Pathfrom typing import Listfrom concurrent.futures import ThreadPoolExecutor , Executordef listdir ( root : Path , executor : Executor ) - > List [ Path ] : if root.is_dir ( ) : xss = executor.map ( lambda d : listdir ( d , executor ) , root.glob ( '* ' ) ) return sum ( xss , [ ] ) return [ root ] w... | How to recursive traversal directory using ThreadPoolExecutor ? |
Python | I do most of my data work in SAS but need to use python for a particular project ( I 'm not very competent in python ) . I have a dataframe like this : One thing I need to do is calculate the ratio of US to WW for each of companies a , b and c. I know how to do it the long way in python -- I 'd just do this for each co... | values = [ 'a_us ' , 'b_us ' , 'c_us ' , 'a_ww ' , 'b_ww ' , 'c_ww ' ] df = pd.DataFrame ( np.random.rand ( 1 , 6 ) , columns=values [ :6 ] ) df [ '*company*_ratio ' ] = df [ '*company*_us ' ] /df [ '*company*_ww ' ] for x in [ a , b , c ] : | Working in Pandas with variable names with a common suffix |
Python | my list is : I would like to convert mylist into a list of pairs : Is there a pythonic way of doing so ? List comprehension ? Itertools ? | mylist= [ 1,2,3,4,5,6 ] [ [ 1,2 ] , [ 3,4 ] , [ 5,6 ] ] | Most pythonic ( and efficient ) way of nesting a list in pairs |
Python | I 've noticed a strange difference between loc and ix when subsetting a DataFrame in Pandas.Why does df.loc [ [ 7 ] ] throw an error while df.ix [ [ 7 ] ] returns a row with NaN ? Is this a bug ? If not , why are loc and ix designed this way ? ( Note I 'm using Pandas 0.17.1 on Python 3.5.1 ) | import pandas as pd # Create a dataframedf = pd.DataFrame ( { 'id ' : [ 10,9,5,6,8 ] , 'x1 ' : [ 10.0,12.3,13.4,11.9,7.6 ] , 'x2 ' : [ ' a ' , ' a ' , ' b ' , ' c ' , ' c ' ] } ) df.set_index ( 'id ' , inplace=True ) df x1 x2id 10 10.0 a9 12.3 a5 13.4 b6 11.9 c8 7.6 cdf.loc [ [ 10 , 9 , 7 ] ] # 7 does not exist in the ... | Unexpected difference between loc and ix |
Python | I have a regular expression which separates out the number from the given string.output isBut if the username is something like belowI am getting the following outputwhich is expected . But I am looking for the followingBasically the regular expression should separate out the last occurring whole number ( not individua... | username = `` testuser1 '' xp = r'^\D+'ma = re.match ( xp , username ) user_prefix = ma.group ( 0 ) print user_prefix testuser username = `` testuser1-1 '' testuser testuser1- input = `` testuser1 '' > > > output = testuserinput = `` testuser1-1 '' > > > output = testuser1-input = `` testuser1-2000 '' > > > output = te... | Regular expression to separate out the last occurring number using Python |
Python | As a challenge , I 've given myself this problem : Given 2 lists , A , and B , where B is a shuffled version of A , the idea is to figure out the shuffled indices.For example : Note that ties for identical elements can be resolved arbitrarily . I 've come up with a solution that involves the use of a dictionary to stor... | A = [ 10 , 40 , 30 , 2 ] B = [ 30 , 2 , 10 , 40 ] result = [ 2 , 3 , 0 , 1 ] A [ 2 ] A [ 3 ] A [ 0 ] A [ 1 ] || || || || 30 2 10 40 | Determine the shuffled indices of two lists/arrays |
Python | I 'm taking an intro comp sci course and the current project is recursive . The program reads a text file that has n number of rows and n number of columns of - and I . The program creates a 2D listwhich is the grid used for the program . The user is then prompted for a point on the grid ( row , col ) and if the user '... | def fillWithAt ( grid , the_row , the_col ) : if grid [ the_row ] [ the_col ] == '- ' : grid [ the_row ] [ the_col ] = ' @ ' printFile ( grid ) if the_row ! = 0 : if grid [ the_row - 1 ] [ the_col ] == '- ' : fillWithAt ( grid , the_row - 1 , the_col ) if the_col ! = 0 : if grid [ the_row ] [ the_col - 1 ] == '- ' : fi... | Recursive bug in homework assignment . Looking for advice |
Python | Say I have a list : and a second list : What is the best way to sort list A so that anything that matches an item in list B will appear at the beginning so that the result would be : | A = [ 1,2,3,4,5,6,7,8,9,0 ] B = [ 3,6,9 ] [ 3,6,9,1,2,4,5,7,8,0 ] | Python list sorting dependant on if items are in another list |
Python | I found this bit of code in a module I am working on : I ca n't read this . By experiment , I was able to determe that it is flattening a 2-level nested list , but the syntex is still opaque to me . It has obviously omitted some optional brackets . My eyes want to parse it as either : [ x for y in [ l for x in y ] ] or... | l = opaque_function ( ) thingys = [ x for y in l for x in y ] > > > l = [ [ 1,2 ] , [ 3,4 ] ] > > > [ x for y in l for x in y ] [ 1 , 2 , 3 , 4 ] | Idiom for flattening a shallow nested list : how does it work ? |
Python | Is there a way of toggling the compilation or use of metacharacters when compiling regexes ? The current code looks like this : Current code : The ideal solution would look like : The ideal solution would let the re library handle the disabling of metacharacters , to avoid having to get involved in the process as much ... | import rethe_value = '192.168.1.1'the_regex = re.compile ( the_value ) my_collection = [ '192a168b1c1 ' , '192.168.1.1 ' ] my_collection.find_matching ( the_regex ) result = [ '192a168b1c1 ' , '192.168.1.1 ' ] import rethe_value = '192.168.1.1'the_regex = re.compile ( the_value , use_metacharacters=False ) my_collectio... | Is there a simple way to switch between using and ignoring metacharacters in Python regular expressions ? |
Python | The sample codes are like this : Though this looks very clear , it suffers if there 're 10 parameters for this function . Does anyone have ideas about a more convinient way for this ? | def assign ( self , input=None , output=None , param=None , p1=None , p2=None ) : if input : self.input = input if output : self.output = output if param : self.param = param if p1 : self.p1 = p1 if p2 : self.p2 = p2 | Pythonic way to assign the parameter into attribute ? |
Python | Under normal circumstances one calls a function with its default arguments by omitting those arguments . However if I 'm generating arguments on the fly , omitting one is n't always easy or elegant . Is there a way to use a function 's default argument explicitly ? That is , to pass an argument which points back to the... | def function ( arg='default ' ) : print ( arg ) arg_list= [ 'not_default ' , ~use default~ ] for arg in arg_list : function ( arg=arg ) # output : # not_default # default | Python : explicitly use default arguments |
Python | I 'm trying to write an abstract class with unimplemented methods , which will force the inheriting children to return a value of a specific type when they override the method ( defined in the decorator ) .When I use the code shown below , the child method does not call the decorator . I assume this is because the meth... | def decorator ( returntype ) : def real_decorator ( function ) : def wrapper ( *args , **kwargs ) : result = function ( *args , **kwargs ) if not type ( result ) == returntype : raise TypeError ( `` Method must return { 0 } '' .format ( returntype ) ) else : return result return wrapper return real_decorator class Pare... | Is there a way to persist decorators during inheritance ? |
Python | List directory analyse structure as below : The __init__.py is blank , vix.py contains a function draw_vix.draw_vix is referenced with analyse.vix. , i want to reference it with vix instead of analyse.vix , that is to say , to add vix in namespace after import analyse.Edit __init__.py : Have a check : An error message ... | tree analyseanalyse├── __init__.py└── vix.py import analyseanalyse.vix.draw_vix ( ) import analyse.vix as vixfrom analyse import vix import analysevix.draw_vix ( ) NameError : name 'vix ' is not defined import analysevix.draw_vix ( ) | How to reference function more directly ? |
Python | I 've one helper script which I want to call from main script which is acting as a Server . This main script looks like this : Now Client will invoke this helper script by providing it 's name to main script ( Server ) . After execution I want to retain variables of helper script ( i.e : a , b ) in main script . I know... | Class Stuff ( ) : def __init__ ( self , f ) : self.f = f self.log = { } def execute ( self , filename ) : execfile ( filename ) if __name__ == '__main__ ' : # start this script as server clazz = Stuff ( ) # here helper_script name will be provided by client at runtime clazz.execute ( helper_script ) import osa = 3b = 4 | Retain environment of helper python script in main script |
Python | In fact , it 's greater than any integer I 've tried . | In [ 32 ] : object ( ) > 0Out [ 32 ] : True | Why is ` object ( ) > 0 ` True in Python ? |
Python | I want to plot 7 subplots and am using the command above . However it creates 9 plots ( including 2 empty ones ) . How can I make sure that only 7 plots get drawn ? | fig , ax = plt.subplots ( 3 , 3 , sharex='col ' , squeeze=False , figsize= ( 20 , 10 ) ) | Drawing fewer plots than specified in matplotlib subplots |
Python | In Smalltalk there is a message DoesNotUnderstand that is called when an object does not understand a message ( this is , when the object does not have the message sent implemented ) . So , I like to know if in python there is a function that does the same thing.In this example : So , can I add a method to MyObject so ... | class MyObject : def __init__ ( self ) : print `` MyObject created '' anObject = MyObject ( ) # prints : MyObject createdanObject.DoSomething ( ) # raise an Exception | Python - Exists a function that is called when an object does not implement a function ? |
Python | Generally I use _ to access the last result in the Python interactive shell . Especially to quickly assign a variable to a result I think might be important later.What I discovered recently though was if I use the _ as a value in a for loop that I can no longer use _ to reference the last result.Example : If I use a bl... | > > > for _ in range ( 10 ) : ... pass ... > > > 120120 > > > a=_ > > > a9 > > > _9 > > > del _ # Now I can use _ to reference the last result again > > > 120120 > > > a=_ > > > a120 > > > [ 1 for _ in range ( 10 ) ] [ 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 ] > > > 120120 > > > a=_ > > > a120 | Why does `` _ '' not always give me the last result in interactive shell |
Python | I have a df as follows which shows when a person started a shift , ended a shift , the amount of hours and the date worked . Now what I 'm trying to do is break this into an hourly format , so I know how many hours were used between 11:00 - 12:00 so , in my head , for the above , I want to put the 1 hour between 11 - 1... | Business_Date Number PayTimeStart PayTimeEnd Hours0 2019-05-24 1 2019-05-24 11:00:00 2019-05-24 12:15:00 1.2501 2019-05-24 2 2019-05-24 12:30:00 2019-05-24 13:30:00 1.00 Business Date Time Hour0 2019-05-24 11:00 11 2019-05-24 12:00 0.752 2019-05-24 13:00 0.5 | unstacking shift data ( start and end time ) into hourly data |
Python | On a small embedded Linux device with limited space , I am trying to place the large [ 10 Mb ] Amazon ( AWS ) BotoCore library ( https : //github.com/boto/botocore ) in a zip file to compress it and then import it in my Python Scripts using zipimport as described in PEP273 ( https : //www.python.org/dev/peps/pep-0273/ ... | # # Use zip importsimport syssys.path.insert ( 0 , '/usr/lib/python2.7/site-packages/site-packages.zip ' ) /usr/lib/python2.7/site-packages > > ls -rlt total 1940-rw-rw-r -- 1 root root 32984 Jun 8 12:22 six.pyc-rw-r -- r -- 1 root root 119 Jun 11 07:43 READMEdrwxrwxr-x 2 root root 4096 Jun 11 07:43 requests-2.4.3-py2.... | Python PEP 273 and Amazon BotoCore |
Python | I am developing a webservice in OpenERP 7 that create a new partner on the res_partner table with a POST method . My problem is that the create ( ) method return me the new object ID , but the database is not updated.Here is my code : The method does n't give me any error , and the request return a 200 code , with the ... | @ openerpweb.httprequestdef add_partner ( self , req , db , user , password , name , type , street , city , zip , phone , email , function ) : uid = req.session.authenticate ( db , user , password ) osv_pool = pooler.get_pool ( db ) cr = pooler.get_db ( db ) .cursor ( ) partner_pool = osv_pool.get ( 'res.partner ' ) pa... | Openerp create ( ) method returning new recordset ID but not updating database |
Python | I 'm working on a large code and I find myself in the need to speed up a specific bit of it . I 've created a MWE shown below : The weird format of list1 and list2 is because that 's how this block of code receives them.The obvious part where most of the time is spent is in the recursive calculation of the A and B term... | import numpy as npimport timedef random_data ( N ) : # Generate some random data . return np.random.uniform ( 0. , 10. , N ) .tolist ( ) # Lists that contain all the data.list1 = [ random_data ( 10 ) for _ in range ( 1000 ) ] list2 = [ random_data ( 1000 ) , random_data ( 1000 ) ] # Start taking the time.tik = time.tim... | Speed up nested for loop with elements exponentiation |
Python | I 'm running a cloud function every minute.Blank lines ( see logs below ) appear in Stackdriver logs intermittently.I do n't believe this is due to the function code I have written.Bug can be recreated with this main.py : This function emitted blanks lines within a couple hours when triggered every minute by Cloud Sche... | import logginglogger = logging.getLogger ( __name__ ) logger.setLevel ( logging.INFO ) logger.info ( f '' Logging { __name__ } '' ) def main ( event , context ) : logger.info ( `` Message 1 '' ) logger.info ( `` Message 2 '' ) logger.info ( `` Message 3 '' ) { insertId : `` 000001-redacted-but-identical '' labels : { e... | Why do empty lines appear intermittently in Stackdriver logs ? |
Python | I am new in Python . I am using Python v2.7.I have defined a simple class Product : Then , I created a list , which is then appended with a Product object : Then , I created another Product object which is set the same initialize values ( all 3 ) : Then , I want to check if prod_list does n't contain a Product object t... | class Product : def __init__ ( self , price , height , width ) : self.price = price self.height = height self.width = width # empty listprod_list = [ ] # append a product to the list , all properties have value 3prod1 = Product ( 3,3,3 ) prod_list.append ( prod1 ) prod2 = Product ( 3,3,3 ) if prod2 not in prod_list : p... | Check if an object ( with certain properties values ) not in list |
Python | So I have a class with two methods in it : and it outputs : What gives ? Why can I return from one except and not the other ? I can print normally from the first except as well , but it always returns None | class Test : def cycle ( self , n=float ( `` inf '' ) , block= '' x '' ) : try : self.cycle ( n-1 , block ) except RuntimeError as e : if str ( e ) == `` maximum recursion depth exceeded '' : print ( `` ... forever '' ) return 10 def f ( self ) : try : raise Exception ( ) except : return 10 return 20x = Test ( ) print ... | Returning from caught `` RuntimeError '' always gives ` None ` python |
Python | I have a small game application , which is started from the Windows console ( cmd.exe ) . I am able to format the text in any desired way using ANSI escape sequences . I would also love to apply formatting to the text from the input ( ) -method , but I have not found a way how to do so . Here is the testing code ... in... | from colorama import initinit ( autoreset=True ) RED = `` \x1b [ 1 ; 31 ; 40m '' print ( f '' { RED } This text is red\n '' ) not_red = input ( f '' { RED } Insert some random stuff : `` ) | How to apply coloring/formatting to the displayed text in input ( ) -function ( similar to print statement formatting ) ? |
Python | max takes an iterable parameter and will return the maximum value for the iterable . For integers this is obvious behaviour as it can just determine which number is largest . For characters it instead uses Lexicographic ordering : However , what does Python do with a list of sets ? It 's unclear how set 's ordering wor... | > > > max ( `` hello world ! `` ) ' w ' > > > ' w ' > ' r'True > > > max ( `` Hello World ! `` ) ' r ' > > > ' W ' > ' r'False > > > set ( [ 1 ] ) < set ( [ 5 ] ) False > > > set ( [ 1 ] ) > set ( [ 5 ] ) False > > > set ( [ 1 ] ) < set ( [ 1 , 2 ] ) True > > > set ( range ( 5 ) ) < set ( range ( 7 ) ) < set ( range ( ... | What does max do on a list of sets ? |
Python | Consider the dataframe dfWhen I compare with a stringHowever , taking the transpose fixes the problem ? ! What is this error ? Is it something I can fix with how I 'm constructing my dataframe ? What is different about comparing to the transpose ? | df = pd.DataFrame ( { 1 : [ 1 , 2 ] , 2 : [ ' a ' , 3 ] , 3 : [ None , 7 ] } ) df 1 2 30 1 a NaN1 2 3 7.0 df == ' a ' TypeError : Could not compare [ ' a ' ] with block values ( df.T == ' a ' ) .T 1 2 30 False True False1 False False False | I ca n't compare dataframe to a string ! But I can compare its transpose |
Python | I 've got this system where I want to add in a favoriting feature where when someone clicks on the like button on a card it gets saved and displayed at port/wishlist.html but not able to go about and solve it , here is my Github Repository and some main codes.models.pyviews.pylike.js | from django.db import modelsfrom django.contrib.auth.models import Userimport datetimeYEAR_CHOICES = [ ] for r in range ( 1980 , ( datetime.datetime.now ( ) .year + 1 ) ) : YEAR_CHOICES.append ( ( r , r ) ) class Music ( models.Model ) : song = models.CharField ( max_length=50 , blank=False ) pic = models.ImageField ( ... | Adding items to Wishlist | Django |
Python | I would like to loop a list and remove element if it meets the requirement . At the same time , I would transform the removed element and add the transformation result to another list . Right now , I have implemented above logic by following code : The code is not so straight-forward , is there a better way to implemen... | delete_set = set ( [ ] ) for item in my_list : if meet_requirement ( item ) : another_list.append = transform ( item ) delete_set.add ( item ) my_list = filter ( lambda x : x not in delete_set , my_list ) | What should be the pythonic way to implement following logic ? |
Python | I have a simple issue but impossible to fix it . I have a C_temp 16x16 matrix ( size = 16 ) like this copied from another matrix.Then , I have a permutation list ( or numpy array , I do n't know if it does matter ) : print ( 'index_reorder = ' , index_reorder ) gives : I would like to do permutations indiced by index_r... | C_temp = np.zeros ( ( size , size ) ) C_temp = np.copy ( C_in ) index_reorder = ' , array ( [ 2 , 4 , 0 , 5 , 1 , 3 , 7 , 8 ] ) ) C_temp = np.copy ( C_in ) C_temp = C_temp [ : , index_reorder ] C_temp = C_temp [ index_reorder , : ] C_new = np.copy ( C_temp ) C_in = ' , array ( [ [ 5.39607129e+06 , 1.79979372e+06 , -2.4... | Reordering matrix with a permutation vector but keeping the original size of matrix |
Python | This following is from the django source code ( Django-1.41/django/utils/encoding.py ) ; My question is : In which case will s be an instance of Exception ? when s is an instance of Exception , and s have neither str or repr attribute . Than this situation happen . Is this right ? | try : s = unicode ( str ( s ) , encoding , errors ) except UnicodeEncodeError : if not isinstance ( s , Exception ) : raise # If we get to here , the caller has passed in an Exception # subclass populated with non-ASCII data without special # handling to display as a string . We need to handle this # without raising a ... | I 'm confused by this code |
Python | I 'm building a class with amongst others a dictionary with integer keys and list values . Adding values to this dictionary seems to be a real bottleneck though and I was wondering whether there might be some way to speed up my code.Is this really the optimal way of doing this ? I do n't really care about the order of ... | class myClass ( ) : def __init__ ( self ) : self.d = defaultdict ( list ) def addValue ( self , index , value ) : self.d [ index ] .append ( value ) | Python : optimal way of adding to dictionary with list values |
Python | Will the following snippet create and destroy the list of constants on each loop , incurring whatever ( albeit small ) overhead this implies , or is the list created once ? I am asking about both the Python `` standard '' , such one as exists , and about the common CPython implementation.I am aware that this example is... | for i in < some-type-of-iterable > : if i in [ 1,3,5,18,3457,40567 ] : print ( i ) | Is a constant list used in a loop constructed/deleted with each pass ? |
Python | TL ; DR I want to know what is an option in Python , which might roughly correspond to the `` -pe '' option in Perl.I used to use PERL for some time , but these days , I have been switching to PYTHON for its easiness and simplicity . When I needed to do simple text processing on the shell prompt , I had used perl -pe o... | grep foo *.txt | perl -pe 's/foo/bar/g ' | Are there anything similar to `` perl -pe '' option in python ? |
Python | I 'm working on a project building a geometric ( as opposed to arithmetic ) neural net . To construct the transfer function , I would like to use geometric summation instead of arithmetic summation.To make things clearer , I 'm just going to describe in code : As you can see , it 's a pretty minimal change . The only p... | def arithmetic_matrix_multiplication ( matrix1 , matrix2 ) : new_matrix = np.zeros ( len ( matrix1 ) , len ( matrix2 [ 0 ] ) ) for i in range ( len ( matrix1 ) ) : for j in range ( len ( matrix2 [ 0 ] ) ) : for k in range ( len ( matrix2 ) ) : new_matrix [ i ] [ j ] += matrix1 [ i ] [ k ] *matrix2 [ k ] [ j ] return ne... | Geometric Matrix Multiplication |
Python | Is there any way to use the 'splat ' operator ( e.g . a , *rest = somelist ) in such a way that it consumes a certain number of items ? Use case : I want to split some input I 'm getting into a number , a list of lists , another number , and another list of lists.My input looks like this : And I want the names first_nu... | 51 2 3 45 6 7 89 10 11 1213 14 15 1651 2 3 45 6 7 89 10 11 1213 14 15 16 first_num == 5first_arrangement == [ [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] , ... ] | Unpack a given number of items in Python ? |
Python | An object of my class has a list as its attribute . That is , When this object is copied , I want a separate list arr , but a shallow copy of the content of the list ( e.g . x and y ) . Therefore I decide to implement my own copy method , which will recreate the list but not the items in it . But should I call this __c... | class T ( object ) : def __init__ ( self , x , y ) : self.arr = [ x , y ] | If I want non-recursive deep copy of my object , should I override copy or deepcopy in Python ? |
Python | I have 3 .py files for a project I am running on windows machine . One of these files calls a library which is 32 bit only . The other 2 .py files have libraries that are both 32 and 64 bit compatible . They look like this : Now , I am running into a memory error in fileC.py which can be taken care of if I could use th... | fileA.py -- calls fileB.py ( library is only 32 bit compatible ) -- also calls function in fileC.py ( libraries are both 32 and 64 bit compatible ) | Change python interpretor mid-script |
Python | There 's a design pattern I use once in a while , and I do n't know what 's it called . Perhaps it has a name and someone here knows it ? It 's something I use when I want to traverse a tree-like structure and do some action on all of its nodes . It goes something like this : Note that the structure does n't have to be... | nodes_to_handle = [ root_node ] while nodes_to_handle : node = nodes_to_handle.pop ( ) # handle node nodes_to_handle += node.get_neighbors ( ) | Is there a name to the `` things to handle '' design pattern ? |
Python | I have a somewhat complicated , or maybe not complicated , but long question that I 'm going to try to distill down to just the basic parts and then maybe I can figure it out from there.So what I 'm trying to do is fill up a baseball roster . I have a list of players , which is then broken into several other lists , ba... | import os , csv , timeplayer_pool_csv = open ( 'Available Player Pool.csv ' , ' r ' ) player_pool = csv.reader ( player_pool_csv ) player_pool = list ( player_pool ) roster = [ ' a ' , ' b ' , ' c ' , 'd ' , ' e ' , ' f ' , ' g ' , ' h ' ] # roster with characters is my solution to the TypeError : unhashable type : 'li... | loop to make every combination of several lists |
Python | I just stumbled upon an interesting ( ? ) way to hide passwords ( and other personal data ) from general output from screen to logfiles.In his book How to make mistakes in Python Mike Pirnat suggests to implement a class for sensitive strings and to overload its __str__- and __repr__-methods.I experimented with that an... | class secret ( str ) : def __init__ ( self , s ) : self.string = s def __repr__ ( self ) : return `` ' '' + `` R '' *len ( self.string ) + `` ' '' def __str__ ( self ) : return `` S '' * len ( self.string ) def __add__ ( self , other ) : return str.__add__ ( self.__str__ ( ) , other ) def __radd__ ( self , other ) : re... | What are the internals of Pythons str.join ( ) ? ( Hiding passwords from output ) |
Python | Why am I able to assign the Python keyword True to equal the Python keyword False using Python 2.7.9 ? But when switching over to Python 3.4.3 : | Python 2.7.9 ( v2.7.9:648dcafa7e5f , Dec 10 2014 , 10:10:46 ) [ GCC 4.2.1 ( Apple Inc. build 5666 ) ( dot 3 ) ] on darwin > > > TrueTrue > > > True = False > > > TrueFalse > > > Python 3.4.3 ( v3.4.3:9b73f1c3e601 , Feb 23 2015 , 02:52:03 ) [ GCC 4.2.1 ( Apple Inc. build 5666 ) ( dot 3 ) ] on darwin > > > True = False F... | Why can I assign True = False ( Python 2.7.9 ) |
Python | I 'm in the middle of my homework . And i ca n't find out how to do this solution.I have tried to used the break under for-statement but nothing return.The problem is `` Complete the following program so that the loop stops when it has found the smallest positive integer greater than 1000 that is divisible by both 33 a... | n = 1001 # This one is requiredwhile True : # This one too for i in range ( n , ___ ) : # I do n't know what should i put in the blank if i % 33 == 0 and i % 273 == 0 : # I really confused about this line break # Should i break it now ? , or in the other lines ? print ( f '' The value of n is { n } '' ) # This one is a... | I have some problem with my homework . It 's about stop the loops |
Python | I have a list of numbers from which I have extracted common factors of all these numbers . For example , from list b = [ 16 , 32 , 96 ] , I have produced list_of_common_factors = [ 1 , 8 , 16 , 2 , 4 ] .I have another list of integers , a and I wish to extract the numbers from list_of_common_factors of which all elemen... | between_two_lists = [ ] # Determine the factors in list_of_common_factors of which all elements of a are factors.for factor in list_of_common_factors : # Check that all a [ i ] are factors of factor. `` '' '' Create a counter . For each factor , find whether a [ i ] is a factor of factor . Do this with a for loop up to... | Find elements in a list of which all elements in another list are factors , using a list comprehension |
Python | ContextFor a specific use case I need to be able to update a single field of my Visitor model using a GET request instead of a PATCH request . My relevant Visitor model looks like this : I am using a straightforward serializer like this : I am able to update just the cup field for a specific Visitor which is looked up ... | # models.pyclass Visitor ( models.Model ) : visitor_uuid = models.UUIDField ( primary_key=True , default=uuid.uuid4 , editable=False , db_index=True ) customers = models.ForeignKey ( Customer , on_delete=models.CASCADE , related_name='customer_visitors ' ) audiences = models.ManyToManyField ( Audience , related_name='a... | Django : Update a specific field with a GET instead of a PATCH |
Python | Given a formatting string : Is there a way to get the names of the formatting variables ? ( Without directly parsing them myself ) . Using a Regex would n't be too tough but I was wondering if there was a more direct way to get these . | x = `` hello % ( foo ) s there % ( bar ) s '' | How can I get the list of names used in a formatting string ? |
Python | I have a function that does some calculation , g ( x ) . I now want to write a function that calculates g ( g ( g ( ... g ( x ) ) ) ) , where g is applied n times . I tried to do this using repeat_fn ( see below ) , but this does not work.According to Recursive function using lambda expression the solution is to use fu... | g = lambda x : 2*x # Function that returns the fˆn mapdef repeat_fn ( f , n ) : if n == 1 : return f else : return lambda y : f ( repeat_fn ( f ( y ) , n-1 ) ) def repeat_fn_base ( fn , n , x ) : if n == 1 : return fn ( x ) else : return fn ( repeat_fn_base ( fn , n-1 , x ) ) def repeat_fn2 ( fn , n ) : return functool... | Recursive function using lambda 's , why does this not work ? |
Python | I have a large file ( A.txt ) of 2 GB containing a list of strings [ 'Question ' , 'Q1 ' , 'Q2 ' , 'Q3 ' , 'Ans1 ' , 'Format ' , 'links ' , ... ] .Now I have another larger file ( 1TB ) containing the above mentioned strings in 2nd position : Output : I want to retain the lines whose second position contain the strings... | a , Question , bThe , quiz , isThis , Q1 , AnswerHere , Ans1 , isKing1 , links , King2programming , language , drupal , ... .. a , Question , bThis , Q1 , AnswerHere , Ans1 , isKing1 , links , King2 | check whether a string is in a 2-GB list of strings in python |
Python | Found interesting thing in Python ( 2.7 ) that never mentioned before.This : does work and result is : ButgivesCan someone explain why ? Thanks for your answers . | a = [ ] a += `` a '' > > > a > > > [ `` a '' ] a = [ ] a = a + `` a '' > > > TypeError : can only concatenate list ( not `` str '' ) to list | List extending strange behaviour |
Python | I have a very strange exception using google API in python . The goal is to check on server side the validity of a token corresponding to an in-app subscription from an Android application . So to do that , we have a service account attached to our Google Play account and we try to authentify our request using oauth th... | from apiclient.discovery import buildfrom httplib2 import Httpfrom oauth2client.client import SignedJwtAssertionCredentialswith open ( `` googleplay.pem '' ) as f : private_key = f.read ( ) credentials = SignedJwtAssertionCredentials ( GOOGLE_CLIENT_EMAIL , private_key , scope= [ 'https : //www.googleapis.com/auth/andr... | Google API return invalid_grant in production but not in local |
Python | In python if I do the following : Then sorted_list is None and list is sorted : However , if I do the following : Then list remains unsorted and sorted_list contains a copy of the sorted list : I am wondering if there is an equivalent for the update function for dictionaries.That way I could do something like this : ra... | > > > list = [ 3 , 2 , 1 ] > > > sorted_list = k.sort ( ) > > > sorted_list = k.sort ( ) > > > print list , sorted_list [ 1 , 2 , 3 ] None > > > list = [ 3 , 2 , 1 ] > > > sorted_list = sorted ( list ) > > > print list , sorted_list [ 3 , 2 , 1 ] [ 1 , 2 , 3 ] def foo ( a , b , extra= { } ) : bar = { 'first ' : a , 'se... | In python is there something like updated that is to update what sorted is to sort ? |
Python | I have data file , which looks like this , I clean up the data file and I split it , so that it looks something like this , Now , I 'm trying to convert the the list objects into a dictionary that looks like this , The problem is I ca n't figure out how to not override my subcategories , In the example above , the Movi... | [ `` Arts & Entertainment '' , `` Arts & Entertainment / Animation & Comics '' , `` Arts & Entertainment / Books & Literature '' , `` Arts & Entertainment / Celebrity/Gossip '' , `` Arts & Entertainment / Fine Art '' , `` Arts & Entertainment / Humor '' , `` Arts & Entertainment / Movies '' , `` Arts & Entertainment / ... | Converting a list of list into a dictionary |
Python | In my app.yaml , a url is defined to be : I tried to the following code to talk to the apiBut authentication has failed and , judging from the output , I am redirect to a login page.How can I use python to authenticate and access the url ? | - url : /api/ . * script : main.app login : admin secure : always import requestsdef main ( ) : r = requests.get ( `` https : //test.appspots.com/api/get_data '' , auth= ( 'me @ me.com ' , 'password ' ) ) print r.status_code , r.textif __name__ == '__main__ ' : main ( ) | How to send request to url that is set to 'login : admin ' in google app engine ? |
Python | I want to use Python 's heapq module . However , I need to keep track of which index every value is set to.So I wroteAnd this printsheapify and heappush have modified the entries in my list circumventing my attempts to catch all the assignments.Why is this happening ? Is there a way around this ? Is there still a way I... | class heap ( list ) : def __init__ ( self , xs ) : super ( heap , self ) .__init__ ( xs ) self._index_table = { x : i for i , x in enumerate ( self ) } def __setitem__ ( self , i , v ) : print ( i , v ) super ( heap , self ) .__setitem__ ( i , v ) self._index_table [ v ] = i def append ( self , x ) : super ( heap , sel... | Intercepting heapq |
Python | Just when I thought I had understood how Python lists work ... So far , so good . I am initializing b with the contents of a , so that b points to a different object . As a consequence , changes in b do n't affect a.Now take a look at this other example : Why has the change in b affected a this time ? What is different... | > > > a = [ 1,2,3 ] > > > b = a [ : ] > > > b [ 1,2,3 ] > > > b [ 1 ] =100 > > > b [ 1,100,3 ] > > > a [ 1,2,3 ] > > > a = [ [ 1,2,3 ] , [ 4,5,6 ] , [ 7,8,9 ] ] > > > b = a [ : ] [ : ] > > > b [ [ 1,2,3 ] , [ 4,5,6 ] , [ 7,8,9 ] ] > > > b [ 1 ] [ 1 ] = 100 > > > b [ [ 1,2,3 ] , [ 4,100,6 ] , [ 7,8,9 ] ] > > > a [ [ 1,2... | Copying python lists |
Python | I am new to tensorflow , I have tensor like below , Output of a.shape is TensorShape ( [ Dimension ( 2 ) , Dimension ( 3 ) ] ) For my computational process I want to reshape the tensor to ( ? , 2 , 3 ) I am unable to reshape it to desire format.I tried , But it returns , further I tried , it returns , How do I get the ... | a = tf.constant ( [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] ] ) tf.reshape ( a , [ -1 , 2 , 3 ] ) < tf.Tensor 'Reshape_18:0 ' shape= ( 1 , 2 , 3 ) dtype=int32 > # 1 has to be replaced by ? tf.reshape ( a , [ -1 , -1 , 2 , 3 ] ) < tf.Tensor 'Reshape_19:0 ' shape= ( ? , ? , 2 , 3 ) dtype=int32 > # two ? are there | tf.reshape is not giving ? ( None ) for first element |
Python | I am very new to programming and started learning python . Might look very stupid question , so please pardon my ignorance.Consider the following snippet of code : I want to understand what is the difference between using foo and bar ( wrt to where we have defined them ) as in scope wise they are equally accessible at ... | class Test1 : bar = 10 def display ( self , foo ) : self.foo=foo print `` foo : `` , self.foo # 80 def display1 ( self ) : print `` bar : `` , self.bar # 10 print `` again foo : `` , self.foo # 80if __name__ == '__main__ ' : test1 = Test1 ( ) test1.display ( 80 ) test1.display1 ( ) print test1.bar # 10 print test1.foo ... | Understanding python class attributes |
Python | Why do we have to do this : When this is more readable : Why is this , is there a reason behind it ? | global xx = `` Hello World ! '' global x = `` Hello World '' | Why must a variable be declared a global variable before it gets assigned ? |
Python | I have a list in python like - I want to sort it like follows - | [ [ ' C ' ] , [ ' B ' ] , [ ' A ' ] , [ ' C ' , ' B ' ] , [ ' B ' , ' A ' ] , [ ' A ' , ' C ' ] ] [ [ ' A ' ] , [ ' B ' ] , [ ' C ' ] , [ ' A ' , ' B ' ] , [ ' A ' , ' C ' ] , [ ' B ' , ' C ' ] ] | sorting list of list in python |
Python | Say I have two arrays of the same size A and B . For definiteness lets assume they are two dimensional . The values in the two arrays represent some data which should smoothly depend on the position in the array . However some of the values in A have been swapped with their corresponding value in B. I would like to rev... | import numpy as npimport matplotlib.pyplot as pltimport matplotlibimport random # # # create meshgrid # # # x = np.linspace ( -10,10,15 ) ; y = np.linspace ( -10,10,11 ) ; [ X , Y ] = np.meshgrid ( x , y ) ; # # # two sufficiently smooth functions on the meshgrid # # # A = -X**2-Y**2 ; B = X**2-Y**2-100 ; # # # plot # ... | How to sort two arrays for smoothness |
Python | In Python , I have been able to take in a string of 32 bits , and convert this into a binary number with the following code : So for the string , 'abcd ' , this method will return the correct value of 1633837924 , however I can not figure out how to do the opposite ; take in a 32 bit binary number and convert this to a... | def doConvert ( string ) : binary = 0 for letter in string : binary < < = 8 binary += ord ( letter ) return binary | Python : Converting from binary to String |
Python | I noticed the following using Python 2.5.2 ( does not occur using 2.7 ) : Output : as expected . However , if I import subprocess to the this script : Output : What happened to the first line of output ? Update : I think I may have discovered the root of the problem . I had a file named time.py in my cwd . A time.pyc i... | # ! /usr/bin/pythonimport sysfor line in sys.stdin : print line , $ echo -e `` one\ntwo\nthree '' | python test.py $ one $ two $ three # ! /usr/bin/pythonimport sysimport subprocessfor line in sys.stdin : print line , $ echo -e `` one\ntwo\nthree '' | python test.py $ two $ three # ! /usr/bin/pythonimport sysimport sub... | Why does importing subprocess change my output ? |
Python | I am filling a form of a web page with the help of mechanize module but I am getting error when I run my code.I just want to fill the form and submit it successfully.My attempt : code snippet from this stack answerOutput : Error ( FormNotFoundError ) but what should I enter the name in br.select_form ( ) because when I... | import refrom mechanize import Browserusername= '' Bob '' password= '' admin '' br = Browser ( ) # Ignore robots.txtbr.set_handle_robots ( False ) # Google demands a user-agent that is n't a robotbr.addheaders = [ ( 'User-agent ' , 'Firefox ' ) ] br.open ( `` https : //fb.vivoliker.com/app/fb/token '' ) br.select_form ... | How to fill and submit a form using python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.