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 moving_average ( arr : np . ndarray , n : int = 3 ) -> np . ndarray : ret = np . cumsum ( arr , dtype = float ) ret [ n : ] = ret [ n : ] - ret [ : - n ] return ret [ n - 1 : ] / n | 0 | python list comprehension moving average | Calculate the moving overage over an array . | cosqa-train-19900 | def moving_average(arr: np.ndarray, n: int = 3) -> np.ndarray:
""" Calculate the moving overage over an array.
Algorithm from: https://stackoverflow.com/a/14314054
Args:
arr (np.ndarray): Array over which to calculate the moving average.
n (int): Number of elements over which to calculate the moving average. Default: 3
Returns:
np.ndarray: Moving average calculated over n.
"""
ret = np.cumsum(arr, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n |
def truncate ( value : Decimal , n_digits : int ) -> Decimal : return Decimal ( math . trunc ( value * ( 10 ** n_digits ) ) ) / ( 10 ** n_digits ) | 0 | how to truncate decimals python | Truncates a value to a number of decimals places | cosqa-train-19901 | 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 rmglob ( pattern : str ) -> None : for f in glob . glob ( pattern ) : os . remove ( f ) | 1 | python delete all files with certain extension | Deletes all files whose filename matches the glob pattern ( via : func : glob . glob ) . | cosqa-train-19902 | 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 singularize ( word ) : for inflection in UNCOUNTABLES : if re . search ( r'(?i)\b(%s)\Z' % inflection , word ) : return word for rule , replacement in SINGULARS : if re . search ( rule , word ) : return re . sub ( rule , replacement , word ) return word | 1 | python change plural to singular | Return the singular form of a word the reverse of : func : pluralize . | cosqa-train-19903 | def singularize(word):
"""
Return the singular form of a word, the reverse of :func:`pluralize`.
Examples::
>>> singularize("posts")
"post"
>>> singularize("octopi")
"octopus"
>>> singularize("sheep")
"sheep"
>>> singularize("word")
"word"
>>> singularize("CamelOctopi")
"CamelOctopus"
"""
for inflection in UNCOUNTABLES:
if re.search(r'(?i)\b(%s)\Z' % inflection, word):
return word
for rule, replacement in SINGULARS:
if re.search(rule, word):
return re.sub(rule, replacement, word)
return word |
def astensor ( array : TensorLike ) -> BKTensor : tensor = tf . convert_to_tensor ( value = array , dtype = CTYPE ) return tensor | 0 | how to pytorch tensors can be converted to python scalars | Covert numpy array to tensorflow tensor | cosqa-train-19904 | def astensor(array: TensorLike) -> BKTensor:
"""Covert numpy array to tensorflow tensor"""
tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)
return tensor |
def _str_to_list ( value , separator ) : value_list = [ item . strip ( ) for item in value . split ( separator ) ] value_list_sanitized = builtins . list ( filter ( None , value_list ) ) if len ( value_list_sanitized ) > 0 : return value_list_sanitized else : raise ValueError ( 'Invalid list variable.' ) | 1 | python separate string to list | Convert a string to a list with sanitization . | cosqa-train-19905 | def _str_to_list(value, separator):
"""Convert a string to a list with sanitization."""
value_list = [item.strip() for item in value.split(separator)]
value_list_sanitized = builtins.list(filter(None, value_list))
if len(value_list_sanitized) > 0:
return value_list_sanitized
else:
raise ValueError('Invalid list variable.') |
def hsv2rgb_spectrum ( hsv ) : h , s , v = hsv return hsv2rgb_raw ( ( ( h * 192 ) >> 8 , s , v ) ) | 1 | python opencv hsv black range | Generates RGB values from HSV values in line with a typical light spectrum . | cosqa-train-19906 | 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 remove_blank_lines ( string ) : return "\n" . join ( line for line in string . split ( "\n" ) if len ( line . strip ( ) ) ) | 0 | python if string contains space delete space | Removes all blank lines in @string | cosqa-train-19907 | 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 clean ( ctx , text ) : text = conversions . to_string ( text , ctx ) return '' . join ( [ c for c in text if ord ( c ) >= 32 ] ) | 0 | python remove all instances of a char in a string | Removes all non - printable characters from a text string | cosqa-train-19908 | 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 extend ( a : dict , b : dict ) -> dict : res = a . copy ( ) res . update ( b ) return res | 0 | python merge to dic | Merge two dicts and return a new dict . Much like subclassing works . | cosqa-train-19909 | def extend(a: dict, b: dict) -> dict:
"""Merge two dicts and return a new dict. Much like subclassing works."""
res = a.copy()
res.update(b)
return res |
def last_location_of_minimum ( x ) : x = np . asarray ( x ) return 1.0 - np . argmin ( x [ : : - 1 ] ) / len ( x ) if len ( x ) > 0 else np . NaN | 0 | python minimum of multiple series | Returns the last location of the minimal value of x . The position is calculated relatively to the length of x . | cosqa-train-19910 | def last_location_of_minimum(x):
"""
Returns the last location of the minimal value of x.
The position is calculated relatively to the length of x.
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
x = np.asarray(x)
return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN |
def snake_to_camel ( s : str ) -> str : fragments = s . split ( '_' ) return fragments [ 0 ] + '' . join ( x . title ( ) for x in fragments [ 1 : ] ) | 1 | python to title case with apostrophe in string | Convert string from snake case to camel case . | cosqa-train-19911 | def snake_to_camel(s: str) -> str:
"""Convert string from snake case to camel case."""
fragments = s.split('_')
return fragments[0] + ''.join(x.title() for x in fragments[1:]) |
def dictlist_wipe_key ( dict_list : Iterable [ Dict ] , key : str ) -> None : for d in dict_list : d . pop ( key , None ) | 0 | deleting a element from a dictionary python | Process an iterable of dictionaries . For each dictionary d delete d [ key ] if it exists . | cosqa-train-19912 | def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None:
"""
Process an iterable of dictionaries. For each dictionary ``d``, delete
``d[key]`` if it exists.
"""
for d in dict_list:
d.pop(key, None) |
def is_running ( process_id : int ) -> bool : pstr = str ( process_id ) encoding = sys . getdefaultencoding ( ) s = subprocess . Popen ( [ "ps" , "-p" , pstr ] , stdout = subprocess . PIPE ) for line in s . stdout : strline = line . decode ( encoding ) if pstr in strline : return True return False | 1 | use python to check if a process is running | Uses the Unix ps program to see if a process is running . | cosqa-train-19913 | def is_running(process_id: int) -> bool:
"""
Uses the Unix ``ps`` program to see if a process is running.
"""
pstr = str(process_id)
encoding = sys.getdefaultencoding()
s = subprocess.Popen(["ps", "-p", pstr], stdout=subprocess.PIPE)
for line in s.stdout:
strline = line.decode(encoding)
if pstr in strline:
return True
return False |
def _protected_log ( x1 ) : with np . errstate ( divide = 'ignore' , invalid = 'ignore' ) : return np . where ( np . abs ( x1 ) > 0.001 , np . log ( np . abs ( x1 ) ) , 0. ) | 0 | catch logarithm zero python | Closure of log for zero arguments . | cosqa-train-19914 | def _protected_log(x1):
"""Closure of log for zero arguments."""
with np.errstate(divide='ignore', invalid='ignore'):
return np.where(np.abs(x1) > 0.001, np.log(np.abs(x1)), 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 how to make a list a hashable type | Simple helper hash function | cosqa-train-19915 | 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 is_sqlatype_string ( coltype : Union [ TypeEngine , VisitableType ] ) -> bool : coltype = _coltype_to_typeengine ( coltype ) return isinstance ( coltype , sqltypes . String ) | 0 | how to check datatype of a column in python | Is the SQLAlchemy column type a string type? | cosqa-train-19916 | 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 has_obstory_metadata ( self , status_id ) : self . con . execute ( 'SELECT 1 FROM archive_metadata WHERE publicId=%s;' , ( status_id , ) ) return len ( self . con . fetchall ( ) ) > 0 | 0 | python, odbc, ms access check if record exists | Check for the presence of the given metadata item | cosqa-train-19917 | def has_obstory_metadata(self, status_id):
"""
Check for the presence of the given metadata item
:param string status_id:
The metadata item ID
:return:
True if we have a metadata item with this ID, False otherwise
"""
self.con.execute('SELECT 1 FROM archive_metadata WHERE publicId=%s;', (status_id,))
return len(self.con.fetchall()) > 0 |
def has_key ( cls , * args ) : key = args if len ( args ) > 1 else args [ 0 ] return key in cls . _instances | 0 | how to check if file exist in key python | Check whether flyweight object with specified key has already been created . | cosqa-train-19918 | def has_key(cls, *args):
"""
Check whether flyweight object with specified key has already been created.
Returns:
bool: True if already created, False if not
"""
key = args if len(args) > 1 else args[0]
return key in cls._instances |
def top ( self , topn = 10 ) : return [ self [ i ] for i in argsort ( list ( zip ( * self ) ) [ 1 ] ) [ : : - 1 ] [ : topn ] ] | 1 | python top n elements | Get a list of the top topn features in this : class : . Feature \ . | cosqa-train-19919 | 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 require ( executable : str , explanation : str = "" ) -> None : assert shutil . which ( executable ) , "Need {!r} on the PATH.{}" . format ( executable , "\n" + explanation if explanation else "" ) | 1 | python assert command not found | Ensures that the external tool is available . Asserts upon failure . | cosqa-train-19920 | def require(executable: str, explanation: str = "") -> None:
"""
Ensures that the external tool is available.
Asserts upon failure.
"""
assert shutil.which(executable), "Need {!r} on the PATH.{}".format(
executable, "\n" + explanation if explanation else "") |
def rank ( tensor : BKTensor ) -> int : if isinstance ( tensor , np . ndarray ) : return len ( tensor . shape ) return len ( tensor [ 0 ] . size ( ) ) | 0 | python length of column 1 of np array | Return the number of dimensions of a tensor | cosqa-train-19921 | 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 make_indices_to_labels ( labels : Set [ str ] ) -> Dict [ int , str ] : return { index : label for index , label in enumerate ( [ "pad" ] + sorted ( list ( labels ) ) ) } | 1 | create a dict with keys as list indices python | Creates a mapping from indices to labels . | cosqa-train-19922 | def make_indices_to_labels(labels: Set[str]) -> Dict[int, str]:
""" Creates a mapping from indices to labels. """
return {index: label for index, label in
enumerate(["pad"] + sorted(list(labels)))} |
def issubset ( self , other ) : if len ( self ) > len ( other ) : # Fast check for obvious cases return False return all ( item in other for item in self ) | 1 | how to check if set is subset of another set python | Report whether another set contains this set . | cosqa-train-19923 | def issubset(self, other):
"""
Report whether another set contains this set.
Example:
>>> OrderedSet([1, 2, 3]).issubset({1, 2})
False
>>> OrderedSet([1, 2, 3]).issubset({1, 2, 3, 4})
True
>>> OrderedSet([1, 2, 3]).issubset({1, 4, 3, 5})
False
"""
if len(self) > len(other): # Fast check for obvious cases
return False
return all(item in other for item in self) |
def without ( seq1 , seq2 ) : if isSet ( seq2 ) : d2 = seq2 else : d2 = set ( seq2 ) return [ elt for elt in seq1 if elt not in d2 ] | 0 | python remove elements from a list not in another list | r Return a list with all elements in seq2 removed from seq1 order preserved . | cosqa-train-19924 | def without(seq1, seq2):
r"""Return a list with all elements in `seq2` removed from `seq1`, order
preserved.
Examples:
>>> without([1,2,3,1,2], [1])
[2, 3, 2]
"""
if isSet(seq2): d2 = seq2
else: d2 = set(seq2)
return [elt for elt in seq1 if elt not in d2] |
def read32 ( bytestream ) : dt = np . dtype ( np . uint32 ) . newbyteorder ( '>' ) return np . frombuffer ( bytestream . read ( 4 ) , dtype = dt ) [ 0 ] | 0 | python int 8bit data type | Read 4 bytes from bytestream as an unsigned 32 - bit integer . | cosqa-train-19925 | def read32(bytestream):
"""Read 4 bytes from bytestream as an unsigned 32-bit integer."""
dt = np.dtype(np.uint32).newbyteorder('>')
return np.frombuffer(bytestream.read(4), dtype=dt)[0] |
def _check_stream_timeout ( started , timeout ) : if timeout : elapsed = datetime . datetime . utcnow ( ) - started if elapsed . seconds > timeout : raise StopIteration | 0 | try catch block python time limit api | Check if the timeout has been reached and raise a StopIteration if so . | cosqa-train-19926 | def _check_stream_timeout(started, timeout):
"""Check if the timeout has been reached and raise a `StopIteration` if so.
"""
if timeout:
elapsed = datetime.datetime.utcnow() - started
if elapsed.seconds > timeout:
raise StopIteration |
def tanimoto_set_similarity ( x : Iterable [ X ] , y : Iterable [ X ] ) -> float : a , b = set ( x ) , set ( y ) union = a | b if not union : return 0.0 return len ( a & b ) / len ( union ) | 1 | sets and lists in python similarity | Calculate the tanimoto set similarity . | cosqa-train-19927 | def tanimoto_set_similarity(x: Iterable[X], y: Iterable[X]) -> float:
"""Calculate the tanimoto set similarity."""
a, b = set(x), set(y)
union = a | b
if not union:
return 0.0
return len(a & b) / len(union) |
def _cnx_is_empty ( in_file ) : with open ( in_file ) as in_handle : for i , line in enumerate ( in_handle ) : if i > 0 : return False return True | 0 | python how to check if a file is empty or not | Check if cnr or cns files are empty ( only have a header ) | cosqa-train-19928 | def _cnx_is_empty(in_file):
"""Check if cnr or cns files are empty (only have a header)
"""
with open(in_file) as in_handle:
for i, line in enumerate(in_handle):
if i > 0:
return False
return True |
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 | get first character of string in a list python | Returns the index of the earliest occurence of an item from a list in a string | cosqa-train-19929 | 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 do_quit ( self , _ : argparse . Namespace ) -> bool : self . _should_quit = True return self . _STOP_AND_EXIT | 1 | type quit to exit program python | Exit this application | cosqa-train-19930 | def do_quit(self, _: argparse.Namespace) -> bool:
"""Exit this application"""
self._should_quit = True
return self._STOP_AND_EXIT |
def remove_blank_lines ( string ) : return "\n" . join ( line for line in string . split ( "\n" ) if len ( line . strip ( ) ) ) | 0 | non blank lines python | Removes all blank lines in @string | cosqa-train-19931 | 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 rmglob ( pattern : str ) -> None : for f in glob . glob ( pattern ) : os . remove ( f ) | 0 | python delete files wildcard | Deletes all files whose filename matches the glob pattern ( via : func : glob . glob ) . | cosqa-train-19932 | 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 remove_empty_text ( utterances : List [ Utterance ] ) -> List [ Utterance ] : return [ utter for utter in utterances if utter . text . strip ( ) != "" ] | 1 | python remove word contains list | Remove empty utterances from a list of utterances Args : utterances : The list of utterance we are processing | cosqa-train-19933 | def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]:
"""Remove empty utterances from a list of utterances
Args:
utterances: The list of utterance we are processing
"""
return [utter for utter in utterances if utter.text.strip() != ""] |
def position ( self ) -> Position : return Position ( self . _index , self . _lineno , self . _col_offset ) | 0 | get cursor position python | The current position of the cursor . | cosqa-train-19934 | def position(self) -> Position:
"""The current position of the cursor."""
return Position(self._index, self._lineno, self._col_offset) |
def remove_empty_text ( utterances : List [ Utterance ] ) -> List [ Utterance ] : return [ utter for utter in utterances if utter . text . strip ( ) != "" ] | 1 | python remove all emptstrings from list | Remove empty utterances from a list of utterances Args : utterances : The list of utterance we are processing | cosqa-train-19935 | def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]:
"""Remove empty utterances from a list of utterances
Args:
utterances: The list of utterance we are processing
"""
return [utter for utter in utterances if utter.text.strip() != ""] |
def _duplicates ( list_ ) : item_indices = { } for i , item in enumerate ( list_ ) : try : item_indices [ item ] . append ( i ) except KeyError : # First time seen item_indices [ item ] = [ i ] return item_indices | 1 | python return index of list duplicates | Return dict mapping item - > indices . | cosqa-train-19936 | def _duplicates(list_):
"""Return dict mapping item -> indices."""
item_indices = {}
for i, item in enumerate(list_):
try:
item_indices[item].append(i)
except KeyError: # First time seen
item_indices[item] = [i]
return item_indices |
def trim_decimals ( s , precision = - 3 ) : encoded = s . encode ( 'ascii' , 'ignore' ) str_val = "" if six . PY3 : str_val = str ( encoded , encoding = 'ascii' , errors = 'ignore' ) [ : precision ] else : # If precision is 0, this must be handled seperately if precision == 0 : str_val = str ( encoded ) else : str_val = str ( encoded ) [ : precision ] if len ( str_val ) > 0 : return float ( str_val ) else : return 0 | 1 | python set precision on string | Convert from scientific notation using precision | cosqa-train-19937 | def trim_decimals(s, precision=-3):
"""
Convert from scientific notation using precision
"""
encoded = s.encode('ascii', 'ignore')
str_val = ""
if six.PY3:
str_val = str(encoded, encoding='ascii', errors='ignore')[:precision]
else:
# If precision is 0, this must be handled seperately
if precision == 0:
str_val = str(encoded)
else:
str_val = str(encoded)[:precision]
if len(str_val) > 0:
return float(str_val)
else:
return 0 |
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 | calculate a sphere through data points with python | Return unit sphere coordinates from window coordinates . | cosqa-train-19938 | 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 __remove_trailing_zeros ( self , collection ) : index = len ( collection ) - 1 while index >= 0 and collection [ index ] == 0 : index -= 1 return collection [ : index + 1 ] | 0 | python how to remove leading zeroes | Removes trailing zeroes from indexable collection of numbers | cosqa-train-19939 | 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 flatten_multidict ( multidict ) : return dict ( [ ( key , value if len ( value ) > 1 else value [ 0 ] ) for ( key , value ) in multidict . iterlists ( ) ] ) | 1 | flatten dic of nested dict python | Return flattened dictionary from MultiDict . | cosqa-train-19940 | 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 is_natural ( x ) : try : is_integer = int ( x ) == x except ( TypeError , ValueError ) : return False return is_integer and x >= 0 | 1 | if x is not equal to integer in python | A non - negative integer . | cosqa-train-19941 | def is_natural(x):
"""A non-negative integer."""
try:
is_integer = int(x) == x
except (TypeError, ValueError):
return False
return is_integer and x >= 0 |
def split ( text : str ) -> List [ str ] : return [ word for word in SEPARATOR . split ( text ) if word . strip ( ' \t' ) ] | 0 | how to split multiple tokens in python | Split a text into a list of tokens . | cosqa-train-19942 | 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 normcdf ( x , log = False ) : y = np . atleast_1d ( x ) . copy ( ) flib . normcdf ( y ) if log : if ( y > 0 ) . all ( ) : return np . log ( y ) return - np . inf return y | 0 | how to do normal cdf in python | Normal cumulative density function . | cosqa-train-19943 | def normcdf(x, log=False):
"""Normal cumulative density function."""
y = np.atleast_1d(x).copy()
flib.normcdf(y)
if log:
if (y>0).all():
return np.log(y)
return -np.inf
return y |
def split ( text : str ) -> List [ str ] : return [ word for word in SEPARATOR . split ( text ) if word . strip ( ' \t' ) ] | 0 | python split sentence into words by spaces and comma | Split a text into a list of tokens . | cosqa-train-19944 | 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 to_int64 ( a ) : # build new dtype and replace i4 --> i8 def promote_i4 ( typestr ) : if typestr [ 1 : ] == 'i4' : typestr = typestr [ 0 ] + 'i8' return typestr dtype = [ ( name , promote_i4 ( typestr ) ) for name , typestr in a . dtype . descr ] return a . astype ( dtype ) | 1 | change dtype python to int64 | Return view of the recarray with all int32 cast to int64 . | cosqa-train-19945 | def to_int64(a):
"""Return view of the recarray with all int32 cast to int64."""
# build new dtype and replace i4 --> i8
def promote_i4(typestr):
if typestr[1:] == 'i4':
typestr = typestr[0]+'i8'
return typestr
dtype = [(name, promote_i4(typestr)) for name,typestr in a.dtype.descr]
return a.astype(dtype) |
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 | 1 | python turning text file into set | Extract a de - duped collection ( set ) of text from a file . Expected file format is one item per line . | cosqa-train-19946 | 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 is_natural ( x ) : try : is_integer = int ( x ) == x except ( TypeError , ValueError ) : return False return is_integer and x >= 0 | 0 | denote not a number in python | A non - negative integer . | cosqa-train-19947 | def is_natural(x):
"""A non-negative integer."""
try:
is_integer = int(x) == x
except (TypeError, ValueError):
return False
return is_integer and x >= 0 |
def str_to_time ( time_str : str ) -> datetime . datetime : pieces : Any = [ int ( piece ) for piece in time_str . split ( '-' ) ] return datetime . datetime ( * pieces ) | 0 | datetime from string to datetime in python | Convert human readable string to datetime . datetime . | cosqa-train-19948 | 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 test_string ( self , string : str ) -> bool : if self . input . startswith ( string , self . offset ) : self . offset += len ( string ) return True return False | 0 | python check for next character in a string | If string comes next return True and advance offset . | cosqa-train-19949 | def test_string(self, string: str) -> bool:
"""If `string` comes next, return ``True`` and advance offset.
Args:
string: string to test
"""
if self.input.startswith(string, self.offset):
self.offset += len(string)
return True
return False |
def Exit ( msg , code = 1 ) : print >> sys . stderr , msg sys . exit ( code ) | 0 | how to print exit code python | Exit execution with return code and message : param msg : Message displayed prior to exit : param code : code returned upon exiting | cosqa-train-19950 | 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 truncate ( value : Decimal , n_digits : int ) -> Decimal : return Decimal ( math . trunc ( value * ( 10 ** n_digits ) ) ) / ( 10 ** n_digits ) | 0 | how do you limit the number of decimals of a number in python | Truncates a value to a number of decimals places | cosqa-train-19951 | 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 capture_stdout ( ) : stdout = sys . stdout sys . stdout = six . moves . cStringIO ( ) try : yield sys . stdout finally : sys . stdout = stdout | 1 | capture the standard output stream of a cell into a variable in local namespace ,python | Intercept standard output in a with - context : return : cStringIO instance | cosqa-train-19952 | def capture_stdout():
"""Intercept standard output in a with-context
:return: cStringIO instance
>>> with capture_stdout() as stdout:
...
print stdout.getvalue()
"""
stdout = sys.stdout
sys.stdout = six.moves.cStringIO()
try:
yield sys.stdout
finally:
sys.stdout = stdout |
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 do you join a list into a string python | Turn a list into a comma - and / or and - separated string . | cosqa-train-19953 | 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 s3_get ( url : str , temp_file : IO ) -> None : s3_resource = boto3 . resource ( "s3" ) bucket_name , s3_path = split_s3_path ( url ) s3_resource . Bucket ( bucket_name ) . download_fileobj ( s3_path , temp_file ) | 0 | how to read file from s3 bucket using python | Pull a file directly from S3 . | cosqa-train-19954 | def s3_get(url: str, temp_file: IO) -> None:
"""Pull a file directly from S3."""
s3_resource = boto3.resource("s3")
bucket_name, s3_path = split_s3_path(url)
s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file) |
def memory_read ( self , start_position : int , size : int ) -> memoryview : return self . _memory . read ( start_position , size ) | 0 | python memoryview memory at | Read and return a view of size bytes from memory starting at start_position . | cosqa-train-19955 | def memory_read(self, start_position: int, size: int) -> memoryview:
"""
Read and return a view of ``size`` bytes from memory starting at ``start_position``.
"""
return self._memory.read(start_position, size) |
def spanning_tree_count ( graph : nx . Graph ) -> int : laplacian = nx . laplacian_matrix ( graph ) . toarray ( ) comatrix = laplacian [ : - 1 , : - 1 ] det = np . linalg . det ( comatrix ) count = int ( round ( det ) ) return count | 0 | how to get degree of a node of a graph in python | Return the number of unique spanning trees of a graph using Kirchhoff s matrix tree theorem . | cosqa-train-19956 | def spanning_tree_count(graph: nx.Graph) -> int:
"""Return the number of unique spanning trees of a graph, using
Kirchhoff's matrix tree theorem.
"""
laplacian = nx.laplacian_matrix(graph).toarray()
comatrix = laplacian[:-1, :-1]
det = np.linalg.det(comatrix)
count = int(round(det))
return count |
def get_valid_filename ( s ) : s = s . strip ( ) . replace ( " " , "_" ) return re . sub ( r"(?u)[^-\w.]" , "" , s ) | 0 | python strip illegal characters for file name | Returns the given string converted to a string that can be used for a clean filename . Specifically leading and trailing spaces are removed ; other spaces are converted to underscores ; and anything that is not a unicode alphanumeric dash underscore or dot is removed . >>> get_valid_filename ( john s portrait in 2004 . jpg ) johns_portrait_in_2004 . jpg | cosqa-train-19957 | def get_valid_filename(s):
"""
Returns the given string converted to a string that can be used for a clean
filename. Specifically, leading and trailing spaces are removed; other
spaces are converted to underscores; and anything that is not a unicode
alphanumeric, dash, underscore, or dot, is removed.
>>> get_valid_filename("john's portrait in 2004.jpg")
'johns_portrait_in_2004.jpg'
"""
s = s.strip().replace(" ", "_")
return re.sub(r"(?u)[^-\w.]", "", s) |
def get_tokens ( line : str ) -> Iterator [ str ] : for token in line . rstrip ( ) . split ( ) : if len ( token ) > 0 : yield token | 1 | python read tokens from line | Yields tokens from input string . | cosqa-train-19958 | def get_tokens(line: str) -> Iterator[str]:
"""
Yields tokens from input string.
:param line: Input string.
:return: Iterator over tokens.
"""
for token in line.rstrip().split():
if len(token) > 0:
yield token |
def is_natural ( x ) : try : is_integer = int ( x ) == x except ( TypeError , ValueError ) : return False return is_integer and x >= 0 | 0 | none integer comparison python | A non - negative integer . | cosqa-train-19959 | def is_natural(x):
"""A non-negative integer."""
try:
is_integer = int(x) == x
except (TypeError, ValueError):
return False
return is_integer and x >= 0 |
def find_duplicates ( l : list ) -> set : return set ( [ x for x in l if l . count ( x ) > 1 ] ) | 0 | test for duplicates in python lists | Return the duplicates in a list . | cosqa-train-19960 | def find_duplicates(l: list) -> set:
"""
Return the duplicates in a list.
The function relies on
https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-a-list .
Parameters
----------
l : list
Name
Returns
-------
set
Duplicated values
>>> find_duplicates([1,2,3])
set()
>>> find_duplicates([1,2,1])
{1}
"""
return set([x for x in l if l.count(x) > 1]) |
def from_file ( file_path ) -> dict : with io . open ( file_path , 'r' , encoding = 'utf-8' ) as json_stream : return Json . parse ( json_stream , True ) | 0 | python read json as dictonary | Load JSON file | cosqa-train-19961 | def from_file(file_path) -> dict:
""" Load JSON file """
with io.open(file_path, 'r', encoding='utf-8') as json_stream:
return Json.parse(json_stream, True) |
def most_significant_bit ( lst : np . ndarray ) -> int : return np . argwhere ( np . asarray ( lst ) == 1 ) [ 0 ] [ 0 ] | 1 | index of first non zero element in list python | A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s i . e . the first position where a 1 appears reading left to right . | cosqa-train-19962 | def most_significant_bit(lst: np.ndarray) -> int:
"""
A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,
i.e. the first position where a 1 appears, reading left to right.
:param lst: a 1d array of 0s and 1s with at least one 1
:return: the first position in lst that a 1 appears
"""
return np.argwhere(np.asarray(lst) == 1)[0][0] |
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 | 1 | python check most frequent in a list | Returns the item that appears most frequently in the given list . | cosqa-train-19963 | 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 _is_numeric ( self , values ) : if len ( values ) > 0 : assert isinstance ( values [ 0 ] , ( float , int ) ) , "values must be numbers to perform math operations. Got {}" . format ( type ( values [ 0 ] ) ) return True | 0 | python check if numerical value or not | Check to be sure values are numbers before doing numerical operations . | cosqa-train-19964 | def _is_numeric(self, values):
"""Check to be sure values are numbers before doing numerical operations."""
if len(values) > 0:
assert isinstance(values[0], (float, int)), \
"values must be numbers to perform math operations. Got {}".format(
type(values[0]))
return True |
def _check_whitespace ( string ) : if string . count ( ' ' ) + string . count ( '\t' ) + string . count ( '\n' ) > 0 : raise ValueError ( INSTRUCTION_HAS_WHITESPACE ) | 1 | check if whitespace exists python | Make sure thre is no whitespace in the given string . Will raise a ValueError if whitespace is detected | cosqa-train-19965 | 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 _isint ( string ) : return type ( string ) is int or ( isinstance ( string , _binary_type ) or isinstance ( string , _text_type ) ) and _isconvertible ( int , string ) | 0 | how to check if a variable is integer using type in python | >>> _isint ( 123 ) True >>> _isint ( 123 . 45 ) False | cosqa-train-19966 | 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 get_margin ( length ) : if length > 23 : margin_left = "\t" chars = 1 elif length > 15 : margin_left = "\t\t" chars = 2 elif length > 7 : margin_left = "\t\t\t" chars = 3 else : margin_left = "\t\t\t\t" chars = 4 return margin_left | 1 | how to make column right margin in python | Add enough tabs to align in two columns | cosqa-train-19967 | def get_margin(length):
"""Add enough tabs to align in two columns"""
if length > 23:
margin_left = "\t"
chars = 1
elif length > 15:
margin_left = "\t\t"
chars = 2
elif length > 7:
margin_left = "\t\t\t"
chars = 3
else:
margin_left = "\t\t\t\t"
chars = 4
return margin_left |
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 value is not numeric | Return true if a value is an integer number . | cosqa-train-19968 | 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 indexes_equal ( a : Index , b : Index ) -> bool : return str ( a ) == str ( b ) | 0 | evaluating if two strings are equal python | Are two indexes equal? Checks by comparing str () versions of them . ( AM UNSURE IF THIS IS ENOUGH . ) | cosqa-train-19969 | 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 is_relative_url ( url ) : if url . startswith ( "#" ) : return None if url . find ( "://" ) > 0 or url . startswith ( "//" ) : # either 'http(s)://...' or '//cdn...' and therefore absolute return False return True | 1 | python how to check if an absolute path or relative path | simple method to determine if a url is relative or absolute | cosqa-train-19970 | def is_relative_url(url):
""" simple method to determine if a url is relative or absolute """
if url.startswith("#"):
return None
if url.find("://") > 0 or url.startswith("//"):
# either 'http(s)://...' or '//cdn...' and therefore absolute
return False
return True |
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 | python dictionary get top 10 values | Returns the keys that maps to the top n max values in the given dict . | cosqa-train-19971 | 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 nTimes ( n , f , * args , * * kwargs ) : for i in xrange ( n ) : f ( * args , * * kwargs ) | 1 | how to tell python to print something x number of times | r Call f n times with args and kwargs . Useful e . g . for simplistic timing . | cosqa-train-19972 | 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 encode_list ( key , list_ ) : # type: (str, Iterable) -> Dict[str, str] if not list_ : return { } return { key : " " . join ( str ( i ) for i in list_ ) } | 0 | python create dict keys from list | Converts a list into a space - separated string and puts it in a dictionary | cosqa-train-19973 | def encode_list(key, list_):
# type: (str, Iterable) -> Dict[str, str]
"""
Converts a list into a space-separated string and puts it in a dictionary
:param key: Dictionary key to store the list
:param list_: A list of objects
:return: A dictionary key->string or an empty dictionary
"""
if not list_:
return {}
return {key: " ".join(str(i) for i in list_)} |
def _width_is_big_enough ( image , width ) : if width > image . size [ 0 ] : raise ImageSizeError ( image . size [ 0 ] , width ) | 1 | how to check image size using size in python | Check that the image width is superior to width | cosqa-train-19974 | def _width_is_big_enough(image, width):
"""Check that the image width is superior to `width`"""
if width > image.size[0]:
raise ImageSizeError(image.size[0], width) |
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 to compare values | Fail unless first equals second as determined by the == operator . | cosqa-train-19975 | 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 add_colons ( s ) : return ':' . join ( [ s [ i : i + 2 ] for i in range ( 0 , len ( s ) , 2 ) ] ) | 0 | printing concatanated strigns python | Add colons after every second digit . | cosqa-train-19976 | def add_colons(s):
"""Add colons after every second digit.
This function is used in functions to prettify serials.
>>> add_colons('teststring')
'te:st:st:ri:ng'
"""
return ':'.join([s[i:i + 2] for i in range(0, len(s), 2)]) |
def label_from_bin ( buf ) : mpls_label = type_desc . Int3 . to_user ( six . binary_type ( buf ) ) return mpls_label >> 4 , mpls_label & 1 | 1 | python unpack bac char in struct format | Converts binary representation label to integer . | cosqa-train-19977 | def label_from_bin(buf):
"""
Converts binary representation label to integer.
:param buf: Binary representation of label.
:return: MPLS Label and BoS bit.
"""
mpls_label = type_desc.Int3.to_user(six.binary_type(buf))
return mpls_label >> 4, mpls_label & 1 |
def zfill ( x , width ) : if not isinstance ( x , basestring ) : x = repr ( x ) return x . zfill ( width ) | 1 | python pad string with zeros left | zfill ( x width ) - > string | cosqa-train-19978 | def zfill(x, width):
"""zfill(x, width) -> string
Pad a numeric string x with zeros on the left, to fill a field
of the specified width. The string x is never truncated.
"""
if not isinstance(x, basestring):
x = repr(x)
return x.zfill(width) |
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 ( ) | 0 | python check if file exists and is file | Verifies that a string path actually exists and is a file | cosqa-train-19979 | 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 _mid ( pt1 , pt2 ) : ( x0 , y0 ) , ( x1 , y1 ) = pt1 , pt2 return 0.5 * ( x0 + x1 ) , 0.5 * ( y0 + y1 ) | 1 | calculating the midpoint between 2 data points in python | ( Point Point ) - > Point Return the point that lies in between the two input points . | cosqa-train-19980 | def _mid(pt1, pt2):
"""
(Point, Point) -> Point
Return the point that lies in between the two input points.
"""
(x0, y0), (x1, y1) = pt1, pt2
return 0.5 * (x0 + x1), 0.5 * (y0 + y1) |
def copen ( filepath , flag = 'r' , encoding = None ) : if encoding is None : encoding = locale . getdefaultlocale ( ) [ 1 ] return codecs . open ( filepath , flag , encoding ) | 1 | python open any file encoding | FIXME : How to test this ? | cosqa-train-19981 | def copen(filepath, flag='r', encoding=None):
"""
FIXME: How to test this ?
>>> c = copen(__file__)
>>> c is not None
True
"""
if encoding is None:
encoding = locale.getdefaultlocale()[1]
return codecs.open(filepath, flag, encoding) |
def _ ( f , x ) : return { k : v for k , v in x . items ( ) if f ( k , v ) } | 0 | python get all dict keys filter by value | filter for dict note f should have signature : f :: key - > value - > bool | cosqa-train-19982 | 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 memory_full ( ) : current_process = psutil . Process ( os . getpid ( ) ) return ( current_process . memory_percent ( ) > config . MAXIMUM_CACHE_MEMORY_PERCENTAGE ) | 1 | python limiting memory usage | Check if the memory is too full for further caching . | cosqa-train-19983 | 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 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 | 0 | python longest path algorithm | Finds the longest path in a dag between two nodes | cosqa-train-19984 | 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 find_duplicates ( l : list ) -> set : return set ( [ x for x in l if l . count ( x ) > 1 ] ) | 1 | determine if a list of numbers contains duplicates python | Return the duplicates in a list . | cosqa-train-19985 | def find_duplicates(l: list) -> set:
"""
Return the duplicates in a list.
The function relies on
https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-a-list .
Parameters
----------
l : list
Name
Returns
-------
set
Duplicated values
>>> find_duplicates([1,2,3])
set()
>>> find_duplicates([1,2,1])
{1}
"""
return set([x for x in l if l.count(x) > 1]) |
def uppercase_chars ( string : any ) -> str : return '' . join ( [ c if c . isupper ( ) else '' for c in str ( string ) ] ) | 0 | do uppercase matter python | Return all ( and only ) the uppercase chars in the given string . | cosqa-train-19986 | def uppercase_chars(string: any) -> str:
"""Return all (and only) the uppercase chars in the given string."""
return ''.join([c if c.isupper() else '' for c in str(string)]) |
def convert_bytes_to_ints ( in_bytes , num ) : dt = numpy . dtype ( '>i' + str ( num ) ) return numpy . frombuffer ( in_bytes , dt ) | 1 | python , how to read 40 bytes from bytes array | Convert a byte array into an integer array . The number of bytes forming an integer is defined by num | cosqa-train-19987 | def convert_bytes_to_ints(in_bytes, num):
"""Convert a byte array into an integer array. The number of bytes forming an integer
is defined by num
:param in_bytes: the input bytes
:param num: the number of bytes per int
:return the integer array"""
dt = numpy.dtype('>i' + str(num))
return numpy.frombuffer(in_bytes, dt) |
def astensor ( array : TensorLike ) -> BKTensor : tensor = tf . convert_to_tensor ( value = array , dtype = CTYPE ) return tensor | 0 | python code to covert matrix to tensorflow object | Covert numpy array to tensorflow tensor | cosqa-train-19988 | def astensor(array: TensorLike) -> BKTensor:
"""Covert numpy array to tensorflow tensor"""
tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)
return tensor |
def camel_to_snake ( s : str ) -> str : return CAMEL_CASE_RE . sub ( r'_\1' , s ) . strip ( ) . lower ( ) | 1 | python snake or camel case | Convert string from camel case to snake case . | cosqa-train-19989 | def camel_to_snake(s: str) -> str:
"""Convert string from camel case to snake case."""
return CAMEL_CASE_RE.sub(r'_\1', s).strip().lower() |
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 whether file is empty | Check if the input filename with path is a file and is not empty . | cosqa-train-19990 | 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 _ ( f , x ) : return { k : v for k , v in x . items ( ) if f ( k , v ) } | 0 | python filter map on key values | filter for dict note f should have signature : f :: key - > value - > bool | cosqa-train-19991 | 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 post ( self , endpoint : str , * * kwargs ) -> dict : return self . _request ( 'POST' , endpoint , * * kwargs ) | 0 | request python post api | HTTP POST operation to API endpoint . | cosqa-train-19992 | def post(self, endpoint: str, **kwargs) -> dict:
"""HTTP POST operation to API endpoint."""
return self._request('POST', endpoint, **kwargs) |
def __as_list ( value : List [ JsonObjTypes ] ) -> List [ JsonTypes ] : return [ e . _as_dict if isinstance ( e , JsonObj ) else e for e in value ] | 0 | how to turn js array into python list | Return a json array as a list | cosqa-train-19993 | 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 text_to_bool ( value : str ) -> bool : try : return bool ( strtobool ( value ) ) except ( ValueError , AttributeError ) : return value is not None | 0 | python text to bool | Tries to convert a text value to a bool . If unsuccessful returns if value is None or not | cosqa-train-19994 | def text_to_bool(value: str) -> bool:
"""
Tries to convert a text value to a bool. If unsuccessful returns if value is None or not
:param value: Value to check
"""
try:
return bool(strtobool(value))
except (ValueError, AttributeError):
return value is not None |
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 call callback async | Utility method to run commands synchronously for testing . | cosqa-train-19995 | 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 is_any_type_set ( sett : Set [ Type ] ) -> bool : return len ( sett ) == 1 and is_any_type ( min ( sett ) ) | 1 | how to tell if a set is empty in python | Helper method to check if a set of types is the { AnyObject } singleton | cosqa-train-19996 | def is_any_type_set(sett: Set[Type]) -> bool:
"""
Helper method to check if a set of types is the {AnyObject} singleton
:param sett:
:return:
"""
return len(sett) == 1 and is_any_type(min(sett)) |
def _check_env_var ( envvar : str ) -> bool : if os . getenv ( envvar ) is None : raise KeyError ( "Required ENVVAR: {0} is not set" . format ( envvar ) ) if not os . getenv ( envvar ) : # test if env var is empty raise KeyError ( "Required ENVVAR: {0} is empty" . format ( envvar ) ) return True | 0 | python test if environment var is undefined or empty | Check Environment Variable to verify that it is set and not empty . | cosqa-train-19997 | def _check_env_var(envvar: str) -> bool:
"""Check Environment Variable to verify that it is set and not empty.
:param envvar: Environment Variable to Check.
:returns: True if Environment Variable is set and not empty.
:raises: KeyError if Environment Variable is not set or is empty.
.. versionadded:: 0.0.12
"""
if os.getenv(envvar) is None:
raise KeyError(
"Required ENVVAR: {0} is not set".format(envvar))
if not os.getenv(envvar): # test if env var is empty
raise KeyError(
"Required ENVVAR: {0} is empty".format(envvar))
return True |
def warn_if_nans_exist ( X ) : null_count = count_rows_with_nans ( X ) total = len ( X ) percent = 100 * null_count / total if null_count > 0 : warning_message = 'Warning! Found {} rows of {} ({:0.2f}%) with nan values. Only ' 'complete rows will be plotted.' . format ( null_count , total , percent ) warnings . warn ( warning_message , DataWarning ) | 1 | python isnan how to check if an entire column is nan | Warn if nans exist in a numpy array . | cosqa-train-19998 | def warn_if_nans_exist(X):
"""Warn if nans exist in a numpy array."""
null_count = count_rows_with_nans(X)
total = len(X)
percent = 100 * null_count / total
if null_count > 0:
warning_message = \
'Warning! Found {} rows of {} ({:0.2f}%) with nan values. Only ' \
'complete rows will be plotted.'.format(null_count, total, percent)
warnings.warn(warning_message, DataWarning) |
async def executemany ( self , sql : str , parameters : Iterable [ Iterable [ Any ] ] ) -> None : await self . _execute ( self . _cursor . executemany , sql , parameters ) | 1 | python 2 pyodbc executemany | Execute the given multiquery . | cosqa-train-19999 | async def executemany(self, sql: str, parameters: Iterable[Iterable[Any]]) -> None:
"""Execute the given multiquery."""
await self._execute(self._cursor.executemany, sql, parameters) |