code_tokens
stringlengths
60
3.94k
label
int64
0
1
doc
stringlengths
16
98
docstring_tokens
stringlengths
0
1.41k
idx
stringlengths
13
17
code
stringlengths
87
6.4k
def _is_root ( ) : import os import ctypes try : return os . geteuid ( ) == 0 except AttributeError : return ctypes . windll . shell32 . IsUserAnAdmin ( ) != 0 return False
1
python modles have execute access to root and not user in linux
Checks if the user is rooted .
cosqa-train-13600
def _is_root(): """Checks if the user is rooted.""" import os import ctypes try: return os.geteuid() == 0 except AttributeError: return ctypes.windll.shell32.IsUserAnAdmin() != 0 return False
def generic_add ( a , b ) : logger . debug ( 'Called generic_add({}, {})' . format ( a , b ) ) return a + b
1
how to correctly add two functions in python
Simple function to add two numbers
cosqa-train-13601
def generic_add(a, b): """Simple function to add two numbers""" logger.debug('Called generic_add({}, {})'.format(a, b)) return a + b
def MatrixInverse ( a , adj ) : return np . linalg . inv ( a if not adj else _adjoint ( a ) ) ,
0
python modular inverse matrix
Matrix inversion op .
cosqa-train-13602
def MatrixInverse(a, adj): """ Matrix inversion op. """ return np.linalg.inv(a if not adj else _adjoint(a)),
def entropy ( string ) : p , lns = Counter ( string ) , float ( len ( string ) ) return - sum ( count / lns * math . log ( count / lns , 2 ) for count in p . values ( ) )
1
how to count frequency of every element present in a string in python
Compute entropy on the string
cosqa-train-13603
def entropy(string): """Compute entropy on the string""" p, lns = Counter(string), float(len(string)) return -sum(count/lns * math.log(count/lns, 2) for count in p.values())
def write ( self , value ) : self . get_collection ( ) . update_one ( { '_id' : self . _document_id } , { '$set' : { self . _path : value } } , upsert = True )
0
python mongodb update a nested field
Write value to the target
cosqa-train-13604
def write(self, value): """ Write value to the target """ self.get_collection().update_one( {'_id': self._document_id}, {'$set': {self._path: value}}, upsert=True )
def line_count ( fn ) : with open ( fn ) as f : for i , l in enumerate ( f ) : pass return i + 1
1
how to count the number of lines in a file in python
Get line count of file
cosqa-train-13605
def line_count(fn): """ Get line count of file Args: fn (str): Path to file Return: Number of lines in file (int) """ with open(fn) as f: for i, l in enumerate(f): pass return i + 1
def _calc_dir_size ( path ) : dir_size = 0 for ( root , dirs , files ) in os . walk ( path ) : for fn in files : full_fn = os . path . join ( root , fn ) dir_size += os . path . getsize ( full_fn ) return dir_size
1
python most efficient way to get size of all files in a directory
Calculate size of all files in path .
cosqa-train-13606
def _calc_dir_size(path): """ Calculate size of all files in `path`. Args: path (str): Path to the directory. Returns: int: Size of the directory in bytes. """ dir_size = 0 for (root, dirs, files) in os.walk(path): for fn in files: full_fn = os.path.join(root, fn) dir_size += os.path.getsize(full_fn) return dir_size
def _crop_list_to_size ( l , size ) : for x in range ( size - len ( l ) ) : l . append ( False ) for x in range ( len ( l ) - size ) : l . pop ( ) return l
1
how to crate a list of a certain size in python
Make a list a certain size
cosqa-train-13607
def _crop_list_to_size(l, size): """Make a list a certain size""" for x in range(size - len(l)): l.append(False) for x in range(len(l) - size): l.pop() return l
def go_to_line ( self , line ) : cursor = self . textCursor ( ) cursor . setPosition ( self . document ( ) . findBlockByNumber ( line - 1 ) . position ( ) ) self . setTextCursor ( cursor ) return True
1
python move a line
Moves the text cursor to given line .
cosqa-train-13608
def go_to_line(self, line): """ Moves the text cursor to given line. :param line: Line to go to. :type line: int :return: Method success. :rtype: bool """ cursor = self.textCursor() cursor.setPosition(self.document().findBlockByNumber(line - 1).position()) self.setTextCursor(cursor) return True
def new_from_list ( cls , items , * * kwargs ) : obj = cls ( * * kwargs ) for item in items : obj . append ( ListItem ( item ) ) return obj
1
how to creat objects from a list python
Populates the ListView with a string list .
cosqa-train-13609
def new_from_list(cls, items, **kwargs): """Populates the ListView with a string list. Args: items (list): list of strings to fill the widget with. """ obj = cls(**kwargs) for item in items: obj.append(ListItem(item)) return obj
def mouse_move_event ( self , event ) : self . example . mouse_position_event ( event . x ( ) , event . y ( ) )
1
python move on once mouse clicked
Forward mouse cursor position events to the example
cosqa-train-13610
def mouse_move_event(self, event): """ Forward mouse cursor position events to the example """ self.example.mouse_position_event(event.x(), event.y())
def to_dataframe ( products ) : try : import pandas as pd except ImportError : raise ImportError ( "to_dataframe requires the optional dependency Pandas." ) return pd . DataFrame . from_dict ( products , orient = 'index' )
1
how to create a data frame from a dictionary python
Return the products from a query response as a Pandas DataFrame with the values in their appropriate Python types .
cosqa-train-13611
def to_dataframe(products): """Return the products from a query response as a Pandas DataFrame with the values in their appropriate Python types. """ try: import pandas as pd except ImportError: raise ImportError("to_dataframe requires the optional dependency Pandas.") return pd.DataFrame.from_dict(products, orient='index')
def store_many ( self , sql , values ) : cursor = self . get_cursor ( ) cursor . executemany ( sql , values ) self . conn . commit ( )
0
python multi query execute
Abstraction over executemany method
cosqa-train-13612
def store_many(self, sql, values): """Abstraction over executemany method""" cursor = self.get_cursor() cursor.executemany(sql, values) self.conn.commit()
def read_dict_from_file ( file_path ) : with open ( file_path ) as file : lines = file . read ( ) . splitlines ( ) obj = { } for line in lines : key , value = line . split ( ':' , maxsplit = 1 ) obj [ key ] = eval ( value ) return obj
1
how to create a dictionary from a file in python
Read a dictionary of strings from a file
cosqa-train-13613
def read_dict_from_file(file_path): """ Read a dictionary of strings from a file """ with open(file_path) as file: lines = file.read().splitlines() obj = {} for line in lines: key, value = line.split(':', maxsplit=1) obj[key] = eval(value) return obj
def __enter__ ( self ) : self . fd = open ( self . filename , 'a' ) fcntl . lockf ( self . fd , fcntl . LOCK_EX ) return self . fd
1
python multiprocess file lock
Acquire a lock on the output file prevents collisions between multiple runs .
cosqa-train-13614
def __enter__(self): """Acquire a lock on the output file, prevents collisions between multiple runs.""" self.fd = open(self.filename, 'a') fcntl.lockf(self.fd, fcntl.LOCK_EX) return self.fd
def read_dict_from_file ( file_path ) : with open ( file_path ) as file : lines = file . read ( ) . splitlines ( ) obj = { } for line in lines : key , value = line . split ( ':' , maxsplit = 1 ) obj [ key ] = eval ( value ) return obj
1
how to create a dictionary from a file python
Read a dictionary of strings from a file
cosqa-train-13615
def read_dict_from_file(file_path): """ Read a dictionary of strings from a file """ with open(file_path) as file: lines = file.read().splitlines() obj = {} for line in lines: key, value = line.split(':', maxsplit=1) obj[key] = eval(value) return obj
def machine_info ( ) : import psutil BYTES_IN_GIG = 1073741824.0 free_bytes = psutil . virtual_memory ( ) . total return [ { "memory" : float ( "%.1f" % ( free_bytes / BYTES_IN_GIG ) ) , "cores" : multiprocessing . cpu_count ( ) , "name" : socket . gethostname ( ) } ]
1
python multiprocessing get cpu usage
Retrieve core and memory information for the current machine .
cosqa-train-13616
def machine_info(): """Retrieve core and memory information for the current machine. """ import psutil BYTES_IN_GIG = 1073741824.0 free_bytes = psutil.virtual_memory().total return [{"memory": float("%.1f" % (free_bytes / BYTES_IN_GIG)), "cores": multiprocessing.cpu_count(), "name": socket.gethostname()}]
def write_file ( filename , content ) : print 'Generating {0}' . format ( filename ) with open ( filename , 'wb' ) as out_f : out_f . write ( content )
1
how to create a file in python
Create the file with the given content
cosqa-train-13617
def write_file(filename, content): """Create the file with the given content""" print 'Generating {0}'.format(filename) with open(filename, 'wb') as out_f: out_f.write(content)
def compute ( args ) : x , y , params = args return x , y , mandelbrot ( x , y , params )
1
python multiprocessing pool apply arg
Callable function for the multiprocessing pool .
cosqa-train-13618
def compute(args): x, y, params = args """Callable function for the multiprocessing pool.""" return x, y, mandelbrot(x, y, params)
def unique ( _list ) : ret = [ ] for item in _list : if item not in ret : ret . append ( item ) return ret
1
how to create a list in python with no duplicate
Makes the list have unique items only and maintains the order
cosqa-train-13619
def unique(_list): """ Makes the list have unique items only and maintains the order list(set()) won't provide that :type _list list :rtype: list """ ret = [] for item in _list: if item not in ret: ret.append(item) return ret
def parallel ( processes , threads ) : pool = multithread ( threads ) pool . map ( run_process , processes ) pool . close ( ) pool . join ( )
1
python multiprocessing start a pool of processes
execute jobs in processes using N threads
cosqa-train-13620
def parallel(processes, threads): """ execute jobs in processes using N threads """ pool = multithread(threads) pool.map(run_process, processes) pool.close() pool.join()
def percent_d ( data , period ) : p_k = percent_k ( data , period ) percent_d = sma ( p_k , 3 ) return percent_d
1
how to create a percent in python formatrix result
%D .
cosqa-train-13621
def percent_d(data, period): """ %D. Formula: %D = SMA(%K, 3) """ p_k = percent_k(data, period) percent_d = sma(p_k, 3) return percent_d
def handle_m2m ( self , sender , instance , * * kwargs ) : self . handle_save ( instance . __class__ , instance )
1
python mutiple many to one relationship
Handle many to many relationships
cosqa-train-13622
def handle_m2m(self, sender, instance, **kwargs): """ Handle many to many relationships """ self.handle_save(instance.__class__, instance)
def token ( name ) : def wrap ( f ) : tokenizers . append ( ( name , f ) ) return f return wrap
1
how to create a tokenization code in python
Marker for a token
cosqa-train-13623
def token(name): """Marker for a token :param str name: Name of tokenizer """ def wrap(f): tokenizers.append((name, f)) return f return wrap
def title ( self ) : with switch_window ( self . _browser , self . name ) : return self . _browser . title
1
python mygui set title of window
The title of this window
cosqa-train-13624
def title(self): """ The title of this window """ with switch_window(self._browser, self.name): return self._browser.title
def input_yn ( conf_mess ) : ui_erase_ln ( ) ui_print ( conf_mess ) with term . cbreak ( ) : input_flush ( ) val = input_by_key ( ) return bool ( val . lower ( ) == 'y' )
1
how to create a yes or no response in python
Print Confirmation Message and Get Y / N response from user .
cosqa-train-13625
def input_yn(conf_mess): """Print Confirmation Message and Get Y/N response from user.""" ui_erase_ln() ui_print(conf_mess) with term.cbreak(): input_flush() val = input_by_key() return bool(val.lower() == 'y')
def get_last_id ( self , cur , table = 'reaction' ) : cur . execute ( "SELECT seq FROM sqlite_sequence WHERE name='{0}'" . format ( table ) ) result = cur . fetchone ( ) if result is not None : id = result [ 0 ] else : id = 0 return id
0
python mysql get last id
Get the id of the last written row in table
cosqa-train-13626
def get_last_id(self, cur, table='reaction'): """ Get the id of the last written row in table Parameters ---------- cur: database connection().cursor() object table: str 'reaction', 'publication', 'publication_system', 'reaction_system' Returns: id """ cur.execute("SELECT seq FROM sqlite_sequence WHERE name='{0}'" .format(table)) result = cur.fetchone() if result is not None: id = result[0] else: id = 0 return id
def from_dict ( cls , d ) : return cls ( * * { k : v for k , v in d . items ( ) if k in cls . ENTRIES } )
1
how to create an object from a dictionary key in python
Create an instance from a dictionary .
cosqa-train-13627
def from_dict(cls, d): """Create an instance from a dictionary.""" return cls(**{k: v for k, v in d.items() if k in cls.ENTRIES})
def _dictfetchall ( self , cursor ) : columns = [ col [ 0 ] for col in cursor . description ] return [ dict ( zip ( columns , row ) ) for row in cursor . fetchall ( ) ]
1
python mysql result as dict
Return all rows from a cursor as a dict .
cosqa-train-13628
def _dictfetchall(self, cursor): """ Return all rows from a cursor as a dict. """ columns = [col[0] for col in cursor.description] return [ dict(zip(columns, row)) for row in cursor.fetchall() ]
def create_node ( self , network , participant ) : return self . models . MCMCPAgent ( network = network , participant = participant )
0
how to create empty node python
Create a node for a participant .
cosqa-train-13629
def create_node(self, network, participant): """Create a node for a participant.""" return self.models.MCMCPAgent(network=network, participant=participant)
def index_nearest ( array , value ) : idx = ( np . abs ( array - value ) ) . argmin ( ) return idx
1
python nearest value in a list
Finds index of nearest value in array . Args : array : numpy array value : Returns : int http : // stackoverflow . com / questions / 2566412 / find - nearest - value - in - numpy - array
cosqa-train-13630
def index_nearest(array, value): """ Finds index of nearest value in array. Args: array: numpy array value: Returns: int http://stackoverflow.com/questions/2566412/find-nearest-value-in-numpy-array """ idx = (np.abs(array-value)).argmin() return idx
def a2s ( a ) : s = np . zeros ( ( 6 , ) , 'f' ) # make the a matrix for i in range ( 3 ) : s [ i ] = a [ i ] [ i ] s [ 3 ] = a [ 0 ] [ 1 ] s [ 4 ] = a [ 1 ] [ 2 ] s [ 5 ] = a [ 0 ] [ 2 ] return s
1
how to create matrix in python 10?10 all ones
convert 3 3 a matrix to 6 element s list ( see Tauxe 1998 )
cosqa-train-13631
def a2s(a): """ convert 3,3 a matrix to 6 element "s" list (see Tauxe 1998) """ s = np.zeros((6,), 'f') # make the a matrix for i in range(3): s[i] = a[i][i] s[3] = a[0][1] s[4] = a[1][2] s[5] = a[0][2] return s
def flatten ( lis ) : new_lis = [ ] for item in lis : if isinstance ( item , collections . Sequence ) and not isinstance ( item , basestring ) : new_lis . extend ( flatten ( item ) ) else : new_lis . append ( item ) return new_lis
1
python nested list flatten
Given a list possibly nested to any level return it flattened .
cosqa-train-13632
def flatten(lis): """Given a list, possibly nested to any level, return it flattened.""" new_lis = [] for item in lis: if isinstance(item, collections.Sequence) and not isinstance(item, basestring): new_lis.extend(flatten(item)) else: new_lis.append(item) return new_lis
def doc_parser ( ) : parser = argparse . ArgumentParser ( prog = 'ambry' , description = 'Ambry {}. Management interface for ambry, libraries ' 'and repositories. ' . format ( ambry . _meta . __version__ ) ) return parser
1
how to create nested argparse in python
Utility function to allow getting the arguments for a single command for Sphinx documentation
cosqa-train-13633
def doc_parser(): """Utility function to allow getting the arguments for a single command, for Sphinx documentation""" parser = argparse.ArgumentParser( prog='ambry', description='Ambry {}. Management interface for ambry, libraries ' 'and repositories. '.format(ambry._meta.__version__)) return parser
def has_edge ( self , edge ) : u , v = edge return ( u , v ) in self . edge_properties
0
python networkx check edge attribute exist
Return whether an edge exists .
cosqa-train-13634
def has_edge(self, edge): """ Return whether an edge exists. @type edge: tuple @param edge: Edge. @rtype: boolean @return: Truth-value for edge existence. """ u, v = edge return (u, v) in self.edge_properties
def safe_int ( val , default = None ) : try : val = int ( val ) except ( ValueError , TypeError ) : val = default return val
1
how to default value in python
Returns int () of val if val is not convertable to int use default instead
cosqa-train-13635
def safe_int(val, default=None): """ Returns int() of val if val is not convertable to int use default instead :param val: :param default: """ try: val = int(val) except (ValueError, TypeError): val = default return val
def next ( self ) : item = six . next ( self . _item_iter ) result = self . _item_to_value ( self . _parent , item ) # Since we've successfully got the next value from the # iterator, we update the number of remaining. self . _remaining -= 1 return result
1
python next item in loop
Get the next value in the page .
cosqa-train-13636
def next(self): """Get the next value in the page.""" item = six.next(self._item_iter) result = self._item_to_value(self._parent, item) # Since we've successfully got the next value from the # iterator, we update the number of remaining. self._remaining -= 1 return result
def _Enum ( docstring , * names ) : enums = dict ( zip ( names , range ( len ( names ) ) ) ) reverse = dict ( ( value , key ) for key , value in enums . iteritems ( ) ) enums [ 'reverse_mapping' ] = reverse enums [ '__doc__' ] = docstring return type ( 'Enum' , ( object , ) , enums )
1
how to define an enum in python
Utility to generate enum classes used by annotations .
cosqa-train-13637
def _Enum(docstring, *names): """Utility to generate enum classes used by annotations. Args: docstring: Docstring for the generated enum class. *names: Enum names. Returns: A class that contains enum names as attributes. """ enums = dict(zip(names, range(len(names)))) reverse = dict((value, key) for key, value in enums.iteritems()) enums['reverse_mapping'] = reverse enums['__doc__'] = docstring return type('Enum', (object,), enums)
def purge_duplicates ( list_in ) : _list = [ ] for item in list_in : if item not in _list : _list . append ( item ) return _list
1
python no duplicate in list
Remove duplicates from list while preserving order .
cosqa-train-13638
def purge_duplicates(list_in): """Remove duplicates from list while preserving order. Parameters ---------- list_in: Iterable Returns ------- list List of first occurences in order """ _list = [] for item in list_in: if item not in _list: _list.append(item) return _list
def __eq__ ( self , other ) : return isinstance ( other , self . __class__ ) and self . _freeze ( ) == other . _freeze ( )
1
how to define object equality python
Determine if two objects are equal .
cosqa-train-13639
def __eq__(self, other): """Determine if two objects are equal.""" return isinstance(other, self.__class__) \ and self._freeze() == other._freeze()
def is_a_sequence ( var , allow_none = False ) : return isinstance ( var , ( list , tuple ) ) or ( var is None and allow_none )
0
python nonetype in a if
Returns True if var is a list or a tuple ( but not a string! )
cosqa-train-13640
def is_a_sequence(var, allow_none=False): """ Returns True if var is a list or a tuple (but not a string!) """ return isinstance(var, (list, tuple)) or (var is None and allow_none)
def earth_orientation ( date ) : x_p , y_p , s_prime = np . deg2rad ( _earth_orientation ( date ) ) return rot3 ( - s_prime ) @ rot2 ( x_p ) @ rot1 ( y_p )
1
how to deifne a rotation in python
Earth orientation as a rotating matrix
cosqa-train-13641
def earth_orientation(date): """Earth orientation as a rotating matrix """ x_p, y_p, s_prime = np.deg2rad(_earth_orientation(date)) return rot3(-s_prime) @ rot2(x_p) @ rot1(y_p)
def listlike ( obj ) : return hasattr ( obj , "__iter__" ) and not issubclass ( type ( obj ) , str ) and not issubclass ( type ( obj ) , unicode )
0
python nonetype' object is not iterable
Is an object iterable like a list ( and not a string ) ?
cosqa-train-13642
def listlike(obj): """Is an object iterable like a list (and not a string)?""" return hasattr(obj, "__iter__") \ and not issubclass(type(obj), str)\ and not issubclass(type(obj), unicode)
def delete_all_eggs ( self ) : path_to_delete = os . path . join ( self . egg_directory , "lib" , "python" ) if os . path . exists ( path_to_delete ) : shutil . rmtree ( path_to_delete )
0
how to delete all python files on my computer windows 10
delete all the eggs in the directory specified
cosqa-train-13643
def delete_all_eggs(self): """ delete all the eggs in the directory specified """ path_to_delete = os.path.join(self.egg_directory, "lib", "python") if os.path.exists(path_to_delete): shutil.rmtree(path_to_delete)
def Gaussian ( x , mu , sig ) : return sympy . exp ( - ( x - mu ) ** 2 / ( 2 * sig ** 2 ) ) / sympy . sqrt ( 2 * sympy . pi * sig ** 2 )
0
python normal distribution scipy
Gaussian pdf . : param x : free variable . : param mu : mean of the distribution . : param sig : standard deviation of the distribution . : return : sympy . Expr for a Gaussian pdf .
cosqa-train-13644
def Gaussian(x, mu, sig): """ Gaussian pdf. :param x: free variable. :param mu: mean of the distribution. :param sig: standard deviation of the distribution. :return: sympy.Expr for a Gaussian pdf. """ return sympy.exp(-(x - mu)**2/(2*sig**2))/sympy.sqrt(2*sympy.pi*sig**2)
def remove_examples_all ( ) : d = examples_all_dir ( ) if d . exists ( ) : log . debug ( 'remove %s' , d ) d . rmtree ( ) else : log . debug ( 'nothing to remove: %s' , d )
1
how to delete directory if exists in python
remove arduino / examples / all directory .
cosqa-train-13645
def remove_examples_all(): """remove arduino/examples/all directory. :rtype: None """ d = examples_all_dir() if d.exists(): log.debug('remove %s', d) d.rmtree() else: log.debug('nothing to remove: %s', d)
def denorm ( self , arr ) : if type ( arr ) is not np . ndarray : arr = to_np ( arr ) if len ( arr . shape ) == 3 : arr = arr [ None ] return self . transform . denorm ( np . rollaxis ( arr , 1 , 4 ) )
1
python normalise image array
Reverse the normalization done to a batch of images .
cosqa-train-13646
def denorm(self,arr): """Reverse the normalization done to a batch of images. Arguments: arr: of shape/size (N,3,sz,sz) """ if type(arr) is not np.ndarray: arr = to_np(arr) if len(arr.shape)==3: arr = arr[None] return self.transform.denorm(np.rollaxis(arr,1,4))
def delete_index ( index ) : logger . info ( "Deleting search index: '%s'" , index ) client = get_client ( ) return client . indices . delete ( index = index )
1
how to delete item at indice python
Delete index entirely ( removes all documents and mapping ) .
cosqa-train-13647
def delete_index(index): """Delete index entirely (removes all documents and mapping).""" logger.info("Deleting search index: '%s'", index) client = get_client() return client.indices.delete(index=index)
def _normalize ( mat : np . ndarray ) : return ( ( mat - mat . min ( ) ) * ( 255 / mat . max ( ) ) ) . astype ( np . uint8 )
0
python normalize grayscale image
rescales a numpy array so that min is 0 and max is 255
cosqa-train-13648
def _normalize(mat: np.ndarray): """rescales a numpy array, so that min is 0 and max is 255""" return ((mat - mat.min()) * (255 / mat.max())).astype(np.uint8)
def _removeTags ( tags , objects ) : for t in tags : for o in objects : o . tags . remove ( t ) return True
1
how to delete objects in python
Removes tags from objects
cosqa-train-13649
def _removeTags(tags, objects): """ Removes tags from objects """ for t in tags: for o in objects: o.tags.remove(t) return True
def normalize ( X ) : X = coo_matrix ( X ) X . data = X . data / sqrt ( bincount ( X . row , X . data ** 2 ) ) [ X . row ] return X
0
python normalize matrix column
equivalent to scipy . preprocessing . normalize on sparse matrices but lets avoid another depedency just for a small utility function
cosqa-train-13650
def normalize(X): """ equivalent to scipy.preprocessing.normalize on sparse matrices , but lets avoid another depedency just for a small utility function """ X = coo_matrix(X) X.data = X.data / sqrt(bincount(X.row, X.data ** 2))[X.row] return X
def rm ( venv_name ) : inenv = InenvManager ( ) venv = inenv . get_venv ( venv_name ) click . confirm ( "Delete dir {}" . format ( venv . path ) ) shutil . rmtree ( venv . path )
1
how to delete one environment in python
Removes the venv by name
cosqa-train-13651
def rm(venv_name): """ Removes the venv by name """ inenv = InenvManager() venv = inenv.get_venv(venv_name) click.confirm("Delete dir {}".format(venv.path)) shutil.rmtree(venv.path)
def test ( nose_argsuments ) : from nose import run params = [ '__main__' , '-c' , 'nose.ini' ] params . extend ( nose_argsuments ) run ( argv = params )
1
python nose start context
Run application tests
cosqa-train-13652
def test(nose_argsuments): """ Run application tests """ from nose import run params = ['__main__', '-c', 'nose.ini'] params.extend(nose_argsuments) run(argv=params)
def __del__ ( self ) : if self . _delete_file : try : os . remove ( self . name ) except ( OSError , IOError ) : pass
1
how to delete self file in python
Deletes the database file .
cosqa-train-13653
def __del__(self): """Deletes the database file.""" if self._delete_file: try: os.remove(self.name) except (OSError, IOError): pass
def request ( self , method , url , body = None , headers = { } ) : self . _send_request ( method , url , body , headers )
1
python not sending requests
Send a complete request to the server .
cosqa-train-13654
def request(self, method, url, body=None, headers={}): """Send a complete request to the server.""" self._send_request(method, url, body, headers)
def sometimesish ( fn ) : def wrapped ( * args , * * kwargs ) : if random . randint ( 1 , 2 ) == 1 : return fn ( * args , * * kwargs ) return wrapped
0
how to detect the output of random function in python
Has a 50 / 50 chance of calling a function
cosqa-train-13655
def sometimesish(fn): """ Has a 50/50 chance of calling a function """ def wrapped(*args, **kwargs): if random.randint(1, 2) == 1: return fn(*args, **kwargs) return wrapped
def _not ( condition = None , * * kwargs ) : result = True if condition is not None : result = not run ( condition , * * kwargs ) return result
0
python not with multiple conditions
Return the opposite of input condition .
cosqa-train-13656
def _not(condition=None, **kwargs): """ Return the opposite of input condition. :param condition: condition to process. :result: not condition. :rtype: bool """ result = True if condition is not None: result = not run(condition, **kwargs) return result
def is_numeric_dtype ( dtype ) : dtype = np . dtype ( dtype ) return np . issubsctype ( getattr ( dtype , 'base' , None ) , np . number )
1
how to determine data types in python
Return True if dtype is a numeric type .
cosqa-train-13657
def is_numeric_dtype(dtype): """Return ``True`` if ``dtype`` is a numeric type.""" dtype = np.dtype(dtype) return np.issubsctype(getattr(dtype, 'base', None), np.number)
def fn_min ( self , a , axis = None ) : return numpy . nanmin ( self . _to_ndarray ( a ) , axis = axis )
1
python np array get min values
Return the minimum of an array ignoring any NaNs .
cosqa-train-13658
def fn_min(self, a, axis=None): """ Return the minimum of an array, ignoring any NaNs. :param a: The array. :return: The minimum value of the array. """ return numpy.nanmin(self._to_ndarray(a), axis=axis)
def load_library ( version ) : check_version ( version ) module_name = SUPPORTED_LIBRARIES [ version ] lib = sys . modules . get ( module_name ) if lib is None : lib = importlib . import_module ( module_name ) return lib
1
how to determine language for python libraries
Load the correct module according to the version
cosqa-train-13659
def load_library(version): """ Load the correct module according to the version :type version: ``str`` :param version: the version of the library to be loaded (e.g. '2.6') :rtype: module object """ check_version(version) module_name = SUPPORTED_LIBRARIES[version] lib = sys.modules.get(module_name) if lib is None: lib = importlib.import_module(module_name) return lib
def _scale_shape ( dshape , scale = ( 1 , 1 , 1 ) ) : nshape = np . round ( np . array ( dshape ) * np . array ( scale ) ) return tuple ( nshape . astype ( np . int ) )
1
python np image scale
returns the shape after scaling ( should be the same as ndimage . zoom
cosqa-train-13660
def _scale_shape(dshape, scale = (1,1,1)): """returns the shape after scaling (should be the same as ndimage.zoom""" nshape = np.round(np.array(dshape) * np.array(scale)) return tuple(nshape.astype(np.int))
def find_geom ( geom , geoms ) : for i , g in enumerate ( geoms ) : if g is geom : return i
1
how to determine the index of an object on a list python
Returns the index of a geometry in a list of geometries avoiding expensive equality checks of in operator .
cosqa-train-13661
def find_geom(geom, geoms): """ Returns the index of a geometry in a list of geometries avoiding expensive equality checks of `in` operator. """ for i, g in enumerate(geoms): if g is geom: return i
def torecarray ( * args , * * kwargs ) : import numpy as np return toarray ( * args , * * kwargs ) . view ( np . recarray )
1
python numpy arrary with same space
Convenient shorthand for toarray ( * args ** kwargs ) . view ( np . recarray ) .
cosqa-train-13662
def torecarray(*args, **kwargs): """ Convenient shorthand for ``toarray(*args, **kwargs).view(np.recarray)``. """ import numpy as np return toarray(*args, **kwargs).view(np.recarray)
def isTestCaseDisabled ( test_case_class , method_name ) : test_method = getattr ( test_case_class , method_name ) return getattr ( test_method , "__test__" , 'not nose' ) is False
0
how to disable a test in python
I check to see if a method on a TestCase has been disabled via nose s convention for disabling a TestCase . This makes it so that users can mix nose s parameterized tests with green as a runner .
cosqa-train-13663
def isTestCaseDisabled(test_case_class, method_name): """ I check to see if a method on a TestCase has been disabled via nose's convention for disabling a TestCase. This makes it so that users can mix nose's parameterized tests with green as a runner. """ test_method = getattr(test_case_class, method_name) return getattr(test_method, "__test__", 'not nose') is False
def ma ( self ) : a = self . array return numpy . ma . MaskedArray ( a , mask = numpy . logical_not ( numpy . isfinite ( a ) ) )
1
python numpy array how to return rows not include nan
Represent data as a masked array .
cosqa-train-13664
def ma(self): """Represent data as a masked array. The array is returned with column-first indexing, i.e. for a data file with columns X Y1 Y2 Y3 ... the array a will be a[0] = X, a[1] = Y1, ... . inf and nan are filtered via :func:`numpy.isfinite`. """ a = self.array return numpy.ma.MaskedArray(a, mask=numpy.logical_not(numpy.isfinite(a)))
def gtype ( n ) : t = type ( n ) . __name__ return str ( t ) if t != 'Literal' else 'Literal, {}' . format ( n . language )
1
how to display the data type python
Return the a string with the data type of a value for Graph data
cosqa-train-13665
def gtype(n): """ Return the a string with the data type of a value, for Graph data """ t = type(n).__name__ return str(t) if t != 'Literal' else 'Literal, {}'.format(n.language)
def get_column ( self , X , column ) : if isinstance ( X , pd . DataFrame ) : return X [ column ] . values return X [ : , column ]
1
python numpy array how to select column
Return a column of the given matrix .
cosqa-train-13666
def get_column(self, X, column): """Return a column of the given matrix. Args: X: `numpy.ndarray` or `pandas.DataFrame`. column: `int` or `str`. Returns: np.ndarray: Selected column. """ if isinstance(X, pd.DataFrame): return X[column].values return X[:, column]
def filter_symlog ( y , base = 10.0 ) : log_base = np . log ( base ) sign = np . sign ( y ) logs = np . log ( np . abs ( y ) / log_base ) return sign * logs
1
how to do a logriithmic scale graph in python
Symmetrical logarithmic scale .
cosqa-train-13667
def filter_symlog(y, base=10.0): """Symmetrical logarithmic scale. Optional arguments: *base*: The base of the logarithm. """ log_base = np.log(base) sign = np.sign(y) logs = np.log(np.abs(y) / log_base) return sign * logs
def length ( self ) : return np . sqrt ( np . sum ( self ** 2 , axis = 1 ) ) . view ( np . ndarray )
0
python numpy array two dim list
Array of vector lengths
cosqa-train-13668
def length(self): """Array of vector lengths""" return np.sqrt(np.sum(self**2, axis=1)).view(np.ndarray)
def assert_is_not ( expected , actual , message = None , extra = None ) : assert expected is not actual , _assert_fail_message ( message , expected , actual , "is" , extra )
0
how to do an assert to check for none in python
Raises an AssertionError if expected is actual .
cosqa-train-13669
def assert_is_not(expected, actual, message=None, extra=None): """Raises an AssertionError if expected is actual.""" assert expected is not actual, _assert_fail_message( message, expected, actual, "is", extra )
def flatten_array ( grid ) : grid = [ grid [ i ] [ j ] for i in range ( len ( grid ) ) for j in range ( len ( grid [ i ] ) ) ] while type ( grid [ 0 ] ) is list : grid = flatten_array ( grid ) return grid
1
python numpy flatten reshape
Takes a multi - dimensional array and returns a 1 dimensional array with the same contents .
cosqa-train-13670
def flatten_array(grid): """ Takes a multi-dimensional array and returns a 1 dimensional array with the same contents. """ grid = [grid[i][j] for i in range(len(grid)) for j in range(len(grid[i]))] while type(grid[0]) is list: grid = flatten_array(grid) return grid
def exp_fit_fun ( x , a , tau , c ) : # pylint: disable=invalid-name return a * np . exp ( - x / tau ) + c
1
how to do an exponential fit in python
Function used to fit the exponential decay .
cosqa-train-13671
def exp_fit_fun(x, a, tau, c): """Function used to fit the exponential decay.""" # pylint: disable=invalid-name return a * np.exp(-x / tau) + c
def to_distribution_values ( self , values ) : with warnings . catch_warnings ( ) : warnings . simplefilter ( "ignore" ) # avoid RuntimeWarning: divide by zero encountered in log return numpy . log ( values )
0
python numpy log of float array
Returns numpy array of natural logarithms of values .
cosqa-train-13672
def to_distribution_values(self, values): """ Returns numpy array of natural logarithms of ``values``. """ with warnings.catch_warnings(): warnings.simplefilter("ignore") # avoid RuntimeWarning: divide by zero encountered in log return numpy.log(values)
def downcaseTokens ( s , l , t ) : return [ tt . lower ( ) for tt in map ( _ustr , t ) ]
1
how to do lowercase in python
Helper parse action to convert tokens to lower case .
cosqa-train-13673
def downcaseTokens(s,l,t): """Helper parse action to convert tokens to lower case.""" return [ tt.lower() for tt in map(_ustr,t) ]
def fn_min ( self , a , axis = None ) : return numpy . nanmin ( self . _to_ndarray ( a ) , axis = axis )
1
python numpy minimum value of array
Return the minimum of an array ignoring any NaNs .
cosqa-train-13674
def fn_min(self, a, axis=None): """ Return the minimum of an array, ignoring any NaNs. :param a: The array. :return: The minimum value of the array. """ return numpy.nanmin(self._to_ndarray(a), axis=axis)
def downcaseTokens ( s , l , t ) : return [ tt . lower ( ) for tt in map ( _ustr , t ) ]
1
how to do lowercase on python
Helper parse action to convert tokens to lower case .
cosqa-train-13675
def downcaseTokens(s,l,t): """Helper parse action to convert tokens to lower case.""" return [ tt.lower() for tt in map(_ustr,t) ]
def get_tweepy_auth ( twitter_api_key , twitter_api_secret , twitter_access_token , twitter_access_token_secret ) : auth = tweepy . OAuthHandler ( twitter_api_key , twitter_api_secret ) auth . set_access_token ( twitter_access_token , twitter_access_token_secret ) return auth
1
python oauth2 authentication for twitter
Make a tweepy auth object
cosqa-train-13676
def get_tweepy_auth(twitter_api_key, twitter_api_secret, twitter_access_token, twitter_access_token_secret): """Make a tweepy auth object""" auth = tweepy.OAuthHandler(twitter_api_key, twitter_api_secret) auth.set_access_token(twitter_access_token, twitter_access_token_secret) return auth
def replace_tab_indent ( s , replace = " " ) : prefix = get_indent_prefix ( s ) return prefix . replace ( "\t" , replace ) + s [ len ( prefix ) : ]
0
how to do tabs in a python string
: param str s : string with tabs : param str replace : e . g . 4 spaces : rtype : str
cosqa-train-13677
def replace_tab_indent(s, replace=" "): """ :param str s: string with tabs :param str replace: e.g. 4 spaces :rtype: str """ prefix = get_indent_prefix(s) return prefix.replace("\t", replace) + s[len(prefix):]
def to_json ( obj ) : i = StringIO . StringIO ( ) w = Writer ( i , encoding = 'UTF-8' ) w . write_value ( obj ) return i . getvalue ( )
0
python object into json
Return a json string representing the python object obj .
cosqa-train-13678
def to_json(obj): """Return a json string representing the python object obj.""" i = StringIO.StringIO() w = Writer(i, encoding='UTF-8') w.write_value(obj) return i.getvalue()
def seconds ( num ) : now = pytime . time ( ) end = now + num until ( end )
1
how to do things after a set amount of time in python
Pause for this many seconds
cosqa-train-13679
def seconds(num): """ Pause for this many seconds """ now = pytime.time() end = now + num until(end)
def dict_merge ( set1 , set2 ) : return dict ( list ( set1 . items ( ) ) + list ( set2 . items ( ) ) )
1
python one liner union of two dicts
Joins two dictionaries .
cosqa-train-13680
def dict_merge(set1, set2): """Joins two dictionaries.""" return dict(list(set1.items()) + list(set2.items()))
def _draw_lines_internal ( self , coords , colour , bg ) : for i , ( x , y ) in enumerate ( coords ) : if i == 0 : self . _screen . move ( x , y ) else : self . _screen . draw ( x , y , colour = colour , bg = bg , thin = True )
0
how to draw a line in python screen
Helper to draw lines connecting a set of nodes that are scaled for the Screen .
cosqa-train-13681
def _draw_lines_internal(self, coords, colour, bg): """Helper to draw lines connecting a set of nodes that are scaled for the Screen.""" for i, (x, y) in enumerate(coords): if i == 0: self._screen.move(x, y) else: self._screen.draw(x, y, colour=colour, bg=bg, thin=True)
def _replace_file ( path , content ) : if os . path . exists ( path ) : with open ( path , 'r' ) as f : if content == f . read ( ) : print ( "Not overwriting {} because it is unchanged" . format ( path ) , file = sys . stderr ) return with open ( path , 'w' ) as f : f . write ( content )
1
python only write file if doesn't already have contents
Writes a file if it doesn t already exist with the same content .
cosqa-train-13682
def _replace_file(path, content): """Writes a file if it doesn't already exist with the same content. This is useful because cargo uses timestamps to decide whether to compile things.""" if os.path.exists(path): with open(path, 'r') as f: if content == f.read(): print("Not overwriting {} because it is unchanged".format(path), file=sys.stderr) return with open(path, 'w') as f: f.write(content)
def vline ( self , x , y , height , color ) : self . rect ( x , y , 1 , height , color , fill = True )
0
how to draw the straight line in python
Draw a vertical line up to a given length .
cosqa-train-13683
def vline(self, x, y, height, color): """Draw a vertical line up to a given length.""" self.rect(x, y, 1, height, color, fill=True)
def do_serial ( self , p ) : try : self . serial . port = p self . serial . open ( ) print 'Opening serial port: %s' % p except Exception , e : print 'Unable to open serial port: %s' % p
1
python open serial port on windows
Set the serial port e . g . : / dev / tty . usbserial - A4001ib8
cosqa-train-13684
def do_serial(self, p): """Set the serial port, e.g.: /dev/tty.usbserial-A4001ib8""" try: self.serial.port = p self.serial.open() print 'Opening serial port: %s' % p except Exception, e: print 'Unable to open serial port: %s' % p
def chmod_add_excute ( filename ) : st = os . stat ( filename ) os . chmod ( filename , st . st_mode | stat . S_IEXEC )
0
how to edit a fie in python without permission
Adds execute permission to file . : param filename : : return :
cosqa-train-13685
def chmod_add_excute(filename): """ Adds execute permission to file. :param filename: :return: """ st = os.stat(filename) os.chmod(filename, st.st_mode | stat.S_IEXEC)
def delete ( filething ) : f = FLAC ( filething ) filething . fileobj . seek ( 0 ) f . delete ( filething )
1
python open wipe out a file
Remove tags from a file .
cosqa-train-13686
def delete(filething): """Remove tags from a file. Args: filething (filething) Raises: mutagen.MutagenError """ f = FLAC(filething) filething.fileobj.seek(0) f.delete(filething)
def _float_feature ( value ) : if not isinstance ( value , list ) : value = [ value ] return tf . train . Feature ( float_list = tf . train . FloatList ( value = value ) )
1
how to enable float values in python
Wrapper for inserting float features into Example proto .
cosqa-train-13687
def _float_feature(value): """Wrapper for inserting float features into Example proto.""" if not isinstance(value, list): value = [value] return tf.train.Feature(float_list=tf.train.FloatList(value=value))
def paste ( xsel = False ) : selection = "primary" if xsel else "clipboard" try : return subprocess . Popen ( [ "xclip" , "-selection" , selection , "-o" ] , stdout = subprocess . PIPE ) . communicate ( ) [ 0 ] . decode ( "utf-8" ) except OSError as why : raise XclipNotFound
1
python openclipboard access is denied win32clipboard
Returns system clipboard contents .
cosqa-train-13688
def paste(xsel=False): """Returns system clipboard contents.""" selection = "primary" if xsel else "clipboard" try: return subprocess.Popen(["xclip", "-selection", selection, "-o"], stdout=subprocess.PIPE).communicate()[0].decode("utf-8") except OSError as why: raise XclipNotFound
def read_credentials ( fname ) : with open ( fname , 'r' ) as f : username = f . readline ( ) . strip ( '\n' ) password = f . readline ( ) . strip ( '\n' ) return username , password
1
how to extract username and password from password file in python
read a simple text file from a private location to get username and password
cosqa-train-13689
def read_credentials(fname): """ read a simple text file from a private location to get username and password """ with open(fname, 'r') as f: username = f.readline().strip('\n') password = f.readline().strip('\n') return username, password
def _rgbtomask ( self , obj ) : dat = obj . get_image ( ) . get_data ( ) # RGB arrays return dat . sum ( axis = 2 ) . astype ( np . bool )
0
python opencv apply 2d mask to 3 band image
Convert RGB arrays from mask canvas object back to boolean mask .
cosqa-train-13690
def _rgbtomask(self, obj): """Convert RGB arrays from mask canvas object back to boolean mask.""" dat = obj.get_image().get_data() # RGB arrays return dat.sum(axis=2).astype(np.bool)
def get_bound ( pts ) : ( x0 , y0 , x1 , y1 ) = ( INF , INF , - INF , - INF ) for ( x , y ) in pts : x0 = min ( x0 , x ) y0 = min ( y0 , y ) x1 = max ( x1 , x ) y1 = max ( y1 , y ) return ( x0 , y0 , x1 , y1 )
1
how to figure out bounds in python
Compute a minimal rectangle that covers all the points .
cosqa-train-13691
def get_bound(pts): """Compute a minimal rectangle that covers all the points.""" (x0, y0, x1, y1) = (INF, INF, -INF, -INF) for (x, y) in pts: x0 = min(x0, x) y0 = min(y0, y) x1 = max(x1, x) y1 = max(y1, y) return (x0, y0, x1, y1)
def screen_cv2 ( self ) : pil_image = self . screen . convert ( 'RGB' ) cv2_image = np . array ( pil_image ) pil_image . close ( ) # Convert RGB to BGR cv2_image = cv2_image [ : , : , : : - 1 ] return cv2_image
1
python opencv black screen
cv2 Image of current window screen
cosqa-train-13692
def screen_cv2(self): """cv2 Image of current window screen""" pil_image = self.screen.convert('RGB') cv2_image = np.array(pil_image) pil_image.close() # Convert RGB to BGR cv2_image = cv2_image[:, :, ::-1] return cv2_image
def match_aspect_to_viewport ( self ) : viewport = self . viewport self . aspect = float ( viewport . width ) / viewport . height
0
python opencv camera default resolution
Updates Camera . aspect to match the viewport s aspect ratio .
cosqa-train-13693
def match_aspect_to_viewport(self): """Updates Camera.aspect to match the viewport's aspect ratio.""" viewport = self.viewport self.aspect = float(viewport.width) / viewport.height
def filter_list_by_indices ( lst , indices ) : return [ x for i , x in enumerate ( lst ) if i in indices ]
1
how to filter numbers based on list of indices in python
Return a modified list containing only the indices indicated .
cosqa-train-13694
def filter_list_by_indices(lst, indices): """Return a modified list containing only the indices indicated. Args: lst: Original list of values indices: List of indices to keep from the original list Returns: list: Filtered list of values """ return [x for i, x in enumerate(lst) if i in indices]
def read_img ( path ) : img = cv2 . resize ( cv2 . imread ( path , 0 ) , ( 80 , 30 ) ) . astype ( np . float32 ) / 255 img = np . expand_dims ( img . transpose ( 1 , 0 ) , 0 ) return img
1
python opencv load image to numpy
Reads image specified by path into numpy . ndarray
cosqa-train-13695
def read_img(path): """ Reads image specified by path into numpy.ndarray""" img = cv2.resize(cv2.imread(path, 0), (80, 30)).astype(np.float32) / 255 img = np.expand_dims(img.transpose(1, 0), 0) return img
def _remove_keywords ( d ) : return { k : v for k , v in iteritems ( d ) if k not in RESERVED }
1
how to filter through dict python
copy the dict filter_keywords
cosqa-train-13696
def _remove_keywords(d): """ copy the dict, filter_keywords Parameters ---------- d : dict """ return { k:v for k, v in iteritems(d) if k not in RESERVED }
def read_img ( path ) : img = cv2 . resize ( cv2 . imread ( path , 0 ) , ( 80 , 30 ) ) . astype ( np . float32 ) / 255 img = np . expand_dims ( img . transpose ( 1 , 0 ) , 0 ) return img
1
python opencv not reading image from full path
Reads image specified by path into numpy . ndarray
cosqa-train-13697
def read_img(path): """ Reads image specified by path into numpy.ndarray""" img = cv2.resize(cv2.imread(path, 0), (80, 30)).astype(np.float32) / 255 img = np.expand_dims(img.transpose(1, 0), 0) return img
def filter_bolts ( table , header ) : bolts_info = [ ] for row in table : if row [ 0 ] == 'bolt' : bolts_info . append ( row ) return bolts_info , header
1
how to filter value from a table in python
filter to keep bolts
cosqa-train-13698
def filter_bolts(table, header): """ filter to keep bolts """ bolts_info = [] for row in table: if row[0] == 'bolt': bolts_info.append(row) return bolts_info, header
def _openpyxl_read_xl ( xl_path : str ) : try : wb = load_workbook ( filename = xl_path , read_only = True ) except : raise else : return wb
1
python openpyxl remain style
Use openpyxl to read an Excel file .
cosqa-train-13699
def _openpyxl_read_xl(xl_path: str): """ Use openpyxl to read an Excel file. """ try: wb = load_workbook(filename=xl_path, read_only=True) except: raise else: return wb