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 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 |
python modify list of strings while iterating
|
Returns a list produced by applying : func : multiple_replace to every string in stringlist .
|
cosqa-train-18600
|
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 __replace_all ( repls : dict , input : str ) -> str : return re . sub ( '|' . join ( re . escape ( key ) for key in repls . keys ( ) ) , lambda k : repls [ k . group ( 0 ) ] , input )
| 1 |
how to replace a certain word for another word in a string in python
|
Replaces from a string ** input ** all the occurrences of some symbols according to mapping ** repls ** .
|
cosqa-train-18601
|
def __replace_all(repls: dict, input: str) -> str:
""" Replaces from a string **input** all the occurrences of some
symbols according to mapping **repls**.
:param dict repls: where #key is the old character and
#value is the one to substitute with;
:param str input: original string where to apply the
replacements;
:return: *(str)* the string with the desired characters replaced
"""
return re.sub('|'.join(re.escape(key) for key in repls.keys()),
lambda k: repls[k.group(0)], input)
|
def astensor ( array : TensorLike ) -> BKTensor : tensor = tf . convert_to_tensor ( value = array , dtype = CTYPE ) return tensor
| 1 |
numpy to tensor python
|
Covert numpy array to tensorflow tensor
|
cosqa-train-18602
|
def astensor(array: TensorLike) -> BKTensor:
"""Covert numpy array to tensorflow tensor"""
tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)
return tensor
|
def _rindex ( mylist : Sequence [ T ] , x : T ) -> int : return len ( mylist ) - mylist [ : : - 1 ] . index ( x ) - 1
| 1 |
finding last index in python
|
Index of the last occurrence of x in the sequence .
|
cosqa-train-18603
|
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 set_range ( self , min_val , max_val ) : if min_val > max_val : max_val , min_val = min_val , max_val self . values = ( ( ( self . values * 1.0 - self . values . min ( ) ) / ( self . values . max ( ) - self . values . min ( ) ) ) * ( max_val - min_val ) + min_val )
| 0 |
how to custom set range on color bar python
|
Set the range of the colormap to [ * min_val * * max_val * ]
|
cosqa-train-18604
|
def set_range(self, min_val, max_val):
"""Set the range of the colormap to [*min_val*, *max_val*]
"""
if min_val > max_val:
max_val, min_val = min_val, max_val
self.values = (((self.values * 1.0 - self.values.min()) /
(self.values.max() - self.values.min()))
* (max_val - min_val) + min_val)
|
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 |
how to read lines into a set python
|
Extract a de - duped collection ( set ) of text from a file . Expected file format is one item per line .
|
cosqa-train-18605
|
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 Exit ( msg , code = 1 ) : print >> sys . stderr , msg sys . exit ( code )
| 0 |
how to write an exit function python
|
Exit execution with return code and message : param msg : Message displayed prior to exit : param code : code returned upon exiting
|
cosqa-train-18606
|
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 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 )
| 0 |
array condition && python
|
Returns True if test is True for all array elements . Otherwise returns False .
|
cosqa-train-18607
|
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 remove_blank_lines ( string ) : return "\n" . join ( line for line in string . split ( "\n" ) if len ( line . strip ( ) ) )
| 1 |
python how to detect string with all white spaces
|
Removes all blank lines in @string
|
cosqa-train-18608
|
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 genfirstvalues ( cursor : Cursor , arraysize : int = 1000 ) -> Generator [ Any , None , None ] : return ( row [ 0 ] for row in genrows ( cursor , arraysize ) )
| 0 |
how to get first 5 records of array python
|
Generate the first value in each row .
|
cosqa-train-18609
|
def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \
-> Generator[Any, None, None]:
"""
Generate the first value in each row.
Args:
cursor: the cursor
arraysize: split fetches into chunks of this many records
Yields:
the first value of each row
"""
return (row[0] for row in genrows(cursor, arraysize))
|
def _parse_tuple_string ( argument ) : if isinstance ( argument , str ) : return tuple ( int ( p . strip ( ) ) for p in argument . split ( ',' ) ) return argument
| 0 |
python passing a tuple in function that takes a string
|
Return a tuple from parsing a b c d - > ( a b c d )
|
cosqa-train-18610
|
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_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 ] ] )
| 1 |
how to get the first 5 elements of a sorted dictionary in python
|
Returns the keys that maps to the top n max values in the given dict .
|
cosqa-train-18611
|
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 debugTreePrint ( node , pfx = "->" ) : print pfx , node . item for c in node . children : debugTreePrint ( c , " " + pfx )
| 0 |
how to make a python program draw a tree using recursion
|
Purely a debugging aid : Ascii - art picture of a tree descended from node
|
cosqa-train-18612
|
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 _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' )
| 1 |
make a 2d empty array python
|
Create an empty array with appropriate shape .
|
cosqa-train-18613
|
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 check_key ( self , key : str ) -> bool : keys = self . get_keys ( ) return key in keys
| 1 |
python detect key exist or not
|
Checks if key exists in datastore . True if yes False if no .
|
cosqa-train-18614
|
def check_key(self, key: str) -> bool:
"""
Checks if key exists in datastore. True if yes, False if no.
:param: SHA512 hash key
:return: whether or key not exists in datastore
"""
keys = self.get_keys()
return key in keys
|
def 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
| 0 |
how do you add values to a set in python
|
Add value to a set in a dictionary by key
|
cosqa-train-18615
|
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 has_value ( cls , value : int ) -> bool : return any ( value == item . value for item in cls )
| 1 |
python check if value in enum
|
True if specified value exists in int enum ; otherwise False .
|
cosqa-train-18616
|
def has_value(cls, value: int) -> bool:
"""True if specified value exists in int enum; otherwise, False."""
return any(value == item.value for item in cls)
|
def to_bytes ( data : Any ) -> bytearray : # noqa if isinstance ( data , int ) : return bytearray ( [ data ] ) return bytearray ( data , encoding = 'latin-1' )
| 1 |
turn a string into a bytearray python
|
Convert anything to a bytearray . See - http : // stackoverflow . com / questions / 7585435 / best - way - to - convert - string - to - bytes - in - python - 3 - http : // stackoverflow . com / questions / 10459067 / how - to - convert - my - bytearrayb - x9e - x18k - x9a - to - something - like - this - x9e - x1
|
cosqa-train-18617
|
def to_bytes(data: Any) -> bytearray:
"""
Convert anything to a ``bytearray``.
See
- http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3
- http://stackoverflow.com/questions/10459067/how-to-convert-my-bytearrayb-x9e-x18k-x9a-to-something-like-this-x9e-x1
""" # noqa
if isinstance(data, int):
return bytearray([data])
return bytearray(data, encoding='latin-1')
|
def read_text_from_file ( path : str ) -> str : with open ( path ) as text_file : content = text_file . read ( ) return content
| 0 |
get content of textfile as string python
|
Reads text file contents
|
cosqa-train-18618
|
def read_text_from_file(path: str) -> str:
""" Reads text file contents """
with open(path) as text_file:
content = text_file.read()
return content
|
def from_uuid ( value : uuid . UUID ) -> ulid . ULID : return ulid . ULID ( value . bytes )
| 1 |
python uuid to integer
|
Create a new : class : ~ulid . ulid . ULID instance from the given : class : ~uuid . UUID value .
|
cosqa-train-18619
|
def from_uuid(value: uuid.UUID) -> ulid.ULID:
"""
Create a new :class:`~ulid.ulid.ULID` instance from the given :class:`~uuid.UUID` value.
:param value: UUIDv4 value
:type value: :class:`~uuid.UUID`
:return: ULID from UUID value
:rtype: :class:`~ulid.ulid.ULID`
"""
return ulid.ULID(value.bytes)
|
def to_bytes ( data : Any ) -> bytearray : # noqa if isinstance ( data , int ) : return bytearray ( [ data ] ) return bytearray ( data , encoding = 'latin-1' )
| 0 |
how to turn a string into bytes python
|
Convert anything to a bytearray . See - http : // stackoverflow . com / questions / 7585435 / best - way - to - convert - string - to - bytes - in - python - 3 - http : // stackoverflow . com / questions / 10459067 / how - to - convert - my - bytearrayb - x9e - x18k - x9a - to - something - like - this - x9e - x1
|
cosqa-train-18620
|
def to_bytes(data: Any) -> bytearray:
"""
Convert anything to a ``bytearray``.
See
- http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3
- http://stackoverflow.com/questions/10459067/how-to-convert-my-bytearrayb-x9e-x18k-x9a-to-something-like-this-x9e-x1
""" # noqa
if isinstance(data, int):
return bytearray([data])
return bytearray(data, encoding='latin-1')
|
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
| 0 |
python test if path is absolute or relative
|
simple method to determine if a url is relative or absolute
|
cosqa-train-18621
|
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 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 ] ]
| 1 |
how to get max value of columns 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-18622
|
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 returned ( n ) : ## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk for pos in randwalk ( ) >> drop ( 1 ) >> takei ( xrange ( n - 1 ) ) : if pos == Origin : return True return False
| 0 |
random walk python making sure walker is in bounds
|
Generate a random walk and return True if the walker has returned to the origin after taking n steps .
|
cosqa-train-18623
|
def returned(n):
"""Generate a random walk and return True if the walker has returned to
the origin after taking `n` steps.
"""
## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk
for pos in randwalk() >> drop(1) >> takei(xrange(n-1)):
if pos == Origin:
return True
return False
|
def dictlist_wipe_key ( dict_list : Iterable [ Dict ] , key : str ) -> None : for d in dict_list : d . pop ( key , None )
| 0 |
delete from a python dict
|
Process an iterable of dictionaries . For each dictionary d delete d [ key ] if it exists .
|
cosqa-train-18624
|
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 split ( text : str ) -> List [ str ] : return [ word for word in SEPARATOR . split ( text ) if word . strip ( ' \t' ) ]
| 1 |
split on multiple tokens python split
|
Split a text into a list of tokens .
|
cosqa-train-18625
|
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 make_indices_to_labels ( labels : Set [ str ] ) -> Dict [ int , str ] : return { index : label for index , label in enumerate ( [ "pad" ] + sorted ( list ( labels ) ) ) }
| 0 |
creating dictionary using indices as map values python
|
Creates a mapping from indices to labels .
|
cosqa-train-18626
|
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 get_terminal_width ( ) : # http://www.brandonrubin.me/2014/03/18/python-snippet-get-terminal-width/ command = [ 'tput' , 'cols' ] try : width = int ( subprocess . check_output ( command ) ) except OSError as e : print ( "Invalid Command '{0}': exit status ({1})" . format ( command [ 0 ] , e . errno ) ) except subprocess . CalledProcessError as e : print ( "'{0}' returned non-zero exit status: ({1})" . format ( command , e . returncode ) ) else : return width
| 0 |
determine powershell width using python
|
- > #int width of the terminal window
|
cosqa-train-18627
|
def get_terminal_width():
""" -> #int width of the terminal window """
# http://www.brandonrubin.me/2014/03/18/python-snippet-get-terminal-width/
command = ['tput', 'cols']
try:
width = int(subprocess.check_output(command))
except OSError as e:
print(
"Invalid Command '{0}': exit status ({1})".format(
command[0], e.errno))
except subprocess.CalledProcessError as e:
print(
"'{0}' returned non-zero exit status: ({1})".format(
command, e.returncode))
else:
return width
|
def flatten_multidict ( multidict ) : return dict ( [ ( key , value if len ( value ) > 1 else value [ 0 ] ) for ( key , value ) in multidict . iterlists ( ) ] )
| 1 |
python flatten dict items
|
Return flattened dictionary from MultiDict .
|
cosqa-train-18628
|
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 _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
| 1 |
how to check if file is empty python
|
Check if cnr or cns files are empty ( only have a header )
|
cosqa-train-18629
|
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 flush ( self ) : if len ( self . _buffer ) > 0 : self . logger . log ( self . level , self . _buffer ) self . _buffer = str ( )
| 1 |
python logging auto flush
|
Ensure all logging output has been flushed
|
cosqa-train-18630
|
def flush(self):
"""
Ensure all logging output has been flushed
"""
if len(self._buffer) > 0:
self.logger.log(self.level, self._buffer)
self._buffer = str()
|
def _brief_print_list ( lst , limit = 7 ) : lst = list ( lst ) if len ( lst ) > limit : return _brief_print_list ( lst [ : limit // 2 ] , limit ) + ', ..., ' + _brief_print_list ( lst [ - limit // 2 : ] , limit ) return ', ' . join ( [ "'%s'" % str ( i ) for i in lst ] )
| 0 |
how to print half a list in python
|
Print at most limit elements of list .
|
cosqa-train-18631
|
def _brief_print_list(lst, limit=7):
"""Print at most `limit` elements of list."""
lst = list(lst)
if len(lst) > limit:
return _brief_print_list(lst[:limit//2], limit) + ', ..., ' + \
_brief_print_list(lst[-limit//2:], limit)
return ', '.join(["'%s'"%str(i) for i in lst])
|
def assert_or_raise ( stmt : bool , exception : Exception , * exception_args , * * exception_kwargs ) -> None : if not stmt : raise exception ( * exception_args , * * exception_kwargs )
| 0 |
python raise with or without brackets
|
If the statement is false raise the given exception .
|
cosqa-train-18632
|
def assert_or_raise(stmt: bool, exception: Exception,
*exception_args, **exception_kwargs) -> None:
"""
If the statement is false, raise the given exception.
"""
if not stmt:
raise exception(*exception_args, **exception_kwargs)
|
def strip_codes ( s : Any ) -> str : return codepat . sub ( '' , str ( s ) if ( s or ( s == 0 ) ) else '' )
| 1 |
remove logic symbol from python string
|
Strip all color codes from a string . Returns empty string for falsey inputs .
|
cosqa-train-18633
|
def strip_codes(s: Any) -> str:
""" Strip all color codes from a string.
Returns empty string for "falsey" inputs.
"""
return codepat.sub('', str(s) if (s or (s == 0)) else '')
|
def is_line_in_file ( filename : str , line : str ) -> bool : assert "\n" not in line with open ( filename , "r" ) as file : for fileline in file : if fileline == line : return True return False
| 0 |
check if line is in file python
|
Detects whether a line is present within a file .
|
cosqa-train-18634
|
def is_line_in_file(filename: str, line: str) -> bool:
"""
Detects whether a line is present within a file.
Args:
filename: file to check
line: line to search for (as an exact match)
"""
assert "\n" not in line
with open(filename, "r") as file:
for fileline in file:
if fileline == line:
return True
return False
|
def assign_parent ( node : astroid . node_classes . NodeNG ) -> astroid . node_classes . NodeNG : while node and isinstance ( node , ( astroid . AssignName , astroid . Tuple , astroid . List ) ) : node = node . parent return node
| 0 |
get parent node of a node using python
|
return the higher parent which is not an AssignName Tuple or List node
|
cosqa-train-18635
|
def assign_parent(node: astroid.node_classes.NodeNG) -> astroid.node_classes.NodeNG:
"""return the higher parent which is not an AssignName, Tuple or List node
"""
while node and isinstance(node, (astroid.AssignName, astroid.Tuple, astroid.List)):
node = node.parent
return node
|
def columns_equal ( a : Column , b : Column ) -> bool : return ( a . name == b . name and column_types_equal ( a . type , b . type ) and a . nullable == b . nullable )
| 1 |
check whether two column names are identical in python
|
Are two SQLAlchemy columns are equal? Checks based on :
|
cosqa-train-18636
|
def columns_equal(a: Column, b: Column) -> bool:
"""
Are two SQLAlchemy columns are equal? Checks based on:
- column ``name``
- column ``type`` (see :func:`column_types_equal`)
- ``nullable``
"""
return (
a.name == b.name and
column_types_equal(a.type, b.type) and
a.nullable == b.nullable
)
|
def PrintIndented ( self , file , ident , code ) : for entry in code : print >> file , '%s%s' % ( ident , entry )
| 1 |
how to indent a whole grouping of code in opython at once
|
Takes an array add indentation to each entry and prints it .
|
cosqa-train-18637
|
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 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 |
how to get maximum of a specific column in python list
|
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-18638
|
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 clean_map ( obj : Mapping [ Any , Any ] ) -> Mapping [ Any , Any ] : return { k : v for k , v in obj . items ( ) if v is not None }
| 1 |
how to remove all element from a python dictionary
|
Return a new copied dictionary without the keys with None values from the given Mapping object .
|
cosqa-train-18639
|
def clean_map(obj: Mapping[Any, Any]) -> Mapping[Any, Any]:
"""
Return a new copied dictionary without the keys with ``None`` values from
the given Mapping object.
"""
return {k: v for k, v in obj.items() if v is not None}
|
def sample_normal ( mean , var , rng ) : ret = numpy . sqrt ( var ) * rng . randn ( * mean . shape ) + mean return ret
| 1 |
how to sample a multivariate normal distribution python
|
Sample from independent normal distributions
|
cosqa-train-18640
|
def sample_normal(mean, var, rng):
"""Sample from independent normal distributions
Each element is an independent normal distribution.
Parameters
----------
mean : numpy.ndarray
Means of the normal distribution. Shape --> (batch_num, sample_dim)
var : numpy.ndarray
Variance of the normal distribution. Shape --> (batch_num, sample_dim)
rng : numpy.random.RandomState
Returns
-------
ret : numpy.ndarray
The sampling result. Shape --> (batch_num, sample_dim)
"""
ret = numpy.sqrt(var) * rng.randn(*mean.shape) + mean
return ret
|
def factors ( n ) : return set ( reduce ( list . __add__ , ( [ i , n // i ] for i in range ( 1 , int ( n ** 0.5 ) + 1 ) if n % i == 0 ) ) )
| 1 |
finding factors in python and return list
|
Computes all the integer factors of the number n
|
cosqa-train-18641
|
def factors(n):
"""
Computes all the integer factors of the number `n`
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utool as ut
>>> result = sorted(ut.factors(10))
>>> print(result)
[1, 2, 5, 10]
References:
http://stackoverflow.com/questions/6800193/finding-all-the-factors
"""
return set(reduce(list.__add__,
([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))
|
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 index if there are duplicates
|
Return dict mapping item - > indices .
|
cosqa-train-18642
|
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 is_quoted ( arg : str ) -> bool : return len ( arg ) > 1 and arg [ 0 ] == arg [ - 1 ] and arg [ 0 ] in constants . QUOTES
| 0 |
python how to check for double quotes
|
Checks if a string is quoted : param arg : the string being checked for quotes : return : True if a string is quoted
|
cosqa-train-18643
|
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_system_flags ( ) -> FrozenSet [ Flag ] : return frozenset ( { Seen , Recent , Deleted , Flagged , Answered , Draft } )
| 0 |
return a set in python
|
Return the set of implemented system flags .
|
cosqa-train-18644
|
def get_system_flags() -> FrozenSet[Flag]:
"""Return the set of implemented system flags."""
return frozenset({Seen, Recent, Deleted, Flagged, Answered, Draft})
|
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 |
longest path in tree python
|
Finds the longest path in a dag between two nodes
|
cosqa-train-18645
|
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 get_property_as_float ( self , name : str ) -> float : return float ( self . __instrument . get_property ( name ) )
| 1 |
how to define a floating value in python
|
Return the value of a float property .
|
cosqa-train-18646
|
def get_property_as_float(self, name: str) -> float:
"""Return the value of a float property.
:return: The property value (float).
Raises exception if property with name doesn't exist.
.. versionadded:: 1.0
Scriptable: Yes
"""
return float(self.__instrument.get_property(name))
|
def rollapply ( data , window , fn ) : res = data . copy ( ) res [ : ] = np . nan n = len ( data ) if window > n : return res for i in range ( window - 1 , n ) : res . iloc [ i ] = fn ( data . iloc [ i - window + 1 : i + 1 ] ) return res
| 0 |
sliding windows and rolling window in timeseries python
|
Apply a function fn over a rolling window of size window .
|
cosqa-train-18647
|
def rollapply(data, window, fn):
"""
Apply a function fn over a rolling window of size window.
Args:
* data (Series or DataFrame): Series or DataFrame
* window (int): Window size
* fn (function): Function to apply over the rolling window.
For a series, the return value is expected to be a single
number. For a DataFrame, it shuold return a new row.
Returns:
* Object of same dimensions as data
"""
res = data.copy()
res[:] = np.nan
n = len(data)
if window > n:
return res
for i in range(window - 1, n):
res.iloc[i] = fn(data.iloc[i - window + 1:i + 1])
return res
|
def is_unitary ( matrix : np . ndarray ) -> bool : rows , cols = matrix . shape if rows != cols : return False return np . allclose ( np . eye ( rows ) , matrix . dot ( matrix . T . conj ( ) ) )
| 0 |
python check that matrix is invertable
|
A helper function that checks if a matrix is unitary .
|
cosqa-train-18648
|
def is_unitary(matrix: np.ndarray) -> bool:
"""
A helper function that checks if a matrix is unitary.
:param matrix: a matrix to test unitarity of
:return: true if and only if matrix is unitary
"""
rows, cols = matrix.shape
if rows != cols:
return False
return np.allclose(np.eye(rows), matrix.dot(matrix.T.conj()))
|
def flatten_list ( x : List [ Any ] ) -> List [ Any ] : # noqa return [ item for sublist in x for item in sublist ]
| 0 |
python flatten list in list
|
Converts a list of lists into a flat list . Args : x : list of lists
|
cosqa-train-18649
|
def flatten_list(x: List[Any]) -> List[Any]:
"""
Converts a list of lists into a flat list.
Args:
x: list of lists
Returns:
flat list
As per
http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python
""" # noqa
return [item for sublist in x for item in sublist]
|
def get_table_names_from_metadata ( metadata : MetaData ) -> List [ str ] : return [ table . name for table in metadata . tables . values ( ) ]
| 1 |
python sqlalchemy how to read the table names from a sqllite database
|
Returns all database table names found in an SQLAlchemy : class : MetaData object .
|
cosqa-train-18650
|
def get_table_names_from_metadata(metadata: MetaData) -> List[str]:
"""
Returns all database table names found in an SQLAlchemy :class:`MetaData`
object.
"""
return [table.name for table in metadata.tables.values()]
|
def _mid ( pt1 , pt2 ) : ( x0 , y0 ) , ( x1 , y1 ) = pt1 , pt2 return 0.5 * ( x0 + x1 ) , 0.5 * ( y0 + y1 )
| 0 |
python calculate the midpoint of two points
|
( Point Point ) - > Point Return the point that lies in between the two input points .
|
cosqa-train-18651
|
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 indexes_equal ( a : Index , b : Index ) -> bool : return str ( a ) == str ( b )
| 0 |
python checking if two strings are equal
|
Are two indexes equal? Checks by comparing str () versions of them . ( AM UNSURE IF THIS IS ENOUGH . )
|
cosqa-train-18652
|
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 long_substr ( data ) : substr = '' if len ( data ) > 1 and len ( data [ 0 ] ) > 0 : for i in range ( len ( data [ 0 ] ) ) : for j in range ( len ( data [ 0 ] ) - i + 1 ) : if j > len ( substr ) and all ( data [ 0 ] [ i : i + j ] in x for x in data ) : substr = data [ 0 ] [ i : i + j ] elif len ( data ) == 1 : substr = data [ 0 ] return substr
| 0 |
python finding longest common string in text
|
Return the longest common substring in a list of strings . Credit : http : // stackoverflow . com / questions / 2892931 / longest - common - substring - from - more - than - two - strings - python
|
cosqa-train-18653
|
def long_substr(data):
"""Return the longest common substring in a list of strings.
Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python
"""
substr = ''
if len(data) > 1 and len(data[0]) > 0:
for i in range(len(data[0])):
for j in range(len(data[0])-i+1):
if j > len(substr) and all(data[0][i:i+j] in x for x in data):
substr = data[0][i:i+j]
elif len(data) == 1:
substr = data[0]
return substr
|
def truncate ( value : Decimal , n_digits : int ) -> Decimal : return Decimal ( math . trunc ( value * ( 10 ** n_digits ) ) ) / ( 10 ** n_digits )
| 0 |
how to limit a number to two decimals python
|
Truncates a value to a number of decimals places
|
cosqa-train-18654
|
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 binary ( length ) : num = randint ( 1 , 999999 ) mask = '0' * length return ( mask + '' . join ( [ str ( num >> i & 1 ) for i in range ( 7 , - 1 , - 1 ) ] ) ) [ - length : ]
| 0 |
python generating random numbers of given bit length
|
returns a a random string that represent a binary representation
|
cosqa-train-18655
|
def binary(length):
"""
returns a a random string that represent a binary representation
:param length: number of bits
"""
num = randint(1, 999999)
mask = '0' * length
return (mask + ''.join([str(num >> i & 1) for i in range(7, -1, -1)]))[-length:]
|
def is_finite ( value : Any ) -> bool : return isinstance ( value , int ) or ( isinstance ( value , float ) and isfinite ( value ) )
| 1 |
python check if number isinfinite
|
Return true if a value is a finite number .
|
cosqa-train-18656
|
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 clear ( self ) -> None : self . _headers = httputil . HTTPHeaders ( { "Server" : "TornadoServer/%s" % tornado . version , "Content-Type" : "text/html; charset=UTF-8" , "Date" : httputil . format_timestamp ( time . time ( ) ) , } ) self . set_default_headers ( ) self . _write_buffer = [ ] # type: List[bytes] self . _status_code = 200 self . _reason = httputil . responses [ 200 ]
| 0 |
python tornado set default header
|
Resets all headers and content for this response .
|
cosqa-train-18657
|
def clear(self) -> None:
"""Resets all headers and content for this response."""
self._headers = httputil.HTTPHeaders(
{
"Server": "TornadoServer/%s" % tornado.version,
"Content-Type": "text/html; charset=UTF-8",
"Date": httputil.format_timestamp(time.time()),
}
)
self.set_default_headers()
self._write_buffer = [] # type: List[bytes]
self._status_code = 200
self._reason = httputil.responses[200]
|
def is_closing ( self ) -> bool : return self . stream . closed ( ) or self . client_terminated or self . server_terminated
| 0 |
python how to tell if a socket is closed
|
Return True if this connection is closing .
|
cosqa-train-18658
|
def is_closing(self) -> bool:
"""Return ``True`` if this connection is closing.
The connection is considered closing if either side has
initiated its closing handshake or if the stream has been
shut down uncleanly.
"""
return self.stream.closed() or self.client_terminated or self.server_terminated
|
def DeleteLog ( ) -> None : if os . path . exists ( Logger . FileName ) : os . remove ( Logger . FileName )
| 1 |
python delete logfile still in use
|
Delete log file .
|
cosqa-train-18659
|
def DeleteLog() -> None:
"""Delete log file."""
if os.path.exists(Logger.FileName):
os.remove(Logger.FileName)
|
def copy_session ( session : requests . Session ) -> requests . Session : new = requests . Session ( ) new . cookies = requests . utils . cookiejar_from_dict ( requests . utils . dict_from_cookiejar ( session . cookies ) ) new . headers = session . headers . copy ( ) return new
| 0 |
python copy cookies to a new request
|
Duplicates a requests . Session .
|
cosqa-train-18660
|
def copy_session(session: requests.Session) -> requests.Session:
"""Duplicates a requests.Session."""
new = requests.Session()
new.cookies = requests.utils.cookiejar_from_dict(requests.utils.dict_from_cookiejar(session.cookies))
new.headers = session.headers.copy()
return new
|
def listify ( a ) : if a is None : return [ ] elif not isinstance ( a , ( tuple , list , np . ndarray ) ) : return [ a ] return list ( a )
| 0 |
turn a list into an array python
|
Convert a scalar a to a list and all iterables to list as well .
|
cosqa-train-18661
|
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 _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 |
turn a string into a list and remove parentheses python
|
Convert a string to a list with sanitization .
|
cosqa-train-18662
|
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 _run_sync ( self , method : Callable , * args , * * kwargs ) -> Any : if self . loop . is_running ( ) : raise RuntimeError ( "Event loop is already running." ) if not self . is_connected : self . loop . run_until_complete ( self . connect ( ) ) task = asyncio . Task ( method ( * args , * * kwargs ) , loop = self . loop ) result = self . loop . run_until_complete ( task ) self . loop . run_until_complete ( self . quit ( ) ) return result
| 1 |
are python threads asyncronous
|
Utility method to run commands synchronously for testing .
|
cosqa-train-18663
|
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_line_in_file ( filename : str , line : str ) -> bool : assert "\n" not in line with open ( filename , "r" ) as file : for fileline in file : if fileline == line : return True return False
| 1 |
check if string in a file line python
|
Detects whether a line is present within a file .
|
cosqa-train-18664
|
def is_line_in_file(filename: str, line: str) -> bool:
"""
Detects whether a line is present within a file.
Args:
filename: file to check
line: line to search for (as an exact match)
"""
assert "\n" not in line
with open(filename, "r") as file:
for fileline in file:
if fileline == line:
return True
return False
|
def __remove_trailing_zeros ( self , collection ) : index = len ( collection ) - 1 while index >= 0 and collection [ index ] == 0 : index -= 1 return collection [ : index + 1 ]
| 0 |
remove leading zeroes in python
|
Removes trailing zeroes from indexable collection of numbers
|
cosqa-train-18665
|
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 memory_full ( ) : current_process = psutil . Process ( os . getpid ( ) ) return ( current_process . memory_percent ( ) > config . MAXIMUM_CACHE_MEMORY_PERCENTAGE )
| 0 |
python cpu usage monitor not full
|
Check if the memory is too full for further caching .
|
cosqa-train-18666
|
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 check_consistent_length ( * arrays ) : uniques = np . unique ( [ _num_samples ( X ) for X in arrays if X is not None ] ) if len ( uniques ) > 1 : raise ValueError ( "Found arrays with inconsistent numbers of samples: %s" % str ( uniques ) )
| 1 |
python check each element in list is same size
|
Check that all arrays have consistent first dimensions .
|
cosqa-train-18667
|
def check_consistent_length(*arrays):
"""Check that all arrays have consistent first dimensions.
Checks whether all objects in arrays have the same shape or length.
Parameters
----------
arrays : list or tuple of input objects.
Objects that will be checked for consistent length.
"""
uniques = np.unique([_num_samples(X) for X in arrays if X is not None])
if len(uniques) > 1:
raise ValueError("Found arrays with inconsistent numbers of samples: %s"
% str(uniques))
|
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 |
python 3 interger to byte
|
Take a str and transform it into a byte array .
|
cosqa-train-18668
|
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 _cleanup ( path : str ) -> None : if os . path . isdir ( path ) : shutil . rmtree ( path )
| 1 |
how to clean a directory in python
|
Cleanup temporary directory .
|
cosqa-train-18669
|
def _cleanup(path: str) -> None:
"""Cleanup temporary directory."""
if os.path.isdir(path):
shutil.rmtree(path)
|
def indexes_equal ( a : Index , b : Index ) -> bool : return str ( a ) == str ( b )
| 1 |
how do you check if two strings are the same in python
|
Are two indexes equal? Checks by comparing str () versions of them . ( AM UNSURE IF THIS IS ENOUGH . )
|
cosqa-train-18670
|
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 __getattr__ ( self , item : str ) -> Callable : return functools . partial ( self . call_action , item )
| 1 |
how to call on method python
|
Get a callable that sends the actual API request internally .
|
cosqa-train-18671
|
def __getattr__(self, item: str) -> Callable:
"""Get a callable that sends the actual API request internally."""
return functools.partial(self.call_action, item)
|
def calculate_single_tanimoto_set_distances ( target : Iterable [ X ] , dict_of_sets : Mapping [ Y , Set [ X ] ] ) -> Mapping [ Y , float ] : target_set = set ( target ) return { k : tanimoto_set_similarity ( target_set , s ) for k , s in dict_of_sets . items ( ) }
| 1 |
python calculate similarity for two dictionaries
|
Return a dictionary of distances keyed by the keys in the given dict .
|
cosqa-train-18672
|
def calculate_single_tanimoto_set_distances(target: Iterable[X], dict_of_sets: Mapping[Y, Set[X]]) -> Mapping[Y, float]:
"""Return a dictionary of distances keyed by the keys in the given dict.
Distances are calculated based on pairwise tanimoto similarity of the sets contained
:param set target: A set
:param dict_of_sets: A dict of {x: set of y}
:type dict_of_sets: dict
:return: A similarity dicationary based on the set overlap (tanimoto) score between the target set and the sets in
dos
:rtype: dict
"""
target_set = set(target)
return {
k: tanimoto_set_similarity(target_set, s)
for k, s in dict_of_sets.items()
}
|
def top ( self , topn = 10 ) : return [ self [ i ] for i in argsort ( list ( zip ( * self ) ) [ 1 ] ) [ : : - 1 ] [ : topn ] ]
| 0 |
how to get top10 in python
|
Get a list of the top topn features in this : class : . Feature \ .
|
cosqa-train-18673
|
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 chars ( string : any ) -> str : return '' . join ( [ c if c . isalpha ( ) else '' for c in str ( string ) ] )
| 1 |
python any alphabet in string
|
Return all ( and only ) the chars in the given string .
|
cosqa-train-18674
|
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 quaternion_imag ( quaternion ) : return numpy . array ( quaternion [ 1 : 4 ] , dtype = numpy . float64 , copy = True )
| 1 |
python array with real and imag
|
Return imaginary part of quaternion .
|
cosqa-train-18675
|
def quaternion_imag(quaternion):
"""Return imaginary part of quaternion.
>>> quaternion_imag([3, 0, 1, 2])
array([ 0., 1., 2.])
"""
return numpy.array(quaternion[1:4], dtype=numpy.float64, copy=True)
|
def get_case_insensitive_dict_key ( d : Dict , k : str ) -> Optional [ str ] : for key in d . keys ( ) : if k . lower ( ) == key . lower ( ) : return key return None
| 0 |
is dict key case sensitive in python
|
Within the dictionary d find a key that matches ( in case - insensitive fashion ) the key k and return it ( or None if there isn t one ) .
|
cosqa-train-18676
|
def get_case_insensitive_dict_key(d: Dict, k: str) -> Optional[str]:
"""
Within the dictionary ``d``, find a key that matches (in case-insensitive
fashion) the key ``k``, and return it (or ``None`` if there isn't one).
"""
for key in d.keys():
if k.lower() == key.lower():
return key
return None
|
def inverted_dict ( d ) : return dict ( ( force_hashable ( v ) , k ) for ( k , v ) in viewitems ( dict ( d ) ) )
| 1 |
invert key and values dictionary python
|
Return a dict with swapped keys and values
|
cosqa-train-18677
|
def inverted_dict(d):
"""Return a dict with swapped keys and values
>>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0}
True
"""
return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))
|
def to_bytes ( data : Any ) -> bytearray : # noqa if isinstance ( data , int ) : return bytearray ( [ data ] ) return bytearray ( data , encoding = 'latin-1' )
| 1 |
python change string to bytearray
|
Convert anything to a bytearray . See - http : // stackoverflow . com / questions / 7585435 / best - way - to - convert - string - to - bytes - in - python - 3 - http : // stackoverflow . com / questions / 10459067 / how - to - convert - my - bytearrayb - x9e - x18k - x9a - to - something - like - this - x9e - x1
|
cosqa-train-18678
|
def to_bytes(data: Any) -> bytearray:
"""
Convert anything to a ``bytearray``.
See
- http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3
- http://stackoverflow.com/questions/10459067/how-to-convert-my-bytearrayb-x9e-x18k-x9a-to-something-like-this-x9e-x1
""" # noqa
if isinstance(data, int):
return bytearray([data])
return bytearray(data, encoding='latin-1')
|
def remove_blank_lines ( string ) : return "\n" . join ( line for line in string . split ( "\n" ) if len ( line . strip ( ) ) )
| 0 |
how to remove none in python string
|
Removes all blank lines in @string
|
cosqa-train-18679
|
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 snake_case ( a_string ) : partial = re . sub ( '(.)([A-Z][a-z]+)' , r'\1_\2' , a_string ) return re . sub ( '([a-z0-9])([A-Z])' , r'\1_\2' , partial ) . lower ( )
| 0 |
lower case a string in python
|
Returns a snake cased version of a string .
|
cosqa-train-18680
|
def snake_case(a_string):
"""Returns a snake cased version of a string.
:param a_string: any :class:`str` object.
Usage:
>>> snake_case('FooBar')
"foo_bar"
"""
partial = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', a_string)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', partial).lower()
|
async def executemany ( self , sql : str , parameters : Iterable [ Iterable [ Any ] ] ) -> None : await self . _execute ( self . _cursor . executemany , sql , parameters )
| 1 |
python sqlite executemany dict
|
Execute the given multiquery .
|
cosqa-train-18681
|
async def executemany(self, sql: str, parameters: Iterable[Iterable[Any]]) -> None:
"""Execute the given multiquery."""
await self._execute(self._cursor.executemany, sql, parameters)
|
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 csv to two dimentional array numpy
|
Convert a CSV object to a numpy array .
|
cosqa-train-18682
|
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 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 |
python select the second element of a string within a list
|
Returns the index of the earliest occurence of an item from a list in a string
|
cosqa-train-18683
|
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 flatten_multidict ( multidict ) : return dict ( [ ( key , value if len ( value ) > 1 else value [ 0 ] ) for ( key , value ) in multidict . iterlists ( ) ] )
| 1 |
flatten dict of dict python
|
Return flattened dictionary from MultiDict .
|
cosqa-train-18684
|
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 access_token ( self ) : access_token = self . session . get ( self . access_token_key ) if access_token : if not self . expires_at : # user provided access_token, just return it return access_token timestamp = time . time ( ) if self . expires_at - timestamp > 60 : return access_token self . fetch_access_token ( ) return self . session . get ( self . access_token_key )
| 1 |
get wechat access token python
|
WeChat access token
|
cosqa-train-18685
|
def access_token(self):
""" WeChat access token """
access_token = self.session.get(self.access_token_key)
if access_token:
if not self.expires_at:
# user provided access_token, just return it
return access_token
timestamp = time.time()
if self.expires_at - timestamp > 60:
return access_token
self.fetch_access_token()
return self.session.get(self.access_token_key)
|
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 )
| 0 |
how to test for nan in python
|
Warn if nans exist in a numpy array .
|
cosqa-train-18686
|
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)
|
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 )
| 0 |
python how to change all int64 columns to int16
|
Return view of the recarray with all int32 cast to int64 .
|
cosqa-train-18687
|
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 __next__ ( self ) : self . current += 1 if self . current > self . total : raise StopIteration else : return self . iterable [ self . current - 1 ]
| 1 |
python how to get next element of iterator
|
: return : int
|
cosqa-train-18688
|
def __next__(self):
"""
:return: int
"""
self.current += 1
if self.current > self.total:
raise StopIteration
else:
return self.iterable[self.current - 1]
|
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 |
checking for empty file python
|
Check if cnr or cns files are empty ( only have a header )
|
cosqa-train-18689
|
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 join_states ( * states : State ) -> State : vectors = [ ket . vec for ket in states ] vec = reduce ( outer_product , vectors ) return State ( vec . tensor , vec . qubits )
| 1 |
python qutip compute inner product between two state vectors
|
Join two state vectors into a larger qubit state
|
cosqa-train-18690
|
def join_states(*states: State) -> State:
"""Join two state vectors into a larger qubit state"""
vectors = [ket.vec for ket in states]
vec = reduce(outer_product, vectors)
return State(vec.tensor, vec.qubits)
|
def blk_coverage_1d ( blk , size ) : rem = size % blk maxpix = size - rem return maxpix , rem
| 0 |
blockout region in image python opencv code
|
Return the part of a 1d array covered by a block .
|
cosqa-train-18691
|
def blk_coverage_1d(blk, size):
"""Return the part of a 1d array covered by a block.
:param blk: size of the 1d block
:param size: size of the 1d a image
:return: a tuple of size covered and remaining size
Example:
>>> blk_coverage_1d(7, 100)
(98, 2)
"""
rem = size % blk
maxpix = size - rem
return maxpix, rem
|
def cpu_count ( ) -> int : if multiprocessing is None : return 1 try : return multiprocessing . cpu_count ( ) except NotImplementedError : pass try : return os . sysconf ( "SC_NPROCESSORS_CONF" ) except ( AttributeError , ValueError ) : pass gen_log . error ( "Could not detect number of processors; assuming 1" ) return 1
| 1 |
python get number of gpu
|
Returns the number of processors on this machine .
|
cosqa-train-18692
|
def cpu_count() -> int:
"""Returns the number of processors on this machine."""
if multiprocessing is None:
return 1
try:
return multiprocessing.cpu_count()
except NotImplementedError:
pass
try:
return os.sysconf("SC_NPROCESSORS_CONF")
except (AttributeError, ValueError):
pass
gen_log.error("Could not detect number of processors; assuming 1")
return 1
|
def debugTreePrint ( node , pfx = "->" ) : print pfx , node . item for c in node . children : debugTreePrint ( c , " " + pfx )
| 0 |
how to recursively print a tree python
|
Purely a debugging aid : Ascii - art picture of a tree descended from node
|
cosqa-train-18693
|
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 rmglob ( pattern : str ) -> None : for f in glob . glob ( pattern ) : os . remove ( f )
| 1 |
delete files using wildcards python
|
Deletes all files whose filename matches the glob pattern ( via : func : glob . glob ) .
|
cosqa-train-18694
|
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 from_file ( file_path ) -> dict : with io . open ( file_path , 'r' , encoding = 'utf-8' ) as json_stream : return Json . parse ( json_stream , True )
| 1 |
python load json to dict
|
Load JSON file
|
cosqa-train-18695
|
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_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 get most frequent item in list
|
Returns the item that appears most frequently in the given list .
|
cosqa-train-18696
|
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 array2string ( arr : numpy . ndarray ) -> str : shape = str ( arr . shape ) [ 1 : - 1 ] if shape . endswith ( "," ) : shape = shape [ : - 1 ] return numpy . array2string ( arr , threshold = 11 ) + "%s[%s]" % ( arr . dtype , shape )
| 0 |
python ndarray string cut out
|
Format numpy array as a string .
|
cosqa-train-18697
|
def array2string(arr: numpy.ndarray) -> str:
"""Format numpy array as a string."""
shape = str(arr.shape)[1:-1]
if shape.endswith(","):
shape = shape[:-1]
return numpy.array2string(arr, threshold=11) + "%s[%s]" % (arr.dtype, shape)
|
def dotproduct ( X , Y ) : return sum ( [ x * y for x , y in zip ( X , Y ) ] )
| 0 |
dot product simple multiplication python
|
Return the sum of the element - wise product of vectors x and y . >>> dotproduct ( [ 1 2 3 ] [ 1000 100 10 ] ) 1230
|
cosqa-train-18698
|
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 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 )
| 0 |
how to compare similarity of two numbers on python
|
Calculate the tanimoto set similarity .
|
cosqa-train-18699
|
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)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.