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 min_depth ( self , root ) : if root is None : return 0 if root . left is not None or root . right is not None : return max ( self . minDepth ( root . left ) , self . minDepth ( root . right ) ) + 1 return min ( self . minDepth ( root . left ) , self . minDepth ( root . right ) ) + 1
1
get depth of tree node python elementree
: type root : TreeNode : rtype : int
cosqa-train-13300
def min_depth(self, root): """ :type root: TreeNode :rtype: int """ if root is None: return 0 if root.left is not None or root.right is not None: return max(self.minDepth(root.left), self.minDepth(root.right))+1 return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
def stats ( self ) : printDebug ( "Classes.....: %d" % len ( self . all_classes ) ) printDebug ( "Properties..: %d" % len ( self . all_properties ) )
1
python how to print information about functions methods
shotcut to pull out useful info for interactive use
cosqa-train-13301
def stats(self): """ shotcut to pull out useful info for interactive use """ printDebug("Classes.....: %d" % len(self.all_classes)) printDebug("Properties..: %d" % len(self.all_properties))
def get_dimension_array ( array ) : if all ( isinstance ( el , list ) for el in array ) : result = [ len ( array ) , len ( max ( [ x for x in array ] , key = len , ) ) ] # elif array and isinstance(array, list): else : result = [ len ( array ) , 1 ] return result
1
get dimensions of python list
Get dimension of an array getting the number of rows and the max num of columns .
cosqa-train-13302
def get_dimension_array(array): """ Get dimension of an array getting the number of rows and the max num of columns. """ if all(isinstance(el, list) for el in array): result = [len(array), len(max([x for x in array], key=len,))] # elif array and isinstance(array, list): else: result = [len(array), 1] return result
def rand_elem ( seq , n = None ) : return map ( random . choice , repeat ( seq , n ) if n is not None else repeat ( seq ) )
1
python how to random pick a few elemts
returns a random element from seq n times . If n is None it continues indefinitly
cosqa-train-13303
def rand_elem(seq, n=None): """returns a random element from seq n times. If n is None, it continues indefinitly""" return map(random.choice, repeat(seq, n) if n is not None else repeat(seq))
def AmericanDateToEpoch ( self , date_str ) : try : epoch = time . strptime ( date_str , "%m/%d/%Y" ) return int ( calendar . timegm ( epoch ) ) * 1000000 except ValueError : return 0
0
get epoch of a date in python
Take a US format date and return epoch .
cosqa-train-13304
def AmericanDateToEpoch(self, date_str): """Take a US format date and return epoch.""" try: epoch = time.strptime(date_str, "%m/%d/%Y") return int(calendar.timegm(epoch)) * 1000000 except ValueError: return 0
def _remove_from_index ( index , obj ) : try : index . value_map [ indexed_value ( index , obj ) ] . remove ( obj . id ) except KeyError : pass
1
python how to remove from an index
Removes object obj from the index .
cosqa-train-13305
def _remove_from_index(index, obj): """Removes object ``obj`` from the ``index``.""" try: index.value_map[indexed_value(index, obj)].remove(obj.id) except KeyError: pass
def PopTask ( self ) : try : _ , task = heapq . heappop ( self . _heap ) except IndexError : return None self . _task_identifiers . remove ( task . identifier ) return task
0
get first element in queue python
Retrieves and removes the first task from the heap .
cosqa-train-13306
def PopTask(self): """Retrieves and removes the first task from the heap. Returns: Task: the task or None if the heap is empty. """ try: _, task = heapq.heappop(self._heap) except IndexError: return None self._task_identifiers.remove(task.identifier) return task
def remove_punctuation ( text , exceptions = [ ] ) : all_but = [ r'\w' , r'\s' ] all_but . extend ( exceptions ) pattern = '[^{}]' . format ( '' . join ( all_but ) ) return re . sub ( pattern , '' , text )
1
python how to remove punctuation from a text
Return a string with punctuation removed .
cosqa-train-13307
def remove_punctuation(text, exceptions=[]): """ Return a string with punctuation removed. Parameters: text (str): The text to remove punctuation from. exceptions (list): List of symbols to keep in the given text. Return: str: The input text without the punctuation. """ all_but = [ r'\w', r'\s' ] all_but.extend(exceptions) pattern = '[^{}]'.format(''.join(all_but)) return re.sub(pattern, '', text)
def path_for_import ( name ) : return os . path . dirname ( os . path . abspath ( import_module ( name ) . __file__ ) )
1
get full name of path in python
Returns the directory path for the given package or module .
cosqa-train-13308
def path_for_import(name): """ Returns the directory path for the given package or module. """ return os.path.dirname(os.path.abspath(import_module(name).__file__))
def dict_keys_without_hyphens ( a_dict ) : return dict ( ( key . replace ( '-' , '_' ) , val ) for key , val in a_dict . items ( ) )
0
python how to remove punctuation marks in a dictionary
Return the a new dict with underscores instead of hyphens in keys .
cosqa-train-13309
def dict_keys_without_hyphens(a_dict): """Return the a new dict with underscores instead of hyphens in keys.""" return dict( (key.replace('-', '_'), val) for key, val in a_dict.items())
def get_func_name ( func ) : func_name = getattr ( func , '__name__' , func . __class__ . __name__ ) module_name = func . __module__ if module_name is not None : module_name = func . __module__ return '{}.{}' . format ( module_name , func_name ) return func_name
1
get function name python
Return a name which includes the module name and function name .
cosqa-train-13310
def get_func_name(func): """Return a name which includes the module name and function name.""" func_name = getattr(func, '__name__', func.__class__.__name__) module_name = func.__module__ if module_name is not None: module_name = func.__module__ return '{}.{}'.format(module_name, func_name) return func_name
def _init_unique_sets ( self ) : ks = dict ( ) for t in self . _unique_checks : key = t [ 0 ] ks [ key ] = set ( ) # empty set return ks
1
python how to represent unique set
Initialise sets used for uniqueness checking .
cosqa-train-13311
def _init_unique_sets(self): """Initialise sets used for uniqueness checking.""" ks = dict() for t in self._unique_checks: key = t[0] ks[key] = set() # empty set return ks
def eval_Rf ( self , Vf ) : return sl . inner ( self . Df , Vf , axis = self . cri . axisM ) - self . Sf
1
get gradient of rbf interpolation python
Evaluate smooth term in Vf .
cosqa-train-13312
def eval_Rf(self, Vf): """Evaluate smooth term in Vf.""" return sl.inner(self.Df, Vf, axis=self.cri.axisM) - self.Sf
def _update_index_on_df ( df , index_names ) : if index_names : df = df . set_index ( index_names ) # Remove names from unnamed indexes index_names = _denormalize_index_names ( index_names ) df . index . names = index_names return df
1
python how to restructure the index on a data frame
Helper function to restore index information after collection . Doesn t use self so we can serialize this .
cosqa-train-13313
def _update_index_on_df(df, index_names): """Helper function to restore index information after collection. Doesn't use self so we can serialize this.""" if index_names: df = df.set_index(index_names) # Remove names from unnamed indexes index_names = _denormalize_index_names(index_names) df.index.names = index_names return df
def _hue ( color , * * kwargs ) : h = colorsys . rgb_to_hls ( * [ x / 255.0 for x in color . value [ : 3 ] ] ) [ 0 ] return NumberValue ( h * 360.0 )
1
get hue value from hsv image python
Get hue value of HSL color .
cosqa-train-13314
def _hue(color, **kwargs): """ Get hue value of HSL color. """ h = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[0] return NumberValue(h * 360.0)
def is_integer ( dtype ) : dtype = tf . as_dtype ( dtype ) if hasattr ( dtype , 'is_integer' ) : return dtype . is_integer return np . issubdtype ( np . dtype ( dtype ) , np . integer )
0
python how to say is type positive integer
Returns whether this is a ( non - quantized ) integer type .
cosqa-train-13315
def is_integer(dtype): """Returns whether this is a (non-quantized) integer type.""" dtype = tf.as_dtype(dtype) if hasattr(dtype, 'is_integer'): return dtype.is_integer return np.issubdtype(np.dtype(dtype), np.integer)
def uniquify_list ( L ) : return [ e for i , e in enumerate ( L ) if L . index ( e ) == i ]
1
get index of unique elements in list python
Same order unique list using only a list compression .
cosqa-train-13316
def uniquify_list(L): """Same order unique list using only a list compression.""" return [e for i, e in enumerate(L) if L.index(e) == i]
def _find_value ( key , * args ) : for arg in args : v = _get_value ( arg , key ) if v is not None : return v
0
get key of certain value in python
Find a value for key in any of the objects given as args
cosqa-train-13317
def _find_value(key, *args): """Find a value for 'key' in any of the objects given as 'args'""" for arg in args: v = _get_value(arg, key) if v is not None: return v
def set_cursor ( self , x , y ) : curses . curs_set ( 1 ) self . screen . move ( y , x )
1
python how to simulate mouse click move cursor
Sets the cursor to the desired position .
cosqa-train-13318
def set_cursor(self, x, y): """ Sets the cursor to the desired position. :param x: X position :param y: Y position """ curses.curs_set(1) self.screen.move(y, x)
def _latest_date ( self , query , datetime_field_name ) : return list ( query . aggregate ( django . db . models . Max ( datetime_field_name ) ) . values ( ) ) [ 0 ]
1
get largest date from a list python
Given a QuerySet and the name of field containing datetimes return the latest ( most recent ) date .
cosqa-train-13319
def _latest_date(self, query, datetime_field_name): """Given a QuerySet and the name of field containing datetimes, return the latest (most recent) date. Return None if QuerySet is empty. """ return list( query.aggregate(django.db.models.Max(datetime_field_name)).values() )[0]
def _normalize_abmn ( abmn ) : abmn_2d = np . atleast_2d ( abmn ) abmn_normalized = np . hstack ( ( np . sort ( abmn_2d [ : , 0 : 2 ] , axis = 1 ) , np . sort ( abmn_2d [ : , 2 : 4 ] , axis = 1 ) , ) ) return abmn_normalized
1
python how to standardize numpy array
return a normalized version of abmn
cosqa-train-13320
def _normalize_abmn(abmn): """return a normalized version of abmn """ abmn_2d = np.atleast_2d(abmn) abmn_normalized = np.hstack(( np.sort(abmn_2d[:, 0:2], axis=1), np.sort(abmn_2d[:, 2:4], axis=1), )) return abmn_normalized
def list_files ( directory ) : return [ f for f in pathlib . Path ( directory ) . iterdir ( ) if f . is_file ( ) and not f . name . startswith ( '.' ) ]
1
get list of files from a folder in python
Returns all files in a given directory
cosqa-train-13321
def list_files(directory): """Returns all files in a given directory """ return [f for f in pathlib.Path(directory).iterdir() if f.is_file() and not f.name.startswith('.')]
def is_collection ( obj ) : col = getattr ( obj , '__getitem__' , False ) val = False if ( not col ) else True if isinstance ( obj , basestring ) : val = False return val
1
python how to tell if an object is a collectio
Tests if an object is a collection .
cosqa-train-13322
def is_collection(obj): """Tests if an object is a collection.""" col = getattr(obj, '__getitem__', False) val = False if (not col) else True if isinstance(obj, basestring): val = False return val
def _random_x ( self ) : return ( tuple ( random . random ( ) for _ in range ( self . fmodel . dim_x ) ) , )
1
get matrix of random floating values python
If the database is empty generate a random vector .
cosqa-train-13323
def _random_x(self): """If the database is empty, generate a random vector.""" return (tuple(random.random() for _ in range(self.fmodel.dim_x)),)
def model_field_attr ( model , model_field , attr ) : fields = dict ( [ ( field . name , field ) for field in model . _meta . fields ] ) return getattr ( fields [ model_field ] , attr )
1
get multiple fields from model python
Returns the specified attribute for the specified field on the model class .
cosqa-train-13324
def model_field_attr(model, model_field, attr): """ Returns the specified attribute for the specified field on the model class. """ fields = dict([(field.name, field) for field in model._meta.fields]) return getattr(fields[model_field], attr)
def is_builtin_type ( tp ) : return hasattr ( __builtins__ , tp . __name__ ) and tp is getattr ( __builtins__ , tp . __name__ )
0
python how to tell type checker something is callable
Checks if the given type is a builtin one .
cosqa-train-13325
def is_builtin_type(tp): """Checks if the given type is a builtin one. """ return hasattr(__builtins__, tp.__name__) and tp is getattr(__builtins__, tp.__name__)
def get_next_weekday ( self , including_today = False ) : weekday = self . date_time . weekday ( ) return Weekday . get_next ( weekday , including_today = including_today )
1
get next day date python
Gets next week day
cosqa-train-13326
def get_next_weekday(self, including_today=False): """Gets next week day :param including_today: If today is sunday and requesting next sunday :return: Date of next monday, tuesday .. """ weekday = self.date_time.weekday() return Weekday.get_next(weekday, including_today=including_today)
def Unlock ( fd , path ) : try : fcntl . flock ( fd , fcntl . LOCK_UN | fcntl . LOCK_NB ) except IOError as e : if e . errno == errno . EWOULDBLOCK : raise IOError ( 'Exception unlocking %s. Locked by another process.' % path ) else : raise IOError ( 'Exception unlocking %s. %s.' % ( path , str ( e ) ) )
1
python how to unlock a locked file
Release the lock on the file .
cosqa-train-13327
def Unlock(fd, path): """Release the lock on the file. Args: fd: int, the file descriptor of the file to unlock. path: string, the name of the file to lock. Raises: IOError, raised from flock while attempting to release a file lock. """ try: fcntl.flock(fd, fcntl.LOCK_UN | fcntl.LOCK_NB) except IOError as e: if e.errno == errno.EWOULDBLOCK: raise IOError('Exception unlocking %s. Locked by another process.' % path) else: raise IOError('Exception unlocking %s. %s.' % (path, str(e)))
def line_count ( fn ) : with open ( fn ) as f : for i , l in enumerate ( f ) : pass return i + 1
1
get number of lines in file python enumerate
Get line count of file
cosqa-train-13328
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 get_page_and_url ( session , url ) : reply = get_reply ( session , url ) return reply . text , reply . url
1
python how to use session to access other urls from same page
Download an HTML page using the requests session and return the final URL after following redirects .
cosqa-train-13329
def get_page_and_url(session, url): """ Download an HTML page using the requests session and return the final URL after following redirects. """ reply = get_reply(session, url) return reply.text, reply.url
def get_table_width ( table ) : columns = transpose_table ( prepare_rows ( table ) ) widths = [ max ( len ( cell ) for cell in column ) for column in columns ] return len ( '+' + '|' . join ( '-' * ( w + 2 ) for w in widths ) + '+' )
0
get number of rows in a prettytable python
Gets the width of the table that would be printed . : rtype : int
cosqa-train-13330
def get_table_width(table): """ Gets the width of the table that would be printed. :rtype: ``int`` """ columns = transpose_table(prepare_rows(table)) widths = [max(len(cell) for cell in column) for column in columns] return len('+' + '|'.join('-' * (w + 2) for w in widths) + '+')
def set_time ( filename , mod_time ) : log . debug ( 'Setting modified time to %s' , mod_time ) mtime = calendar . timegm ( mod_time . utctimetuple ( ) ) # utctimetuple discards microseconds, so restore it (for consistency) mtime += mod_time . microsecond / 1000000 atime = os . stat ( filename ) . st_atime os . utime ( filename , ( atime , mtime ) )
0
python howto modify file create time
Set the modified time of a file
cosqa-train-13331
def set_time(filename, mod_time): """ Set the modified time of a file """ log.debug('Setting modified time to %s', mod_time) mtime = calendar.timegm(mod_time.utctimetuple()) # utctimetuple discards microseconds, so restore it (for consistency) mtime += mod_time.microsecond / 1000000 atime = os.stat(filename).st_atime os.utime(filename, (atime, mtime))
def root_parent ( self , category = None ) : return next ( filter ( lambda c : c . is_root , self . hierarchy ( ) ) )
1
get parent node python
Returns the topmost parent of the current category .
cosqa-train-13332
def root_parent(self, category=None): """ Returns the topmost parent of the current category. """ return next(filter(lambda c: c.is_root, self.hierarchy()))
def display_iframe_url ( target , * * kwargs ) : txt = iframe_url ( target , * * kwargs ) display ( HTML ( txt ) )
0
python html iframe contents
Display the contents of a URL in an IPython notebook . : param target : the target url . : type target : string
cosqa-train-13333
def display_iframe_url(target, **kwargs): """Display the contents of a URL in an IPython notebook. :param target: the target url. :type target: string .. seealso:: `iframe_url()` for additional arguments.""" txt = iframe_url(target, **kwargs) display(HTML(txt))
def grandparent_path ( self ) : return os . path . basename ( os . path . join ( self . path , '../..' ) )
1
get parent path python
return grandparent s path string
cosqa-train-13334
def grandparent_path(self): """ return grandparent's path string """ return os.path.basename(os.path.join(self.path, '../..'))
def _gzip ( self , response ) : bytesio = six . BytesIO ( ) with gzip . GzipFile ( fileobj = bytesio , mode = 'w' ) as gz : gz . write ( response ) return bytesio . getvalue ( )
1
python html response gzip
Apply gzip compression to a response .
cosqa-train-13335
def _gzip(self, response): """Apply gzip compression to a response.""" bytesio = six.BytesIO() with gzip.GzipFile(fileobj=bytesio, mode='w') as gz: gz.write(response) return bytesio.getvalue()
def unmatched ( match ) : start , end = match . span ( 0 ) return match . string [ : start ] + match . string [ end : ]
0
get part after regex match in python
Return unmatched part of re . Match object .
cosqa-train-13336
def unmatched(match): """Return unmatched part of re.Match object.""" start, end = match.span(0) return match.string[:start]+match.string[end:]
def safe_quotes ( text , escape_single_quotes = False ) : if isinstance ( text , str ) : safe_text = text . replace ( '"' , """ ) if escape_single_quotes : safe_text = safe_text . replace ( "'" , "\'" ) return safe_text . replace ( 'True' , 'true' ) return text
0
python html safe text
htmlify string
cosqa-train-13337
def safe_quotes(text, escape_single_quotes=False): """htmlify string""" if isinstance(text, str): safe_text = text.replace('"', """) if escape_single_quotes: safe_text = safe_text.replace("'", "\'") return safe_text.replace('True', 'true') return text
def get_points ( self ) : return [ ( k , self . runtime . _ring [ k ] ) for k in self . runtime . _keys ]
1
get python dicitonary keys as list
Returns a ketama compatible list of ( position nodename ) tuples .
cosqa-train-13338
def get_points(self): """Returns a ketama compatible list of (position, nodename) tuples. """ return [(k, self.runtime._ring[k]) for k in self.runtime._keys]
def getheader ( self , name , default = None ) : return self . aiohttp_response . headers . get ( name , default )
1
python http get response header
Returns a given response header .
cosqa-train-13339
def getheader(self, name, default=None): """Returns a given response header.""" return self.aiohttp_response.headers.get(name, default)
def previous_quarter ( d ) : from django_toolkit . datetime_util import quarter as datetime_quarter return quarter ( ( datetime_quarter ( datetime ( d . year , d . month , d . day ) ) [ 0 ] + timedelta ( days = - 1 ) ) . date ( ) )
1
get quarter from datetime python
Retrieve the previous quarter for dt
cosqa-train-13340
def previous_quarter(d): """ Retrieve the previous quarter for dt """ from django_toolkit.datetime_util import quarter as datetime_quarter return quarter( (datetime_quarter(datetime(d.year, d.month, d.day))[0] + timedelta(days=-1)).date() )
def remote_file_exists ( self , url ) : status = requests . head ( url ) . status_code if status != 200 : raise RemoteFileDoesntExist
0
python http server, determine if file requested exists
Checks whether the remote file exists .
cosqa-train-13341
def remote_file_exists(self, url): """ Checks whether the remote file exists. :param url: The url that has to be checked. :type url: String :returns: **True** if remote file exists and **False** if it doesn't exist. """ status = requests.head(url).status_code if status != 200: raise RemoteFileDoesntExist
def parse_querystring ( self , req , name , field ) : return core . get_value ( req . args , name , field )
1
get query string from url python
Pull a querystring value from the request .
cosqa-train-13342
def parse_querystring(self, req, name, field): """Pull a querystring value from the request.""" return core.get_value(req.args, name, field)
def is_gzipped_fastq ( file_name ) : _ , ext = os . path . splitext ( file_name ) return file_name . endswith ( ".fastq.gz" ) or file_name . endswith ( ".fq.gz" )
1
python identify gzipped files
Determine whether indicated file appears to be a gzipped FASTQ .
cosqa-train-13343
def is_gzipped_fastq(file_name): """ Determine whether indicated file appears to be a gzipped FASTQ. :param str file_name: Name/path of file to check as gzipped FASTQ. :return bool: Whether indicated file appears to be in gzipped FASTQ format. """ _, ext = os.path.splitext(file_name) return file_name.endswith(".fastq.gz") or file_name.endswith(".fq.gz")
def remove_duplicates ( lst ) : dset = set ( ) return [ l for l in lst if l not in dset and not dset . add ( l ) ]
1
get rid of duplicates in python list
Emulate what a Python set () does but keeping the element s order .
cosqa-train-13344
def remove_duplicates(lst): """ Emulate what a Python ``set()`` does, but keeping the element's order. """ dset = set() return [l for l in lst if l not in dset and not dset.add(l)]
def MultiArgMax ( x ) : m = x . max ( ) return ( i for i , v in enumerate ( x ) if v == m )
1
python identify maximum integer in array
Get tuple ( actually a generator ) of indices where the max value of array x occurs . Requires that x have a max () method as x . max () ( in the case of NumPy ) is much faster than max ( x ) . For a simpler faster argmax when there is only a single maximum entry or when knowing only the first index where the maximum occurs call argmax () on a NumPy array .
cosqa-train-13345
def MultiArgMax(x): """ Get tuple (actually a generator) of indices where the max value of array x occurs. Requires that x have a max() method, as x.max() (in the case of NumPy) is much faster than max(x). For a simpler, faster argmax when there is only a single maximum entry, or when knowing only the first index where the maximum occurs, call argmax() on a NumPy array. :param x: Any sequence that has a max() method. :returns: Generator with the indices where the max value occurs. """ m = x.max() return (i for i, v in enumerate(x) if v == m)
def bytesize ( arr ) : byte_size = np . prod ( arr . shape ) * np . dtype ( arr . dtype ) . itemsize return byte_size
1
get size of array in python
Returns the memory byte size of a Numpy array as an integer .
cosqa-train-13346
def bytesize(arr): """ Returns the memory byte size of a Numpy array as an integer. """ byte_size = np.prod(arr.shape) * np.dtype(arr.dtype).itemsize return byte_size
def _findNearest ( arr , value ) : arr = np . array ( arr ) # find nearest value in array idx = ( abs ( arr - value ) ) . argmin ( ) return arr [ idx ]
1
python identify nearest value in array
Finds the value in arr that value is closest to
cosqa-train-13347
def _findNearest(arr, value): """ Finds the value in arr that value is closest to """ arr = np.array(arr) # find nearest value in array idx = (abs(arr-value)).argmin() return arr[idx]
def get_page_text ( self , page ) : url = self . get_page_text_url ( page ) return self . _get_url ( url )
1
get text from a page python
Downloads and returns the full text of a particular page in the document .
cosqa-train-13348
def get_page_text(self, page): """ Downloads and returns the full text of a particular page in the document. """ url = self.get_page_text_url(page) return self._get_url(url)
def is_iterable ( value ) : return isinstance ( value , np . ndarray ) or isinstance ( value , list ) or isinstance ( value , tuple ) , value
1
python if in array object not iterable
must be an iterable ( list array tuple )
cosqa-train-13349
def is_iterable(value): """must be an iterable (list, array, tuple)""" return isinstance(value, np.ndarray) or isinstance(value, list) or isinstance(value, tuple), value
def legend_title_header_element ( feature , parent ) : _ = feature , parent # NOQA header = legend_title_header [ 'string_format' ] return header . capitalize ( )
1
get the column name as legend python
Retrieve legend title header string from definitions .
cosqa-train-13350
def legend_title_header_element(feature, parent): """Retrieve legend title header string from definitions.""" _ = feature, parent # NOQA header = legend_title_header['string_format'] return header.capitalize()
def isin ( elems , line ) : found = False for e in elems : if e in line . lower ( ) : found = True break return found
1
python if list of items is in line
Check if an element from a list is in a string .
cosqa-train-13351
def isin(elems, line): """Check if an element from a list is in a string. :type elems: list :type line: str """ found = False for e in elems: if e in line.lower(): found = True break return found
def datatype ( dbtype , description , cursor ) : dt = cursor . db . introspection . get_field_type ( dbtype , description ) if type ( dt ) is tuple : return dt [ 0 ] else : return dt
1
get the data type of a column in python
Google AppEngine Helper to convert a data type into a string .
cosqa-train-13352
def datatype(dbtype, description, cursor): """Google AppEngine Helper to convert a data type into a string.""" dt = cursor.db.introspection.get_field_type(dbtype, description) if type(dt) is tuple: return dt[0] else: return dt
def is_listish ( obj ) : if isinstance ( obj , ( list , tuple , set ) ) : return True return is_sequence ( obj )
1
python if something is list
Check if something quacks like a list .
cosqa-train-13353
def is_listish(obj): """Check if something quacks like a list.""" if isinstance(obj, (list, tuple, set)): return True return is_sequence(obj)
def reduce_fn ( x ) : values = x . values if pd and isinstance ( x , pd . Series ) else x for v in values : if not is_nan ( v ) : return v return np . NaN
1
get the first value in a series python
Aggregation function to get the first non - zero value .
cosqa-train-13354
def reduce_fn(x): """ Aggregation function to get the first non-zero value. """ values = x.values if pd and isinstance(x, pd.Series) else x for v in values: if not is_nan(v): return v return np.NaN
def is_in ( self , search_list , pair ) : index = - 1 for nr , i in enumerate ( search_list ) : if ( np . all ( i == pair ) ) : return nr return index
0
get the index of second occurance of an element in list python
If pair is in search_list return the index . Otherwise return - 1
cosqa-train-13355
def is_in(self, search_list, pair): """ If pair is in search_list, return the index. Otherwise return -1 """ index = -1 for nr, i in enumerate(search_list): if(np.all(i == pair)): return nr return index
def normalized_distance ( self , image ) : return self . __distance ( self . __original_image_for_distance , image , bounds = self . bounds ( ) )
1
python image get the distance of two shape
Calculates the distance of a given image to the original image .
cosqa-train-13356
def normalized_distance(self, image): """Calculates the distance of a given image to the original image. Parameters ---------- image : `numpy.ndarray` The image that should be compared to the original image. Returns ------- :class:`Distance` The distance between the given image and the original image. """ return self.__distance( self.__original_image_for_distance, image, bounds=self.bounds())
def calculate_size ( name , count ) : data_size = 0 data_size += calculate_size_str ( name ) data_size += INT_SIZE_IN_BYTES return data_size
1
get the size of a data set in python bytes
Calculates the request payload size
cosqa-train-13357
def calculate_size(name, count): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += INT_SIZE_IN_BYTES return data_size
def uint32_to_uint8 ( cls , img ) : return np . flipud ( img . view ( dtype = np . uint8 ) . reshape ( img . shape + ( 4 , ) ) )
1
python img int8 change to int24
Cast uint32 RGB image to 4 uint8 channels .
cosqa-train-13358
def uint32_to_uint8(cls, img): """ Cast uint32 RGB image to 4 uint8 channels. """ return np.flipud(img.view(dtype=np.uint8).reshape(img.shape + (4,)))
def _get_minidom_tag_value ( station , tag_name ) : tag = station . getElementsByTagName ( tag_name ) [ 0 ] . firstChild if tag : return tag . nodeValue return None
1
get the text value of an xml element python
get a value from a tag ( if it exists )
cosqa-train-13359
def _get_minidom_tag_value(station, tag_name): """get a value from a tag (if it exists)""" tag = station.getElementsByTagName(tag_name)[0].firstChild if tag: return tag.nodeValue return None
def to_bytes ( self ) : chunks = [ PNG_SIGN ] chunks . extend ( c [ 1 ] for c in self . chunks ) return b"" . join ( chunks )
1
python img to bytearray
Convert the entire image to bytes . : rtype : bytes
cosqa-train-13360
def to_bytes(self): """Convert the entire image to bytes. :rtype: bytes """ chunks = [PNG_SIGN] chunks.extend(c[1] for c in self.chunks) return b"".join(chunks)
def get_time ( filename ) : ts = os . stat ( filename ) . st_mtime return datetime . datetime . utcfromtimestamp ( ts )
1
get the time created of a file python
Get the modified time for a file as a datetime instance
cosqa-train-13361
def get_time(filename): """ Get the modified time for a file as a datetime instance """ ts = os.stat(filename).st_mtime return datetime.datetime.utcfromtimestamp(ts)
def poke_array ( self , store , name , elemtype , elements , container , visited , _stack ) : raise NotImplementedError
1
python implement stack on array
abstract method
cosqa-train-13362
def poke_array(self, store, name, elemtype, elements, container, visited, _stack): """abstract method""" raise NotImplementedError
def mean ( inlist ) : sum = 0 for item in inlist : sum = sum + item return sum / float ( len ( inlist ) )
1
get theaverage in a list in python
Returns the arithematic mean of the values in the passed list . Assumes a 1D list but will function on the 1st dim of an array ( ! ) .
cosqa-train-13363
def mean(inlist): """ Returns the arithematic mean of the values in the passed list. Assumes a '1D' list, but will function on the 1st dim of an array(!). Usage: lmean(inlist) """ sum = 0 for item in inlist: sum = sum + item return sum / float(len(inlist))
def impute_data ( self , x ) : imp = Imputer ( missing_values = 'NaN' , strategy = 'mean' , axis = 0 ) return imp . fit_transform ( x )
1
python impute nan is not in list
Imputes data set containing Nan values
cosqa-train-13364
def impute_data(self,x): """Imputes data set containing Nan values""" imp = Imputer(missing_values='NaN', strategy='mean', axis=0) return imp.fit_transform(x)
def impute_data ( self , x ) : imp = Imputer ( missing_values = 'NaN' , strategy = 'mean' , axis = 0 ) return imp . fit_transform ( x )
0
python imuting missing categorical value
Imputes data set containing Nan values
cosqa-train-13365
def impute_data(self,x): """Imputes data set containing Nan values""" imp = Imputer(missing_values='NaN', strategy='mean', axis=0) return imp.fit_transform(x)
def _uniquify ( _list ) : seen = set ( ) result = [ ] for x in _list : if x not in seen : result . append ( x ) seen . add ( x ) return result
1
get unique elements of python list
Remove duplicates in a list .
cosqa-train-13366
def _uniquify(_list): """Remove duplicates in a list.""" seen = set() result = [] for x in _list: if x not in seen: result.append(x) seen.add(x) return result
def setup_path ( ) : import os . path import sys if sys . argv [ 0 ] : top_dir = os . path . dirname ( os . path . abspath ( sys . argv [ 0 ] ) ) sys . path = [ os . path . join ( top_dir , "src" ) ] + sys . path pass return
1
python include functions in folder
Sets up the python include paths to include src
cosqa-train-13367
def setup_path(): """Sets up the python include paths to include src""" import os.path; import sys if sys.argv[0]: top_dir = os.path.dirname(os.path.abspath(sys.argv[0])) sys.path = [os.path.join(top_dir, "src")] + sys.path pass return
def convert_2_utc ( self , datetime_ , timezone ) : datetime_ = self . tz_mapper [ timezone ] . localize ( datetime_ ) return datetime_ . astimezone ( pytz . UTC )
1
get utc offset datetime python
convert to datetime to UTC offset .
cosqa-train-13368
def convert_2_utc(self, datetime_, timezone): """convert to datetime to UTC offset.""" datetime_ = self.tz_mapper[timezone].localize(datetime_) return datetime_.astimezone(pytz.UTC)
def layout ( self , indent = ' ' ) : self . __indent ( self . head , indent ) self . __indent ( self . meta , indent ) self . __indent ( self . stylesheet , indent ) self . __indent ( self . header , indent ) self . __indent ( self . body , indent , initial = 3 ) self . __indent ( self . footer , indent ) self . __indent ( self . body_pre_docinfo , indent , initial = 3 ) self . __indent ( self . docinfo , indent )
0
python indent block of stetaments
This will indent each new tag in the body by given number of spaces .
cosqa-train-13369
def layout(self, indent=' '): """This will indent each new tag in the body by given number of spaces.""" self.__indent(self.head, indent) self.__indent(self.meta, indent) self.__indent(self.stylesheet, indent) self.__indent(self.header, indent) self.__indent(self.body, indent, initial=3) self.__indent(self.footer, indent) self.__indent(self.body_pre_docinfo, indent, initial=3) self.__indent(self.docinfo, indent)
def get_week_start_end_day ( ) : t = date . today ( ) wd = t . weekday ( ) return ( t - timedelta ( wd ) , t + timedelta ( 6 - wd ) )
1
get week end ing date in python
Get the week start date and end date
cosqa-train-13370
def get_week_start_end_day(): """ Get the week start date and end date """ t = date.today() wd = t.weekday() return (t - timedelta(wd), t + timedelta(6 - wd))
def _frombuffer ( ptr , frames , channels , dtype ) : framesize = channels * dtype . itemsize data = np . frombuffer ( ffi . buffer ( ptr , frames * framesize ) , dtype = dtype ) data . shape = - 1 , channels return data
1
python init numpy with buffer
Create NumPy array from a pointer to some memory .
cosqa-train-13371
def _frombuffer(ptr, frames, channels, dtype): """Create NumPy array from a pointer to some memory.""" framesize = channels * dtype.itemsize data = np.frombuffer(ffi.buffer(ptr, frames * framesize), dtype=dtype) data.shape = -1, channels return data
def get_stripped_file_lines ( filename ) : try : lines = open ( filename ) . readlines ( ) except FileNotFoundError : fatal ( "Could not open file: {!r}" . format ( filename ) ) return [ line . strip ( ) for line in lines ]
1
get white space out of files in python
Return lines of a file with whitespace removed
cosqa-train-13372
def get_stripped_file_lines(filename): """ Return lines of a file with whitespace removed """ try: lines = open(filename).readlines() except FileNotFoundError: fatal("Could not open file: {!r}".format(filename)) return [line.strip() for line in lines]
def pagerank_limit_push ( s , r , w_i , a_i , push_node , rho ) : # Calculate the A and B quantities to infinity A_inf = rho * r [ push_node ] B_inf = ( 1 - rho ) * r [ push_node ] # Update approximate Pagerank and residual vectors s [ push_node ] += A_inf r [ push_node ] = 0.0 # Update residual vector at push node's adjacent nodes r [ a_i ] += B_inf * w_i
1
python initialize pagerank vector
Performs a random step without a self - loop .
cosqa-train-13373
def pagerank_limit_push(s, r, w_i, a_i, push_node, rho): """ Performs a random step without a self-loop. """ # Calculate the A and B quantities to infinity A_inf = rho*r[push_node] B_inf = (1-rho)*r[push_node] # Update approximate Pagerank and residual vectors s[push_node] += A_inf r[push_node] = 0.0 # Update residual vector at push node's adjacent nodes r[a_i] += B_inf * w_i
def from_dict ( cls , d ) : return cls ( * * { k : v for k , v in d . items ( ) if k in cls . ENTRIES } )
0
python instance dictionary by dict or {}
Create an instance from a dictionary .
cosqa-train-13374
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 set_clear_color ( self , color = 'black' , alpha = None ) : self . glir . command ( 'FUNC' , 'glClearColor' , * Color ( color , alpha ) . rgba )
1
glclearcolor not working python
Set the screen clear color
cosqa-train-13375
def set_clear_color(self, color='black', alpha=None): """Set the screen clear color This is a wrapper for gl.glClearColor. Parameters ---------- color : str | tuple | instance of Color Color to use. See vispy.color.Color for options. alpha : float | None Alpha to use. """ self.glir.command('FUNC', 'glClearColor', *Color(color, alpha).rgba)
def to_gtp ( coord ) : if coord is None : return 'pass' y , x = coord return '{}{}' . format ( _GTP_COLUMNS [ x ] , go . N - y )
1
gps latitude longitude type in python
Converts from a Minigo coordinate to a GTP coordinate .
cosqa-train-13376
def to_gtp(coord): """Converts from a Minigo coordinate to a GTP coordinate.""" if coord is None: return 'pass' y, x = coord return '{}{}'.format(_GTP_COLUMNS[x], go.N - y)
def _get_ipv4_from_binary ( self , bin_addr ) : return socket . inet_ntop ( socket . AF_INET , struct . pack ( "!L" , bin_addr ) )
1
python int to ip
Converts binary address to Ipv4 format .
cosqa-train-13377
def _get_ipv4_from_binary(self, bin_addr): """Converts binary address to Ipv4 format.""" return socket.inet_ntop(socket.AF_INET, struct.pack("!L", bin_addr))
def find_lt ( a , x ) : i = bs . bisect_left ( a , x ) if i : return i - 1 raise ValueError
1
grab smallest value in an array of ints python
Find rightmost value less than x .
cosqa-train-13378
def find_lt(a, x): """Find rightmost value less than x.""" i = bs.bisect_left(a, x) if i: return i - 1 raise ValueError
def partition_all ( n , iterable ) : it = iter ( iterable ) while True : chunk = list ( itertools . islice ( it , n ) ) if not chunk : break yield chunk
1
python integer partition all permutations of certain size
Partition a list into equally sized pieces including last smaller parts http : // stackoverflow . com / questions / 5129102 / python - equivalent - to - clojures - partition - all
cosqa-train-13379
def partition_all(n, iterable): """Partition a list into equally sized pieces, including last smaller parts http://stackoverflow.com/questions/5129102/python-equivalent-to-clojures-partition-all """ it = iter(iterable) while True: chunk = list(itertools.islice(it, n)) if not chunk: break yield chunk
def _hess_two_param ( self , funct , p0 , p1 , dl = 2e-5 , rts = False , * * kwargs ) : vals0 = self . get_values ( p0 ) vals1 = self . get_values ( p1 ) f00 = funct ( * * kwargs ) self . update ( p0 , vals0 + dl ) f10 = funct ( * * kwargs ) self . update ( p1 , vals1 + dl ) f11 = funct ( * * kwargs ) self . update ( p0 , vals0 ) f01 = funct ( * * kwargs ) if rts : self . update ( p0 , vals0 ) self . update ( p1 , vals1 ) return ( f11 - f10 - f01 + f00 ) / ( dl ** 2 )
1
gradient and hessian function syntax in python
Hessian of func wrt two parameters p0 and p1 . ( see _graddoc )
cosqa-train-13380
def _hess_two_param(self, funct, p0, p1, dl=2e-5, rts=False, **kwargs): """ Hessian of `func` wrt two parameters `p0` and `p1`. (see _graddoc) """ vals0 = self.get_values(p0) vals1 = self.get_values(p1) f00 = funct(**kwargs) self.update(p0, vals0+dl) f10 = funct(**kwargs) self.update(p1, vals1+dl) f11 = funct(**kwargs) self.update(p0, vals0) f01 = funct(**kwargs) if rts: self.update(p0, vals0) self.update(p1, vals1) return (f11 - f10 - f01 + f00) / (dl**2)
def dict_hash ( dct ) : dct_s = json . dumps ( dct , sort_keys = True ) try : m = md5 ( dct_s ) except TypeError : m = md5 ( dct_s . encode ( ) ) return m . hexdigest ( )
1
hash a dictionary python content
Return a hash of the contents of a dictionary
cosqa-train-13381
def dict_hash(dct): """Return a hash of the contents of a dictionary""" dct_s = json.dumps(dct, sort_keys=True) try: m = md5(dct_s) except TypeError: m = md5(dct_s.encode()) return m.hexdigest()
def is_timestamp ( obj ) : return isinstance ( obj , datetime . datetime ) or is_string ( obj ) or is_int ( obj ) or is_float ( obj )
1
python invalid type typecast
Yaml either have automatically converted it to a datetime object or it is a string that will be validated later .
cosqa-train-13382
def is_timestamp(obj): """ Yaml either have automatically converted it to a datetime object or it is a string that will be validated later. """ return isinstance(obj, datetime.datetime) or is_string(obj) or is_int(obj) or is_float(obj)
def generate_hash ( filepath ) : fr = FileReader ( filepath ) data = fr . read_bin ( ) return _calculate_sha256 ( data )
1
hash contents of a file in python
Public function that reads a local file and generates a SHA256 hash digest for it
cosqa-train-13383
def generate_hash(filepath): """Public function that reads a local file and generates a SHA256 hash digest for it""" fr = FileReader(filepath) data = fr.read_bin() return _calculate_sha256(data)
def _run_cmd_get_output ( cmd ) : process = subprocess . Popen ( cmd . split ( ) , stdout = subprocess . PIPE ) out , err = process . communicate ( ) return out or err
0
python invoke process an get output
Runs a shell command returns console output .
cosqa-train-13384
def _run_cmd_get_output(cmd): """Runs a shell command, returns console output. Mimics python3's subprocess.getoutput """ process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE) out, err = process.communicate() return out or err
def hash_iterable ( it ) : hash_value = hash ( type ( it ) ) for value in it : hash_value = hash ( ( hash_value , value ) ) return hash_value
0
hashable data type python
Perform a O ( 1 ) memory hash of an iterable of arbitrary length .
cosqa-train-13385
def hash_iterable(it): """Perform a O(1) memory hash of an iterable of arbitrary length. hash(tuple(it)) creates a temporary tuple containing all values from it which could be a problem if it is large. See discussion at: https://groups.google.com/forum/#!msg/python-ideas/XcuC01a8SYs/e-doB9TbDwAJ """ hash_value = hash(type(it)) for value in it: hash_value = hash((hash_value, value)) return hash_value
def unique_iter ( seq ) : seen = set ( ) return [ x for x in seq if x not in seen and not seen . add ( x ) ]
1
python is a set empty
See http : // www . peterbe . com / plog / uniqifiers - benchmark Originally f8 written by Dave Kirby
cosqa-train-13386
def unique_iter(seq): """ See http://www.peterbe.com/plog/uniqifiers-benchmark Originally f8 written by Dave Kirby """ seen = set() return [x for x in seq if x not in seen and not seen.add(x)]
def generate_hash ( filepath ) : fr = FileReader ( filepath ) data = fr . read_bin ( ) return _calculate_sha256 ( data )
1
hashcode for a file python
Public function that reads a local file and generates a SHA256 hash digest for it
cosqa-train-13387
def generate_hash(filepath): """Public function that reads a local file and generates a SHA256 hash digest for it""" fr = FileReader(filepath) data = fr.read_bin() return _calculate_sha256(data)
def is_listish ( obj ) : if isinstance ( obj , ( list , tuple , set ) ) : return True return is_sequence ( obj )
1
python is list no na
Check if something quacks like a list .
cosqa-train-13388
def is_listish(obj): """Check if something quacks like a list.""" if isinstance(obj, (list, tuple, set)): return True return is_sequence(obj)
def set_mlimits ( self , row , column , min = None , max = None ) : subplot = self . get_subplot_at ( row , column ) subplot . set_mlimits ( min , max )
1
heatmap python set the axis limits
Set limits for the point meta ( colormap ) .
cosqa-train-13389
def set_mlimits(self, row, column, min=None, max=None): """Set limits for the point meta (colormap). Point meta values outside this range will be clipped. :param min: value for start of the colormap. :param max: value for end of the colormap. """ subplot = self.get_subplot_at(row, column) subplot.set_mlimits(min, max)
def _not_none ( items ) : if not isinstance ( items , ( tuple , list ) ) : items = ( items , ) return all ( item is not _none for item in items )
1
python is not none and condition
Whether the item is a placeholder or contains a placeholder .
cosqa-train-13390
def _not_none(items): """Whether the item is a placeholder or contains a placeholder.""" if not isinstance(items, (tuple, list)): items = (items,) return all(item is not _none for item in items)
def find_geom ( geom , geoms ) : for i , g in enumerate ( geoms ) : if g is geom : return i
1
hoe to get index of a element in a list in python
Returns the index of a geometry in a list of geometries avoiding expensive equality checks of in operator .
cosqa-train-13391
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 is_symlink ( self ) : try : return S_ISLNK ( self . lstat ( ) . st_mode ) except OSError as e : if e . errno != ENOENT : raise # Path doesn't exist return False
1
python is or not symlink
Whether this path is a symbolic link .
cosqa-train-13392
def is_symlink(self): """ Whether this path is a symbolic link. """ try: return S_ISLNK(self.lstat().st_mode) except OSError as e: if e.errno != ENOENT: raise # Path doesn't exist return False
def _validate_input_data ( self , data , request ) : validator = self . _get_input_validator ( request ) if isinstance ( data , ( list , tuple ) ) : return map ( validator . validate , data ) else : return validator . validate ( data )
0
hot to include input validation in python flask
Validate input data .
cosqa-train-13393
def _validate_input_data(self, data, request): """ Validate input data. :param request: the HTTP request :param data: the parsed data :return: if validation is performed and succeeds the data is converted into whatever format the validation uses (by default Django's Forms) If not, the data is returned unchanged. :raises: HttpStatusCodeError if data is not valid """ validator = self._get_input_validator(request) if isinstance(data, (list, tuple)): return map(validator.validate, data) else: return validator.validate(data)
def isdir ( path , * * kwargs ) : import os . path return os . path . isdir ( path , * * kwargs )
1
python isdir doesn't work
Check if * path * is a directory
cosqa-train-13394
def isdir(path, **kwargs): """Check if *path* is a directory""" import os.path return os.path.isdir(path, **kwargs)
def set ( self , f ) : self . stop ( ) self . _create_timer ( f ) self . start ( )
1
how call a function every 5 seconds python
Call a function after a delay unless another function is set in the meantime .
cosqa-train-13395
def set(self, f): """Call a function after a delay, unless another function is set in the meantime.""" self.stop() self._create_timer(f) self.start()
def is_date_type ( cls ) : if not isinstance ( cls , type ) : return False return issubclass ( cls , date ) and not issubclass ( cls , datetime )
1
python isinstance of a date
Return True if the class is a date type .
cosqa-train-13396
def is_date_type(cls): """Return True if the class is a date type.""" if not isinstance(cls, type): return False return issubclass(cls, date) and not issubclass(cls, datetime)
def dimensions ( self ) : size = self . pdf . getPage ( 0 ) . mediaBox return { 'w' : float ( size [ 2 ] ) , 'h' : float ( size [ 3 ] ) }
1
how can i can calculate the width and height of a image in pdf with python reportlab
Get width and height of a PDF
cosqa-train-13397
def dimensions(self): """Get width and height of a PDF""" size = self.pdf.getPage(0).mediaBox return {'w': float(size[2]), 'h': float(size[3])}
def finditer ( self , string , pos = 0 , endpos = sys . maxint ) : scanner = self . scanner ( string , pos , endpos ) return iter ( scanner . search , None )
0
python iter a pattern in string
Return a list of all non - overlapping matches of pattern in string .
cosqa-train-13398
def finditer(self, string, pos=0, endpos=sys.maxint): """Return a list of all non-overlapping matches of pattern in string.""" scanner = self.scanner(string, pos, endpos) return iter(scanner.search, None)
def set ( cls , color ) : sys . stdout . write ( cls . colors . get ( color , cls . colors [ 'RESET' ] ) )
1
how can i change the color of type in python
Sets the terminal to the passed color . : param color : one of the availabe colors .
cosqa-train-13399
def set(cls, color): """ Sets the terminal to the passed color. :param color: one of the availabe colors. """ sys.stdout.write(cls.colors.get(color, cls.colors['RESET']))