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 _parse_tuple_string ( argument ) : if isinstance ( argument , str ) : return tuple ( int ( p . strip ( ) ) for p in argument . split ( ',' ) ) return argument
0
python split a string to a tuple
Return a tuple from parsing a b c d - > ( a b c d )
cosqa-train-17400
def _parse_tuple_string(argument): """ Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) """ if isinstance(argument, str): return tuple(int(p.strip()) for p in argument.split(',')) return argument
def calculate_dimensions ( image , long_side , short_side ) : if image . width >= image . height : return '{0}x{1}' . format ( long_side , short_side ) return '{0}x{1}' . format ( short_side , long_side )
1
how i check dimensions image python
Returns the thumbnail dimensions depending on the images format .
cosqa-train-17401
def calculate_dimensions(image, long_side, short_side): """Returns the thumbnail dimensions depending on the images format.""" if image.width >= image.height: return '{0}x{1}'.format(long_side, short_side) return '{0}x{1}'.format(short_side, long_side)
def fmt_camel ( name ) : words = split_words ( name ) assert len ( words ) > 0 first = words . pop ( 0 ) . lower ( ) return first + '' . join ( [ word . capitalize ( ) for word in words ] )
1
how to capitalize first item in list python
Converts name to lower camel case . Words are identified by capitalization dashes and underscores .
cosqa-train-17402
def fmt_camel(name): """ Converts name to lower camel case. Words are identified by capitalization, dashes, and underscores. """ words = split_words(name) assert len(words) > 0 first = words.pop(0).lower() return first + ''.join([word.capitalize() for word in words])
def from_file ( filename , mime = False ) : m = _get_magic_type ( mime ) return m . from_file ( filename )
0
python how to determine file is pdf type
Accepts a filename and returns the detected filetype . Return value is the mimetype if mime = True otherwise a human readable name .
cosqa-train-17403
def from_file(filename, mime=False): """" Accepts a filename and returns the detected filetype. Return value is the mimetype if mime=True, otherwise a human readable name. >>> magic.from_file("testdata/test.pdf", mime=True) 'application/pdf' """ m = _get_magic_type(mime) return m.from_file(filename)
def list_to_str ( list , separator = ',' ) : list = [ str ( x ) for x in list ] return separator . join ( list )
0
python change list of int to string
>>> list = [ 0 0 7 ] >>> list_to_str ( list ) 0 0 7
cosqa-train-17404
def list_to_str(list, separator=','): """ >>> list = [0, 0, 7] >>> list_to_str(list) '0,0,7' """ list = [str(x) for x in list] return separator.join(list)
def try_cast_int ( s ) : try : temp = re . findall ( '\d' , str ( s ) ) temp = '' . join ( temp ) return int ( temp ) except : return s
1
cast str as int in python
( str ) - > int All the digits in a given string are concatenated and converted into a single number .
cosqa-train-17405
def try_cast_int(s): """(str) -> int All the digits in a given string are concatenated and converted into a single number. """ try: temp = re.findall('\d', str(s)) temp = ''.join(temp) return int(temp) except: return s
def clean_column_names ( df : DataFrame ) -> DataFrame : f = df . copy ( ) f . columns = [ col . strip ( ) for col in f . columns ] return f
0
remove columns from df python
Strip the whitespace from all column names in the given DataFrame and return the result .
cosqa-train-17406
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 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
how to make a comma seprated list into a one string in python
Turn a list into a comma - and / or and - separated string .
cosqa-train-17407
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 getIndex ( predicateFn : Callable [ [ T ] , bool ] , items : List [ T ] ) -> int : try : return next ( i for i , v in enumerate ( items ) if predicateFn ( v ) ) except StopIteration : return - 1
0
using a for loop to evaluate the first index in a list python
Finds the index of an item in list which satisfies predicate : param predicateFn : predicate function to run on items of list : param items : list of tuples : return : first index for which predicate function returns True
cosqa-train-17408
def getIndex(predicateFn: Callable[[T], bool], items: List[T]) -> int: """ Finds the index of an item in list, which satisfies predicate :param predicateFn: predicate function to run on items of list :param items: list of tuples :return: first index for which predicate function returns True """ try: return next(i for i, v in enumerate(items) if predicateFn(v)) except StopIteration: return -1
def isarray ( array , test , dim = 2 ) : if dim > 1 : return all ( isarray ( array [ i ] , test , dim - 1 ) for i in range ( len ( array ) ) ) return all ( test ( i ) for i in array )
1
how to check all items in an array python
Returns True if test is True for all array elements . Otherwise returns False .
cosqa-train-17409
def isarray(array, test, dim=2): """Returns True if test is True for all array elements. Otherwise, returns False. """ if dim > 1: return all(isarray(array[i], test, dim - 1) for i in range(len(array))) return all(test(i) for i in array)
def is_quoted ( arg : str ) -> bool : return len ( arg ) > 1 and arg [ 0 ] == arg [ - 1 ] and arg [ 0 ] in constants . QUOTES
1
python match single or double quoted strings
Checks if a string is quoted : param arg : the string being checked for quotes : return : True if a string is quoted
cosqa-train-17410
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 get_language ( ) : from parler import appsettings language = dj_get_language ( ) if language is None and appsettings . PARLER_DEFAULT_ACTIVATE : return appsettings . PARLER_DEFAULT_LANGUAGE_CODE else : return language
1
detect language to english python
Wrapper around Django s get_language utility . For Django > = 1 . 8 get_language returns None in case no translation is activate . Here we patch this behavior e . g . for back - end functionality requiring access to translated fields
cosqa-train-17411
def get_language(): """ Wrapper around Django's `get_language` utility. For Django >= 1.8, `get_language` returns None in case no translation is activate. Here we patch this behavior e.g. for back-end functionality requiring access to translated fields """ from parler import appsettings language = dj_get_language() if language is None and appsettings.PARLER_DEFAULT_ACTIVATE: return appsettings.PARLER_DEFAULT_LANGUAGE_CODE else: return language
def chars ( string : any ) -> str : return '' . join ( [ c if c . isalpha ( ) else '' for c in str ( string ) ] )
0
python check a sting is all alpha
Return all ( and only ) the chars in the given string .
cosqa-train-17412
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 infer_format ( filename : str ) -> str : _ , ext = os . path . splitext ( filename ) return ext
0
python get a specific format file name
Return extension identifying format of given filename
cosqa-train-17413
def infer_format(filename:str) -> str: """Return extension identifying format of given filename""" _, ext = os.path.splitext(filename) return ext
def rate_limited ( max_per_hour : int , * args : Any ) -> Callable [ ... , Any ] : return util . rate_limited ( max_per_hour , * args )
1
python limit the execution time of the given functio
Rate limit a function .
cosqa-train-17414
def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]: """Rate limit a function.""" return util.rate_limited(max_per_hour, *args)
def _find_conda ( ) : if 'CONDA_EXE' in os . environ : conda = os . environ [ 'CONDA_EXE' ] else : conda = util . which ( 'conda' ) return conda
1
how to set conda and python path in windows
Find the conda executable robustly across conda versions .
cosqa-train-17415
def _find_conda(): """Find the conda executable robustly across conda versions. Returns ------- conda : str Path to the conda executable. Raises ------ IOError If the executable cannot be found in either the CONDA_EXE environment variable or in the PATH. Notes ----- In POSIX platforms in conda >= 4.4, conda can be set up as a bash function rather than an executable. (This is to enable the syntax ``conda activate env-name``.) In this case, the environment variable ``CONDA_EXE`` contains the path to the conda executable. In other cases, we use standard search for the appropriate name in the PATH. See https://github.com/airspeed-velocity/asv/issues/645 for more details. """ if 'CONDA_EXE' in os.environ: conda = os.environ['CONDA_EXE'] else: conda = util.which('conda') return conda
def nTimes ( n , f , * args , * * kwargs ) : for i in xrange ( n ) : f ( * args , * * kwargs )
1
how to print something x amount of times in python on the same line
r Call f n times with args and kwargs . Useful e . g . for simplistic timing .
cosqa-train-17416
def nTimes(n, f, *args, **kwargs): r"""Call `f` `n` times with `args` and `kwargs`. Useful e.g. for simplistic timing. Examples: >>> nTimes(3, sys.stdout.write, 'hallo\n') hallo hallo hallo """ for i in xrange(n): f(*args, **kwargs)
def elmo_loss2ppl ( losses : List [ np . ndarray ] ) -> float : avg_loss = np . mean ( losses ) return float ( np . exp ( avg_loss ) )
1
how to get accuracy percentage in python mlp
Calculates perplexity by loss
cosqa-train-17417
def elmo_loss2ppl(losses: List[np.ndarray]) -> float: """ Calculates perplexity by loss Args: losses: list of numpy arrays of model losses Returns: perplexity : float """ avg_loss = np.mean(losses) return float(np.exp(avg_loss))
def url_concat ( url , args ) : if not args : return url if url [ - 1 ] not in ( '?' , '&' ) : url += '&' if ( '?' in url ) else '?' return url + urllib . urlencode ( args )
0
python build url with query string
Concatenate url and argument dictionary regardless of whether url has existing query parameters .
cosqa-train-17418
def url_concat(url, args): """Concatenate url and argument dictionary regardless of whether url has existing query parameters. >>> url_concat("http://example.com/foo?a=b", dict(c="d")) 'http://example.com/foo?a=b&c=d' """ if not args: return url if url[-1] not in ('?', '&'): url += '&' if ('?' in url) else '?' return url + urllib.urlencode(args)
def get_versions ( reporev = True ) : import sys import platform import qtpy import qtpy . QtCore revision = None if reporev : from spyder . utils import vcs revision , branch = vcs . get_git_revision ( os . path . dirname ( __dir__ ) ) if not sys . platform == 'darwin' : # To avoid a crash with our Mac app system = platform . system ( ) else : system = 'Darwin' return { 'spyder' : __version__ , 'python' : platform . python_version ( ) , # "2.7.3" 'bitness' : 64 if sys . maxsize > 2 ** 32 else 32 , 'qt' : qtpy . QtCore . __version__ , 'qt_api' : qtpy . API_NAME , # PyQt5 'qt_api_ver' : qtpy . PYQT_VERSION , 'system' : system , # Linux, Windows, ... 'release' : platform . release ( ) , # XP, 10.6, 2.2.0, etc. 'revision' : revision , # '9fdf926eccce' }
0
how to open spyder 3 on python 3
Get version information for components used by Spyder
cosqa-train-17419
def get_versions(reporev=True): """Get version information for components used by Spyder""" import sys import platform import qtpy import qtpy.QtCore revision = None if reporev: from spyder.utils import vcs revision, branch = vcs.get_git_revision(os.path.dirname(__dir__)) if not sys.platform == 'darwin': # To avoid a crash with our Mac app system = platform.system() else: system = 'Darwin' return { 'spyder': __version__, 'python': platform.python_version(), # "2.7.3" 'bitness': 64 if sys.maxsize > 2**32 else 32, 'qt': qtpy.QtCore.__version__, 'qt_api': qtpy.API_NAME, # PyQt5 'qt_api_ver': qtpy.PYQT_VERSION, 'system': system, # Linux, Windows, ... 'release': platform.release(), # XP, 10.6, 2.2.0, etc. 'revision': revision, # '9fdf926eccce' }
def indexes_equal ( a : Index , b : Index ) -> bool : return str ( a ) == str ( b )
0
check if 2 strings are same python
Are two indexes equal? Checks by comparing str () versions of them . ( AM UNSURE IF THIS IS ENOUGH . )
cosqa-train-17420
def indexes_equal(a: Index, b: Index) -> bool: """ Are two indexes equal? Checks by comparing ``str()`` versions of them. (AM UNSURE IF THIS IS ENOUGH.) """ return str(a) == str(b)
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
0
python finding the first location of a character in a string
Returns the index of the earliest occurence of an item from a list in a string
cosqa-train-17421
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 csv_to_numpy ( string_like , dtype = None ) : # type: (str) -> np.array stream = StringIO ( string_like ) return np . genfromtxt ( stream , dtype = dtype , delimiter = ',' )
0
python read csv to a numpy nd array
Convert a CSV object to a numpy array .
cosqa-train-17422
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 count ( args ) : counts = defaultdict ( int ) for arg in args : for item in arg : counts [ item ] = counts [ item ] + 1 return counts
0
count occurrences in a list python
count occurences in a list of lists >>> count ( [[ a b ] [ a ]] ) defaultdict ( int { a : 2 b : 1 } )
cosqa-train-17423
def count(args): """ count occurences in a list of lists >>> count([['a','b'],['a']]) defaultdict(int, {'a' : 2, 'b' : 1}) """ counts = defaultdict(int) for arg in args: for item in arg: counts[item] = counts[item] + 1 return counts
def _isint ( string ) : return type ( string ) is int or ( isinstance ( string , _binary_type ) or isinstance ( string , _text_type ) ) and _isconvertible ( int , string )
1
python 3 check if string is int
>>> _isint ( 123 ) True >>> _isint ( 123 . 45 ) False
cosqa-train-17424
def _isint(string): """ >>> _isint("123") True >>> _isint("123.45") False """ return type(string) is int or \ (isinstance(string, _binary_type) or isinstance(string, _text_type)) and \ _isconvertible(int, string)
def shape ( self ) -> Tuple [ int , ... ] : return tuple ( bins . bin_count for bins in self . _binnings )
0
width of bins python histogram
Shape of histogram s data .
cosqa-train-17425
def shape(self) -> Tuple[int, ...]: """Shape of histogram's data. Returns ------- One-element tuple with the number of bins along each axis. """ return tuple(bins.bin_count for bins in self._binnings)
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
10 largest values from dictionary python
Returns the keys that maps to the top n max values in the given dict .
cosqa-train-17426
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 pset ( iterable = ( ) , pre_size = 8 ) : if not iterable : return _EMPTY_PSET return PSet . _from_iterable ( iterable , pre_size = pre_size )
0
python 3 create a set with size limit
Creates a persistent set from iterable . Optionally takes a sizing parameter equivalent to that used for : py : func : pmap .
cosqa-train-17427
def pset(iterable=(), pre_size=8): """ Creates a persistent set from iterable. Optionally takes a sizing parameter equivalent to that used for :py:func:`pmap`. >>> s1 = pset([1, 2, 3, 2]) >>> s1 pset([1, 2, 3]) """ if not iterable: return _EMPTY_PSET return PSet._from_iterable(iterable, pre_size=pre_size)
def hsv2rgb_spectrum ( hsv ) : h , s , v = hsv return hsv2rgb_raw ( ( ( h * 192 ) >> 8 , s , v ) )
0
cv2 python brightness hsv
Generates RGB values from HSV values in line with a typical light spectrum .
cosqa-train-17428
def hsv2rgb_spectrum(hsv): """Generates RGB values from HSV values in line with a typical light spectrum.""" h, s, v = hsv return hsv2rgb_raw(((h * 192) >> 8, s, v))
def post ( self , endpoint : str , * * kwargs ) -> dict : return self . _request ( 'POST' , endpoint , * * kwargs )
0
python call post rest service
HTTP POST operation to API endpoint .
cosqa-train-17429
def post(self, endpoint: str, **kwargs) -> dict: """HTTP POST operation to API endpoint.""" return self._request('POST', endpoint, **kwargs)
def clean ( ctx , text ) : text = conversions . to_string ( text , ctx ) return '' . join ( [ c for c in text if ord ( c ) >= 32 ] )
1
how to remove chinesse characters from a hypertext in a string python
Removes all non - printable characters from a text string
cosqa-train-17430
def clean(ctx, text): """ Removes all non-printable characters from a text string """ text = conversions.to_string(text, ctx) return ''.join([c for c in text if ord(c) >= 32])
def __as_list ( value : List [ JsonObjTypes ] ) -> List [ JsonTypes ] : return [ e . _as_dict if isinstance ( e , JsonObj ) else e for e in value ]
1
python list feilds of json array]
Return a json array as a list
cosqa-train-17431
def __as_list(value: List[JsonObjTypes]) -> List[JsonTypes]: """ Return a json array as a list :param value: array :return: array with JsonObj instances removed """ return [e._as_dict if isinstance(e, JsonObj) else e for e in value]
def __add_method ( m : lmap . Map , key : T , method : Method ) -> lmap . Map : return m . assoc ( key , method )
1
patch a dictionary that values are method calls python
Swap the methods atom to include method with key .
cosqa-train-17432
def __add_method(m: lmap.Map, key: T, method: Method) -> lmap.Map: """Swap the methods atom to include method with key.""" return m.assoc(key, method)
def isfile_notempty ( inputfile : str ) -> bool : try : return isfile ( inputfile ) and getsize ( inputfile ) > 0 except TypeError : raise TypeError ( 'inputfile is not a valid type' )
0
python test if file empty
Check if the input filename with path is a file and is not empty .
cosqa-train-17433
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 pack_bits ( longbits ) : byte = longbits & ( 0x0101010101010101 ) byte = ( byte | ( byte >> 7 ) ) & ( 0x0003000300030003 ) byte = ( byte | ( byte >> 14 ) ) & ( 0x0000000f0000000f ) byte = ( byte | ( byte >> 28 ) ) & ( 0x00000000000000ff ) return byte
1
python change to 64 bit
Crunch a 64 - bit int ( 8 bool bytes ) into a bitfield .
cosqa-train-17434
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
def __iter__ ( self ) : def generator ( ) : for i , obj in enumerate ( self . _sequence ) : if i >= self . _limit : break yield obj raise StopIteration return generator
0
python generator' object has no attribute
Define a generator function and return it
cosqa-train-17435
def __iter__(self): """Define a generator function and return it""" def generator(): for i, obj in enumerate(self._sequence): if i >= self._limit: break yield obj raise StopIteration return generator
def clean_int ( x ) -> int : try : return int ( x ) except ValueError : raise forms . ValidationError ( "Cannot convert to integer: {}" . format ( repr ( x ) ) )
0
python form validation numbers only
Returns its parameter as an integer or raises django . forms . ValidationError .
cosqa-train-17436
def clean_int(x) -> int: """ Returns its parameter as an integer, or raises ``django.forms.ValidationError``. """ try: return int(x) except ValueError: raise forms.ValidationError( "Cannot convert to integer: {}".format(repr(x)))
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
python iterating through delimited text file that has no line breaks
Helper for iterating only nonempty lines without line breaks
cosqa-train-17437
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 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
how to check if i have 32 or 64 bit python
checks if you are on a 64 bit platform
cosqa-train-17438
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 strtobytes ( input , encoding ) : py_version = sys . version_info [ 0 ] if py_version >= 3 : return _strtobytes_py3 ( input , encoding ) return _strtobytes_py2 ( input , encoding )
0
python2 string to byte array
Take a str and transform it into a byte array .
cosqa-train-17439
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 _skip_section ( self ) : self . _last = self . _f . readline ( ) while len ( self . _last ) > 0 and len ( self . _last [ 0 ] . strip ( ) ) == 0 : self . _last = self . _f . readline ( )
0
python skip current line
Skip a section
cosqa-train-17440
def _skip_section(self): """Skip a section""" self._last = self._f.readline() while len(self._last) > 0 and len(self._last[0].strip()) == 0: self._last = self._f.readline()
def strings_to_integers ( strings : Iterable [ str ] ) -> Iterable [ int ] : return strings_to_ ( strings , lambda x : int ( float ( x ) ) )
1
pythonconvert list of strings to int
Convert a list of strings to a list of integers .
cosqa-train-17441
def strings_to_integers(strings: Iterable[str]) -> Iterable[int]: """ Convert a list of strings to a list of integers. :param strings: a list of string :return: a list of converted integers .. doctest:: >>> strings_to_integers(['1', '1.0', '-0.2']) [1, 1, 0] """ return strings_to_(strings, lambda x: int(float(x)))
def is_finite ( value : Any ) -> bool : return isinstance ( value , int ) or ( isinstance ( value , float ) and isfinite ( value ) )
1
python check if value is infinity
Return true if a value is a finite number .
cosqa-train-17442
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 format_repr ( obj , attributes ) -> str : attribute_repr = ', ' . join ( ( '{}={}' . format ( attr , repr ( getattr ( obj , attr ) ) ) for attr in attributes ) ) return "{0}({1})" . format ( obj . __class__ . __qualname__ , attribute_repr )
0
how to make a string of an object in python
Format an object s repr method with specific attributes .
cosqa-train-17443
def format_repr(obj, attributes) -> str: """Format an object's repr method with specific attributes.""" attribute_repr = ', '.join(('{}={}'.format(attr, repr(getattr(obj, attr))) for attr in attributes)) return "{0}({1})".format(obj.__class__.__qualname__, attribute_repr)
def _read_words ( filename ) : with tf . gfile . GFile ( filename , "r" ) as f : if sys . version_info [ 0 ] >= 3 : return f . read ( ) . replace ( "\n" , " %s " % EOS ) . split ( ) else : return f . read ( ) . decode ( "utf-8" ) . replace ( "\n" , " %s " % EOS ) . split ( )
0
python tensorflow read text file
Reads words from a file .
cosqa-train-17444
def _read_words(filename): """Reads words from a file.""" with tf.gfile.GFile(filename, "r") as f: if sys.version_info[0] >= 3: return f.read().replace("\n", " %s " % EOS).split() else: return f.read().decode("utf-8").replace("\n", " %s " % EOS).split()
def _my_hash ( arg_list ) : # type: (List[Any]) -> int res = 0 for arg in arg_list : res = res * 31 + hash ( arg ) return res
1
hash function generates fixed length code in python
Simple helper hash function
cosqa-train-17445
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 u16le_list_to_byte_list ( data ) : byteData = [ ] for h in data : byteData . extend ( [ h & 0xff , ( h >> 8 ) & 0xff ] ) return byteData
0
python 16bit list to bytearray
!
cosqa-train-17446
def u16le_list_to_byte_list(data): """! @brief Convert a halfword array into a byte array""" byteData = [] for h in data: byteData.extend([h & 0xff, (h >> 8) & 0xff]) return byteData
def _kbhit_unix ( ) -> bool : dr , dw , de = select . select ( [ sys . stdin ] , [ ] , [ ] , 0 ) return dr != [ ]
0
python detect keypress hardware
Under UNIX : is a keystroke available?
cosqa-train-17447
def _kbhit_unix() -> bool: """ Under UNIX: is a keystroke available? """ dr, dw, de = select.select([sys.stdin], [], [], 0) return dr != []
def listify ( a ) : if a is None : return [ ] elif not isinstance ( a , ( tuple , list , np . ndarray ) ) : return [ a ] return list ( a )
0
how to turn python list into an array
Convert a scalar a to a list and all iterables to list as well .
cosqa-train-17448
def listify(a): """ Convert a scalar ``a`` to a list and all iterables to list as well. Examples -------- >>> listify(0) [0] >>> listify([1,2,3]) [1, 2, 3] >>> listify('a') ['a'] >>> listify(np.array([1,2,3])) [1, 2, 3] >>> listify('string') ['string'] """ if a is None: return [] elif not isinstance(a, (tuple, list, np.ndarray)): return [a] return list(a)
def sort_by_modified ( files_or_folders : list ) -> list : return sorted ( files_or_folders , key = os . path . getmtime , reverse = True )
0
python sort the files according to the change time
Sort files or folders by modified time
cosqa-train-17449
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 position ( self ) -> Position : return Position ( self . _index , self . _lineno , self . _col_offset )
0
to know curremt position of file cursor the function use in python
The current position of the cursor .
cosqa-train-17450
def position(self) -> Position: """The current position of the cursor.""" return Position(self._index, self._lineno, self._col_offset)
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
how to get pylint ot work for python 3
Run verbose PyLint on source . Optionally specify fmt = html for HTML output .
cosqa-train-17451
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 clean_column_names ( df : DataFrame ) -> DataFrame : f = df . copy ( ) f . columns = [ col . strip ( ) for col in f . columns ] return f
0
how to remove data columns in python
Strip the whitespace from all column names in the given DataFrame and return the result .
cosqa-train-17452
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 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 check if path is directory or file
Verifies that a string path actually exists and is a file
cosqa-train-17453
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 _gauss ( mean : int , sigma : int ) -> int : return int ( random . gauss ( mean , sigma ) )
1
generation of random numbers with given mean, sd, min and max value python
Creates a variation from a base value
cosqa-train-17454
def _gauss(mean: int, sigma: int) -> int: """ Creates a variation from a base value Args: mean: base value sigma: gaussian sigma Returns: random value """ return int(random.gauss(mean, sigma))
def split ( text : str ) -> List [ str ] : return [ word for word in SEPARATOR . split ( text ) if word . strip ( ' \t' ) ]
1
split each sentence token and stoe in list using python
Split a text into a list of tokens .
cosqa-train-17455
def split(text: str) -> List[str]: """Split a text into a list of tokens. :param text: the text to split :return: tokens """ return [word for word in SEPARATOR.split(text) if word.strip(' \t')]
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
how to extract the number that appears the most frequently in a list in python
Returns the item that appears most frequently in the given list .
cosqa-train-17456
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 rmglob ( pattern : str ) -> None : for f in glob . glob ( pattern ) : os . remove ( f )
0
python delete glob files
Deletes all files whose filename matches the glob pattern ( via : func : glob . glob ) .
cosqa-train-17457
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 try_cast_int ( s ) : try : temp = re . findall ( '\d' , str ( s ) ) temp = '' . join ( temp ) return int ( temp ) except : return s
1
how can i cast a string in int python
( str ) - > int All the digits in a given string are concatenated and converted into a single number .
cosqa-train-17458
def try_cast_int(s): """(str) -> int All the digits in a given string are concatenated and converted into a single number. """ try: temp = re.findall('\d', str(s)) temp = ''.join(temp) return int(temp) except: return s
def _parse_tuple_string ( argument ) : if isinstance ( argument , str ) : return tuple ( int ( p . strip ( ) ) for p in argument . split ( ',' ) ) return argument
0
how to delete quotes in python so that the string will turn into a tuple
Return a tuple from parsing a b c d - > ( a b c d )
cosqa-train-17459
def _parse_tuple_string(argument): """ Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) """ if isinstance(argument, str): return tuple(int(p.strip()) for p in argument.split(',')) return argument
def get_column_names ( engine : Engine , tablename : str ) -> List [ str ] : return [ info . name for info in gen_columns_info ( engine , tablename ) ]
1
how toget all the column names in a database python
Get all the database column names for the specified table .
cosqa-train-17460
def get_column_names(engine: Engine, tablename: str) -> List[str]: """ Get all the database column names for the specified table. """ return [info.name for info in gen_columns_info(engine, tablename)]
def get_last_weekday_in_month ( year , month , weekday ) : day = date ( year , month , monthrange ( year , month ) [ 1 ] ) while True : if day . weekday ( ) == weekday : break day = day - timedelta ( days = 1 ) return day
0
last weekday of month in python
Get the last weekday in a given month . e . g :
cosqa-train-17461
def get_last_weekday_in_month(year, month, weekday): """Get the last weekday in a given month. e.g: >>> # the last monday in Jan 2013 >>> Calendar.get_last_weekday_in_month(2013, 1, MON) datetime.date(2013, 1, 28) """ day = date(year, month, monthrange(year, month)[1]) while True: if day.weekday() == weekday: break day = day - timedelta(days=1) return day
def _gauss ( mean : int , sigma : int ) -> int : return int ( random . gauss ( mean , sigma ) )
1
python random number with gaussian distribution
Creates a variation from a base value
cosqa-train-17462
def _gauss(mean: int, sigma: int) -> int: """ Creates a variation from a base value Args: mean: base value sigma: gaussian sigma Returns: random value """ return int(random.gauss(mean, sigma))
def fetchallfirstvalues ( self , sql : str , * args ) -> List [ Any ] : rows = self . fetchall ( sql , * args ) return [ row [ 0 ] for row in rows ]
1
extract first row froma table in python sql
Executes SQL ; returns list of first values of each row .
cosqa-train-17463
def fetchallfirstvalues(self, sql: str, *args) -> List[Any]: """Executes SQL; returns list of first values of each row.""" rows = self.fetchall(sql, *args) return [row[0] for row in rows]
def fcast ( value : float ) -> TensorLike : newvalue = tf . cast ( value , FTYPE ) if DEVICE == 'gpu' : newvalue = newvalue . gpu ( ) # Why is this needed? # pragma: no cover return newvalue
0
python long tensor to float tensor
Cast to float tensor
cosqa-train-17464
def fcast(value: float) -> TensorLike: """Cast to float tensor""" newvalue = tf.cast(value, FTYPE) if DEVICE == 'gpu': newvalue = newvalue.gpu() # Why is this needed? # pragma: no cover return newvalue
def PrintIndented ( self , file , ident , code ) : for entry in code : print >> file , '%s%s' % ( ident , entry )
0
python write a list indent line
Takes an array add indentation to each entry and prints it .
cosqa-train-17465
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 truncate ( value : Decimal , n_digits : int ) -> Decimal : return Decimal ( math . trunc ( value * ( 10 ** n_digits ) ) ) / ( 10 ** n_digits )
1
how to a truncate decimals in python
Truncates a value to a number of decimals places
cosqa-train-17466
def truncate(value: Decimal, n_digits: int) -> Decimal: """Truncates a value to a number of decimals places""" return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)
def replace_keys ( record : Mapping , key_map : Mapping ) -> dict : return { key_map [ k ] : v for k , v in record . items ( ) if k in key_map }
1
python new dictionary using old key
New record with renamed keys including keys only found in key_map .
cosqa-train-17467
def replace_keys(record: Mapping, key_map: Mapping) -> dict: """New record with renamed keys including keys only found in key_map.""" return {key_map[k]: v for k, v in record.items() if k in key_map}
def sort_by_modified ( files_or_folders : list ) -> list : return sorted ( files_or_folders , key = os . path . getmtime , reverse = True )
0
sort files based on modified time on python
Sort files or folders by modified time
cosqa-train-17468
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 debugTreePrint ( node , pfx = "->" ) : print pfx , node . item for c in node . children : debugTreePrint ( c , " " + pfx )
0
python print tree values
Purely a debugging aid : Ascii - art picture of a tree descended from node
cosqa-train-17469
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 has_changed ( filename ) : key = os . path . abspath ( filename ) mtime = get_mtime ( key ) if key not in _mtime_cache : _mtime_cache [ key ] = mtime return True return mtime > _mtime_cache [ key ]
1
python check for files edited within time
Check if filename has changed since the last check . If this is the first check assume the file is changed .
cosqa-train-17470
def has_changed (filename): """Check if filename has changed since the last check. If this is the first check, assume the file is changed.""" key = os.path.abspath(filename) mtime = get_mtime(key) if key not in _mtime_cache: _mtime_cache[key] = mtime return True return mtime > _mtime_cache[key]
def argmax ( self , rows : List [ Row ] , column : ComparableColumn ) -> List [ Row ] : if not rows : return [ ] value_row_pairs = [ ( row . values [ column . name ] , row ) for row in rows ] if not value_row_pairs : return [ ] # Returns a list containing the row with the max cell value. return [ sorted ( value_row_pairs , key = lambda x : x [ 0 ] , reverse = True ) [ 0 ] [ 1 ] ]
0
max elemet in a column python
Takes a list of rows and a column name and returns a list containing a single row ( dict from columns to cells ) that has the maximum numerical value in the given column . We return a list instead of a single dict to be consistent with the return type of select and all_rows .
cosqa-train-17471
def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]: """ Takes a list of rows and a column name and returns a list containing a single row (dict from columns to cells) that has the maximum numerical value in the given column. We return a list instead of a single dict to be consistent with the return type of ``select`` and ``all_rows``. """ if not rows: return [] value_row_pairs = [(row.values[column.name], row) for row in rows] if not value_row_pairs: return [] # Returns a list containing the row with the max cell value. return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]
def lower_camel_case_from_underscores ( string ) : components = string . split ( '_' ) string = components [ 0 ] for component in components [ 1 : ] : string += component [ 0 ] . upper ( ) + component [ 1 : ] return string
0
python underscore line above
generate a lower - cased camelCase string from an underscore_string . For example : my_variable_name - > myVariableName
cosqa-train-17472
def lower_camel_case_from_underscores(string): """generate a lower-cased camelCase string from an underscore_string. For example: my_variable_name -> myVariableName""" components = string.split('_') string = components[0] for component in components[1:]: string += component[0].upper() + component[1:] return string
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 from str to bytes
Take a str and transform it into a byte array .
cosqa-train-17473
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 memory_full ( ) : current_process = psutil . Process ( os . getpid ( ) ) return ( current_process . memory_percent ( ) > config . MAXIMUM_CACHE_MEMORY_PERCENTAGE )
1
python flask cap memory limit
Check if the memory is too full for further caching .
cosqa-train-17474
def memory_full(): """Check if the memory is too full for further caching.""" current_process = psutil.Process(os.getpid()) return (current_process.memory_percent() > config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)
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
using dot file with python graphviz
Print out a neat targets dependency tree based on requested targets .
cosqa-train-17475
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 valid_substitution ( strlen , index ) : values = index [ 0 ] return all ( [ strlen > i for i in values ] )
0
substring string indices must be integers python
skip performing substitutions that are outside the bounds of the string
cosqa-train-17476
def valid_substitution(strlen, index): """ skip performing substitutions that are outside the bounds of the string """ values = index[0] return all([strlen > i for i in values])
def isarray ( array , test , dim = 2 ) : if dim > 1 : return all ( isarray ( array [ i ] , test , dim - 1 ) for i in range ( len ( array ) ) ) return all ( test ( i ) for i in array )
1
python test if array contains an element
Returns True if test is True for all array elements . Otherwise returns False .
cosqa-train-17477
def isarray(array, test, dim=2): """Returns True if test is True for all array elements. Otherwise, returns False. """ if dim > 1: return all(isarray(array[i], test, dim - 1) for i in range(len(array))) return all(test(i) for i in array)
def flatten_multidict ( multidict ) : return dict ( [ ( key , value if len ( value ) > 1 else value [ 0 ] ) for ( key , value ) in multidict . iterlists ( ) ] )
0
python tuple dict key to nested dict
Return flattened dictionary from MultiDict .
cosqa-train-17478
def flatten_multidict(multidict): """Return flattened dictionary from ``MultiDict``.""" return dict([(key, value if len(value) > 1 else value[0]) for (key, value) in multidict.iterlists()])
def chars ( string : any ) -> str : return '' . join ( [ c if c . isalpha ( ) else '' for c in str ( string ) ] )
0
python detect alpha characters in string
Return all ( and only ) the chars in the given string .
cosqa-train-17479
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 _check_whitespace ( string ) : if string . count ( ' ' ) + string . count ( '\t' ) + string . count ( '\n' ) > 0 : raise ValueError ( INSTRUCTION_HAS_WHITESPACE )
1
how to check for invalid whitespace in python
Make sure thre is no whitespace in the given string . Will raise a ValueError if whitespace is detected
cosqa-train-17480
def _check_whitespace(string): """ Make sure thre is no whitespace in the given string. Will raise a ValueError if whitespace is detected """ if string.count(' ') + string.count('\t') + string.count('\n') > 0: raise ValueError(INSTRUCTION_HAS_WHITESPACE)
def _gauss ( mean : int , sigma : int ) -> int : return int ( random . gauss ( mean , sigma ) )
0
how to generate random numbers on normal distribution with python
Creates a variation from a base value
cosqa-train-17481
def _gauss(mean: int, sigma: int) -> int: """ Creates a variation from a base value Args: mean: base value sigma: gaussian sigma Returns: random value """ return int(random.gauss(mean, sigma))
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
threading multiple asyncrous python threads in teststand
Utility method to run commands synchronously for testing .
cosqa-train-17482
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 replace_in_list ( stringlist : Iterable [ str ] , replacedict : Dict [ str , str ] ) -> List [ str ] : newlist = [ ] for fromstring in stringlist : newlist . append ( multiple_replace ( fromstring , replacedict ) ) return newlist
1
replace in for loop from a string using python
Returns a list produced by applying : func : multiple_replace to every string in stringlist .
cosqa-train-17483
def replace_in_list(stringlist: Iterable[str], replacedict: Dict[str, str]) -> List[str]: """ Returns a list produced by applying :func:`multiple_replace` to every string in ``stringlist``. Args: stringlist: list of source strings replacedict: dictionary mapping "original" to "replacement" strings Returns: list of final strings """ newlist = [] for fromstring in stringlist: newlist.append(multiple_replace(fromstring, replacedict)) return newlist
def string ( value ) -> str : return system_json . dumps ( Json ( value ) . safe_object ( ) , ensure_ascii = False )
0
javascript equivalent of python string literal
string dict / object / value to JSON
cosqa-train-17484
def string(value) -> str: """ string dict/object/value to JSON """ return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)
def dict_of_sets_add ( dictionary , key , value ) : # type: (DictUpperBound, Any, Any) -> None set_objs = dictionary . get ( key , set ( ) ) set_objs . add ( value ) dictionary [ key ] = set_objs
1
how to add items to a set in python
Add value to a set in a dictionary by key
cosqa-train-17485
def dict_of_sets_add(dictionary, key, value): # type: (DictUpperBound, Any, Any) -> None """Add value to a set in a dictionary by key Args: dictionary (DictUpperBound): Dictionary to which to add values key (Any): Key within dictionary value (Any): Value to add to set in dictionary Returns: None """ set_objs = dictionary.get(key, set()) set_objs.add(value) dictionary[key] = set_objs
def arcball_map_to_sphere ( point , center , radius ) : v0 = ( point [ 0 ] - center [ 0 ] ) / radius v1 = ( center [ 1 ] - point [ 1 ] ) / radius n = v0 * v0 + v1 * v1 if n > 1.0 : # position outside of sphere n = math . sqrt ( n ) return numpy . array ( [ v0 / n , v1 / n , 0.0 ] ) else : return numpy . array ( [ v0 , v1 , math . sqrt ( 1.0 - n ) ] )
1
compute points on a sphere python
Return unit sphere coordinates from window coordinates .
cosqa-train-17486
def arcball_map_to_sphere(point, center, radius): """Return unit sphere coordinates from window coordinates.""" v0 = (point[0] - center[0]) / radius v1 = (center[1] - point[1]) / radius n = v0*v0 + v1*v1 if n > 1.0: # position outside of sphere n = math.sqrt(n) return numpy.array([v0/n, v1/n, 0.0]) else: return numpy.array([v0, v1, math.sqrt(1.0 - n)])
def is_rate_limited ( response ) : if ( response . status_code == codes . too_many_requests and 'Retry-After' in response . headers and int ( response . headers [ 'Retry-After' ] ) >= 0 ) : return True return False
0
python rate limit function
Checks if the response has been rate limited by CARTO APIs
cosqa-train-17487
def is_rate_limited(response): """ Checks if the response has been rate limited by CARTO APIs :param response: The response rate limited by CARTO APIs :type response: requests.models.Response class :return: Boolean """ if (response.status_code == codes.too_many_requests and 'Retry-After' in response.headers and int(response.headers['Retry-After']) >= 0): return True return False
def _create_empty_array ( self , frames , always_2d , dtype ) : import numpy as np if always_2d or self . channels > 1 : shape = frames , self . channels else : shape = frames , return np . empty ( shape , dtype , order = 'C' )
0
make empty array python without numpy
Create an empty array with appropriate shape .
cosqa-train-17488
def _create_empty_array(self, frames, always_2d, dtype): """Create an empty array with appropriate shape.""" import numpy as np if always_2d or self.channels > 1: shape = frames, self.channels else: shape = frames, return np.empty(shape, dtype, order='C')
def is_integer ( value : Any ) -> bool : return ( isinstance ( value , int ) and not isinstance ( value , bool ) ) or ( isinstance ( value , float ) and isfinite ( value ) and int ( value ) == value )
0
python check if float equals to int
Return true if a value is an integer number .
cosqa-train-17489
def is_integer(value: Any) -> bool: """Return true if a value is an integer number.""" return (isinstance(value, int) and not isinstance(value, bool)) or ( isinstance(value, float) and isfinite(value) and int(value) == value )
def rank ( tensor : BKTensor ) -> int : if isinstance ( tensor , np . ndarray ) : return len ( tensor . shape ) return len ( tensor [ 0 ] . size ( ) )
1
how to get the number of columns in an matrix python
Return the number of dimensions of a tensor
cosqa-train-17490
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 timeit ( func , * args , * * kwargs ) : start_time = time . time ( ) res = func ( * args , * * kwargs ) timing = time . time ( ) - start_time return res , timing
0
how to use timeit on a function in python
Time execution of function . Returns ( res seconds ) .
cosqa-train-17491
def timeit(func, *args, **kwargs): """ Time execution of function. Returns (res, seconds). >>> res, timing = timeit(time.sleep, 1) """ start_time = time.time() res = func(*args, **kwargs) timing = time.time() - start_time return res, timing
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
python bit shift on large values
Crunch a 64 - bit int ( 8 bool bytes ) into a bitfield .
cosqa-train-17492
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
def assert_equal ( first , second , msg_fmt = "{msg}" ) : if isinstance ( first , dict ) and isinstance ( second , dict ) : assert_dict_equal ( first , second , msg_fmt ) elif not first == second : msg = "{!r} != {!r}" . format ( first , second ) fail ( msg_fmt . format ( msg = msg , first = first , second = second ) )
0
python assert equals dict
Fail unless first equals second as determined by the == operator .
cosqa-train-17493
def assert_equal(first, second, msg_fmt="{msg}"): """Fail unless first equals second, as determined by the '==' operator. >>> assert_equal(5, 5.0) >>> assert_equal("Hello World!", "Goodbye!") Traceback (most recent call last): ... AssertionError: 'Hello World!' != 'Goodbye!' The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument """ if isinstance(first, dict) and isinstance(second, dict): assert_dict_equal(first, second, msg_fmt) elif not first == second: msg = "{!r} != {!r}".format(first, second) fail(msg_fmt.format(msg=msg, first=first, second=second))
def _rindex ( mylist : Sequence [ T ] , x : T ) -> int : return len ( mylist ) - mylist [ : : - 1 ] . index ( x ) - 1
1
python get last index of
Index of the last occurrence of x in the sequence .
cosqa-train-17494
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 iter_lines ( file_like : Iterable [ str ] ) -> Generator [ str , None , None ] : for line in file_like : line = line . rstrip ( '\r\n' ) if line : yield line
1
how to not read blank lines from file in python
Helper for iterating only nonempty lines without line breaks
cosqa-train-17495
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 do_quit ( self , _ : argparse . Namespace ) -> bool : self . _should_quit = True return self . _STOP_AND_EXIT
1
python using "0" to quit
Exit this application
cosqa-train-17496
def do_quit(self, _: argparse.Namespace) -> bool: """Exit this application""" self._should_quit = True return self._STOP_AND_EXIT
def set_cell_value ( cell , value ) : if OPENPYXL_MAJOR_VERSION > 1 : cell . value = value else : cell . internal_value = value
1
how to set width for cell with python openyxl
Convenience method for setting the value of an openpyxl cell
cosqa-train-17497
def set_cell_value(cell, value): """ Convenience method for setting the value of an openpyxl cell This is necessary since the value property changed from internal_value to value between version 1.* and 2.*. """ if OPENPYXL_MAJOR_VERSION > 1: cell.value = value else: cell.internal_value = value
def dotproduct ( X , Y ) : return sum ( [ x * y for x , y in zip ( X , Y ) ] )
0
how to calculate product of two strings in python
Return the sum of the element - wise product of vectors x and y . >>> dotproduct ( [ 1 2 3 ] [ 1000 100 10 ] ) 1230
cosqa-train-17498
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 argmax ( self , rows : List [ Row ] , column : ComparableColumn ) -> List [ Row ] : if not rows : return [ ] value_row_pairs = [ ( row . values [ column . name ] , row ) for row in rows ] if not value_row_pairs : return [ ] # Returns a list containing the row with the max cell value. return [ sorted ( value_row_pairs , key = lambda x : x [ 0 ] , reverse = True ) [ 0 ] [ 1 ] ]
0
selecting the max value in a column python
Takes a list of rows and a column name and returns a list containing a single row ( dict from columns to cells ) that has the maximum numerical value in the given column . We return a list instead of a single dict to be consistent with the return type of select and all_rows .
cosqa-train-17499
def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]: """ Takes a list of rows and a column name and returns a list containing a single row (dict from columns to cells) that has the maximum numerical value in the given column. We return a list instead of a single dict to be consistent with the return type of ``select`` and ``all_rows``. """ if not rows: return [] value_row_pairs = [(row.values[column.name], row) for row in rows] if not value_row_pairs: return [] # Returns a list containing the row with the max cell value. return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]