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 local_machine_uuid ( ) : result = subprocess . check_output ( 'hal-get-property --udi ' '/org/freedesktop/Hal/devices/computer ' '--key system.hardware.uuid' . split ( ) ) . strip ( ) return uuid . UUID ( hex = result )
| 0 |
windows python get disk uuid
|
Return local machine unique identifier .
|
cosqa-train-18100
|
def local_machine_uuid():
"""Return local machine unique identifier.
>>> uuid = local_machine_uuid()
"""
result = subprocess.check_output(
'hal-get-property --udi '
'/org/freedesktop/Hal/devices/computer '
'--key system.hardware.uuid'.split()
).strip()
return uuid.UUID(hex=result)
|
def get_period_last_3_months ( ) -> str : today = Datum ( ) today . today ( ) # start_date = today - timedelta(weeks=13) start_date = today . clone ( ) start_date . subtract_months ( 3 ) period = get_period ( start_date . date , today . date ) return period
| 0 |
python last day of month two months ago
|
Returns the last week as a period string
|
cosqa-train-18101
|
def get_period_last_3_months() -> str:
""" Returns the last week as a period string """
today = Datum()
today.today()
# start_date = today - timedelta(weeks=13)
start_date = today.clone()
start_date.subtract_months(3)
period = get_period(start_date.date, today.date)
return period
|
def dtypes ( self ) : return [ ( str ( f . name ) , f . dataType . simpleString ( ) ) for f in self . schema . fields ]
| 1 |
get datatypesof columns python
|
Returns all column names and their data types as a list .
|
cosqa-train-18102
|
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 remove_empty_text ( utterances : List [ Utterance ] ) -> List [ Utterance ] : return [ utter for utter in utterances if utter . text . strip ( ) != "" ]
| 0 |
python remove all empty items in list
|
Remove empty utterances from a list of utterances Args : utterances : The list of utterance we are processing
|
cosqa-train-18103
|
def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]:
"""Remove empty utterances from a list of utterances
Args:
utterances: The list of utterance we are processing
"""
return [utter for utter in utterances if utter.text.strip() != ""]
|
def 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 make a set from an existing file python
|
Extract a de - duped collection ( set ) of text from a file . Expected file format is one item per line .
|
cosqa-train-18104
|
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 top ( self , topn = 10 ) : return [ self [ i ] for i in argsort ( list ( zip ( * self ) ) [ 1 ] ) [ : : - 1 ] [ : topn ] ]
| 0 |
python get top n element
|
Get a list of the top topn features in this : class : . Feature \ .
|
cosqa-train-18105
|
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 get_timezone ( ) -> Tuple [ datetime . tzinfo , str ] : dt = get_datetime_now ( ) . astimezone ( ) tzstr = dt . strftime ( "%z" ) tzstr = tzstr [ : - 2 ] + ":" + tzstr [ - 2 : ] return dt . tzinfo , tzstr
| 0 |
how to get a timezones time in python
|
Discover the current time zone and it s standard string representation ( for source { d } ) .
|
cosqa-train-18106
|
def get_timezone() -> Tuple[datetime.tzinfo, str]:
"""Discover the current time zone and it's standard string representation (for source{d})."""
dt = get_datetime_now().astimezone()
tzstr = dt.strftime("%z")
tzstr = tzstr[:-2] + ":" + tzstr[-2:]
return dt.tzinfo, tzstr
|
def indexes_equal ( a : Index , b : Index ) -> bool : return str ( a ) == str ( b )
| 1 |
python test if strings equal
|
Are two indexes equal? Checks by comparing str () versions of them . ( AM UNSURE IF THIS IS ENOUGH . )
|
cosqa-train-18107
|
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 cli_run ( ) : parser = argparse . ArgumentParser ( description = 'Stupidly simple code answers from StackOverflow' ) parser . add_argument ( 'query' , help = "What's the problem ?" , type = str , nargs = '+' ) parser . add_argument ( '-t' , '--tags' , help = 'semicolon separated tags -> python;lambda' ) args = parser . parse_args ( ) main ( args )
| 1 |
how do i check for args in python main
|
docstring for argparse
|
cosqa-train-18108
|
def cli_run():
"""docstring for argparse"""
parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow')
parser.add_argument('query', help="What's the problem ?", type=str, nargs='+')
parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda')
args = parser.parse_args()
main(args)
|
def execute ( cur , * args ) : stmt = args [ 0 ] if len ( args ) > 1 : stmt = stmt . replace ( '%' , '%%' ) . replace ( '?' , '%r' ) print ( stmt % ( args [ 1 ] ) ) return cur . execute ( * args )
| 0 |
python sql with paramters
|
Utility function to print sqlite queries before executing .
|
cosqa-train-18109
|
def execute(cur, *args):
"""Utility function to print sqlite queries before executing.
Use instead of cur.execute(). First argument is cursor.
cur.execute(stmt)
becomes
util.execute(cur, stmt)
"""
stmt = args[0]
if len(args) > 1:
stmt = stmt.replace('%', '%%').replace('?', '%r')
print(stmt % (args[1]))
return cur.execute(*args)
|
def normalize ( numbers ) : total = float ( sum ( numbers ) ) return [ n / total for n in numbers ]
| 1 |
python normalize to normal distribution
|
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-18110
|
def normalize(numbers):
"""Multiply each number by a constant such that the sum is 1.0
>>> normalize([1,2,1])
[0.25, 0.5, 0.25]
"""
total = float(sum(numbers))
return [n / total for n in numbers]
|
def is_sqlatype_string ( coltype : Union [ TypeEngine , VisitableType ] ) -> bool : coltype = _coltype_to_typeengine ( coltype ) return isinstance ( coltype , sqltypes . String )
| 1 |
python check if all are type string in a column
|
Is the SQLAlchemy column type a string type?
|
cosqa-train-18111
|
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 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 |
how to check if a line is in a file in python
|
Detects whether a line is present within a file .
|
cosqa-train-18112
|
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 mmap ( func , iterable ) : if sys . version_info [ 0 ] > 2 : return [ i for i in map ( func , iterable ) ] else : return map ( func , iterable )
| 1 |
python map for loop
|
Wrapper to make map () behave the same on Py2 and Py3 .
|
cosqa-train-18113
|
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 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 series get the minimum
|
Returns the last location of the minimal value of x . The position is calculated relatively to the length of x .
|
cosqa-train-18114
|
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 read csv as numpy array
|
Convert a CSV object to a numpy array .
|
cosqa-train-18115
|
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 normcdf ( x , log = False ) : y = np . atleast_1d ( x ) . copy ( ) flib . normcdf ( y ) if log : if ( y > 0 ) . all ( ) : return np . log ( y ) return - np . inf return y
| 1 |
vectorized normal cdf in python for speed
|
Normal cumulative density function .
|
cosqa-train-18116
|
def normcdf(x, log=False):
"""Normal cumulative density function."""
y = np.atleast_1d(x).copy()
flib.normcdf(y)
if log:
if (y>0).all():
return np.log(y)
return -np.inf
return y
|
def 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 finding first occurance of character in string
|
Returns the index of the earliest occurence of an item from a list in a string
|
cosqa-train-18117
|
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 mmap ( func , iterable ) : if sys . version_info [ 0 ] > 2 : return [ i for i in map ( func , iterable ) ] else : return map ( func , iterable )
| 0 |
python map function replace for loops
|
Wrapper to make map () behave the same on Py2 and Py3 .
|
cosqa-train-18118
|
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 is_orthogonal ( matrix : np . ndarray , * , rtol : float = 1e-5 , atol : float = 1e-8 ) -> bool : return ( matrix . shape [ 0 ] == matrix . shape [ 1 ] and np . all ( np . imag ( matrix ) == 0 ) and np . allclose ( matrix . dot ( matrix . T ) , np . eye ( matrix . shape [ 0 ] ) , rtol = rtol , atol = atol ) )
| 1 |
orthogonalize a matrix python
|
Determines if a matrix is approximately orthogonal .
|
cosqa-train-18119
|
def is_orthogonal(
matrix: np.ndarray,
*,
rtol: float = 1e-5,
atol: float = 1e-8) -> bool:
"""Determines if a matrix is approximately orthogonal.
A matrix is orthogonal if it's square and real and its transpose is its
inverse.
Args:
matrix: The matrix to check.
rtol: The per-matrix-entry relative tolerance on equality.
atol: The per-matrix-entry absolute tolerance on equality.
Returns:
Whether the matrix is orthogonal within the given tolerance.
"""
return (matrix.shape[0] == matrix.shape[1] and
np.all(np.imag(matrix) == 0) and
np.allclose(matrix.dot(matrix.T), np.eye(matrix.shape[0]),
rtol=rtol,
atol=atol))
|
def butlast ( iterable ) : iterable = iter ( iterable ) try : first = next ( iterable ) except StopIteration : return for second in iterable : yield first first = second
| 0 |
python last element in a list of lists
|
Yield all items from iterable except the last one .
|
cosqa-train-18120
|
def butlast(iterable):
"""Yield all items from ``iterable`` except the last one.
>>> list(butlast(['spam', 'eggs', 'ham']))
['spam', 'eggs']
>>> list(butlast(['spam']))
[]
>>> list(butlast([]))
[]
"""
iterable = iter(iterable)
try:
first = next(iterable)
except StopIteration:
return
for second in iterable:
yield first
first = second
|
def year ( date ) : try : fmt = '%m/%d/%Y' return datetime . strptime ( date , fmt ) . timetuple ( ) . tm_year except ValueError : return 0
| 0 |
how to get the year from a date in python
|
Returns the year .
|
cosqa-train-18121
|
def year(date):
""" Returns the year.
:param date:
The string date with this format %m/%d/%Y
:type date:
String
:returns:
int
:example:
>>> year('05/1/2015')
2015
"""
try:
fmt = '%m/%d/%Y'
return datetime.strptime(date, fmt).timetuple().tm_year
except ValueError:
return 0
|
def _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 ] )
| 1 |
how to print half a list python
|
Print at most limit elements of list .
|
cosqa-train-18122
|
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 is_not_null ( df : DataFrame , col_name : str ) -> bool : if ( isinstance ( df , pd . DataFrame ) and col_name in df . columns and df [ col_name ] . notnull ( ) . any ( ) ) : return True else : return False
| 1 |
check whether the col has null value or not python
|
Return True if the given DataFrame has a column of the given name ( string ) and there exists at least one non - NaN value in that column ; return False otherwise .
|
cosqa-train-18123
|
def is_not_null(df: DataFrame, col_name: str) -> bool:
"""
Return ``True`` if the given DataFrame has a column of the given
name (string), and there exists at least one non-NaN value in that
column; return ``False`` otherwise.
"""
if (
isinstance(df, pd.DataFrame)
and col_name in df.columns
and df[col_name].notnull().any()
):
return True
else:
return False
|
def chars ( string : any ) -> str : return '' . join ( [ c if c . isalpha ( ) else '' for c in str ( string ) ] )
| 0 |
check for letters without is alpha python
|
Return all ( and only ) the chars in the given string .
|
cosqa-train-18124
|
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 __remove_method ( m : lmap . Map , key : T ) -> lmap . Map : return m . dissoc ( key )
| 1 |
python map, delete key
|
Swap the methods atom to remove method with key .
|
cosqa-train-18125
|
def __remove_method(m: lmap.Map, key: T) -> lmap.Map:
"""Swap the methods atom to remove method with key."""
return m.dissoc(key)
|
def get_value ( self ) -> Decimal : quantity = self . get_quantity ( ) price = self . get_last_available_price ( ) if not price : # raise ValueError("no price found for", self.full_symbol) return Decimal ( 0 ) value = quantity * price . value return value
| 0 |
datareader python current stock price
|
Returns the current value of stocks
|
cosqa-train-18126
|
def get_value(self) -> Decimal:
""" Returns the current value of stocks """
quantity = self.get_quantity()
price = self.get_last_available_price()
if not price:
# raise ValueError("no price found for", self.full_symbol)
return Decimal(0)
value = quantity * price.value
return value
|
def setup_cache ( app : Flask , cache_config ) -> Optional [ Cache ] : if cache_config and cache_config . get ( 'CACHE_TYPE' ) != 'null' : return Cache ( app , config = cache_config ) return None
| 1 |
python flask add cache
|
Setup the flask - cache on a flask app
|
cosqa-train-18127
|
def setup_cache(app: Flask, cache_config) -> Optional[Cache]:
"""Setup the flask-cache on a flask app"""
if cache_config and cache_config.get('CACHE_TYPE') != 'null':
return Cache(app, config=cache_config)
return None
|
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 |
how to identify last occurrence of character in string in python
|
Returns the index of the earliest occurence of an item from a list in a string
|
cosqa-train-18128
|
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 get_keys_of_max_n ( dict_obj , n ) : return sorted ( [ item [ 0 ] for item in sorted ( dict_obj . items ( ) , key = lambda item : item [ 1 ] , reverse = True ) [ : n ] ] )
| 0 |
get top n fields of dict in python
|
Returns the keys that maps to the top n max values in the given dict .
|
cosqa-train-18129
|
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 year ( date ) : try : fmt = '%m/%d/%Y' return datetime . strptime ( date , fmt ) . timetuple ( ) . tm_year except ValueError : return 0
| 1 |
get year from string date python
|
Returns the year .
|
cosqa-train-18130
|
def year(date):
""" Returns the year.
:param date:
The string date with this format %m/%d/%Y
:type date:
String
:returns:
int
:example:
>>> year('05/1/2015')
2015
"""
try:
fmt = '%m/%d/%Y'
return datetime.strptime(date, fmt).timetuple().tm_year
except ValueError:
return 0
|
def _mid ( pt1 , pt2 ) : ( x0 , y0 ) , ( x1 , y1 ) = pt1 , pt2 return 0.5 * ( x0 + x1 ) , 0.5 * ( y0 + y1 )
| 1 |
creating and finding the midpoints of two points in python
|
( Point Point ) - > Point Return the point that lies in between the two input points .
|
cosqa-train-18131
|
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 valid_file ( path : str ) -> bool : path = Path ( path ) . expanduser ( ) log . debug ( "checking if %s is a valid file" , path ) return path . exists ( ) and path . is_file ( )
| 1 |
python how to verify file locaiton
|
Verifies that a string path actually exists and is a file
|
cosqa-train-18132
|
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 is_inside_lambda ( node : astroid . node_classes . NodeNG ) -> bool : parent = node . parent while parent is not None : if isinstance ( parent , astroid . Lambda ) : return True parent = parent . parent return False
| 1 |
how to check whether a variable is a lambda function in python
|
Return true if given node is inside lambda
|
cosqa-train-18133
|
def is_inside_lambda(node: astroid.node_classes.NodeNG) -> bool:
"""Return true if given node is inside lambda"""
parent = node.parent
while parent is not None:
if isinstance(parent, astroid.Lambda):
return True
parent = parent.parent
return False
|
def read_text_from_file ( path : str ) -> str : with open ( path ) as text_file : content = text_file . read ( ) return content
| 0 |
how can i get text file in python
|
Reads text file contents
|
cosqa-train-18134
|
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 get_domain ( url ) : parse_result = urlparse ( url ) domain = "{schema}://{netloc}" . format ( schema = parse_result . scheme , netloc = parse_result . netloc ) return domain
| 0 |
python get domain of an http address
|
Get domain part of an url .
|
cosqa-train-18135
|
def get_domain(url):
"""
Get domain part of an url.
For example: https://www.python.org/doc/ -> https://www.python.org
"""
parse_result = urlparse(url)
domain = "{schema}://{netloc}".format(
schema=parse_result.scheme, netloc=parse_result.netloc)
return domain
|
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 )
| 1 |
longest string in a list python
|
Returns the longest string size for a string entry across data .
|
cosqa-train-18136
|
def _prm_get_longest_stringsize(string_list):
""" Returns the longest string size for a string entry across data."""
maxlength = 1
for stringar in string_list:
if isinstance(stringar, np.ndarray):
if stringar.ndim > 0:
for string in stringar.ravel():
maxlength = max(len(string), maxlength)
else:
maxlength = max(len(stringar.tolist()), maxlength)
else:
maxlength = max(len(stringar), maxlength)
# Make the string Col longer than needed in order to allow later on slightly larger strings
return int(maxlength * 1.5)
|
def warn_if_nans_exist ( X ) : null_count = count_rows_with_nans ( X ) total = len ( X ) percent = 100 * null_count / total if null_count > 0 : warning_message = 'Warning! Found {} rows of {} ({:0.2f}%) with nan values. Only ' 'complete rows will be plotted.' . format ( null_count , total , percent ) warnings . warn ( warning_message , DataWarning )
| 1 |
how to check if missing values are blanks or nan or none in python
|
Warn if nans exist in a numpy array .
|
cosqa-train-18137
|
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 uppercase_chars ( string : any ) -> str : return '' . join ( [ c if c . isupper ( ) else '' for c in str ( string ) ] )
| 1 |
way to change the string "python" to have all uppercase letters
|
Return all ( and only ) the uppercase chars in the given string .
|
cosqa-train-18138
|
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 remove_empty_text ( utterances : List [ Utterance ] ) -> List [ Utterance ] : return [ utter for utter in utterances if utter . text . strip ( ) != "" ]
| 0 |
python list filters all blank string
|
Remove empty utterances from a list of utterances Args : utterances : The list of utterance we are processing
|
cosqa-train-18139
|
def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]:
"""Remove empty utterances from a list of utterances
Args:
utterances: The list of utterance we are processing
"""
return [utter for utter in utterances if utter.text.strip() != ""]
|
def astensor ( array : TensorLike ) -> BKTensor : tensor = tf . convert_to_tensor ( value = array , dtype = CTYPE ) return tensor
| 1 |
python tensor to array
|
Covert numpy array to tensorflow tensor
|
cosqa-train-18140
|
def astensor(array: TensorLike) -> BKTensor:
"""Covert numpy array to tensorflow tensor"""
tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)
return tensor
|
def is_finite ( value : Any ) -> bool : return isinstance ( value , int ) or ( isinstance ( value , float ) and isfinite ( value ) )
| 0 |
check if value is infinity or not python
|
Return true if a value is a finite number .
|
cosqa-train-18141
|
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 remove_parenthesis_around_tz ( cls , timestr ) : parenthesis = cls . TIMEZONE_PARENTHESIS . match ( timestr ) if parenthesis is not None : return parenthesis . group ( 1 )
| 1 |
python parse timezone abbreviation
|
get rid of parenthesis around timezone : ( GMT ) = > GMT
|
cosqa-train-18142
|
def remove_parenthesis_around_tz(cls, timestr):
"""get rid of parenthesis around timezone: (GMT) => GMT
:return: the new string if parenthesis were found, `None` otherwise
"""
parenthesis = cls.TIMEZONE_PARENTHESIS.match(timestr)
if parenthesis is not None:
return parenthesis.group(1)
|
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 |
compute similarity between data set python
|
Calculate the tanimoto set similarity .
|
cosqa-train-18143
|
def tanimoto_set_similarity(x: Iterable[X], y: Iterable[X]) -> float:
"""Calculate the tanimoto set similarity."""
a, b = set(x), set(y)
union = a | b
if not union:
return 0.0
return len(a & b) / len(union)
|
def get_timezone ( ) -> Tuple [ datetime . tzinfo , str ] : dt = get_datetime_now ( ) . astimezone ( ) tzstr = dt . strftime ( "%z" ) tzstr = tzstr [ : - 2 ] + ":" + tzstr [ - 2 : ] return dt . tzinfo , tzstr
| 1 |
python 3 get timezone from pc
|
Discover the current time zone and it s standard string representation ( for source { d } ) .
|
cosqa-train-18144
|
def get_timezone() -> Tuple[datetime.tzinfo, str]:
"""Discover the current time zone and it's standard string representation (for source{d})."""
dt = get_datetime_now().astimezone()
tzstr = dt.strftime("%z")
tzstr = tzstr[:-2] + ":" + tzstr[-2:]
return dt.tzinfo, tzstr
|
def str_to_time ( time_str : str ) -> datetime . datetime : pieces : Any = [ int ( piece ) for piece in time_str . split ( '-' ) ] return datetime . datetime ( * pieces )
| 0 |
python parse string to date time
|
Convert human readable string to datetime . datetime .
|
cosqa-train-18145
|
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 isarray ( array , test , dim = 2 ) : if dim > 1 : return all ( isarray ( array [ i ] , test , dim - 1 ) for i in range ( len ( array ) ) ) return all ( test ( i ) for i in array )
| 1 |
python how to judge all elements of an array at the same time
|
Returns True if test is True for all array elements . Otherwise returns False .
|
cosqa-train-18146
|
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 _str_to_list ( value , separator ) : value_list = [ item . strip ( ) for item in value . split ( separator ) ] value_list_sanitized = builtins . list ( filter ( None , value_list ) ) if len ( value_list_sanitized ) > 0 : return value_list_sanitized else : raise ValueError ( 'Invalid list variable.' )
| 1 |
python list from delimited string
|
Convert a string to a list with sanitization .
|
cosqa-train-18147
|
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 __as_list ( value : List [ JsonObjTypes ] ) -> List [ JsonTypes ] : return [ e . _as_dict if isinstance ( e , JsonObj ) else e for e in value ]
| 1 |
python json list object serializable
|
Return a json array as a list
|
cosqa-train-18148
|
def __as_list(value: List[JsonObjTypes]) -> List[JsonTypes]:
""" Return a json array as a list
:param value: array
:return: array with JsonObj instances removed
"""
return [e._as_dict if isinstance(e, JsonObj) else e for e in value]
|
def _check_whitespace ( string ) : if string . count ( ' ' ) + string . count ( '\t' ) + string . count ( '\n' ) > 0 : raise ValueError ( INSTRUCTION_HAS_WHITESPACE )
| 1 |
how to check whether string is whitespace in python
|
Make sure thre is no whitespace in the given string . Will raise a ValueError if whitespace is detected
|
cosqa-train-18149
|
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 simple_eq ( one : Instance , two : Instance , attrs : List [ str ] ) -> bool : return all ( getattr ( one , a ) == getattr ( two , a ) for a in attrs )
| 1 |
how to test if atributes are equal in python
|
Test if two objects are equal based on a comparison of the specified attributes attrs .
|
cosqa-train-18150
|
def simple_eq(one: Instance, two: Instance, attrs: List[str]) -> bool:
"""
Test if two objects are equal, based on a comparison of the specified
attributes ``attrs``.
"""
return all(getattr(one, a) == getattr(two, a) for a in attrs)
|
def year ( date ) : try : fmt = '%m/%d/%Y' return datetime . strptime ( date , fmt ) . timetuple ( ) . tm_year except ValueError : return 0
| 1 |
get year from datetime date python
|
Returns the year .
|
cosqa-train-18151
|
def year(date):
""" Returns the year.
:param date:
The string date with this format %m/%d/%Y
:type date:
String
:returns:
int
:example:
>>> year('05/1/2015')
2015
"""
try:
fmt = '%m/%d/%Y'
return datetime.strptime(date, fmt).timetuple().tm_year
except ValueError:
return 0
|
def debugTreePrint ( node , pfx = "->" ) : print pfx , node . item for c in node . children : debugTreePrint ( c , " " + pfx )
| 0 |
how to print a binary tree python
|
Purely a debugging aid : Ascii - art picture of a tree descended from node
|
cosqa-train-18152
|
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 butlast ( iterable ) : iterable = iter ( iterable ) try : first = next ( iterable ) except StopIteration : return for second in iterable : yield first first = second
| 1 |
python last element of a multi diemnsional list
|
Yield all items from iterable except the last one .
|
cosqa-train-18153
|
def butlast(iterable):
"""Yield all items from ``iterable`` except the last one.
>>> list(butlast(['spam', 'eggs', 'ham']))
['spam', 'eggs']
>>> list(butlast(['spam']))
[]
>>> list(butlast([]))
[]
"""
iterable = iter(iterable)
try:
first = next(iterable)
except StopIteration:
return
for second in iterable:
yield first
first = second
|
def __repr__ ( self ) -> str : return '{0}({1})' . format ( type ( self ) . __name__ , repr ( self . string ) )
| 0 |
python self type str
|
Return the string representation of self .
|
cosqa-train-18154
|
def __repr__(self) -> str:
"""Return the string representation of self."""
return '{0}({1})'.format(type(self).__name__, repr(self.string))
|
def _reshuffle ( mat , shape ) : return np . reshape ( np . transpose ( np . reshape ( mat , shape ) , ( 3 , 1 , 2 , 0 ) ) , ( shape [ 3 ] * shape [ 1 ] , shape [ 0 ] * shape [ 2 ] ) )
| 0 |
rearrange matrix rows randomly python
|
Reshuffle the indicies of a bipartite matrix A [ ij kl ] - > A [ lj ki ] .
|
cosqa-train-18155
|
def _reshuffle(mat, shape):
"""Reshuffle the indicies of a bipartite matrix A[ij,kl] -> A[lj,ki]."""
return np.reshape(
np.transpose(np.reshape(mat, shape), (3, 1, 2, 0)),
(shape[3] * shape[1], shape[0] * shape[2]))
|
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 )
| 1 |
python change numpy ndarray to strings
|
Format numpy array as a string .
|
cosqa-train-18156
|
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 load_yaml ( yaml_file : str ) -> Any : with open ( yaml_file , 'r' ) as file : return ruamel . yaml . load ( file , ruamel . yaml . RoundTripLoader )
| 1 |
python parsing yaml file
|
Load YAML from file .
|
cosqa-train-18157
|
def load_yaml(yaml_file: str) -> Any:
"""
Load YAML from file.
:param yaml_file: path to YAML file
:return: content of the YAML as dict/list
"""
with open(yaml_file, 'r') as file:
return ruamel.yaml.load(file, ruamel.yaml.RoundTripLoader)
|
def is_quoted ( arg : str ) -> bool : return len ( arg ) > 1 and arg [ 0 ] == arg [ - 1 ] and arg [ 0 ] in constants . QUOTES
| 0 |
python string compare single quote
|
Checks if a string is quoted : param arg : the string being checked for quotes : return : True if a string is quoted
|
cosqa-train-18158
|
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 memory_full ( ) : current_process = psutil . Process ( os . getpid ( ) ) return ( current_process . memory_percent ( ) > config . MAXIMUM_CACHE_MEMORY_PERCENTAGE )
| 1 |
how to inclrease memory allocated to python
|
Check if the memory is too full for further caching .
|
cosqa-train-18159
|
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 quoted_or_list ( items : List [ str ] ) -> Optional [ str ] : return or_list ( [ f"'{item}'" for item in items ] )
| 0 |
"any" python list of strings
|
Given [ A B C ] return A B or C .
|
cosqa-train-18160
|
def quoted_or_list(items: List[str]) -> Optional[str]:
"""Given [A, B, C] return "'A', 'B', or 'C'".
Note: We use single quotes here, since these are also used by repr().
"""
return or_list([f"'{item}'" for item in items])
|
def _my_hash ( arg_list ) : # type: (List[Any]) -> int res = 0 for arg in arg_list : res = res * 31 + hash ( arg ) return res
| 0 |
how to generate hash value from list in python program
|
Simple helper hash function
|
cosqa-train-18161
|
def _my_hash(arg_list):
# type: (List[Any]) -> int
"""Simple helper hash function"""
res = 0
for arg in arg_list:
res = res * 31 + hash(arg)
return res
|
def __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 |
input string that replaces occurences python
|
Replaces from a string ** input ** all the occurrences of some symbols according to mapping ** repls ** .
|
cosqa-train-18162
|
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 first_digits ( s , default = 0 ) : s = re . split ( r'[^0-9]+' , str ( s ) . strip ( ) . lstrip ( '+-' + charlist . whitespace ) ) if len ( s ) and len ( s [ 0 ] ) : return int ( s [ 0 ] ) return default
| 0 |
get first digits of string only python
|
Return the fist ( left - hand ) digits in a string as a single integer ignoring sign ( + / - ) . >>> first_digits ( + 123 . 456 ) 123
|
cosqa-train-18163
|
def first_digits(s, default=0):
"""Return the fist (left-hand) digits in a string as a single integer, ignoring sign (+/-).
>>> first_digits('+123.456')
123
"""
s = re.split(r'[^0-9]+', str(s).strip().lstrip('+-' + charlist.whitespace))
if len(s) and len(s[0]):
return int(s[0])
return default
|
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 |
python check if every array element satisfies condition
|
Returns True if test is True for all array elements . Otherwise returns False .
|
cosqa-train-18164
|
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 pack_bits ( longbits ) : byte = longbits & ( 0x0101010101010101 ) byte = ( byte | ( byte >> 7 ) ) & ( 0x0003000300030003 ) byte = ( byte | ( byte >> 14 ) ) & ( 0x0000000f0000000f ) byte = ( byte | ( byte >> 28 ) ) & ( 0x00000000000000ff ) return byte
| 1 |
how to do bit masking in python3
|
Crunch a 64 - bit int ( 8 bool bytes ) into a bitfield .
|
cosqa-train-18165
|
def pack_bits( longbits ):
"""Crunch a 64-bit int (8 bool bytes) into a bitfield."""
byte = longbits & (0x0101010101010101)
byte = (byte | (byte>>7)) & (0x0003000300030003)
byte = (byte | (byte>>14)) & (0x0000000f0000000f)
byte = (byte | (byte>>28)) & (0x00000000000000ff)
return byte
|
def run_time ( ) -> timedelta : delta = start_time if start_time else datetime . utcnow ( ) return datetime . utcnow ( ) - delta
| 0 |
how to add offset in current time python
|
cosqa-train-18166
|
def run_time() -> timedelta:
"""
:return:
"""
delta = start_time if start_time else datetime.utcnow()
return datetime.utcnow() - delta
|
|
def uppercase_chars ( string : any ) -> str : return '' . join ( [ c if c . isupper ( ) else '' for c in str ( string ) ] )
| 0 |
python char in a string to uppercase
|
Return all ( and only ) the uppercase chars in the given string .
|
cosqa-train-18167
|
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 butlast ( iterable ) : iterable = iter ( iterable ) try : first = next ( iterable ) except StopIteration : return for second in iterable : yield first first = second
| 1 |
python for in list except the last
|
Yield all items from iterable except the last one .
|
cosqa-train-18168
|
def butlast(iterable):
"""Yield all items from ``iterable`` except the last one.
>>> list(butlast(['spam', 'eggs', 'ham']))
['spam', 'eggs']
>>> list(butlast(['spam']))
[]
>>> list(butlast([]))
[]
"""
iterable = iter(iterable)
try:
first = next(iterable)
except StopIteration:
return
for second in iterable:
yield first
first = second
|
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 |
how to graph a random walk in python
|
Generate a random walk and return True if the walker has returned to the origin after taking n steps .
|
cosqa-train-18169
|
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 get_column_names ( engine : Engine , tablename : str ) -> List [ str ] : return [ info . name for info in gen_columns_info ( engine , tablename ) ]
| 1 |
get columns names of table in python
|
Get all the database column names for the specified table .
|
cosqa-train-18170
|
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 to_np ( * args ) : if len ( args ) > 1 : return ( cp . asnumpy ( x ) for x in args ) else : return cp . asnumpy ( args [ 0 ] )
| 0 |
how do i create a numpy aray from a python list
|
convert GPU arras to numpy and return them
|
cosqa-train-18171
|
def to_np(*args):
""" convert GPU arras to numpy and return them"""
if len(args) > 1:
return (cp.asnumpy(x) for x in args)
else:
return cp.asnumpy(args[0])
|
def count ( self , elem ) : return self . _left_list . count ( elem ) + self . _right_list . count ( elem )
| 0 |
count elements in queue of python
|
Return the number of elements equal to elem present in the queue
|
cosqa-train-18172
|
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 _RetryRequest ( self , timeout = None , * * request_args ) : while True : try : now = time . time ( ) if not timeout : timeout = config . CONFIG [ "Client.http_timeout" ] result = requests . request ( * * request_args ) # By default requests doesn't raise on HTTP error codes. result . raise_for_status ( ) # Requests does not always raise an exception when an incorrect response # is received. This fixes that behaviour. if not result . ok : raise requests . RequestException ( response = result ) return time . time ( ) - now , result # Catch any exceptions that dont have a code (e.g. socket.error). except IOError as e : self . consecutive_connection_errors += 1 # Request failed. If we connected successfully before we attempt a few # connections before we determine that it really failed. This might # happen if the front end is loaded and returns a few throttling 500 # messages. if self . active_base_url is not None : # Propagate 406 immediately without retrying, as 406 is a valid # response that indicates a need for enrollment. response = getattr ( e , "response" , None ) if getattr ( response , "status_code" , None ) == 406 : raise if self . consecutive_connection_errors >= self . retry_error_limit : # We tried several times but this really did not work, just fail it. logging . info ( "Too many connection errors to %s, retrying another URL" , self . active_base_url ) self . active_base_url = None raise e # Back off hard to allow the front end to recover. logging . debug ( "Unable to connect to frontend. Backing off %s seconds." , self . error_poll_min ) self . Wait ( self . error_poll_min ) # We never previously connected, maybe the URL/proxy is wrong? Just fail # right away to allow callers to try a different URL. else : raise e
| 1 |
how to fix the timeout error python requests
|
Retry the request a few times before we determine it failed .
|
cosqa-train-18173
|
def _RetryRequest(self, timeout=None, **request_args):
"""Retry the request a few times before we determine it failed.
Sometimes the frontend becomes loaded and issues a 500 error to throttle the
clients. We wait Client.error_poll_min seconds between each attempt to back
off the frontend. Note that this does not affect any timing algorithm in the
client itself which is controlled by the Timer() class.
Args:
timeout: Timeout for retry.
**request_args: Args to the requests.request call.
Returns:
a tuple of duration, urllib.request.urlopen response.
"""
while True:
try:
now = time.time()
if not timeout:
timeout = config.CONFIG["Client.http_timeout"]
result = requests.request(**request_args)
# By default requests doesn't raise on HTTP error codes.
result.raise_for_status()
# Requests does not always raise an exception when an incorrect response
# is received. This fixes that behaviour.
if not result.ok:
raise requests.RequestException(response=result)
return time.time() - now, result
# Catch any exceptions that dont have a code (e.g. socket.error).
except IOError as e:
self.consecutive_connection_errors += 1
# Request failed. If we connected successfully before we attempt a few
# connections before we determine that it really failed. This might
# happen if the front end is loaded and returns a few throttling 500
# messages.
if self.active_base_url is not None:
# Propagate 406 immediately without retrying, as 406 is a valid
# response that indicates a need for enrollment.
response = getattr(e, "response", None)
if getattr(response, "status_code", None) == 406:
raise
if self.consecutive_connection_errors >= self.retry_error_limit:
# We tried several times but this really did not work, just fail it.
logging.info(
"Too many connection errors to %s, retrying another URL",
self.active_base_url)
self.active_base_url = None
raise e
# Back off hard to allow the front end to recover.
logging.debug(
"Unable to connect to frontend. Backing off %s seconds.",
self.error_poll_min)
self.Wait(self.error_poll_min)
# We never previously connected, maybe the URL/proxy is wrong? Just fail
# right away to allow callers to try a different URL.
else:
raise e
|
def iprotate ( l , steps = 1 ) : if len ( l ) : steps %= len ( l ) if steps : firstPart = l [ : steps ] del l [ : steps ] l . extend ( firstPart ) return l
| 1 |
how to rotate a list left in python 3
|
r Like rotate but modifies l in - place .
|
cosqa-train-18174
|
def iprotate(l, steps=1):
r"""Like rotate, but modifies `l` in-place.
>>> l = [1,2,3]
>>> iprotate(l) is l
True
>>> l
[2, 3, 1]
>>> iprotate(iprotate(l, 2), -3)
[1, 2, 3]
"""
if len(l):
steps %= len(l)
if steps:
firstPart = l[:steps]
del l[:steps]
l.extend(firstPart)
return l
|
def enum_mark_last ( iterable , start = 0 ) : it = iter ( iterable ) count = start try : last = next ( it ) except StopIteration : return for val in it : yield count , False , last last = val count += 1 yield count , True , last
| 0 |
python iterator last value
|
Returns a generator over iterable that tells whether the current item is the last one . Usage : >>> iterable = range ( 10 ) >>> for index is_last item in enum_mark_last ( iterable ) : >>> print ( index item end = \ n if is_last else )
|
cosqa-train-18175
|
def enum_mark_last(iterable, start=0):
"""
Returns a generator over iterable that tells whether the current item is the last one.
Usage:
>>> iterable = range(10)
>>> for index, is_last, item in enum_mark_last(iterable):
>>> print(index, item, end='\n' if is_last else ', ')
"""
it = iter(iterable)
count = start
try:
last = next(it)
except StopIteration:
return
for val in it:
yield count, False, last
last = val
count += 1
yield count, True, last
|
def rate_limited ( max_per_hour : int , * args : Any ) -> Callable [ ... , Any ] : return util . rate_limited ( max_per_hour , * args )
| 0 |
set limits on a function python 3
|
Rate limit a function .
|
cosqa-train-18176
|
def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:
"""Rate limit a function."""
return util.rate_limited(max_per_hour, *args)
|
def memory_usage ( ) : try : import psutil import os except ImportError : return _memory_usage_ps ( ) process = psutil . Process ( os . getpid ( ) ) mem = process . memory_info ( ) [ 0 ] / float ( 2 ** 20 ) return mem
| 1 |
python psutil linux is consuming all the cpu
|
return memory usage of python process in MB
|
cosqa-train-18177
|
def memory_usage():
"""return memory usage of python process in MB
from
http://fa.bianp.net/blog/2013/different-ways-to-get-memory-consumption-or-lessons-learned-from-memory_profiler/
psutil is quicker
>>> isinstance(memory_usage(),float)
True
"""
try:
import psutil
import os
except ImportError:
return _memory_usage_ps()
process = psutil.Process(os.getpid())
mem = process.memory_info()[0] / float(2 ** 20)
return mem
|
def dotproduct ( X , Y ) : return sum ( [ x * y for x , y in zip ( X , Y ) ] )
| 0 |
dot product python loop
|
Return the sum of the element - wise product of vectors x and y . >>> dotproduct ( [ 1 2 3 ] [ 1000 100 10 ] ) 1230
|
cosqa-train-18178
|
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 rmglob ( pattern : str ) -> None : for f in glob . glob ( pattern ) : os . remove ( f )
| 1 |
python delete files with wild card
|
Deletes all files whose filename matches the glob pattern ( via : func : glob . glob ) .
|
cosqa-train-18179
|
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 duration_expired ( start_time , duration_seconds ) : if duration_seconds is not None : delta_seconds = datetime_delta_to_seconds ( dt . datetime . now ( ) - start_time ) if delta_seconds >= duration_seconds : return True return False
| 0 |
how to check python timestamp older than 5 minutes
|
Return True if duration_seconds have expired since start_time
|
cosqa-train-18180
|
def duration_expired(start_time, duration_seconds):
"""
Return True if ``duration_seconds`` have expired since ``start_time``
"""
if duration_seconds is not None:
delta_seconds = datetime_delta_to_seconds(dt.datetime.now() - start_time)
if delta_seconds >= duration_seconds:
return True
return False
|
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 fastest way to map
|
Wrapper to make map () behave the same on Py2 and Py3 .
|
cosqa-train-18181
|
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 get_valid_filename ( s ) : s = str ( s ) . strip ( ) . replace ( ' ' , '_' ) return re . sub ( r'(?u)[^-\w.]' , '' , s )
| 0 |
python invalid filename characters
|
Shamelessly taken from Django . https : // github . com / django / django / blob / master / django / utils / text . py
|
cosqa-train-18182
|
def get_valid_filename(s):
"""
Shamelessly taken from Django.
https://github.com/django/django/blob/master/django/utils/text.py
Return the given string converted to a string that can be used for a clean
filename. Remove leading and trailing spaces; convert other spaces to
underscores; and remove anything that is not an alphanumeric, dash,
underscore, or dot.
>>> get_valid_filename("john's portrait in 2004.jpg")
'johns_portrait_in_2004.jpg'
"""
s = str(s).strip().replace(' ', '_')
return re.sub(r'(?u)[^-\w.]', '', s)
|
async def enter_captcha ( self , url : str , sid : str ) -> str : raise VkCaptchaNeeded ( url , sid )
| 0 |
python submit form captcha requests
|
Override this method for processing captcha .
|
cosqa-train-18183
|
async def enter_captcha(self, url: str, sid: str) -> str:
"""
Override this method for processing captcha.
:param url: link to captcha image
:param sid: captcha id. I do not know why pass here but may be useful
:return captcha value
"""
raise VkCaptchaNeeded(url, sid)
|
def get_from_gnucash26_date ( date_str : str ) -> date : date_format = "%Y%m%d" result = datetime . strptime ( date_str , date_format ) . date ( ) return result
| 1 |
force string to date python
|
Creates a datetime from GnuCash 2 . 6 date string
|
cosqa-train-18184
|
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 genfirstvalues ( cursor : Cursor , arraysize : int = 1000 ) -> Generator [ Any , None , None ] : return ( row [ 0 ] for row in genrows ( cursor , arraysize ) )
| 0 |
get first 100 rows python
|
Generate the first value in each row .
|
cosqa-train-18185
|
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 list_to_str ( lst ) : if len ( lst ) == 1 : str_ = lst [ 0 ] elif len ( lst ) == 2 : str_ = ' and ' . join ( lst ) elif len ( lst ) > 2 : str_ = ', ' . join ( lst [ : - 1 ] ) str_ += ', and {0}' . format ( lst [ - 1 ] ) else : raise ValueError ( 'List of length 0 provided.' ) return str_
| 0 |
python join list to string seperated by comma
|
Turn a list into a comma - and / or and - separated string .
|
cosqa-train-18186
|
def list_to_str(lst):
"""
Turn a list into a comma- and/or and-separated string.
Parameters
----------
lst : :obj:`list`
A list of strings to join into a single string.
Returns
-------
str_ : :obj:`str`
A string with commas and/or ands separating th elements from ``lst``.
"""
if len(lst) == 1:
str_ = lst[0]
elif len(lst) == 2:
str_ = ' and '.join(lst)
elif len(lst) > 2:
str_ = ', '.join(lst[:-1])
str_ += ', and {0}'.format(lst[-1])
else:
raise ValueError('List of length 0 provided.')
return str_
|
def 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 longest directed path
|
Finds the longest path in a dag between two nodes
|
cosqa-train-18187
|
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 clean_column_names ( df : DataFrame ) -> DataFrame : f = df . copy ( ) f . columns = [ col . strip ( ) for col in f . columns ] return f
| 1 |
how to remove columns from a data frame python
|
Strip the whitespace from all column names in the given DataFrame and return the result .
|
cosqa-train-18188
|
def clean_column_names(df: DataFrame) -> DataFrame:
"""
Strip the whitespace from all column names in the given DataFrame
and return the result.
"""
f = df.copy()
f.columns = [col.strip() for col in f.columns]
return f
|
def wait_for_shutdown_signal ( self , please_stop = False , # ASSIGN SIGNAL TO STOP EARLY allow_exit = False , # ALLOW "exit" COMMAND ON CONSOLE TO ALSO STOP THE APP wait_forever = True # IGNORE CHILD THREADS, NEVER EXIT. False => IF NO CHILD THREADS LEFT, THEN EXIT ) : self_thread = Thread . current ( ) if self_thread != MAIN_THREAD or self_thread != self : Log . error ( "Only the main thread can sleep forever (waiting for KeyboardInterrupt)" ) if isinstance ( please_stop , Signal ) : # MUTUAL SIGNALING MAKES THESE TWO EFFECTIVELY THE SAME SIGNAL self . please_stop . on_go ( please_stop . go ) please_stop . on_go ( self . please_stop . go ) else : please_stop = self . please_stop if not wait_forever : # TRIGGER SIGNAL WHEN ALL CHILDREN THEADS ARE DONE with self_thread . child_lock : pending = copy ( self_thread . children ) children_done = AndSignals ( please_stop , len ( pending ) ) children_done . signal . on_go ( self . please_stop . go ) for p in pending : p . stopped . on_go ( children_done . done ) try : if allow_exit : _wait_for_exit ( please_stop ) else : _wait_for_interrupt ( please_stop ) except KeyboardInterrupt as _ : Log . alert ( "SIGINT Detected! Stopping..." ) except SystemExit as _ : Log . alert ( "SIGTERM Detected! Stopping..." ) finally : self . stop ( )
| 1 |
python doesn't stop on keyboard interrupt
|
FOR USE BY PROCESSES THAT NEVER DIE UNLESS EXTERNAL SHUTDOWN IS REQUESTED
|
cosqa-train-18189
|
def wait_for_shutdown_signal(
self,
please_stop=False, # ASSIGN SIGNAL TO STOP EARLY
allow_exit=False, # ALLOW "exit" COMMAND ON CONSOLE TO ALSO STOP THE APP
wait_forever=True # IGNORE CHILD THREADS, NEVER EXIT. False => IF NO CHILD THREADS LEFT, THEN EXIT
):
"""
FOR USE BY PROCESSES THAT NEVER DIE UNLESS EXTERNAL SHUTDOWN IS REQUESTED
CALLING THREAD WILL SLEEP UNTIL keyboard interrupt, OR please_stop, OR "exit"
:param please_stop:
:param allow_exit:
:param wait_forever:: Assume all needed threads have been launched. When done
:return:
"""
self_thread = Thread.current()
if self_thread != MAIN_THREAD or self_thread != self:
Log.error("Only the main thread can sleep forever (waiting for KeyboardInterrupt)")
if isinstance(please_stop, Signal):
# MUTUAL SIGNALING MAKES THESE TWO EFFECTIVELY THE SAME SIGNAL
self.please_stop.on_go(please_stop.go)
please_stop.on_go(self.please_stop.go)
else:
please_stop = self.please_stop
if not wait_forever:
# TRIGGER SIGNAL WHEN ALL CHILDREN THEADS ARE DONE
with self_thread.child_lock:
pending = copy(self_thread.children)
children_done = AndSignals(please_stop, len(pending))
children_done.signal.on_go(self.please_stop.go)
for p in pending:
p.stopped.on_go(children_done.done)
try:
if allow_exit:
_wait_for_exit(please_stop)
else:
_wait_for_interrupt(please_stop)
except KeyboardInterrupt as _:
Log.alert("SIGINT Detected! Stopping...")
except SystemExit as _:
Log.alert("SIGTERM Detected! Stopping...")
finally:
self.stop()
|
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 |
python2 replace text in string
|
Replaces from a string ** input ** all the occurrences of some symbols according to mapping ** repls ** .
|
cosqa-train-18190
|
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 decode ( self , bytes , raw = False ) : return struct . unpack ( self . format , buffer ( bytes ) ) [ 0 ]
| 0 |
python read protobuf from bytes
|
decode ( bytearray raw = False ) - > value
|
cosqa-train-18191
|
def decode(self, bytes, raw=False):
"""decode(bytearray, raw=False) -> value
Decodes the given bytearray according to this PrimitiveType
definition.
NOTE: The parameter ``raw`` is present to adhere to the
``decode()`` inteface, but has no effect for PrimitiveType
definitions.
"""
return struct.unpack(self.format, buffer(bytes))[0]
|
def _rindex ( mylist : Sequence [ T ] , x : T ) -> int : return len ( mylist ) - mylist [ : : - 1 ] . index ( x ) - 1
| 0 |
how to grab the last value of an index in python
|
Index of the last occurrence of x in the sequence .
|
cosqa-train-18192
|
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 non_increasing ( values ) : return all ( x >= y for x , y in zip ( values , values [ 1 : ] ) )
| 0 |
checking if the row value is the same with the row value above it in python
|
True if values are not increasing .
|
cosqa-train-18193
|
def non_increasing(values):
"""True if values are not increasing."""
return all(x >= y for x, y in zip(values, values[1:]))
|
def string ( value ) -> str : return system_json . dumps ( Json ( value ) . safe_object ( ) , ensure_ascii = False )
| 1 |
python string value of a json object
|
string dict / object / value to JSON
|
cosqa-train-18194
|
def string(value) -> str:
""" string dict/object/value to JSON """
return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)
|
def __remove_trailing_zeros ( self , collection ) : index = len ( collection ) - 1 while index >= 0 and collection [ index ] == 0 : index -= 1 return collection [ : index + 1 ]
| 1 |
python how to trim trailing zeroes
|
Removes trailing zeroes from indexable collection of numbers
|
cosqa-train-18195
|
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 get_column_names ( engine : Engine , tablename : str ) -> List [ str ] : return [ info . name for info in gen_columns_info ( engine , tablename ) ]
| 0 |
list python column names
|
Get all the database column names for the specified table .
|
cosqa-train-18196
|
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 strids2ids ( tokens : Iterable [ str ] ) -> List [ int ] : return list ( map ( int , tokens ) )
| 1 |
python gensim dictionary token2id for
|
Returns sequence of integer ids given a sequence of string ids .
|
cosqa-train-18197
|
def strids2ids(tokens: Iterable[str]) -> List[int]:
"""
Returns sequence of integer ids given a sequence of string ids.
:param tokens: List of integer tokens.
:return: List of word ids.
"""
return list(map(int, tokens))
|
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 return the top values in dictionary python
|
Returns the keys that maps to the top n max values in the given dict .
|
cosqa-train-18198
|
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 clean_int ( x ) -> int : try : return int ( x ) except ValueError : raise forms . ValidationError ( "Cannot convert to integer: {}" . format ( repr ( x ) ) )
| 1 |
validating an input is an integer python
|
Returns its parameter as an integer or raises django . forms . ValidationError .
|
cosqa-train-18199
|
def clean_int(x) -> int:
"""
Returns its parameter as an integer, or raises
``django.forms.ValidationError``.
"""
try:
return int(x)
except ValueError:
raise forms.ValidationError(
"Cannot convert to integer: {}".format(repr(x)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.