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 _kbhit_unix ( ) -> bool : dr , dw , de = select . select ( [ sys . stdin ] , [ ] , [ ] , 0 ) return dr != [ ]
0
python read keyboard input from specific
Under UNIX : is a keystroke available?
cosqa-train-18000
def _kbhit_unix() -> bool: """ Under UNIX: is a keystroke available? """ dr, dw, de = select.select([sys.stdin], [], [], 0) return dr != []
def get_default_bucket_key ( buckets : List [ Tuple [ int , int ] ] ) -> Tuple [ int , int ] : return max ( buckets )
1
return key for largest list in python
Returns the default bucket from a list of buckets i . e . the largest bucket .
cosqa-train-18001
def get_default_bucket_key(buckets: List[Tuple[int, int]]) -> Tuple[int, int]: """ Returns the default bucket from a list of buckets, i.e. the largest bucket. :param buckets: List of buckets. :return: The largest bucket in the list. """ return max(buckets)
def translate_dict ( cls , val ) : escaped = ', ' . join ( [ "{} -> {}" . format ( cls . translate_str ( k ) , cls . translate ( v ) ) for k , v in val . items ( ) ] ) return 'Map({})' . format ( escaped )
1
casting map to string python
Translate dicts to scala Maps
cosqa-train-18002
def translate_dict(cls, val): """Translate dicts to scala Maps""" escaped = ', '.join( ["{} -> {}".format(cls.translate_str(k), cls.translate(v)) for k, v in val.items()] ) return 'Map({})'.format(escaped)
def iprotate ( l , steps = 1 ) : if len ( l ) : steps %= len ( l ) if steps : firstPart = l [ : steps ] del l [ : steps ] l . extend ( firstPart ) return l
1
python how to rotate a list
r Like rotate but modifies l in - place .
cosqa-train-18003
def iprotate(l, steps=1): r"""Like rotate, but modifies `l` in-place. >>> l = [1,2,3] >>> iprotate(l) is l True >>> l [2, 3, 1] >>> iprotate(iprotate(l, 2), -3) [1, 2, 3] """ if len(l): steps %= len(l) if steps: firstPart = l[:steps] del l[:steps] l.extend(firstPart) return l
def read_set_from_file ( filename : str ) -> Set [ str ] : collection = set ( ) with open ( filename , 'r' ) as file_ : for line in file_ : collection . add ( line . rstrip ( ) ) return collection
0
python list of unique values in text file
Extract a de - duped collection ( set ) of text from a file . Expected file format is one item per line .
cosqa-train-18004
def read_set_from_file(filename: str) -> Set[str]: """ Extract a de-duped collection (set) of text from a file. Expected file format is one item per line. """ collection = set() with open(filename, 'r') as file_: for line in file_: collection.add(line.rstrip()) return collection
def year ( date ) : try : fmt = '%m/%d/%Y' return datetime . strptime ( date , fmt ) . timetuple ( ) . tm_year except ValueError : return 0
0
python getyear from the date string
Returns the year .
cosqa-train-18005
def year(date): """ Returns the year. :param date: The string date with this format %m/%d/%Y :type date: String :returns: int :example: >>> year('05/1/2015') 2015 """ try: fmt = '%m/%d/%Y' return datetime.strptime(date, fmt).timetuple().tm_year except ValueError: return 0
def _my_hash ( arg_list ) : # type: (List[Any]) -> int res = 0 for arg in arg_list : res = res * 31 + hash ( arg ) return res
0
python create hash of list elements
Simple helper hash function
cosqa-train-18006
def _my_hash(arg_list): # type: (List[Any]) -> int """Simple helper hash function""" res = 0 for arg in arg_list: res = res * 31 + hash(arg) return res
def datetime_iso_format ( date ) : return "{0:0>4}-{1:0>2}-{2:0>2}T{3:0>2}:{4:0>2}:{5:0>2}Z" . format ( date . year , date . month , date . day , date . hour , date . minute , date . second )
0
+python +datetime +format iso format
Return an ISO - 8601 representation of a datetime object .
cosqa-train-18007
def datetime_iso_format(date): """ Return an ISO-8601 representation of a datetime object. """ return "{0:0>4}-{1:0>2}-{2:0>2}T{3:0>2}:{4:0>2}:{5:0>2}Z".format( date.year, date.month, date.day, date.hour, date.minute, date.second)
def check_key ( self , key : str ) -> bool : keys = self . get_keys ( ) return key in keys
1
how to check if key exists in python
Checks if key exists in datastore . True if yes False if no .
cosqa-train-18008
def check_key(self, key: str) -> bool: """ Checks if key exists in datastore. True if yes, False if no. :param: SHA512 hash key :return: whether or key not exists in datastore """ keys = self.get_keys() return key in keys
def get_bin_edges_from_axis ( axis ) -> np . ndarray : # Don't include over- or underflow bins bins = range ( 1 , axis . GetNbins ( ) + 1 ) # Bin edges bin_edges = np . empty ( len ( bins ) + 1 ) bin_edges [ : - 1 ] = [ axis . GetBinLowEdge ( i ) for i in bins ] bin_edges [ - 1 ] = axis . GetBinUpEdge ( axis . GetNbins ( ) ) return bin_edges
1
python hist returns bin edges right
Get bin edges from a ROOT hist axis .
cosqa-train-18009
def get_bin_edges_from_axis(axis) -> np.ndarray: """ Get bin edges from a ROOT hist axis. Note: Doesn't include over- or underflow bins! Args: axis (ROOT.TAxis): Axis from which the bin edges should be extracted. Returns: Array containing the bin edges. """ # Don't include over- or underflow bins bins = range(1, axis.GetNbins() + 1) # Bin edges bin_edges = np.empty(len(bins) + 1) bin_edges[:-1] = [axis.GetBinLowEdge(i) for i in bins] bin_edges[-1] = axis.GetBinUpEdge(axis.GetNbins()) return bin_edges
def top ( self , topn = 10 ) : return [ self [ i ] for i in argsort ( list ( zip ( * self ) ) [ 1 ] ) [ : : - 1 ] [ : topn ] ]
1
python get top n values from list
Get a list of the top topn features in this : class : . Feature \ .
cosqa-train-18010
def top(self, topn=10): """ Get a list of the top ``topn`` features in this :class:`.Feature`\. Examples -------- .. code-block:: python >>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)]) >>> myFeature.top(1) [('trapezoid', 5)] Parameters ---------- topn : int Returns ------- list """ return [self[i] for i in argsort(list(zip(*self))[1])[::-1][:topn]]
def cmd_dot ( conf : Config ) : build_context = BuildContext ( conf ) populate_targets_graph ( build_context , conf ) if conf . output_dot_file is None : write_dot ( build_context , conf , sys . stdout ) else : with open ( conf . output_dot_file , 'w' ) as out_file : write_dot ( build_context , conf , out_file )
1
graphviz dot to png python
Print out a neat targets dependency tree based on requested targets .
cosqa-train-18011
def cmd_dot(conf: Config): """Print out a neat targets dependency tree based on requested targets. Use graphviz to render the dot file, e.g.: > ybt dot :foo :bar | dot -Tpng -o graph.png """ build_context = BuildContext(conf) populate_targets_graph(build_context, conf) if conf.output_dot_file is None: write_dot(build_context, conf, sys.stdout) else: with open(conf.output_dot_file, 'w') as out_file: write_dot(build_context, conf, out_file)
def astensor ( array : TensorLike ) -> BKTensor : tensor = tf . convert_to_tensor ( value = array , dtype = CTYPE ) return tensor
1
how to transform a 2d matrix to tensor python
Covert numpy array to tensorflow tensor
cosqa-train-18012
def astensor(array: TensorLike) -> BKTensor: """Covert numpy array to tensorflow tensor""" tensor = tf.convert_to_tensor(value=array, dtype=CTYPE) return tensor
def grep ( pattern , filename ) : try : # for line in file # if line matches pattern: # return line return next ( ( L for L in open ( filename ) if L . find ( pattern ) >= 0 ) ) except StopIteration : return ''
0
how to grep a string in a file using aspython
Very simple grep that returns the first matching line in a file . String matching only does not do REs as currently implemented .
cosqa-train-18013
def grep(pattern, filename): """Very simple grep that returns the first matching line in a file. String matching only, does not do REs as currently implemented. """ try: # for line in file # if line matches pattern: # return line return next((L for L in open(filename) if L.find(pattern) >= 0)) except StopIteration: return ''
def lowercase_chars ( string : any ) -> str : return '' . join ( [ c if c . islower ( ) else '' for c in str ( string ) ] )
1
python string "any lowercase characters"
Return all ( and only ) the lowercase chars in the given string .
cosqa-train-18014
def lowercase_chars(string: any) -> str: """Return all (and only) the lowercase chars in the given string.""" return ''.join([c if c.islower() else '' for c in str(string)])
def list_to_str ( lst ) : if len ( lst ) == 1 : str_ = lst [ 0 ] elif len ( lst ) == 2 : str_ = ' and ' . join ( lst ) elif len ( lst ) > 2 : str_ = ', ' . join ( lst [ : - 1 ] ) str_ += ', and {0}' . format ( lst [ - 1 ] ) else : raise ValueError ( 'List of length 0 provided.' ) return str_
0
transfer list to string witho commas python
Turn a list into a comma - and / or and - separated string .
cosqa-train-18015
def list_to_str(lst): """ Turn a list into a comma- and/or and-separated string. Parameters ---------- lst : :obj:`list` A list of strings to join into a single string. Returns ------- str_ : :obj:`str` A string with commas and/or ands separating th elements from ``lst``. """ if len(lst) == 1: str_ = lst[0] elif len(lst) == 2: str_ = ' and '.join(lst) elif len(lst) > 2: str_ = ', '.join(lst[:-1]) str_ += ', and {0}'.format(lst[-1]) else: raise ValueError('List of length 0 provided.') return str_
def remove_once ( gset , elem ) : remove = getattr ( gset , 'remove' , None ) if remove is not None : remove ( elem ) else : del gset [ elem ] return elem
1
python delete element from set
Remove the element from a set lists or dict . >>> L = [ Lucy ] ; S = set ( [ Sky ] ) ; D = { Diamonds : True } ; >>> remove_once ( L Lucy ) ; remove_once ( S Sky ) ; remove_once ( D Diamonds ) ; >>> print L S D [] set ( [] ) {}
cosqa-train-18016
def remove_once(gset, elem): """Remove the element from a set, lists or dict. >>> L = ["Lucy"]; S = set(["Sky"]); D = { "Diamonds": True }; >>> remove_once(L, "Lucy"); remove_once(S, "Sky"); remove_once(D, "Diamonds"); >>> print L, S, D [] set([]) {} Returns the element if it was removed. Raises one of the exceptions in :obj:`RemoveError` otherwise. """ remove = getattr(gset, 'remove', None) if remove is not None: remove(elem) else: del gset[elem] return elem
def get_language ( query : str ) -> str : query = query . lower ( ) for language in LANGUAGES : if query . endswith ( language ) : return language return ''
0
detect language of the text python
Tries to work out the highlight . js language of a given file name or shebang . Returns an empty string if none match .
cosqa-train-18017
def get_language(query: str) -> str: """Tries to work out the highlight.js language of a given file name or shebang. Returns an empty string if none match. """ query = query.lower() for language in LANGUAGES: if query.endswith(language): return language return ''
def get_datatype ( self , table : str , column : str ) -> str : return self . flavour . get_datatype ( self , table , column ) . upper ( )
1
python get datatype of sql column
Returns database SQL datatype for a column : e . g . VARCHAR .
cosqa-train-18018
def get_datatype(self, table: str, column: str) -> str: """Returns database SQL datatype for a column: e.g. VARCHAR.""" return self.flavour.get_datatype(self, table, column).upper()
def lint ( fmt = 'colorized' ) : if fmt == 'html' : outfile = 'pylint_report.html' local ( 'pylint -f %s davies > %s || true' % ( fmt , outfile ) ) local ( 'open %s' % outfile ) else : local ( 'pylint -f %s davies || true' % fmt )
0
pylint for python 3
Run verbose PyLint on source . Optionally specify fmt = html for HTML output .
cosqa-train-18019
def lint(fmt='colorized'): """Run verbose PyLint on source. Optionally specify fmt=html for HTML output.""" if fmt == 'html': outfile = 'pylint_report.html' local('pylint -f %s davies > %s || true' % (fmt, outfile)) local('open %s' % outfile) else: local('pylint -f %s davies || true' % fmt)
def chars ( string : any ) -> str : return '' . join ( [ c if c . isalpha ( ) else '' for c in str ( string ) ] )
1
determining alphanumeric characters in a string python
Return all ( and only ) the chars in the given string .
cosqa-train-18020
def chars(string: any) -> str: """Return all (and only) the chars in the given string.""" return ''.join([c if c.isalpha() else '' for c in str(string)])
def is_finite ( value : Any ) -> bool : return isinstance ( value , int ) or ( isinstance ( value , float ) and isfinite ( value ) )
0
python see if value is finite
Return true if a value is a finite number .
cosqa-train-18021
def is_finite(value: Any) -> bool: """Return true if a value is a finite number.""" return isinstance(value, int) or (isinstance(value, float) and isfinite(value))
def _strip_top_comments ( lines : Sequence [ str ] , line_separator : str ) -> str : lines = copy . copy ( lines ) while lines and lines [ 0 ] . startswith ( "#" ) : lines = lines [ 1 : ] return line_separator . join ( lines )
0
delete top comment of python file
Strips # comments that exist at the top of the given lines
cosqa-train-18022
def _strip_top_comments(lines: Sequence[str], line_separator: str) -> str: """Strips # comments that exist at the top of the given lines""" lines = copy.copy(lines) while lines and lines[0].startswith("#"): lines = lines[1:] return line_separator.join(lines)
def find_first_in_list ( txt : str , str_list : [ str ] ) -> int : # type: ignore start = len ( txt ) + 1 for item in str_list : if start > txt . find ( item ) > - 1 : start = txt . find ( item ) return start if len ( txt ) + 1 > start > - 1 else - 1
1
function that returns first occurence of item in string in python
Returns the index of the earliest occurence of an item from a list in a string
cosqa-train-18023
def find_first_in_list(txt: str, str_list: [str]) -> int: # type: ignore """ Returns the index of the earliest occurence of an item from a list in a string Ex: find_first_in_list('foobar', ['bar', 'fin']) -> 3 """ start = len(txt) + 1 for item in str_list: if start > txt.find(item) > -1: start = txt.find(item) return start if len(txt) + 1 > start > -1 else -1
def scope_logger ( cls ) : cls . log = logging . getLogger ( '{0}.{1}' . format ( cls . __module__ , cls . __name__ ) ) return cls
0
make a function that sets up a logger python
Class decorator for adding a class local logger
cosqa-train-18024
def scope_logger(cls): """ Class decorator for adding a class local logger Example: >>> @scope_logger >>> class Test: >>> def __init__(self): >>> self.log.info("class instantiated") >>> t = Test() """ cls.log = logging.getLogger('{0}.{1}'.format(cls.__module__, cls.__name__)) return cls
def is_quoted ( arg : str ) -> bool : return len ( arg ) > 1 and arg [ 0 ] == arg [ - 1 ] and arg [ 0 ] in constants . QUOTES
1
check if string equals quotation marks python
Checks if a string is quoted : param arg : the string being checked for quotes : return : True if a string is quoted
cosqa-train-18025
def is_quoted(arg: str) -> bool: """ Checks if a string is quoted :param arg: the string being checked for quotes :return: True if a string is quoted """ return len(arg) > 1 and arg[0] == arg[-1] and arg[0] in constants.QUOTES
def dotproduct ( X , Y ) : return sum ( [ x * y for x , y in zip ( X , Y ) ] )
0
dot product of two lists of same length python
Return the sum of the element - wise product of vectors x and y . >>> dotproduct ( [ 1 2 3 ] [ 1000 100 10 ] ) 1230
cosqa-train-18026
def dotproduct(X, Y): """Return the sum of the element-wise product of vectors x and y. >>> dotproduct([1, 2, 3], [1000, 100, 10]) 1230 """ return sum([x * y for x, y in zip(X, Y)])
def isfile_notempty ( inputfile : str ) -> bool : try : return isfile ( inputfile ) and getsize ( inputfile ) > 0 except TypeError : raise TypeError ( 'inputfile is not a valid type' )
1
python judge if file empty
Check if the input filename with path is a file and is not empty .
cosqa-train-18027
def isfile_notempty(inputfile: str) -> bool: """Check if the input filename with path is a file and is not empty.""" try: return isfile(inputfile) and getsize(inputfile) > 0 except TypeError: raise TypeError('inputfile is not a valid type')
def read_flat ( self ) : x , y , pixel , meta = self . read ( ) arraycode = 'BH' [ meta [ 'bitdepth' ] > 8 ] pixel = array ( arraycode , itertools . chain ( * pixel ) ) return x , y , pixel , meta
0
how to flatten image python
Read a PNG file and decode it into flat row flat pixel format .
cosqa-train-18028
def read_flat(self): """ Read a PNG file and decode it into flat row flat pixel format. Returns (*width*, *height*, *pixels*, *metadata*). May use excessive memory. `pixels` are returned in flat row flat pixel format. See also the :meth:`read` method which returns pixels in the more stream-friendly boxed row flat pixel format. """ x, y, pixel, meta = self.read() arraycode = 'BH'[meta['bitdepth'] > 8] pixel = array(arraycode, itertools.chain(*pixel)) return x, y, pixel, meta
def SwitchToThisWindow ( handle : int ) -> None : ctypes . windll . user32 . SwitchToThisWindow ( ctypes . c_void_p ( handle ) , 1 )
0
python ctypes how to identify a window
SwitchToThisWindow from Win32 . handle : int the handle of a native window .
cosqa-train-18029
def SwitchToThisWindow(handle: int) -> None: """ SwitchToThisWindow from Win32. handle: int, the handle of a native window. """ ctypes.windll.user32.SwitchToThisWindow(ctypes.c_void_p(handle), 1)
def hex_color_to_tuple ( hex ) : hex = hex [ 1 : ] length = len ( hex ) // 2 return tuple ( int ( hex [ i * 2 : i * 2 + 2 ] , 16 ) for i in range ( length ) )
0
html color to rgb tuple python
convent hex color to tuple #ffffff - > ( 255 255 255 ) #ffff00ff - > ( 255 255 0 255 )
cosqa-train-18030
def hex_color_to_tuple(hex): """ convent hex color to tuple "#ffffff" -> (255, 255, 255) "#ffff00ff" -> (255, 255, 0, 255) """ hex = hex[1:] length = len(hex) // 2 return tuple(int(hex[i*2:i*2+2], 16) for i in range(length))
def is_sqlatype_numeric ( coltype : Union [ TypeEngine , VisitableType ] ) -> bool : coltype = _coltype_to_typeengine ( coltype ) return isinstance ( coltype , sqltypes . Numeric )
1
how to check datatype of column in python
Is the SQLAlchemy column type one that inherits from : class : Numeric such as : class : Float : class : Decimal ?
cosqa-train-18031
def is_sqlatype_numeric(coltype: Union[TypeEngine, VisitableType]) -> bool: """ Is the SQLAlchemy column type one that inherits from :class:`Numeric`, such as :class:`Float`, :class:`Decimal`? """ coltype = _coltype_to_typeengine(coltype) return isinstance(coltype, sqltypes.Numeric)
def mmap ( func , iterable ) : if sys . version_info [ 0 ] > 2 : return [ i for i in map ( func , iterable ) ] else : return map ( func , iterable )
0
map list to every 3 elements python
Wrapper to make map () behave the same on Py2 and Py3 .
cosqa-train-18032
def mmap(func, iterable): """Wrapper to make map() behave the same on Py2 and Py3.""" if sys.version_info[0] > 2: return [i for i in map(func, iterable)] else: return map(func, iterable)
def has_value ( cls , value : int ) -> bool : return any ( value == item . value for item in cls )
0
python enum check if value in enum
True if specified value exists in int enum ; otherwise False .
cosqa-train-18033
def has_value(cls, value: int) -> bool: """True if specified value exists in int enum; otherwise, False.""" return any(value == item.value for item in cls)
def __remove_trailing_zeros ( self , collection ) : index = len ( collection ) - 1 while index >= 0 and collection [ index ] == 0 : index -= 1 return collection [ : index + 1 ]
0
python and remove trailing zeros
Removes trailing zeroes from indexable collection of numbers
cosqa-train-18034
def __remove_trailing_zeros(self, collection): """Removes trailing zeroes from indexable collection of numbers""" index = len(collection) - 1 while index >= 0 and collection[index] == 0: index -= 1 return collection[:index + 1]
def Exit ( msg , code = 1 ) : print >> sys . stderr , msg sys . exit ( code )
0
how do you exit code python and give message to user
Exit execution with return code and message : param msg : Message displayed prior to exit : param code : code returned upon exiting
cosqa-train-18035
def Exit(msg, code=1): """Exit execution with return code and message :param msg: Message displayed prior to exit :param code: code returned upon exiting """ print >> sys.stderr, msg sys.exit(code)
def check64bit ( current_system = "python" ) : if current_system == "python" : return sys . maxsize > 2147483647 elif current_system == "os" : import platform pm = platform . machine ( ) if pm != ".." and pm . endswith ( '64' ) : # recent Python (not Iron) return True else : if 'PROCESSOR_ARCHITEW6432' in os . environ : return True # 32 bit program running on 64 bit Windows try : # 64 bit Windows 64 bit program return os . environ [ 'PROCESSOR_ARCHITECTURE' ] . endswith ( '64' ) except IndexError : pass # not Windows try : # this often works in Linux return '64' in platform . architecture ( ) [ 0 ] except Exception : # is an older version of Python, assume also an older os@ # (best we can guess) return False
0
check if you have 32 or 64 bit python
checks if you are on a 64 bit platform
cosqa-train-18036
def check64bit(current_system="python"): """checks if you are on a 64 bit platform""" if current_system == "python": return sys.maxsize > 2147483647 elif current_system == "os": import platform pm = platform.machine() if pm != ".." and pm.endswith('64'): # recent Python (not Iron) return True else: if 'PROCESSOR_ARCHITEW6432' in os.environ: return True # 32 bit program running on 64 bit Windows try: # 64 bit Windows 64 bit program return os.environ['PROCESSOR_ARCHITECTURE'].endswith('64') except IndexError: pass # not Windows try: # this often works in Linux return '64' in platform.architecture()[0] except Exception: # is an older version of Python, assume also an older os@ # (best we can guess) return False
def clean_column_names ( df : DataFrame ) -> DataFrame : f = df . copy ( ) f . columns = [ col . strip ( ) for col in f . columns ] return f
0
python removing columns from a data frame
Strip the whitespace from all column names in the given DataFrame and return the result .
cosqa-train-18037
def clean_column_names(df: DataFrame) -> DataFrame: """ Strip the whitespace from all column names in the given DataFrame and return the result. """ f = df.copy() f.columns = [col.strip() for col in f.columns] return f
def __rmatmul__ ( self , other ) : return self . T . dot ( np . transpose ( other ) ) . T
1
python matrix multiplication *
Matrix multiplication using binary
cosqa-train-18038
def __rmatmul__(self, other): """ Matrix multiplication using binary `@` operator in Python>=3.5. """ return self.T.dot(np.transpose(other)).T
def decodebytes ( input ) : py_version = sys . version_info [ 0 ] if py_version >= 3 : return _decodebytes_py3 ( input ) return _decodebytes_py2 ( input )
1
how to decode base 64 python
Decode base64 string to byte array .
cosqa-train-18039
def decodebytes(input): """Decode base64 string to byte array.""" py_version = sys.version_info[0] if py_version >= 3: return _decodebytes_py3(input) return _decodebytes_py2(input)
def string ( value ) -> str : return system_json . dumps ( Json ( value ) . safe_object ( ) , ensure_ascii = False )
0
python json formatted string to string
string dict / object / value to JSON
cosqa-train-18040
def string(value) -> str: """ string dict/object/value to JSON """ return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)
def dtypes ( self ) : return [ ( str ( f . name ) , f . dataType . simpleString ( ) ) for f in self . schema . fields ]
1
printing data type off all columns in data frame in python
Returns all column names and their data types as a list .
cosqa-train-18041
def dtypes(self): """Returns all column names and their data types as a list. >>> df.dtypes [('age', 'int'), ('name', 'string')] """ return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]
def parse_reading ( val : str ) -> Optional [ float ] : try : return float ( val ) except ValueError : logging . warning ( 'Reading of "%s" is not a number' , val ) return None
0
python check if float is none
Convert reading value to float ( if possible )
cosqa-train-18042
def parse_reading(val: str) -> Optional[float]: """ Convert reading value to float (if possible) """ try: return float(val) except ValueError: logging.warning('Reading of "%s" is not a number', val) return None
def from_buffer ( buffer , mime = False ) : m = _get_magic_type ( mime ) return m . from_buffer ( buffer )
0
python tell a file type
Accepts a binary string and returns the detected filetype . Return value is the mimetype if mime = True otherwise a human readable name .
cosqa-train-18043
def from_buffer(buffer, mime=False): """ Accepts a binary string and returns the detected filetype. Return value is the mimetype if mime=True, otherwise a human readable name. >>> magic.from_buffer(open("testdata/test.pdf").read(1024)) 'PDF document, version 1.2' """ m = _get_magic_type(mime) return m.from_buffer(buffer)
def mmap ( func , iterable ) : if sys . version_info [ 0 ] > 2 : return [ i for i in map ( func , iterable ) ] else : return map ( func , iterable )
1
using map on lists python
Wrapper to make map () behave the same on Py2 and Py3 .
cosqa-train-18044
def mmap(func, iterable): """Wrapper to make map() behave the same on Py2 and Py3.""" if sys.version_info[0] > 2: return [i for i in map(func, iterable)] else: return map(func, iterable)
def check_key ( self , key : str ) -> bool : keys = self . get_keys ( ) return key in keys
0
python check for existing hash key
Checks if key exists in datastore . True if yes False if no .
cosqa-train-18045
def check_key(self, key: str) -> bool: """ Checks if key exists in datastore. True if yes, False if no. :param: SHA512 hash key :return: whether or key not exists in datastore """ keys = self.get_keys() return key in keys
def capitalize ( string ) : if not string : return string if len ( string ) == 1 : return string . upper ( ) return string [ 0 ] . upper ( ) + string [ 1 : ] . lower ( )
0
how to specify capitalization in python
Capitalize a sentence .
cosqa-train-18046
def capitalize(string): """Capitalize a sentence. Parameters ---------- string : `str` String to capitalize. Returns ------- `str` Capitalized string. Examples -------- >>> capitalize('worD WORD WoRd') 'Word word word' """ if not string: return string if len(string) == 1: return string.upper() return string[0].upper() + string[1:].lower()
def iterate_items ( dictish ) : if hasattr ( dictish , 'iteritems' ) : return dictish . iteritems ( ) if hasattr ( dictish , 'items' ) : return dictish . items ( ) return dictish
1
python iter dictionary items
Return a consistent ( key value ) iterable on dict - like objects including lists of tuple pairs .
cosqa-train-18047
def iterate_items(dictish): """ Return a consistent (key, value) iterable on dict-like objects, including lists of tuple pairs. Example: >>> list(iterate_items({'a': 1})) [('a', 1)] >>> list(iterate_items([('a', 1), ('b', 2)])) [('a', 1), ('b', 2)] """ if hasattr(dictish, 'iteritems'): return dictish.iteritems() if hasattr(dictish, 'items'): return dictish.items() return dictish
def _run_sync ( self , method : Callable , * args , * * kwargs ) -> Any : if self . loop . is_running ( ) : raise RuntimeError ( "Event loop is already running." ) if not self . is_connected : self . loop . run_until_complete ( self . connect ( ) ) task = asyncio . Task ( method ( * args , * * kwargs ) , loop = self . loop ) result = self . loop . run_until_complete ( task ) self . loop . run_until_complete ( self . quit ( ) ) return result
1
test asyncio python not working
Utility method to run commands synchronously for testing .
cosqa-train-18048
def _run_sync(self, method: Callable, *args, **kwargs) -> Any: """ Utility method to run commands synchronously for testing. """ if self.loop.is_running(): raise RuntimeError("Event loop is already running.") if not self.is_connected: self.loop.run_until_complete(self.connect()) task = asyncio.Task(method(*args, **kwargs), loop=self.loop) result = self.loop.run_until_complete(task) self.loop.run_until_complete(self.quit()) return result
def str_to_time ( time_str : str ) -> datetime . datetime : pieces : Any = [ int ( piece ) for piece in time_str . split ( '-' ) ] return datetime . datetime ( * pieces )
1
get datatime from string python
Convert human readable string to datetime . datetime .
cosqa-train-18049
def str_to_time(time_str: str) -> datetime.datetime: """ Convert human readable string to datetime.datetime. """ pieces: Any = [int(piece) for piece in time_str.split('-')] return datetime.datetime(*pieces)
def maybe_infer_dtype_type ( element ) : tipo = None if hasattr ( element , 'dtype' ) : tipo = element . dtype elif is_list_like ( element ) : element = np . asarray ( element ) tipo = element . dtype return tipo
0
how to get data type in python matrix
Try to infer an object s dtype for use in arithmetic ops
cosqa-train-18050
def maybe_infer_dtype_type(element): """Try to infer an object's dtype, for use in arithmetic ops Uses `element.dtype` if that's available. Objects implementing the iterator protocol are cast to a NumPy array, and from there the array's type is used. Parameters ---------- element : object Possibly has a `.dtype` attribute, and possibly the iterator protocol. Returns ------- tipo : type Examples -------- >>> from collections import namedtuple >>> Foo = namedtuple("Foo", "dtype") >>> maybe_infer_dtype_type(Foo(np.dtype("i8"))) numpy.int64 """ tipo = None if hasattr(element, 'dtype'): tipo = element.dtype elif is_list_like(element): element = np.asarray(element) tipo = element.dtype return tipo
def get_keys_of_max_n ( dict_obj , n ) : return sorted ( [ item [ 0 ] for item in sorted ( dict_obj . items ( ) , key = lambda item : item [ 1 ] , reverse = True ) [ : n ] ] )
0
highest 5 values from dictionary python
Returns the keys that maps to the top n max values in the given dict .
cosqa-train-18051
def get_keys_of_max_n(dict_obj, n): """Returns the keys that maps to the top n max values in the given dict. Example: -------- >>> dict_obj = {'a':2, 'b':1, 'c':5} >>> get_keys_of_max_n(dict_obj, 2) ['a', 'c'] """ return sorted([ item[0] for item in sorted( dict_obj.items(), key=lambda item: item[1], reverse=True )[:n] ])
def get_now_sql_datetime ( ) : ## > IMPORTS ## from datetime import datetime , date , time now = datetime . now ( ) now = now . strftime ( "%Y-%m-%dT%H:%M:%S" ) return now
1
python current time mysql
* A datetime stamp in MySQL format : YYYY - MM - DDTHH : MM : SS *
cosqa-train-18052
def get_now_sql_datetime(): """ *A datetime stamp in MySQL format: ``YYYY-MM-DDTHH:MM:SS``* **Return:** - ``now`` -- current time and date in MySQL format **Usage:** .. code-block:: python from fundamentals import times now = times.get_now_sql_datetime() print now # OUT: 2016-03-18T11:08:23 """ ## > IMPORTS ## from datetime import datetime, date, time now = datetime.now() now = now.strftime("%Y-%m-%dT%H:%M:%S") return now
def export_to_dot ( self , filename : str = 'output' ) -> None : with open ( filename + '.dot' , 'w' ) as output : output . write ( self . as_dot ( ) )
0
python graph to file
Export the graph to the dot file filename . dot .
cosqa-train-18053
def export_to_dot(self, filename: str = 'output') -> None: """ Export the graph to the dot file "filename.dot". """ with open(filename + '.dot', 'w') as output: output.write(self.as_dot())
def read_flat ( self ) : x , y , pixel , meta = self . read ( ) arraycode = 'BH' [ meta [ 'bitdepth' ] > 8 ] pixel = array ( arraycode , itertools . chain ( * pixel ) ) return x , y , pixel , meta
1
python how to flatten image
Read a PNG file and decode it into flat row flat pixel format .
cosqa-train-18054
def read_flat(self): """ Read a PNG file and decode it into flat row flat pixel format. Returns (*width*, *height*, *pixels*, *metadata*). May use excessive memory. `pixels` are returned in flat row flat pixel format. See also the :meth:`read` method which returns pixels in the more stream-friendly boxed row flat pixel format. """ x, y, pixel, meta = self.read() arraycode = 'BH'[meta['bitdepth'] > 8] pixel = array(arraycode, itertools.chain(*pixel)) return x, y, pixel, meta
def to_iso_string ( self ) -> str : assert isinstance ( self . value , datetime ) return datetime . isoformat ( self . value )
0
current date in iso string format in python
Returns full ISO string for the given date
cosqa-train-18055
def to_iso_string(self) -> str: """ Returns full ISO string for the given date """ assert isinstance(self.value, datetime) return datetime.isoformat(self.value)
def from_iso_time ( timestring , use_dateutil = True ) : if not _iso8601_time_re . match ( timestring ) : raise ValueError ( 'Not a valid ISO8601-formatted time string' ) if dateutil_available and use_dateutil : return parser . parse ( timestring ) . time ( ) else : if len ( timestring ) > 8 : # has microseconds fmt = '%H:%M:%S.%f' else : fmt = '%H:%M:%S' return datetime . datetime . strptime ( timestring , fmt ) . time ( )
1
check if a string timestamp iso format python
Parse an ISO8601 - formatted datetime string and return a datetime . time object .
cosqa-train-18056
def from_iso_time(timestring, use_dateutil=True): """Parse an ISO8601-formatted datetime string and return a datetime.time object. """ if not _iso8601_time_re.match(timestring): raise ValueError('Not a valid ISO8601-formatted time string') if dateutil_available and use_dateutil: return parser.parse(timestring).time() else: if len(timestring) > 8: # has microseconds fmt = '%H:%M:%S.%f' else: fmt = '%H:%M:%S' return datetime.datetime.strptime(timestring, fmt).time()
def get_timezone ( ) -> Tuple [ datetime . tzinfo , str ] : dt = get_datetime_now ( ) . astimezone ( ) tzstr = dt . strftime ( "%z" ) tzstr = tzstr [ : - 2 ] + ":" + tzstr [ - 2 : ] return dt . tzinfo , tzstr
1
how to print the current timezone in python
Discover the current time zone and it s standard string representation ( for source { d } ) .
cosqa-train-18057
def get_timezone() -> Tuple[datetime.tzinfo, str]: """Discover the current time zone and it's standard string representation (for source{d}).""" dt = get_datetime_now().astimezone() tzstr = dt.strftime("%z") tzstr = tzstr[:-2] + ":" + tzstr[-2:] return dt.tzinfo, tzstr
def decodebytes ( input ) : py_version = sys . version_info [ 0 ] if py_version >= 3 : return _decodebytes_py3 ( input ) return _decodebytes_py2 ( input )
0
python 2 to python 3 decoding
Decode base64 string to byte array .
cosqa-train-18058
def decodebytes(input): """Decode base64 string to byte array.""" py_version = sys.version_info[0] if py_version >= 3: return _decodebytes_py3(input) return _decodebytes_py2(input)
def fix_title_capitalization ( title ) : if re . search ( "[A-Z]" , title ) and re . search ( "[a-z]" , title ) : return title word_list = re . split ( ' +' , title ) final = [ word_list [ 0 ] . capitalize ( ) ] for word in word_list [ 1 : ] : if word . upper ( ) in COMMON_ACRONYMS : final . append ( word . upper ( ) ) elif len ( word ) > 3 : final . append ( word . capitalize ( ) ) else : final . append ( word . lower ( ) ) return " " . join ( final )
0
python test if first letter is capital
Try to capitalize properly a title string .
cosqa-train-18059
def fix_title_capitalization(title): """Try to capitalize properly a title string.""" if re.search("[A-Z]", title) and re.search("[a-z]", title): return title word_list = re.split(' +', title) final = [word_list[0].capitalize()] for word in word_list[1:]: if word.upper() in COMMON_ACRONYMS: final.append(word.upper()) elif len(word) > 3: final.append(word.capitalize()) else: final.append(word.lower()) return " ".join(final)
def argsort_k_smallest ( x , k ) : if k == 0 : return np . array ( [ ] , dtype = np . intp ) if k is None or k >= len ( x ) : return np . argsort ( x ) indices = np . argpartition ( x , k ) [ : k ] values = x [ indices ] return indices [ np . argsort ( values ) ]
1
indices of k smallest elements python
Return no more than k indices of smallest values .
cosqa-train-18060
def argsort_k_smallest(x, k): """ Return no more than ``k`` indices of smallest values. """ if k == 0: return np.array([], dtype=np.intp) if k is None or k >= len(x): return np.argsort(x) indices = np.argpartition(x, k)[:k] values = x[indices] return indices[np.argsort(values)]
def area ( self ) : area = 0.0 for segment in self . segments ( ) : area += ( ( segment . p . x * segment . q . y ) - ( segment . q . x * segment . p . y ) ) / 2 return area
1
python get area of polygon
area () - > number
cosqa-train-18061
def area (self): """area() -> number Returns the area of this Polygon. """ area = 0.0 for segment in self.segments(): area += ((segment.p.x * segment.q.y) - (segment.q.x * segment.p.y))/2 return area
def PrintIndented ( self , file , ident , code ) : for entry in code : print >> file , '%s%s' % ( ident , entry )
0
vs code change indent space for python files only
Takes an array add indentation to each entry and prints it .
cosqa-train-18062
def PrintIndented(self, file, ident, code): """Takes an array, add indentation to each entry and prints it.""" for entry in code: print >>file, '%s%s' % (ident, entry)
def debugTreePrint ( node , pfx = "->" ) : print pfx , node . item for c in node . children : debugTreePrint ( c , " " + pfx )
0
how to code a tree in python
Purely a debugging aid : Ascii - art picture of a tree descended from node
cosqa-train-18063
def debugTreePrint(node,pfx="->"): """Purely a debugging aid: Ascii-art picture of a tree descended from node""" print pfx,node.item for c in node.children: debugTreePrint(c," "+pfx)
def get_from_gnucash26_date ( date_str : str ) -> date : date_format = "%Y%m%d" result = datetime . strptime ( date_str , date_format ) . date ( ) return result
1
cast python variable string to date
Creates a datetime from GnuCash 2 . 6 date string
cosqa-train-18064
def get_from_gnucash26_date(date_str: str) -> date: """ Creates a datetime from GnuCash 2.6 date string """ date_format = "%Y%m%d" result = datetime.strptime(date_str, date_format).date() return result
def remove_blank_lines ( string ) : return "\n" . join ( line for line in string . split ( "\n" ) if len ( line . strip ( ) ) )
0
python str remove blank
Removes all blank lines in @string
cosqa-train-18065
def remove_blank_lines(string): """ Removes all blank lines in @string -> #str without blank lines """ return "\n".join(line for line in string.split("\n") if len(line.strip()))
def uuid2buid ( value ) : if six . PY3 : # pragma: no cover return urlsafe_b64encode ( value . bytes ) . decode ( 'utf-8' ) . rstrip ( '=' ) else : return six . text_type ( urlsafe_b64encode ( value . bytes ) . rstrip ( '=' ) )
0
python turn uuid into string
Convert a UUID object to a 22 - char BUID string
cosqa-train-18066
def uuid2buid(value): """ Convert a UUID object to a 22-char BUID string >>> u = uuid.UUID('33203dd2-f2ef-422f-aeb0-058d6f5f7089') >>> uuid2buid(u) 'MyA90vLvQi-usAWNb19wiQ' """ if six.PY3: # pragma: no cover return urlsafe_b64encode(value.bytes).decode('utf-8').rstrip('=') else: return six.text_type(urlsafe_b64encode(value.bytes).rstrip('='))
def strtobytes ( input , encoding ) : py_version = sys . version_info [ 0 ] if py_version >= 3 : return _strtobytes_py3 ( input , encoding ) return _strtobytes_py2 ( input , encoding )
1
python3 encoding a bytestring
Take a str and transform it into a byte array .
cosqa-train-18067
def strtobytes(input, encoding): """Take a str and transform it into a byte array.""" py_version = sys.version_info[0] if py_version >= 3: return _strtobytes_py3(input, encoding) return _strtobytes_py2(input, encoding)
def gen_lower ( x : Iterable [ str ] ) -> Generator [ str , None , None ] : for string in x : yield string . lower ( )
1
python make all list elements lowercase
Args : x : iterable of strings
cosqa-train-18068
def gen_lower(x: Iterable[str]) -> Generator[str, None, None]: """ Args: x: iterable of strings Yields: each string in lower case """ for string in x: yield string.lower()
def __remove_trailing_zeros ( self , collection ) : index = len ( collection ) - 1 while index >= 0 and collection [ index ] == 0 : index -= 1 return collection [ : index + 1 ]
1
how to remove leading zeroes in python
Removes trailing zeroes from indexable collection of numbers
cosqa-train-18069
def __remove_trailing_zeros(self, collection): """Removes trailing zeroes from indexable collection of numbers""" index = len(collection) - 1 while index >= 0 and collection[index] == 0: index -= 1 return collection[:index + 1]
def iter_lines ( file_like : Iterable [ str ] ) -> Generator [ str , None , None ] : for line in file_like : line = line . rstrip ( '\r\n' ) if line : yield line
0
does readlines in python skip empty lines
Helper for iterating only nonempty lines without line breaks
cosqa-train-18070
def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]: """ Helper for iterating only nonempty lines without line breaks""" for line in file_like: line = line.rstrip('\r\n') if line: yield line
def dag_longest_path ( graph , source , target ) : if source == target : return [ source ] allpaths = nx . all_simple_paths ( graph , source , target ) longest_path = [ ] for l in allpaths : if len ( l ) > len ( longest_path ) : longest_path = l return longest_path
1
finding longest path of dag python
Finds the longest path in a dag between two nodes
cosqa-train-18071
def dag_longest_path(graph, source, target): """ Finds the longest path in a dag between two nodes """ if source == target: return [source] allpaths = nx.all_simple_paths(graph, source, target) longest_path = [] for l in allpaths: if len(l) > len(longest_path): longest_path = l return longest_path
def is_sqlatype_string ( coltype : Union [ TypeEngine , VisitableType ] ) -> bool : coltype = _coltype_to_typeengine ( coltype ) return isinstance ( coltype , sqltypes . String )
0
python check datatype of a column
Is the SQLAlchemy column type a string type?
cosqa-train-18072
def is_sqlatype_string(coltype: Union[TypeEngine, VisitableType]) -> bool: """ Is the SQLAlchemy column type a string type? """ coltype = _coltype_to_typeengine(coltype) return isinstance(coltype, sqltypes.String)
def replace ( s , old , new , maxreplace = - 1 ) : return s . replace ( old , new , maxreplace )
0
how to replace a substring in a python sdtring
replace ( str old new [ maxreplace ] ) - > string
cosqa-train-18073
def replace(s, old, new, maxreplace=-1): """replace (str, old, new[, maxreplace]) -> string Return a copy of string str with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, only the first maxreplace occurrences are replaced. """ return s.replace(old, new, maxreplace)
def most_frequent ( lst ) : lst = lst [ : ] highest_freq = 0 most_freq = None for val in unique ( lst ) : if lst . count ( val ) > highest_freq : most_freq = val highest_freq = lst . count ( val ) return most_freq
0
get most frequent items in list python
Returns the item that appears most frequently in the given list .
cosqa-train-18074
def most_frequent(lst): """ Returns the item that appears most frequently in the given list. """ lst = lst[:] highest_freq = 0 most_freq = None for val in unique(lst): if lst.count(val) > highest_freq: most_freq = val highest_freq = lst.count(val) return most_freq
def _prm_get_longest_stringsize ( string_list ) : maxlength = 1 for stringar in string_list : if isinstance ( stringar , np . ndarray ) : if stringar . ndim > 0 : for string in stringar . ravel ( ) : maxlength = max ( len ( string ) , maxlength ) else : maxlength = max ( len ( stringar . tolist ( ) ) , maxlength ) else : maxlength = max ( len ( stringar ) , maxlength ) # Make the string Col longer than needed in order to allow later on slightly larger strings return int ( maxlength * 1.5 )
0
max length of list of strings python
Returns the longest string size for a string entry across data .
cosqa-train-18075
def _prm_get_longest_stringsize(string_list): """ Returns the longest string size for a string entry across data.""" maxlength = 1 for stringar in string_list: if isinstance(stringar, np.ndarray): if stringar.ndim > 0: for string in stringar.ravel(): maxlength = max(len(string), maxlength) else: maxlength = max(len(stringar.tolist()), maxlength) else: maxlength = max(len(stringar), maxlength) # Make the string Col longer than needed in order to allow later on slightly larger strings return int(maxlength * 1.5)
def rmglob ( pattern : str ) -> None : for f in glob . glob ( pattern ) : os . remove ( f )
0
python re expression to delete all files
Deletes all files whose filename matches the glob pattern ( via : func : glob . glob ) .
cosqa-train-18076
def rmglob(pattern: str) -> None: """ Deletes all files whose filename matches the glob ``pattern`` (via :func:`glob.glob`). """ for f in glob.glob(pattern): os.remove(f)
def list_depth ( list_ , func = max , _depth = 0 ) : depth_list = [ list_depth ( item , func = func , _depth = _depth + 1 ) for item in list_ if util_type . is_listlike ( item ) ] if len ( depth_list ) > 0 : return func ( depth_list ) else : return _depth
1
how to determine depth nested list python
Returns the deepest level of nesting within a list of lists
cosqa-train-18077
def list_depth(list_, func=max, _depth=0): """ Returns the deepest level of nesting within a list of lists Args: list_ : a nested listlike object func : depth aggregation strategy (defaults to max) _depth : internal var Example: >>> # ENABLE_DOCTEST >>> from utool.util_list import * # NOQA >>> list_ = [[[[[1]]], [3]], [[1], [3]], [[1], [3]]] >>> result = (list_depth(list_, _depth=0)) >>> print(result) """ depth_list = [list_depth(item, func=func, _depth=_depth + 1) for item in list_ if util_type.is_listlike(item)] if len(depth_list) > 0: return func(depth_list) else: return _depth
def rank ( tensor : BKTensor ) -> int : if isinstance ( tensor , np . ndarray ) : return len ( tensor . shape ) return len ( tensor [ 0 ] . size ( ) )
0
tensorflow python get shape
Return the number of dimensions of a tensor
cosqa-train-18078
def rank(tensor: BKTensor) -> int: """Return the number of dimensions of a tensor""" if isinstance(tensor, np.ndarray): return len(tensor.shape) return len(tensor[0].size())
def get_longest_line_length ( text ) : lines = text . split ( "\n" ) length = 0 for i in range ( len ( lines ) ) : if len ( lines [ i ] ) > length : length = len ( lines [ i ] ) return length
1
how do you get python code to print longest line of a text
Get the length longest line in a paragraph
cosqa-train-18079
def get_longest_line_length(text): """Get the length longest line in a paragraph""" lines = text.split("\n") length = 0 for i in range(len(lines)): if len(lines[i]) > length: length = len(lines[i]) return length
def flatten_list ( x : List [ Any ] ) -> List [ Any ] : # noqa return [ item for sublist in x for item in sublist ]
1
flatten arbitrary list python
Converts a list of lists into a flat list . Args : x : list of lists
cosqa-train-18080
def flatten_list(x: List[Any]) -> List[Any]: """ Converts a list of lists into a flat list. Args: x: list of lists Returns: flat list As per http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python """ # noqa return [item for sublist in x for item in sublist]
def _rindex ( mylist : Sequence [ T ] , x : T ) -> int : return len ( mylist ) - mylist [ : : - 1 ] . index ( x ) - 1
0
index slicing python get last element
Index of the last occurrence of x in the sequence .
cosqa-train-18081
def _rindex(mylist: Sequence[T], x: T) -> int: """Index of the last occurrence of x in the sequence.""" return len(mylist) - mylist[::-1].index(x) - 1
def csv_to_numpy ( string_like , dtype = None ) : # type: (str) -> np.array stream = StringIO ( string_like ) return np . genfromtxt ( stream , dtype = dtype , delimiter = ',' )
1
python csv read numpy array
Convert a CSV object to a numpy array .
cosqa-train-18082
def csv_to_numpy(string_like, dtype=None): # type: (str) -> np.array """Convert a CSV object to a numpy array. Args: string_like (str): CSV string. dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the contents of each column, individually. This argument can only be used to 'upcast' the array. For downcasting, use the .astype(t) method. Returns: (np.array): numpy array """ stream = StringIO(string_like) return np.genfromtxt(stream, dtype=dtype, delimiter=',')
def constant ( times : np . ndarray , amp : complex ) -> np . ndarray : return np . full ( len ( times ) , amp , dtype = np . complex_ )
1
python square wave with input and end
Continuous constant pulse .
cosqa-train-18083
def constant(times: np.ndarray, amp: complex) -> np.ndarray: """Continuous constant pulse. Args: times: Times to output pulse for. amp: Complex pulse amplitude. """ return np.full(len(times), amp, dtype=np.complex_)
def is_finite ( value : Any ) -> bool : return isinstance ( value , int ) or ( isinstance ( value , float ) and isfinite ( value ) )
0
python check is a float zero
Return true if a value is a finite number .
cosqa-train-18084
def is_finite(value: Any) -> bool: """Return true if a value is a finite number.""" return isinstance(value, int) or (isinstance(value, float) and isfinite(value))
def post ( self , endpoint : str , * * kwargs ) -> dict : return self . _request ( 'POST' , endpoint , * * kwargs )
0
python requests post how to use params
HTTP POST operation to API endpoint .
cosqa-train-18085
def post(self, endpoint: str, **kwargs) -> dict: """HTTP POST operation to API endpoint.""" return self._request('POST', endpoint, **kwargs)
def sort_by_modified ( files_or_folders : list ) -> list : return sorted ( files_or_folders , key = os . path . getmtime , reverse = True )
1
python get files in directory sort by modified time
Sort files or folders by modified time
cosqa-train-18086
def sort_by_modified(files_or_folders: list) -> list: """ Sort files or folders by modified time Args: files_or_folders: list of files or folders Returns: list """ return sorted(files_or_folders, key=os.path.getmtime, reverse=True)
def cli_run ( ) : parser = argparse . ArgumentParser ( description = 'Stupidly simple code answers from StackOverflow' ) parser . add_argument ( 'query' , help = "What's the problem ?" , type = str , nargs = '+' ) parser . add_argument ( '-t' , '--tags' , help = 'semicolon separated tags -> python;lambda' ) args = parser . parse_args ( ) main ( args )
0
call a fucntion argparse cli python
docstring for argparse
cosqa-train-18087
def cli_run(): """docstring for argparse""" parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow') parser.add_argument('query', help="What's the problem ?", type=str, nargs='+') parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda') args = parser.parse_args() main(args)
def flatten_list ( x : List [ Any ] ) -> List [ Any ] : # noqa return [ item for sublist in x for item in sublist ]
0
flatten list in list python
Converts a list of lists into a flat list . Args : x : list of lists
cosqa-train-18088
def flatten_list(x: List[Any]) -> List[Any]: """ Converts a list of lists into a flat list. Args: x: list of lists Returns: flat list As per http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python """ # noqa return [item for sublist in x for item in sublist]
def indices_to_labels ( self , indices : Sequence [ int ] ) -> List [ str ] : return [ ( self . INDEX_TO_LABEL [ index ] ) for index in indices ]
0
list of indices to list of values python
Converts a sequence of indices into their corresponding labels .
cosqa-train-18089
def indices_to_labels(self, indices: Sequence[int]) -> List[str]: """ Converts a sequence of indices into their corresponding labels.""" return [(self.INDEX_TO_LABEL[index]) for index in indices]
def strip_codes ( s : Any ) -> str : return codepat . sub ( '' , str ( s ) if ( s or ( s == 0 ) ) else '' )
0
remove carriage return from string in python
Strip all color codes from a string . Returns empty string for falsey inputs .
cosqa-train-18090
def strip_codes(s: Any) -> str: """ Strip all color codes from a string. Returns empty string for "falsey" inputs. """ return codepat.sub('', str(s) if (s or (s == 0)) else '')
def _ ( f , x ) : return { k : v for k , v in x . items ( ) if f ( k , v ) }
0
python iterate and remove dict filter
filter for dict note f should have signature : f :: key - > value - > bool
cosqa-train-18091
def _(f, x): """ filter for dict, note `f` should have signature: `f::key->value->bool` """ return {k: v for k, v in x.items() if f(k, v)}
def to_jupyter ( graph : BELGraph , chart : Optional [ str ] = None ) -> Javascript : with open ( os . path . join ( HERE , 'render_with_javascript.js' ) , 'rt' ) as f : js_template = Template ( f . read ( ) ) return Javascript ( js_template . render ( * * _get_context ( graph , chart = chart ) ) )
1
rendering a python figure in html with javascript
Render the graph as JavaScript in a Jupyter Notebook .
cosqa-train-18092
def to_jupyter(graph: BELGraph, chart: Optional[str] = None) -> Javascript: """Render the graph as JavaScript in a Jupyter Notebook.""" with open(os.path.join(HERE, 'render_with_javascript.js'), 'rt') as f: js_template = Template(f.read()) return Javascript(js_template.render(**_get_context(graph, chart=chart)))
def valid_file ( path : str ) -> bool : path = Path ( path ) . expanduser ( ) log . debug ( "checking if %s is a valid file" , path ) return path . exists ( ) and path . is_file ( )
1
python how to check if a string is file
Verifies that a string path actually exists and is a file
cosqa-train-18093
def valid_file(path: str) -> bool: """ Verifies that a string path actually exists and is a file :param path: The path to verify :return: **True** if path exist and is a file """ path = Path(path).expanduser() log.debug("checking if %s is a valid file", path) return path.exists() and path.is_file()
def normalize ( numbers ) : total = float ( sum ( numbers ) ) return [ n / total for n in numbers ]
0
python normalize to sum to 1
Multiply each number by a constant such that the sum is 1 . 0 >>> normalize ( [ 1 2 1 ] ) [ 0 . 25 0 . 5 0 . 25 ]
cosqa-train-18094
def normalize(numbers): """Multiply each number by a constant such that the sum is 1.0 >>> normalize([1,2,1]) [0.25, 0.5, 0.25] """ total = float(sum(numbers)) return [n / total for n in numbers]
def is_line_in_file ( filename : str , line : str ) -> bool : assert "\n" not in line with open ( filename , "r" ) as file : for fileline in file : if fileline == line : return True return False
1
how to check for a line in a file using python
Detects whether a line is present within a file .
cosqa-train-18095
def is_line_in_file(filename: str, line: str) -> bool: """ Detects whether a line is present within a file. Args: filename: file to check line: line to search for (as an exact match) """ assert "\n" not in line with open(filename, "r") as file: for fileline in file: if fileline == line: return True return False
def negate_mask ( mask ) : res = np . ones ( mask . shape , dtype = np . int8 ) res [ mask > 0 ] = 0 return res
1
python matrix only return values above 0
Returns the negated mask . If elements of input mask have 0 and non - zero values then the returned matrix will have all elements 0 ( 1 ) where the original one has non - zero ( 0 ) . : param mask : Input mask : type mask : np . array : return : array of same shape and dtype = int8 as input array : rtype : np . array
cosqa-train-18096
def negate_mask(mask): """Returns the negated mask. If elements of input mask have 0 and non-zero values, then the returned matrix will have all elements 0 (1) where the original one has non-zero (0). :param mask: Input mask :type mask: np.array :return: array of same shape and dtype=int8 as input array :rtype: np.array """ res = np.ones(mask.shape, dtype=np.int8) res[mask > 0] = 0 return res
def __remove_trailing_zeros ( self , collection ) : index = len ( collection ) - 1 while index >= 0 and collection [ index ] == 0 : index -= 1 return collection [ : index + 1 ]
1
how do i cut off leading zeroes in python
Removes trailing zeroes from indexable collection of numbers
cosqa-train-18097
def __remove_trailing_zeros(self, collection): """Removes trailing zeroes from indexable collection of numbers""" index = len(collection) - 1 while index >= 0 and collection[index] == 0: index -= 1 return collection[:index + 1]
def _run_sync ( self , method : Callable , * args , * * kwargs ) -> Any : if self . loop . is_running ( ) : raise RuntimeError ( "Event loop is already running." ) if not self . is_connected : self . loop . run_until_complete ( self . connect ( ) ) task = asyncio . Task ( method ( * args , * * kwargs ) , loop = self . loop ) result = self . loop . run_until_complete ( task ) self . loop . run_until_complete ( self . quit ( ) ) return result
0
python asyncio socket examples
Utility method to run commands synchronously for testing .
cosqa-train-18098
def _run_sync(self, method: Callable, *args, **kwargs) -> Any: """ Utility method to run commands synchronously for testing. """ if self.loop.is_running(): raise RuntimeError("Event loop is already running.") if not self.is_connected: self.loop.run_until_complete(self.connect()) task = asyncio.Task(method(*args, **kwargs), loop=self.loop) result = self.loop.run_until_complete(task) self.loop.run_until_complete(self.quit()) return result
def pack_bits ( longbits ) : byte = longbits & ( 0x0101010101010101 ) byte = ( byte | ( byte >> 7 ) ) & ( 0x0003000300030003 ) byte = ( byte | ( byte >> 14 ) ) & ( 0x0000000f0000000f ) byte = ( byte | ( byte >> 28 ) ) & ( 0x00000000000000ff ) return byte
1
how to parse bits into 32 bit in python chunk
Crunch a 64 - bit int ( 8 bool bytes ) into a bitfield .
cosqa-train-18099
def pack_bits( longbits ): """Crunch a 64-bit int (8 bool bytes) into a bitfield.""" byte = longbits & (0x0101010101010101) byte = (byte | (byte>>7)) & (0x0003000300030003) byte = (byte | (byte>>14)) & (0x0000000f0000000f) byte = (byte | (byte>>28)) & (0x00000000000000ff) return byte