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 _check_samples_nodups ( fnames ) : counts = defaultdict ( int ) for f in fnames : for s in get_samples ( f ) : counts [ s ] += 1 duplicates = [ s for s , c in counts . items ( ) if c > 1 ] if duplicates : raise ValueError ( "Duplicate samples found in inputs %s: %s" % ( duplicates , fnames ) )
| 0 |
python identify duplicate observations
|
Ensure a set of input VCFs do not have duplicate samples .
|
cosqa-train-17800
|
def _check_samples_nodups(fnames):
"""Ensure a set of input VCFs do not have duplicate samples.
"""
counts = defaultdict(int)
for f in fnames:
for s in get_samples(f):
counts[s] += 1
duplicates = [s for s, c in counts.items() if c > 1]
if duplicates:
raise ValueError("Duplicate samples found in inputs %s: %s" % (duplicates, fnames))
|
def get_window_dim ( ) : version = sys . version_info if version >= ( 3 , 3 ) : return _size_36 ( ) if platform . system ( ) == 'Windows' : return _size_windows ( ) return _size_27 ( )
| 1 |
python get dimensions of a window
|
gets the dimensions depending on python version and os
|
cosqa-train-17801
|
def get_window_dim():
""" gets the dimensions depending on python version and os"""
version = sys.version_info
if version >= (3, 3):
return _size_36()
if platform.system() == 'Windows':
return _size_windows()
return _size_27()
|
def __remove_trailing_zeros ( self , collection ) : index = len ( collection ) - 1 while index >= 0 and collection [ index ] == 0 : index -= 1 return collection [ : index + 1 ]
| 0 |
trim off specific number of leading zeros python
|
Removes trailing zeroes from indexable collection of numbers
|
cosqa-train-17802
|
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 decode_base64 ( data : str ) -> bytes : missing_padding = len ( data ) % 4 if missing_padding != 0 : data += "=" * ( 4 - missing_padding ) return base64 . decodebytes ( data . encode ( "utf-8" ) )
| 0 |
python base64 incorrect padding
|
Decode base64 padding being optional .
|
cosqa-train-17803
|
def decode_base64(data: str) -> bytes:
"""Decode base64, padding being optional.
:param data: Base64 data as an ASCII byte string
:returns: The decoded byte string.
"""
missing_padding = len(data) % 4
if missing_padding != 0:
data += "=" * (4 - missing_padding)
return base64.decodebytes(data.encode("utf-8"))
|
def get_last_day_of_month ( t : datetime ) -> int : tn = t + timedelta ( days = 32 ) tn = datetime ( year = tn . year , month = tn . month , day = 1 ) tt = tn - timedelta ( hours = 1 ) return tt . day
| 1 |
get last day of the month data python
|
Returns day number of the last day of the month : param t : datetime : return : int
|
cosqa-train-17804
|
def get_last_day_of_month(t: datetime) -> int:
"""
Returns day number of the last day of the month
:param t: datetime
:return: int
"""
tn = t + timedelta(days=32)
tn = datetime(year=tn.year, month=tn.month, day=1)
tt = tn - timedelta(hours=1)
return tt.day
|
def obj_in_list_always ( target_list , obj ) : for item in set ( target_list ) : if item is not obj : return False return True
| 1 |
how to know if a object is in a list twice in python
|
>>> l = [ 1 1 1 ] >>> obj_in_list_always ( l 1 ) True >>> l . append ( 2 ) >>> obj_in_list_always ( l 1 ) False
|
cosqa-train-17805
|
def obj_in_list_always(target_list, obj):
"""
>>> l = [1,1,1]
>>> obj_in_list_always(l, 1)
True
>>> l.append(2)
>>> obj_in_list_always(l, 1)
False
"""
for item in set(target_list):
if item is not obj:
return False
return True
|
def is_finite ( value : Any ) -> bool : return isinstance ( value , int ) or ( isinstance ( value , float ) and isfinite ( value ) )
| 1 |
python check if float has no floating points
|
Return true if a value is a finite number .
|
cosqa-train-17806
|
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 is_sqlatype_string ( coltype : Union [ TypeEngine , VisitableType ] ) -> bool : coltype = _coltype_to_typeengine ( coltype ) return isinstance ( coltype , sqltypes . String )
| 1 |
python check datatype of column
|
Is the SQLAlchemy column type a string type?
|
cosqa-train-17807
|
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_changed ( filename ) : key = os . path . abspath ( filename ) mtime = get_mtime ( key ) if key not in _mtime_cache : _mtime_cache [ key ] = mtime return True return mtime > _mtime_cache [ key ]
| 1 |
python check whether file is updated first time
|
Check if filename has changed since the last check . If this is the first check assume the file is changed .
|
cosqa-train-17808
|
def has_changed (filename):
"""Check if filename has changed since the last check. If this
is the first check, assume the file is changed."""
key = os.path.abspath(filename)
mtime = get_mtime(key)
if key not in _mtime_cache:
_mtime_cache[key] = mtime
return True
return mtime > _mtime_cache[key]
|
def copy_without_prompts ( self ) : text = self . get_selected_text ( ) lines = text . split ( os . linesep ) for index , line in enumerate ( lines ) : if line . startswith ( '>>> ' ) or line . startswith ( '... ' ) : lines [ index ] = line [ 4 : ] text = os . linesep . join ( lines ) QApplication . clipboard ( ) . setText ( text )
| 1 |
pasting data from clipboard in python
|
Copy text to clipboard without prompts
|
cosqa-train-17809
|
def copy_without_prompts(self):
"""Copy text to clipboard without prompts"""
text = self.get_selected_text()
lines = text.split(os.linesep)
for index, line in enumerate(lines):
if line.startswith('>>> ') or line.startswith('... '):
lines[index] = line[4:]
text = os.linesep.join(lines)
QApplication.clipboard().setText(text)
|
def is_sqlatype_numeric ( coltype : Union [ TypeEngine , VisitableType ] ) -> bool : coltype = _coltype_to_typeengine ( coltype ) return isinstance ( coltype , sqltypes . Numeric )
| 1 |
check datatype of datatable column python
|
Is the SQLAlchemy column type one that inherits from : class : Numeric such as : class : Float : class : Decimal ?
|
cosqa-train-17810
|
def is_sqlatype_numeric(coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type one that inherits from :class:`Numeric`,
such as :class:`Float`, :class:`Decimal`?
"""
coltype = _coltype_to_typeengine(coltype)
return isinstance(coltype, sqltypes.Numeric)
|
def 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 check if there is nan in an array python
|
Warn if nans exist in a numpy array .
|
cosqa-train-17811
|
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 check_lengths ( * arrays ) : lengths = [ len ( array ) for array in arrays ] if len ( np . unique ( lengths ) ) > 1 : raise ValueError ( 'Inconsistent data lengths: {}' . format ( lengths ) )
| 1 |
python check data shape
|
tool to ensure input and output data have the same number of samples
|
cosqa-train-17812
|
def check_lengths(*arrays):
"""
tool to ensure input and output data have the same number of samples
Parameters
----------
*arrays : iterable of arrays to be checked
Returns
-------
None
"""
lengths = [len(array) for array in arrays]
if len(np.unique(lengths)) > 1:
raise ValueError('Inconsistent data lengths: {}'.format(lengths))
|
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 |
minimum of a column python
|
Returns the last location of the minimal value of x . The position is calculated relatively to the length of x .
|
cosqa-train-17813
|
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 csv_to_numpy ( string_like , dtype = None ) : # type: (str) -> np.array stream = StringIO ( string_like ) return np . genfromtxt ( stream , dtype = dtype , delimiter = ',' )
| 1 |
python numpy array from csv file
|
Convert a CSV object to a numpy array .
|
cosqa-train-17814
|
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 dag_longest_path ( graph , source , target ) : if source == target : return [ source ] allpaths = nx . all_simple_paths ( graph , source , target ) longest_path = [ ] for l in allpaths : if len ( l ) > len ( longest_path ) : longest_path = l return longest_path
| 1 |
python networkx get longest path
|
Finds the longest path in a dag between two nodes
|
cosqa-train-17815
|
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 _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 list duplicate index
|
Return dict mapping item - > indices .
|
cosqa-train-17816
|
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 stretch ( iterable , n = 2 ) : times = range ( n ) for item in iterable : for i in times : yield item
| 0 |
python 3 iter every n items
|
r Repeat each item in iterable n times .
|
cosqa-train-17817
|
def stretch(iterable, n=2):
r"""Repeat each item in `iterable` `n` times.
Example:
>>> list(stretch(range(3), 2))
[0, 0, 1, 1, 2, 2]
"""
times = range(n)
for item in iterable:
for i in times: yield item
|
def recClearTag ( element ) : children = element . getchildren ( ) if len ( children ) > 0 : for child in children : recClearTag ( child ) element . tag = clearTag ( element . tag )
| 1 |
python xml elementtree delete child
|
Applies maspy . xml . clearTag () to the tag attribute of the element and recursively to all child elements .
|
cosqa-train-17818
|
def recClearTag(element):
"""Applies maspy.xml.clearTag() to the tag attribute of the "element" and
recursively to all child elements.
:param element: an :instance:`xml.etree.Element`
"""
children = element.getchildren()
if len(children) > 0:
for child in children:
recClearTag(child)
element.tag = clearTag(element.tag)
|
def flatten_list ( l : List [ list ] ) -> list : return [ v for inner_l in l for v in inner_l ]
| 0 |
list of lists into a flat list python
|
takes a list of lists l and returns a flat list
|
cosqa-train-17819
|
def flatten_list(l: List[list]) -> list:
""" takes a list of lists, l and returns a flat list
"""
return [v for inner_l in l for v in inner_l]
|
def is_any_type_set ( sett : Set [ Type ] ) -> bool : return len ( sett ) == 1 and is_any_type ( min ( sett ) )
| 1 |
conditional if a variable is not an empty set python
|
Helper method to check if a set of types is the { AnyObject } singleton
|
cosqa-train-17820
|
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 isfinite ( data : mx . nd . NDArray ) -> mx . nd . NDArray : is_data_not_nan = data == data is_data_not_infinite = data . abs ( ) != np . inf return mx . nd . logical_and ( is_data_not_infinite , is_data_not_nan )
| 0 |
python ndarray nonzero indics
|
Performs an element - wise check to determine if the NDArray contains an infinite element or not . TODO : remove this funciton after upgrade to MXNet 1 . 4 . * in favor of mx . ndarray . contrib . isfinite ()
|
cosqa-train-17821
|
def isfinite(data: mx.nd.NDArray) -> mx.nd.NDArray:
"""Performs an element-wise check to determine if the NDArray contains an infinite element or not.
TODO: remove this funciton after upgrade to MXNet 1.4.* in favor of mx.ndarray.contrib.isfinite()
"""
is_data_not_nan = data == data
is_data_not_infinite = data.abs() != np.inf
return mx.nd.logical_and(is_data_not_infinite, is_data_not_nan)
|
def strtobytes ( input , encoding ) : py_version = sys . version_info [ 0 ] if py_version >= 3 : return _strtobytes_py3 ( input , encoding ) return _strtobytes_py2 ( input , encoding )
| 1 |
how is python binary string encoded
|
Take a str and transform it into a byte array .
|
cosqa-train-17822
|
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 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 )
| 1 |
set ranges on colormap python
|
Set the range of the colormap to [ * min_val * * max_val * ]
|
cosqa-train-17823
|
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 closest_values ( L ) : assert len ( L ) >= 2 L . sort ( ) valmin , argmin = min ( ( L [ i ] - L [ i - 1 ] , i ) for i in range ( 1 , len ( L ) ) ) return L [ argmin - 1 ] , L [ argmin ]
| 1 |
minimum distance in a list of pair no in python
|
Closest values
|
cosqa-train-17824
|
def closest_values(L):
"""Closest values
:param L: list of values
:returns: two values from L with minimal distance
:modifies: the order of L
:complexity: O(n log n), for n=len(L)
"""
assert len(L) >= 2
L.sort()
valmin, argmin = min((L[i] - L[i - 1], i) for i in range(1, len(L)))
return L[argmin - 1], L[argmin]
|
def execute_sql ( self , query ) : c = self . con . cursor ( ) c . execute ( query ) result = [ ] if c . rowcount > 0 : try : result = c . fetchall ( ) except psycopg2 . ProgrammingError : pass return result
| 0 |
get the sql query result python postgresql
|
Executes a given query string on an open postgres database .
|
cosqa-train-17825
|
def execute_sql(self, query):
"""
Executes a given query string on an open postgres database.
"""
c = self.con.cursor()
c.execute(query)
result = []
if c.rowcount > 0:
try:
result = c.fetchall()
except psycopg2.ProgrammingError:
pass
return result
|
def _parse_tuple_string ( argument ) : if isinstance ( argument , str ) : return tuple ( int ( p . strip ( ) ) for p in argument . split ( ',' ) ) return argument
| 1 |
python create tuple from part of a list
|
Return a tuple from parsing a b c d - > ( a b c d )
|
cosqa-train-17826
|
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 is_any_type_set ( sett : Set [ Type ] ) -> bool : return len ( sett ) == 1 and is_any_type ( min ( sett ) )
| 1 |
python check if something is equal to any of a set of objects
|
Helper method to check if a set of types is the { AnyObject } singleton
|
cosqa-train-17827
|
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 flatten_list ( x : List [ Any ] ) -> List [ Any ] : # noqa return [ item for sublist in x for item in sublist ]
| 0 |
python flattent list of list
|
Converts a list of lists into a flat list . Args : x : list of lists
|
cosqa-train-17828
|
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 valid_date ( x : str ) -> bool : try : if x != dt . datetime . strptime ( x , DATE_FORMAT ) . strftime ( DATE_FORMAT ) : raise ValueError return True except ValueError : return False
| 1 |
python check if a date is valid
|
Retrun True if x is a valid YYYYMMDD date ; otherwise return False .
|
cosqa-train-17829
|
def valid_date(x: str) -> bool:
"""
Retrun ``True`` if ``x`` is a valid YYYYMMDD date;
otherwise return ``False``.
"""
try:
if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):
raise ValueError
return True
except ValueError:
return False
|
def position ( self ) -> Position : return Position ( self . _index , self . _lineno , self . _col_offset )
| 1 |
to know the current postion of the file cursor the function used is in python
|
The current position of the cursor .
|
cosqa-train-17830
|
def position(self) -> Position:
"""The current position of the cursor."""
return Position(self._index, self._lineno, self._col_offset)
|
def _check_whitespace ( string ) : if string . count ( ' ' ) + string . count ( '\t' ) + string . count ( '\n' ) > 0 : raise ValueError ( INSTRUCTION_HAS_WHITESPACE )
| 0 |
how to check for whitespace in python
|
Make sure thre is no whitespace in the given string . Will raise a ValueError if whitespace is detected
|
cosqa-train-17831
|
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 str_upper ( x ) : sl = _to_string_sequence ( x ) . upper ( ) return column . ColumnStringArrow ( sl . bytes , sl . indices , sl . length , sl . offset , string_sequence = sl )
| 0 |
change column values to uppercase in python
|
Converts all strings in a column to uppercase .
|
cosqa-train-17832
|
def str_upper(x):
"""Converts all strings in a column to uppercase.
:returns: an expression containing the converted strings.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.upper()
Expression = str_upper(text)
Length: 5 dtype: str (expression)
---------------------------------
0 SOMETHING
1 VERY PRETTY
2 IS COMING
3 OUR
4 WAY.
"""
sl = _to_string_sequence(x).upper()
return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl)
|
def _isint ( string ) : return type ( string ) is int or ( isinstance ( string , _binary_type ) or isinstance ( string , _text_type ) ) and _isconvertible ( int , string )
| 1 |
how to see if string is an int python
|
>>> _isint ( 123 ) True >>> _isint ( 123 . 45 ) False
|
cosqa-train-17833
|
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 non_increasing ( values ) : return all ( x >= y for x , y in zip ( values , values [ 1 : ] ) )
| 0 |
if condition for between values python
|
True if values are not increasing .
|
cosqa-train-17834
|
def non_increasing(values):
"""True if values are not increasing."""
return all(x >= y for x, y in zip(values, values[1:]))
|
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 to get min of a column
|
Returns the last location of the minimal value of x . The position is calculated relatively to the length of x .
|
cosqa-train-17835
|
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 read ( self , start_position : int , size : int ) -> memoryview : return memoryview ( self . _bytes ) [ start_position : start_position + size ]
| 1 |
python memoryview memory fragments
|
Return a view into the memory
|
cosqa-train-17836
|
def read(self, start_position: int, size: int) -> memoryview:
"""
Return a view into the memory
"""
return memoryview(self._bytes)[start_position:start_position + size]
|
def _prm_get_longest_stringsize ( string_list ) : maxlength = 1 for stringar in string_list : if isinstance ( stringar , np . ndarray ) : if stringar . ndim > 0 : for string in stringar . ravel ( ) : maxlength = max ( len ( string ) , maxlength ) else : maxlength = max ( len ( stringar . tolist ( ) ) , maxlength ) else : maxlength = max ( len ( stringar ) , maxlength ) # Make the string Col longer than needed in order to allow later on slightly larger strings return int ( maxlength * 1.5 )
| 0 |
python to determine longest string in list
|
Returns the longest string size for a string entry across data .
|
cosqa-train-17837
|
def _prm_get_longest_stringsize(string_list):
""" Returns the longest string size for a string entry across data."""
maxlength = 1
for stringar in string_list:
if isinstance(stringar, np.ndarray):
if stringar.ndim > 0:
for string in stringar.ravel():
maxlength = max(len(string), maxlength)
else:
maxlength = max(len(stringar.tolist()), maxlength)
else:
maxlength = max(len(stringar), maxlength)
# Make the string Col longer than needed in order to allow later on slightly larger strings
return int(maxlength * 1.5)
|
async def stdout ( self ) -> AsyncGenerator [ str , None ] : await self . wait_running ( ) async for line in self . _subprocess . stdout : # type: ignore yield line
| 0 |
python read process output as a stream
|
Asynchronous generator for lines from subprocess stdout .
|
cosqa-train-17838
|
async def stdout(self) -> AsyncGenerator[str, None]:
"""Asynchronous generator for lines from subprocess stdout."""
await self.wait_running()
async for line in self._subprocess.stdout: # type: ignore
yield line
|
def same_network ( atree , btree ) -> bool : return same_hierarchy ( atree , btree ) and same_topology ( atree , btree )
| 0 |
implement a function to check if a binary tree is balanced python
|
True if given trees share the same structure of powernodes independently of ( power ) node names and same edge topology between ( power ) nodes .
|
cosqa-train-17839
|
def same_network(atree, btree) -> bool:
"""True if given trees share the same structure of powernodes,
independently of (power)node names,
and same edge topology between (power)nodes.
"""
return same_hierarchy(atree, btree) and same_topology(atree, btree)
|
def is_strict_numeric ( n : Node ) -> bool : return is_typed_literal ( n ) and cast ( Literal , n ) . datatype in [ XSD . integer , XSD . decimal , XSD . float , XSD . double ]
| 1 |
is python a strict typed language
|
numeric denotes typed literals with datatypes xsd : integer xsd : decimal xsd : float and xsd : double .
|
cosqa-train-17840
|
def is_strict_numeric(n: Node) -> bool:
""" numeric denotes typed literals with datatypes xsd:integer, xsd:decimal, xsd:float, and xsd:double. """
return is_typed_literal(n) and cast(Literal, n).datatype in [XSD.integer, XSD.decimal, XSD.float, XSD.double]
|
def dtypes ( self ) : return [ ( str ( f . name ) , f . dataType . simpleString ( ) ) for f in self . schema . fields ]
| 0 |
listing all types of variable in datframe python
|
Returns all column names and their data types as a list .
|
cosqa-train-17841
|
def dtypes(self):
"""Returns all column names and their data types as a list.
>>> df.dtypes
[('age', 'int'), ('name', 'string')]
"""
return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]
|
def bytes_hack ( buf ) : ub = None if sys . version_info > ( 3 , ) : ub = buf else : ub = bytes ( buf ) return ub
| 1 |
boost python3 bytes extrac
|
Hacky workaround for old installs of the library on systems without python - future that were keeping the 2to3 update from working after auto - update .
|
cosqa-train-17842
|
def bytes_hack(buf):
"""
Hacky workaround for old installs of the library on systems without python-future that were
keeping the 2to3 update from working after auto-update.
"""
ub = None
if sys.version_info > (3,):
ub = buf
else:
ub = bytes(buf)
return ub
|
def camel_to_snake ( s : str ) -> str : return CAMEL_CASE_RE . sub ( r'_\1' , s ) . strip ( ) . lower ( )
| 0 |
python camel to snake
|
Convert string from camel case to snake case .
|
cosqa-train-17843
|
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 genfirstvalues ( cursor : Cursor , arraysize : int = 1000 ) -> Generator [ Any , None , None ] : return ( row [ 0 ] for row in genrows ( cursor , arraysize ) )
| 1 |
selecting the first 10 rows in python
|
Generate the first value in each row .
|
cosqa-train-17844
|
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 get_language ( ) : from parler import appsettings language = dj_get_language ( ) if language is None and appsettings . PARLER_DEFAULT_ACTIVATE : return appsettings . PARLER_DEFAULT_LANGUAGE_CODE else : return language
| 0 |
python language key not found
|
Wrapper around Django s get_language utility . For Django > = 1 . 8 get_language returns None in case no translation is activate . Here we patch this behavior e . g . for back - end functionality requiring access to translated fields
|
cosqa-train-17845
|
def get_language():
"""
Wrapper around Django's `get_language` utility.
For Django >= 1.8, `get_language` returns None in case no translation is activate.
Here we patch this behavior e.g. for back-end functionality requiring access to translated fields
"""
from parler import appsettings
language = dj_get_language()
if language is None and appsettings.PARLER_DEFAULT_ACTIVATE:
return appsettings.PARLER_DEFAULT_LANGUAGE_CODE
else:
return language
|
def valid_file ( path : str ) -> bool : path = Path ( path ) . expanduser ( ) log . debug ( "checking if %s is a valid file" , path ) return path . exists ( ) and path . is_file ( )
| 1 |
python check if a file path is a file or directory
|
Verifies that a string path actually exists and is a file
|
cosqa-train-17846
|
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 flatten_multidict ( multidict ) : return dict ( [ ( key , value if len ( value ) > 1 else value [ 0 ] ) for ( key , value ) in multidict . iterlists ( ) ] )
| 0 |
dictionary python many values to key tuple
|
Return flattened dictionary from MultiDict .
|
cosqa-train-17847
|
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 clean ( ctx , text ) : text = conversions . to_string ( text , ctx ) return '' . join ( [ c for c in text if ord ( c ) >= 32 ] )
| 0 |
delete all non alphanumeric characters in a program python
|
Removes all non - printable characters from a text string
|
cosqa-train-17848
|
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 most_frequent ( lst ) : lst = lst [ : ] highest_freq = 0 most_freq = None for val in unique ( lst ) : if lst . count ( val ) > highest_freq : most_freq = val highest_freq = lst . count ( val ) return most_freq
| 0 |
python list get most frequent item
|
Returns the item that appears most frequently in the given list .
|
cosqa-train-17849
|
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 b64_decode ( data : bytes ) -> bytes : missing_padding = len ( data ) % 4 if missing_padding != 0 : data += b'=' * ( 4 - missing_padding ) return urlsafe_b64decode ( data )
| 0 |
python base64 encode incorrect padding
|
: param data : Base 64 encoded data to decode . : type data : bytes : return : Base 64 decoded data . : rtype : bytes
|
cosqa-train-17850
|
def b64_decode(data: bytes) -> bytes:
"""
:param data: Base 64 encoded data to decode.
:type data: bytes
:return: Base 64 decoded data.
:rtype: bytes
"""
missing_padding = len(data) % 4
if missing_padding != 0:
data += b'=' * (4 - missing_padding)
return urlsafe_b64decode(data)
|
def flatten_list ( x : List [ Any ] ) -> List [ Any ] : # noqa return [ item for sublist in x for item in sublist ]
| 1 |
how to flatten a list of lists in python
|
Converts a list of lists into a flat list . Args : x : list of lists
|
cosqa-train-17851
|
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 str_to_time ( time_str : str ) -> datetime . datetime : pieces : Any = [ int ( piece ) for piece in time_str . split ( '-' ) ] return datetime . datetime ( * pieces )
| 0 |
miliseconds in python datetime from string
|
Convert human readable string to datetime . datetime .
|
cosqa-train-17852
|
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 block_diag ( * blocks : np . ndarray ) -> np . ndarray : for b in blocks : if b . shape [ 0 ] != b . shape [ 1 ] : raise ValueError ( 'Blocks must be square.' ) if not blocks : return np . zeros ( ( 0 , 0 ) , dtype = np . complex128 ) n = sum ( b . shape [ 0 ] for b in blocks ) dtype = functools . reduce ( _merge_dtypes , ( b . dtype for b in blocks ) ) result = np . zeros ( shape = ( n , n ) , dtype = dtype ) i = 0 for b in blocks : j = i + b . shape [ 0 ] result [ i : j , i : j ] = b i = j return result
| 1 |
creating block diagonal matrices in python
|
Concatenates blocks into a block diagonal matrix .
|
cosqa-train-17853
|
def block_diag(*blocks: np.ndarray) -> np.ndarray:
"""Concatenates blocks into a block diagonal matrix.
Args:
*blocks: Square matrices to place along the diagonal of the result.
Returns:
A block diagonal matrix with the given blocks along its diagonal.
Raises:
ValueError: A block isn't square.
"""
for b in blocks:
if b.shape[0] != b.shape[1]:
raise ValueError('Blocks must be square.')
if not blocks:
return np.zeros((0, 0), dtype=np.complex128)
n = sum(b.shape[0] for b in blocks)
dtype = functools.reduce(_merge_dtypes, (b.dtype for b in blocks))
result = np.zeros(shape=(n, n), dtype=dtype)
i = 0
for b in blocks:
j = i + b.shape[0]
result[i:j, i:j] = b
i = j
return result
|
async def fetchall ( self ) -> Iterable [ sqlite3 . Row ] : return await self . _execute ( self . _cursor . fetchall )
| 1 |
python sqlite3 cursor select iterable
|
Fetch all remaining rows .
|
cosqa-train-17854
|
async def fetchall(self) -> Iterable[sqlite3.Row]:
"""Fetch all remaining rows."""
return await self._execute(self._cursor.fetchall)
|
def astensor ( array : TensorLike ) -> BKTensor : tensor = tf . convert_to_tensor ( value = array , dtype = CTYPE ) return tensor
| 0 |
tensorflow python tensor to numpy array
|
Covert numpy array to tensorflow tensor
|
cosqa-train-17855
|
def astensor(array: TensorLike) -> BKTensor:
"""Covert numpy array to tensorflow tensor"""
tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)
return tensor
|
def split ( text : str ) -> List [ str ] : return [ word for word in SEPARATOR . split ( text ) if word . strip ( ' \t' ) ]
| 1 |
python split on whitespace or punctuation
|
Split a text into a list of tokens .
|
cosqa-train-17856
|
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 __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 )
| 0 |
replace multiple characters in python string
|
Replaces from a string ** input ** all the occurrences of some symbols according to mapping ** repls ** .
|
cosqa-train-17857
|
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 iterate_items ( dictish ) : if hasattr ( dictish , 'iteritems' ) : return dictish . iteritems ( ) if hasattr ( dictish , 'items' ) : return dictish . items ( ) return dictish
| 1 |
python 3 dict iteriterms
|
Return a consistent ( key value ) iterable on dict - like objects including lists of tuple pairs .
|
cosqa-train-17858
|
def iterate_items(dictish):
""" Return a consistent (key, value) iterable on dict-like objects,
including lists of tuple pairs.
Example:
>>> list(iterate_items({'a': 1}))
[('a', 1)]
>>> list(iterate_items([('a', 1), ('b', 2)]))
[('a', 1), ('b', 2)]
"""
if hasattr(dictish, 'iteritems'):
return dictish.iteritems()
if hasattr(dictish, 'items'):
return dictish.items()
return dictish
|
def bytes_hack ( buf ) : ub = None if sys . version_info > ( 3 , ) : ub = buf else : ub = bytes ( buf ) return ub
| 0 |
if safe to have both python 2 and 3
|
Hacky workaround for old installs of the library on systems without python - future that were keeping the 2to3 update from working after auto - update .
|
cosqa-train-17859
|
def bytes_hack(buf):
"""
Hacky workaround for old installs of the library on systems without python-future that were
keeping the 2to3 update from working after auto-update.
"""
ub = None
if sys.version_info > (3,):
ub = buf
else:
ub = bytes(buf)
return ub
|
def remove_once ( gset , elem ) : remove = getattr ( gset , 'remove' , None ) if remove is not None : remove ( elem ) else : del gset [ elem ] return elem
| 0 |
python delete value from set
|
Remove the element from a set lists or dict . >>> L = [ Lucy ] ; S = set ( [ Sky ] ) ; D = { Diamonds : True } ; >>> remove_once ( L Lucy ) ; remove_once ( S Sky ) ; remove_once ( D Diamonds ) ; >>> print L S D [] set ( [] ) {}
|
cosqa-train-17860
|
def remove_once(gset, elem):
"""Remove the element from a set, lists or dict.
>>> L = ["Lucy"]; S = set(["Sky"]); D = { "Diamonds": True };
>>> remove_once(L, "Lucy"); remove_once(S, "Sky"); remove_once(D, "Diamonds");
>>> print L, S, D
[] set([]) {}
Returns the element if it was removed. Raises one of the exceptions in
:obj:`RemoveError` otherwise.
"""
remove = getattr(gset, 'remove', None)
if remove is not None: remove(elem)
else: del gset[elem]
return elem
|
def is_prime ( n ) : if n % 2 == 0 and n > 2 : return False return all ( n % i for i in range ( 3 , int ( math . sqrt ( n ) ) + 1 , 2 ) )
| 0 |
def is prime in python
|
Check if n is a prime number
|
cosqa-train-17861
|
def is_prime(n):
"""
Check if n is a prime number
"""
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
|
def get_now_sql_datetime ( ) : ## > IMPORTS ## from datetime import datetime , date , time now = datetime . now ( ) now = now . strftime ( "%Y-%m-%dT%H:%M:%S" ) return now
| 0 |
python get datetime now for mysql
|
* A datetime stamp in MySQL format : YYYY - MM - DDTHH : MM : SS *
|
cosqa-train-17862
|
def get_now_sql_datetime():
"""
*A datetime stamp in MySQL format: ``YYYY-MM-DDTHH:MM:SS``*
**Return:**
- ``now`` -- current time and date in MySQL format
**Usage:**
.. code-block:: python
from fundamentals import times
now = times.get_now_sql_datetime()
print now
# OUT: 2016-03-18T11:08:23
"""
## > IMPORTS ##
from datetime import datetime, date, time
now = datetime.now()
now = now.strftime("%Y-%m-%dT%H:%M:%S")
return now
|
def chars ( string : any ) -> str : return '' . join ( [ c if c . isalpha ( ) else '' for c in str ( string ) ] )
| 0 |
how to check in python string for only contain alphabets, numbers and underscore
|
Return all ( and only ) the chars in the given string .
|
cosqa-train-17863
|
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 strings_to_integers ( strings : Iterable [ str ] ) -> Iterable [ int ] : return strings_to_ ( strings , lambda x : int ( float ( x ) ) )
| 1 |
cast python list of strings to int
|
Convert a list of strings to a list of integers .
|
cosqa-train-17864
|
def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:
"""
Convert a list of strings to a list of integers.
:param strings: a list of string
:return: a list of converted integers
.. doctest::
>>> strings_to_integers(['1', '1.0', '-0.2'])
[1, 1, 0]
"""
return strings_to_(strings, lambda x: int(float(x)))
|
def _isint ( string ) : return type ( string ) is int or ( isinstance ( string , _binary_type ) or isinstance ( string , _text_type ) ) and _isconvertible ( int , string )
| 1 |
python testing if string is int
|
>>> _isint ( 123 ) True >>> _isint ( 123 . 45 ) False
|
cosqa-train-17865
|
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 lint ( fmt = 'colorized' ) : if fmt == 'html' : outfile = 'pylint_report.html' local ( 'pylint -f %s davies > %s || true' % ( fmt , outfile ) ) local ( 'open %s' % outfile ) else : local ( 'pylint -f %s davies || true' % fmt )
| 0 |
python pylint too strict
|
Run verbose PyLint on source . Optionally specify fmt = html for HTML output .
|
cosqa-train-17866
|
def lint(fmt='colorized'):
"""Run verbose PyLint on source. Optionally specify fmt=html for HTML output."""
if fmt == 'html':
outfile = 'pylint_report.html'
local('pylint -f %s davies > %s || true' % (fmt, outfile))
local('open %s' % outfile)
else:
local('pylint -f %s davies || true' % fmt)
|
def count ( args ) : counts = defaultdict ( int ) for arg in args : for item in arg : counts [ item ] = counts [ item ] + 1 return counts
| 0 |
function that counts the number o variabes equal to a certain value in a list python
|
count occurences in a list of lists >>> count ( [[ a b ] [ a ]] ) defaultdict ( int { a : 2 b : 1 } )
|
cosqa-train-17867
|
def count(args):
""" count occurences in a list of lists
>>> count([['a','b'],['a']])
defaultdict(int, {'a' : 2, 'b' : 1})
"""
counts = defaultdict(int)
for arg in args:
for item in arg:
counts[item] = counts[item] + 1
return counts
|
def get_column_names ( engine : Engine , tablename : str ) -> List [ str ] : return [ info . name for info in gen_columns_info ( engine , tablename ) ]
| 0 |
python sqlalchemy get table column names
|
Get all the database column names for the specified table .
|
cosqa-train-17868
|
def get_column_names(engine: Engine, tablename: str) -> List[str]:
"""
Get all the database column names for the specified table.
"""
return [info.name for info in gen_columns_info(engine, tablename)]
|
def url_host ( url : str ) -> str : from urllib . parse import urlparse res = urlparse ( url ) return res . netloc . split ( ':' ) [ 0 ] if res . netloc else ''
| 1 |
python get hostip from url
|
Parses hostname from URL . : param url : URL : return : hostname
|
cosqa-train-17869
|
def url_host(url: str) -> str:
"""
Parses hostname from URL.
:param url: URL
:return: hostname
"""
from urllib.parse import urlparse
res = urlparse(url)
return res.netloc.split(':')[0] if res.netloc else ''
|
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 |
return row with max value 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-17870
|
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 sample_normal ( mean , var , rng ) : ret = numpy . sqrt ( var ) * rng . randn ( * mean . shape ) + mean return ret
| 0 |
how to get random variable normal distribution with python
|
Sample from independent normal distributions
|
cosqa-train-17871
|
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 mmap ( func , iterable ) : if sys . version_info [ 0 ] > 2 : return [ i for i in map ( func , iterable ) ] else : return map ( func , iterable )
| 0 |
python 3 list map lambda
|
Wrapper to make map () behave the same on Py2 and Py3 .
|
cosqa-train-17872
|
def mmap(func, iterable):
"""Wrapper to make map() behave the same on Py2 and Py3."""
if sys.version_info[0] > 2:
return [i for i in map(func, iterable)]
else:
return map(func, iterable)
|
def count ( self , elem ) : return self . _left_list . count ( elem ) + self . _right_list . count ( elem )
| 0 |
how to check length of dequeue in python
|
Return the number of elements equal to elem present in the queue
|
cosqa-train-17873
|
def count(self, elem):
"""
Return the number of elements equal to elem present in the queue
>>> pdeque([1, 2, 1]).count(1)
2
"""
return self._left_list.count(elem) + self._right_list.count(elem)
|
def dictlist_wipe_key ( dict_list : Iterable [ Dict ] , key : str ) -> None : for d in dict_list : d . pop ( key , None )
| 0 |
how to drop an element from a python dictionary
|
Process an iterable of dictionaries . For each dictionary d delete d [ key ] if it exists .
|
cosqa-train-17874
|
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 remove_blank_lines ( string ) : return "\n" . join ( line for line in string . split ( "\n" ) if len ( line . strip ( ) ) )
| 1 |
python trim blank space from string
|
Removes all blank lines in @string
|
cosqa-train-17875
|
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 find_first_in_list ( txt : str , str_list : [ str ] ) -> int : # type: ignore start = len ( txt ) + 1 for item in str_list : if start > txt . find ( item ) > - 1 : start = txt . find ( item ) return start if len ( txt ) + 1 > start > - 1 else - 1
| 0 |
finding last occorance in a string python
|
Returns the index of the earliest occurence of an item from a list in a string
|
cosqa-train-17876
|
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 dictlist_wipe_key ( dict_list : Iterable [ Dict ] , key : str ) -> None : for d in dict_list : d . pop ( key , None )
| 0 |
deleting an element from a dictionary python
|
Process an iterable of dictionaries . For each dictionary d delete d [ key ] if it exists .
|
cosqa-train-17877
|
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 debugTreePrint ( node , pfx = "->" ) : print pfx , node . item for c in node . children : debugTreePrint ( c , " " + pfx )
| 0 |
how to track a tree python
|
Purely a debugging aid : Ascii - art picture of a tree descended from node
|
cosqa-train-17878
|
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 _sum_cycles_from_tokens ( self , tokens : List [ str ] ) -> int : return sum ( ( int ( self . _nonnumber_pattern . sub ( '' , t ) ) for t in tokens ) )
| 1 |
transforming tokens into a count python
|
Sum the total number of cycles over a list of tokens .
|
cosqa-train-17879
|
def _sum_cycles_from_tokens(self, tokens: List[str]) -> int:
"""Sum the total number of cycles over a list of tokens."""
return sum((int(self._nonnumber_pattern.sub('', t)) for t in tokens))
|
def percentile ( sorted_list , percent , key = lambda x : x ) : if not sorted_list : return None if percent == 1 : return float ( sorted_list [ - 1 ] ) if percent == 0 : return float ( sorted_list [ 0 ] ) n = len ( sorted_list ) i = percent * n if ceil ( i ) == i : i = int ( i ) return ( sorted_list [ i - 1 ] + sorted_list [ i ] ) / 2 return float ( sorted_list [ ceil ( i ) - 1 ] )
| 1 |
get percentile of a value in a list python
|
Find the percentile of a sorted list of values .
|
cosqa-train-17880
|
def percentile(sorted_list, percent, key=lambda x: x):
"""Find the percentile of a sorted list of values.
Arguments
---------
sorted_list : list
A sorted (ascending) list of values.
percent : float
A float value from 0.0 to 1.0.
key : function, optional
An optional function to compute a value from each element of N.
Returns
-------
float
The desired percentile of the value list.
Examples
--------
>>> sorted_list = [4,6,8,9,11]
>>> percentile(sorted_list, 0.4)
7.0
>>> percentile(sorted_list, 0.44)
8.0
>>> percentile(sorted_list, 0.6)
8.5
>>> percentile(sorted_list, 0.99)
11.0
>>> percentile(sorted_list, 1)
11.0
>>> percentile(sorted_list, 0)
4.0
"""
if not sorted_list:
return None
if percent == 1:
return float(sorted_list[-1])
if percent == 0:
return float(sorted_list[0])
n = len(sorted_list)
i = percent * n
if ceil(i) == i:
i = int(i)
return (sorted_list[i-1] + sorted_list[i]) / 2
return float(sorted_list[ceil(i)-1])
|
def get_from_gnucash26_date ( date_str : str ) -> date : date_format = "%Y%m%d" result = datetime . strptime ( date_str , date_format ) . date ( ) return result
| 0 |
make a string into a date python
|
Creates a datetime from GnuCash 2 . 6 date string
|
cosqa-train-17881
|
def get_from_gnucash26_date(date_str: str) -> date:
""" Creates a datetime from GnuCash 2.6 date string """
date_format = "%Y%m%d"
result = datetime.strptime(date_str, date_format).date()
return result
|
def 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 |
only keep index of the minimum of each row python
|
Returns the last location of the minimal value of x . The position is calculated relatively to the length of x .
|
cosqa-train-17882
|
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 fib ( n ) : assert n > 0 a , b = 1 , 1 for i in range ( n - 1 ) : a , b = b , a + b return a
| 1 |
fibonacci python code using sentinel loop
|
Fibonacci example function
|
cosqa-train-17883
|
def fib(n):
"""Fibonacci example function
Args:
n (int): integer
Returns:
int: n-th Fibonacci number
"""
assert n > 0
a, b = 1, 1
for i in range(n - 1):
a, b = b, a + b
return a
|
def most_frequent ( lst ) : lst = lst [ : ] highest_freq = 0 most_freq = None for val in unique ( lst ) : if lst . count ( val ) > highest_freq : most_freq = val highest_freq = lst . count ( val ) return most_freq
| 0 |
most frequent item in a list python
|
Returns the item that appears most frequently in the given list .
|
cosqa-train-17884
|
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 valid_file ( path : str ) -> bool : path = Path ( path ) . expanduser ( ) log . debug ( "checking if %s is a valid file" , path ) return path . exists ( ) and path . is_file ( )
| 1 |
how to check if a path is valid in python
|
Verifies that a string path actually exists and is a file
|
cosqa-train-17885
|
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 to_bytes ( data : Any ) -> bytearray : # noqa if isinstance ( data , int ) : return bytearray ( [ data ] ) return bytearray ( data , encoding = 'latin-1' )
| 0 |
python covert str 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-17886
|
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 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 download file from s3 bucket using python
|
Pull a file directly from S3 .
|
cosqa-train-17887
|
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 try_instance_init ( self , instance , late_start = False ) : try : instance . init_try += 1 # Maybe it's a retry if not late_start and instance . init_try > 1 : # Do not try until too frequently, or it's too loopy if instance . last_init_try > time . time ( ) - MODULE_INIT_PERIOD : logger . info ( "Too early to retry initialization, retry period is %d seconds" , MODULE_INIT_PERIOD ) # logger.info("%s / %s", instance.last_init_try, time.time()) return False instance . last_init_try = time . time ( ) logger . info ( "Trying to initialize module: %s" , instance . name ) # If it's an external module, create/update Queues() if instance . is_external : instance . create_queues ( self . daemon . sync_manager ) # The module instance init function says if initialization is ok if not instance . init ( ) : logger . warning ( "Module %s initialisation failed." , instance . name ) return False logger . info ( "Module %s is initialized." , instance . name ) except Exception as exp : # pylint: disable=broad-except # pragma: no cover, simple protection msg = "The module instance %s raised an exception " "on initialization: %s, I remove it!" % ( instance . name , str ( exp ) ) self . configuration_errors . append ( msg ) logger . error ( msg ) logger . exception ( exp ) return False return True
| 0 |
how to tell if an init has been called python
|
Try to initialize the given module instance .
|
cosqa-train-17888
|
def try_instance_init(self, instance, late_start=False):
"""Try to "initialize" the given module instance.
:param instance: instance to init
:type instance: object
:param late_start: If late_start, don't look for last_init_try
:type late_start: bool
:return: True on successful init. False if instance init method raised any Exception.
:rtype: bool
"""
try:
instance.init_try += 1
# Maybe it's a retry
if not late_start and instance.init_try > 1:
# Do not try until too frequently, or it's too loopy
if instance.last_init_try > time.time() - MODULE_INIT_PERIOD:
logger.info("Too early to retry initialization, retry period is %d seconds",
MODULE_INIT_PERIOD)
# logger.info("%s / %s", instance.last_init_try, time.time())
return False
instance.last_init_try = time.time()
logger.info("Trying to initialize module: %s", instance.name)
# If it's an external module, create/update Queues()
if instance.is_external:
instance.create_queues(self.daemon.sync_manager)
# The module instance init function says if initialization is ok
if not instance.init():
logger.warning("Module %s initialisation failed.", instance.name)
return False
logger.info("Module %s is initialized.", instance.name)
except Exception as exp: # pylint: disable=broad-except
# pragma: no cover, simple protection
msg = "The module instance %s raised an exception " \
"on initialization: %s, I remove it!" % (instance.name, str(exp))
self.configuration_errors.append(msg)
logger.error(msg)
logger.exception(exp)
return False
return True
|
def add_colons ( s ) : return ':' . join ( [ s [ i : i + 2 ] for i in range ( 0 , len ( s ) , 2 ) ] )
| 0 |
how to cancatinate semi coloumn in python
|
Add colons after every second digit .
|
cosqa-train-17889
|
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 has_jongsung ( letter ) : if len ( letter ) != 1 : raise Exception ( 'The target string must be one letter.' ) if not is_hangul ( letter ) : raise NotHangulException ( 'The target string must be Hangul' ) code = lt . hangul_index ( letter ) return code % NUM_JONG > 0
| 1 |
check each character in string pythong
|
Check whether this letter contains Jongsung
|
cosqa-train-17890
|
def has_jongsung(letter):
"""Check whether this letter contains Jongsung"""
if len(letter) != 1:
raise Exception('The target string must be one letter.')
if not is_hangul(letter):
raise NotHangulException('The target string must be Hangul')
code = lt.hangul_index(letter)
return code % NUM_JONG > 0
|
def _check_whitespace ( string ) : if string . count ( ' ' ) + string . count ( '\t' ) + string . count ( '\n' ) > 0 : raise ValueError ( INSTRUCTION_HAS_WHITESPACE )
| 1 |
if a string contains whitespace python
|
Make sure thre is no whitespace in the given string . Will raise a ValueError if whitespace is detected
|
cosqa-train-17891
|
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 try_cast_int ( s ) : try : temp = re . findall ( '\d' , str ( s ) ) temp = '' . join ( temp ) return int ( temp ) except : return s
| 1 |
cast a string to a digit in python
|
( str ) - > int All the digits in a given string are concatenated and converted into a single number .
|
cosqa-train-17892
|
def try_cast_int(s):
"""(str) -> int
All the digits in a given string are concatenated and converted into a single number.
"""
try:
temp = re.findall('\d', str(s))
temp = ''.join(temp)
return int(temp)
except:
return s
|
def memory_full ( ) : current_process = psutil . Process ( os . getpid ( ) ) return ( current_process . memory_percent ( ) > config . MAXIMUM_CACHE_MEMORY_PERCENTAGE )
| 0 |
how to clean python idle cache
|
Check if the memory is too full for further caching .
|
cosqa-train-17893
|
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 uppercase_chars ( string : any ) -> str : return '' . join ( [ c if c . isupper ( ) else '' for c in str ( string ) ] )
| 0 |
checking for uppercase in a string python
|
Return all ( and only ) the uppercase chars in the given string .
|
cosqa-train-17894
|
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 zfill ( x , width ) : if not isinstance ( x , basestring ) : x = repr ( x ) return x . zfill ( width )
| 0 |
python string formatting zeropadding
|
zfill ( x width ) - > string
|
cosqa-train-17895
|
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 _skip_section ( self ) : self . _last = self . _f . readline ( ) while len ( self . _last ) > 0 and len ( self . _last [ 0 ] . strip ( ) ) == 0 : self . _last = self . _f . readline ( )
| 0 |
python skip rest of a loop
|
Skip a section
|
cosqa-train-17896
|
def _skip_section(self):
"""Skip a section"""
self._last = self._f.readline()
while len(self._last) > 0 and len(self._last[0].strip()) == 0:
self._last = self._f.readline()
|
def normalize ( numbers ) : total = float ( sum ( numbers ) ) return [ n / total for n in numbers ]
| 1 |
python normalize a set of numbers
|
Multiply each number by a constant such that the sum is 1 . 0 >>> normalize ( [ 1 2 1 ] ) [ 0 . 25 0 . 5 0 . 25 ]
|
cosqa-train-17897
|
def normalize(numbers):
"""Multiply each number by a constant such that the sum is 1.0
>>> normalize([1,2,1])
[0.25, 0.5, 0.25]
"""
total = float(sum(numbers))
return [n / total for n in numbers]
|
def iso_string_to_python_datetime ( isostring : str ) -> Optional [ datetime . datetime ] : if not isostring : return None # if you parse() an empty string, you get today's date return dateutil . parser . parse ( isostring )
| 0 |
python get date from string without datetime
|
Takes an ISO - 8601 string and returns a datetime .
|
cosqa-train-17898
|
def iso_string_to_python_datetime(
isostring: str) -> Optional[datetime.datetime]:
"""
Takes an ISO-8601 string and returns a ``datetime``.
"""
if not isostring:
return None # if you parse() an empty string, you get today's date
return dateutil.parser.parse(isostring)
|
def proper_round ( n ) : return int ( n ) + ( n / abs ( n ) ) * int ( abs ( n - int ( n ) ) >= 0.5 ) if n != 0 else 0
| 1 |
how to round answer to nearest tenth python
|
rounds float to closest int : rtype : int : param n : float
|
cosqa-train-17899
|
def proper_round(n):
"""
rounds float to closest int
:rtype: int
:param n: float
"""
return int(n) + (n / abs(n)) * int(abs(n - int(n)) >= 0.5) if n != 0 else 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.