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 _duplicates ( list_ ) : item_indices = { } for i , item in enumerate ( list_ ) : try : item_indices [ item ] . append ( i ) except KeyError : # First time seen item_indices [ item ] = [ i ] return item_indices
| 1 |
python index for duplicate element
|
Return dict mapping item - > indices .
|
cosqa-train-19300
|
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 insert_ordered ( value , array ) : index = 0 # search for the last array item that value is larger than for n in range ( 0 , len ( array ) ) : if value >= array [ n ] : index = n + 1 array . insert ( index , value ) return index
| 1 |
python progarm to insert an element in sorted array
|
This will insert the value into the array keeping it sorted and returning the index where it was inserted
|
cosqa-train-19301
|
def insert_ordered(value, array):
"""
This will insert the value into the array, keeping it sorted, and returning the
index where it was inserted
"""
index = 0
# search for the last array item that value is larger than
for n in range(0,len(array)):
if value >= array[n]: index = n+1
array.insert(index, value)
return index
|
def _parse_tuple_string ( argument ) : if isinstance ( argument , str ) : return tuple ( int ( p . strip ( ) ) for p in argument . split ( ',' ) ) return argument
| 0 |
python str to named tuple
|
Return a tuple from parsing a b c d - > ( a b c d )
|
cosqa-train-19302
|
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 inverted_dict ( d ) : return dict ( ( force_hashable ( v ) , k ) for ( k , v ) in viewitems ( dict ( d ) ) )
| 1 |
how to invert dictionary in python
|
Return a dict with swapped keys and values
|
cosqa-train-19303
|
def inverted_dict(d):
"""Return a dict with swapped keys and values
>>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0}
True
"""
return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))
|
def check_python_version ( ) : # Required due to multiple with statements on one line req_version = ( 2 , 7 ) cur_version = sys . version_info if cur_version >= req_version : print ( "Python version... %sOK%s (found %s, requires %s)" % ( Bcolors . OKGREEN , Bcolors . ENDC , str ( platform . python_version ( ) ) , str ( req_version [ 0 ] ) + "." + str ( req_version [ 1 ] ) ) ) else : print ( "Python version... %sFAIL%s (found %s, requires %s)" % ( Bcolors . FAIL , Bcolors . ENDC , str ( cur_version ) , str ( req_version ) ) )
| 1 |
how to check verson of python being used
|
Check if the currently running Python version is new enough .
|
cosqa-train-19304
|
def check_python_version():
"""Check if the currently running Python version is new enough."""
# Required due to multiple with statements on one line
req_version = (2, 7)
cur_version = sys.version_info
if cur_version >= req_version:
print("Python version... %sOK%s (found %s, requires %s)" %
(Bcolors.OKGREEN, Bcolors.ENDC, str(platform.python_version()),
str(req_version[0]) + "." + str(req_version[1])))
else:
print("Python version... %sFAIL%s (found %s, requires %s)" %
(Bcolors.FAIL, Bcolors.ENDC, str(cur_version),
str(req_version)))
|
def normalize ( numbers ) : total = float ( sum ( numbers ) ) return [ n / total for n in numbers ]
| 1 |
python normalise list to sum to 1
|
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-19305
|
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 valid_file ( path : str ) -> bool : path = Path ( path ) . expanduser ( ) log . debug ( "checking if %s is a valid file" , path ) return path . exists ( ) and path . is_file ( )
| 0 |
python check if string is file
|
Verifies that a string path actually exists and is a file
|
cosqa-train-19306
|
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 numpy_to_yaml ( representer : Representer , data : np . ndarray ) -> Sequence [ Any ] : return representer . represent_sequence ( "!numpy_array" , data . tolist ( ) )
| 1 |
python read yaml to numpy
|
Write a numpy array to YAML .
|
cosqa-train-19307
|
def numpy_to_yaml(representer: Representer, data: np.ndarray) -> Sequence[Any]:
""" Write a numpy array to YAML.
It registers the array under the tag ``!numpy_array``.
Use with:
.. code-block:: python
>>> yaml = ruamel.yaml.YAML()
>>> yaml.representer.add_representer(np.ndarray, yaml.numpy_to_yaml)
Note:
We cannot use ``yaml.register_class`` because it won't register the proper type.
(It would register the type of the class, rather than of `numpy.ndarray`). Instead,
we use the above approach to register this method explicitly with the representer.
"""
return representer.represent_sequence(
"!numpy_array",
data.tolist()
)
|
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
| 0 |
read string from file into a set python
|
Extract a de - duped collection ( set ) of text from a file . Expected file format is one item per line .
|
cosqa-train-19308
|
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 _ ( f , x ) : return { k : v for k , v in x . items ( ) if f ( k , v ) }
| 0 |
python filter lambda dict
|
filter for dict note f should have signature : f :: key - > value - > bool
|
cosqa-train-19309
|
def _(f, x):
"""
filter for dict, note `f` should have signature: `f::key->value->bool`
"""
return {k: v for k, v in x.items() if f(k, v)}
|
def quaternion_imag ( quaternion ) : return numpy . array ( quaternion [ 1 : 4 ] , dtype = numpy . float64 , copy = True )
| 0 |
python imaginary part of complex number array
|
Return imaginary part of quaternion .
|
cosqa-train-19310
|
def quaternion_imag(quaternion):
"""Return imaginary part of quaternion.
>>> quaternion_imag([3, 0, 1, 2])
array([ 0., 1., 2.])
"""
return numpy.array(quaternion[1:4], dtype=numpy.float64, copy=True)
|
def strings_to_integers ( strings : Iterable [ str ] ) -> Iterable [ int ] : return strings_to_ ( strings , lambda x : int ( float ( x ) ) )
| 1 |
turn a list of str into int python
|
Convert a list of strings to a list of integers .
|
cosqa-train-19311
|
def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:
"""
Convert a list of strings to a list of integers.
:param strings: a list of string
:return: a list of converted integers
.. doctest::
>>> strings_to_integers(['1', '1.0', '-0.2'])
[1, 1, 0]
"""
return strings_to_(strings, lambda x: int(float(x)))
|
def is_sqlatype_string ( coltype : Union [ TypeEngine , VisitableType ] ) -> bool : coltype = _coltype_to_typeengine ( coltype ) return isinstance ( coltype , sqltypes . String )
| 1 |
python check what datatypes contained in a column
|
Is the SQLAlchemy column type a string type?
|
cosqa-train-19312
|
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 url_concat ( url , args ) : if not args : return url if url [ - 1 ] not in ( '?' , '&' ) : url += '&' if ( '?' in url ) else '?' return url + urllib . urlencode ( args )
| 1 |
add dictionary to query string to url python
|
Concatenate url and argument dictionary regardless of whether url has existing query parameters .
|
cosqa-train-19313
|
def url_concat(url, args):
"""Concatenate url and argument dictionary regardless of whether
url has existing query parameters.
>>> url_concat("http://example.com/foo?a=b", dict(c="d"))
'http://example.com/foo?a=b&c=d'
"""
if not args: return url
if url[-1] not in ('?', '&'):
url += '&' if ('?' in url) else '?'
return url + urllib.urlencode(args)
|
def _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
| 0 |
python code to check duplicates of index in a list
|
Return dict mapping item - > indices .
|
cosqa-train-19314
|
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 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 |
how to get percentile of a value in a list python
|
Find the percentile of a sorted list of values .
|
cosqa-train-19315
|
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 top ( self , topn = 10 ) : return [ self [ i ] for i in argsort ( list ( zip ( * self ) ) [ 1 ] ) [ : : - 1 ] [ : topn ] ]
| 0 |
python top 10 list
|
Get a list of the top topn features in this : class : . Feature \ .
|
cosqa-train-19316
|
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 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 |
get first occurence of char in string python
|
Returns the index of the earliest occurence of an item from a list in a string
|
cosqa-train-19317
|
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 _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
| 0 |
same index for duplicates in python
|
Return dict mapping item - > indices .
|
cosqa-train-19318
|
def _duplicates(list_):
"""Return dict mapping item -> indices."""
item_indices = {}
for i, item in enumerate(list_):
try:
item_indices[item].append(i)
except KeyError: # First time seen
item_indices[item] = [i]
return item_indices
|
def is_unicode ( string ) : str_type = str ( type ( string ) ) if str_type . find ( 'str' ) > 0 or str_type . find ( 'unicode' ) > 0 : return True return False
| 0 |
python check if is str
|
Validates that the object itself is some kinda string
|
cosqa-train-19319
|
def is_unicode(string):
"""Validates that the object itself is some kinda string"""
str_type = str(type(string))
if str_type.find('str') > 0 or str_type.find('unicode') > 0:
return True
return False
|
def post ( self , endpoint : str , * * kwargs ) -> dict : return self . _request ( 'POST' , endpoint , * * kwargs )
| 0 |
python post request api
|
HTTP POST operation to API endpoint .
|
cosqa-train-19320
|
def post(self, endpoint: str, **kwargs) -> dict:
"""HTTP POST operation to API endpoint."""
return self._request('POST', endpoint, **kwargs)
|
def cmd_dot ( conf : Config ) : build_context = BuildContext ( conf ) populate_targets_graph ( build_context , conf ) if conf . output_dot_file is None : write_dot ( build_context , conf , sys . stdout ) else : with open ( conf . output_dot_file , 'w' ) as out_file : write_dot ( build_context , conf , out_file )
| 0 |
python graphviz write dot file
|
Print out a neat targets dependency tree based on requested targets .
|
cosqa-train-19321
|
def cmd_dot(conf: Config):
"""Print out a neat targets dependency tree based on requested targets.
Use graphviz to render the dot file, e.g.:
> ybt dot :foo :bar | dot -Tpng -o graph.png
"""
build_context = BuildContext(conf)
populate_targets_graph(build_context, conf)
if conf.output_dot_file is None:
write_dot(build_context, conf, sys.stdout)
else:
with open(conf.output_dot_file, 'w') as out_file:
write_dot(build_context, conf, out_file)
|
def get_caller_module ( ) : stack = inspect . stack ( ) assert len ( stack ) > 1 caller = stack [ 2 ] [ 0 ] return caller . f_globals [ '__name__' ]
| 0 |
how to determine what a python function is called by
|
Returns the name of the caller s module as a string .
|
cosqa-train-19322
|
def get_caller_module():
"""
Returns the name of the caller's module as a string.
>>> get_caller_module()
'__main__'
"""
stack = inspect.stack()
assert len(stack) > 1
caller = stack[2][0]
return caller.f_globals['__name__']
|
def flatten_list ( l : List [ list ] ) -> list : return [ v for inner_l in l for v in inner_l ]
| 0 |
turn a list of lists into a single list python
|
takes a list of lists l and returns a flat list
|
cosqa-train-19323
|
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 _rindex ( mylist : Sequence [ T ] , x : T ) -> int : return len ( mylist ) - mylist [ : : - 1 ] . index ( x ) - 1
| 0 |
get last index of a character in python
|
Index of the last occurrence of x in the sequence .
|
cosqa-train-19324
|
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 shape ( self ) -> Tuple [ int , ... ] : return tuple ( bins . bin_count for bins in self . _binnings )
| 1 |
count of bins in python histogram
|
Shape of histogram s data .
|
cosqa-train-19325
|
def shape(self) -> Tuple[int, ...]:
"""Shape of histogram's data.
Returns
-------
One-element tuple with the number of bins along each axis.
"""
return tuple(bins.bin_count for bins in self._binnings)
|
def stretch ( iterable , n = 2 ) : times = range ( n ) for item in iterable : for i in times : yield item
| 1 |
iterate a specific number of times python
|
r Repeat each item in iterable n times .
|
cosqa-train-19326
|
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 negate_mask ( mask ) : res = np . ones ( mask . shape , dtype = np . int8 ) res [ mask > 0 ] = 0 return res
| 0 |
how to filter matrix values to zero in python
|
Returns the negated mask . If elements of input mask have 0 and non - zero values then the returned matrix will have all elements 0 ( 1 ) where the original one has non - zero ( 0 ) . : param mask : Input mask : type mask : np . array : return : array of same shape and dtype = int8 as input array : rtype : np . array
|
cosqa-train-19327
|
def negate_mask(mask):
"""Returns the negated mask.
If elements of input mask have 0 and non-zero values, then the returned matrix will have all elements 0 (1) where
the original one has non-zero (0).
:param mask: Input mask
:type mask: np.array
:return: array of same shape and dtype=int8 as input array
:rtype: np.array
"""
res = np.ones(mask.shape, dtype=np.int8)
res[mask > 0] = 0
return res
|
def to_iso_string ( self ) -> str : assert isinstance ( self . value , datetime ) return datetime . isoformat ( self . value )
| 1 |
python datetime to iso string
|
Returns full ISO string for the given date
|
cosqa-train-19328
|
def to_iso_string(self) -> str:
""" Returns full ISO string for the given date """
assert isinstance(self.value, datetime)
return datetime.isoformat(self.value)
|
def _run_sync ( self , method : Callable , * args , * * kwargs ) -> Any : if self . loop . is_running ( ) : raise RuntimeError ( "Event loop is already running." ) if not self . is_connected : self . loop . run_until_complete ( self . connect ( ) ) task = asyncio . Task ( method ( * args , * * kwargs ) , loop = self . loop ) result = self . loop . run_until_complete ( task ) self . loop . run_until_complete ( self . quit ( ) ) return result
| 1 |
asyncio python another loop unit tests
|
Utility method to run commands synchronously for testing .
|
cosqa-train-19329
|
def _run_sync(self, method: Callable, *args, **kwargs) -> Any:
"""
Utility method to run commands synchronously for testing.
"""
if self.loop.is_running():
raise RuntimeError("Event loop is already running.")
if not self.is_connected:
self.loop.run_until_complete(self.connect())
task = asyncio.Task(method(*args, **kwargs), loop=self.loop)
result = self.loop.run_until_complete(task)
self.loop.run_until_complete(self.quit())
return result
|
def _mid ( pt1 , pt2 ) : ( x0 , y0 ) , ( x1 , y1 ) = pt1 , pt2 return 0.5 * ( x0 + x1 ) , 0.5 * ( y0 + y1 )
| 1 |
python mid points for all xy pairs
|
( Point Point ) - > Point Return the point that lies in between the two input points .
|
cosqa-train-19330
|
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 top ( self , topn = 10 ) : return [ self [ i ] for i in argsort ( list ( zip ( * self ) ) [ 1 ] ) [ : : - 1 ] [ : topn ] ]
| 0 |
python returns the indices of the top values
|
Get a list of the top topn features in this : class : . Feature \ .
|
cosqa-train-19331
|
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 memory_full ( ) : current_process = psutil . Process ( os . getpid ( ) ) return ( current_process . memory_percent ( ) > config . MAXIMUM_CACHE_MEMORY_PERCENTAGE )
| 0 |
python mem cache multi process
|
Check if the memory is too full for further caching .
|
cosqa-train-19332
|
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 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 ]
| 0 |
python get 3 closest values
|
Closest values
|
cosqa-train-19333
|
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 truncate ( value : Decimal , n_digits : int ) -> Decimal : return Decimal ( math . trunc ( value * ( 10 ** n_digits ) ) ) / ( 10 ** n_digits )
| 1 |
how to truncate to two decimals in python
|
Truncates a value to a number of decimals places
|
cosqa-train-19334
|
def truncate(value: Decimal, n_digits: int) -> Decimal:
"""Truncates a value to a number of decimals places"""
return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)
|
def is_running ( process_id : int ) -> bool : pstr = str ( process_id ) encoding = sys . getdefaultencoding ( ) s = subprocess . Popen ( [ "ps" , "-p" , pstr ] , stdout = subprocess . PIPE ) for line in s . stdout : strline = line . decode ( encoding ) if pstr in strline : return True return False
| 1 |
python check if a process is running or not
|
Uses the Unix ps program to see if a process is running .
|
cosqa-train-19335
|
def is_running(process_id: int) -> bool:
"""
Uses the Unix ``ps`` program to see if a process is running.
"""
pstr = str(process_id)
encoding = sys.getdefaultencoding()
s = subprocess.Popen(["ps", "-p", pstr], stdout=subprocess.PIPE)
for line in s.stdout:
strline = line.decode(encoding)
if pstr in strline:
return True
return False
|
def uconcatenate ( arrs , axis = 0 ) : v = np . concatenate ( arrs , axis = axis ) v = _validate_numpy_wrapper_units ( v , arrs ) return v
| 0 |
concatenate nyumpy arrays python
|
Concatenate a sequence of arrays .
|
cosqa-train-19336
|
def uconcatenate(arrs, axis=0):
"""Concatenate a sequence of arrays.
This wrapper around numpy.concatenate preserves units. All input arrays
must have the same units. See the documentation of numpy.concatenate for
full details.
Examples
--------
>>> from unyt import cm
>>> A = [1, 2, 3]*cm
>>> B = [2, 3, 4]*cm
>>> uconcatenate((A, B))
unyt_array([1, 2, 3, 2, 3, 4], 'cm')
"""
v = np.concatenate(arrs, axis=axis)
v = _validate_numpy_wrapper_units(v, arrs)
return v
|
def Exit ( msg , code = 1 ) : print >> sys . stderr , msg sys . exit ( code )
| 0 |
in python how to create code to exit
|
Exit execution with return code and message : param msg : Message displayed prior to exit : param code : code returned upon exiting
|
cosqa-train-19337
|
def Exit(msg, code=1):
"""Exit execution with return code and message
:param msg: Message displayed prior to exit
:param code: code returned upon exiting
"""
print >> sys.stderr, msg
sys.exit(code)
|
def find_duplicates ( l : list ) -> set : return set ( [ x for x in l if l . count ( x ) > 1 ] )
| 0 |
how to count duplicates in python list
|
Return the duplicates in a list .
|
cosqa-train-19338
|
def find_duplicates(l: list) -> set:
"""
Return the duplicates in a list.
The function relies on
https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-a-list .
Parameters
----------
l : list
Name
Returns
-------
set
Duplicated values
>>> find_duplicates([1,2,3])
set()
>>> find_duplicates([1,2,1])
{1}
"""
return set([x for x in l if l.count(x) > 1])
|
def read32 ( bytestream ) : dt = np . dtype ( np . uint32 ) . newbyteorder ( '>' ) return np . frombuffer ( bytestream . read ( 4 ) , dtype = dt ) [ 0 ]
| 0 |
8 bit uint unpack python
|
Read 4 bytes from bytestream as an unsigned 32 - bit integer .
|
cosqa-train-19339
|
def read32(bytestream):
"""Read 4 bytes from bytestream as an unsigned 32-bit integer."""
dt = np.dtype(np.uint32).newbyteorder('>')
return np.frombuffer(bytestream.read(4), dtype=dt)[0]
|
def url_host ( url : str ) -> str : from urllib . parse import urlparse res = urlparse ( url ) return res . netloc . split ( ':' ) [ 0 ] if res . netloc else ''
| 0 |
python get hostname from url string
|
Parses hostname from URL . : param url : URL : return : hostname
|
cosqa-train-19340
|
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 snake_to_camel ( s : str ) -> str : fragments = s . split ( '_' ) return fragments [ 0 ] + '' . join ( x . title ( ) for x in fragments [ 1 : ] )
| 0 |
python capitalize title case
|
Convert string from snake case to camel case .
|
cosqa-train-19341
|
def snake_to_camel(s: str) -> str:
"""Convert string from snake case to camel case."""
fragments = s.split('_')
return fragments[0] + ''.join(x.title() for x in fragments[1:])
|
def csv_to_numpy ( string_like , dtype = None ) : # type: (str) -> np.array stream = StringIO ( string_like ) return np . genfromtxt ( stream , dtype = dtype , delimiter = ',' )
| 0 |
read csv into numpy array python
|
Convert a CSV object to a numpy array .
|
cosqa-train-19342
|
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 shape ( self ) -> Tuple [ int , ... ] : return tuple ( bins . bin_count for bins in self . _binnings )
| 1 |
number of bins in python histogram
|
Shape of histogram s data .
|
cosqa-train-19343
|
def shape(self) -> Tuple[int, ...]:
"""Shape of histogram's data.
Returns
-------
One-element tuple with the number of bins along each axis.
"""
return tuple(bins.bin_count for bins in self._binnings)
|
def memory_read ( self , start_position : int , size : int ) -> memoryview : return self . _memory . read ( start_position , size )
| 1 |
python memoryview to structure
|
Read and return a view of size bytes from memory starting at start_position .
|
cosqa-train-19344
|
def memory_read(self, start_position: int, size: int) -> memoryview:
"""
Read and return a view of ``size`` bytes from memory starting at ``start_position``.
"""
return self._memory.read(start_position, size)
|
def _cnx_is_empty ( in_file ) : with open ( in_file ) as in_handle : for i , line in enumerate ( in_handle ) : if i > 0 : return False return True
| 1 |
how to check for empty file python
|
Check if cnr or cns files are empty ( only have a header )
|
cosqa-train-19345
|
def _cnx_is_empty(in_file):
"""Check if cnr or cns files are empty (only have a header)
"""
with open(in_file) as in_handle:
for i, line in enumerate(in_handle):
if i > 0:
return False
return True
|
def list_depth ( list_ , func = max , _depth = 0 ) : depth_list = [ list_depth ( item , func = func , _depth = _depth + 1 ) for item in list_ if util_type . is_listlike ( item ) ] if len ( depth_list ) > 0 : return func ( depth_list ) else : return _depth
| 1 |
finding the max depth of list python
|
Returns the deepest level of nesting within a list of lists
|
cosqa-train-19346
|
def list_depth(list_, func=max, _depth=0):
"""
Returns the deepest level of nesting within a list of lists
Args:
list_ : a nested listlike object
func : depth aggregation strategy (defaults to max)
_depth : internal var
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [[[[[1]]], [3]], [[1], [3]], [[1], [3]]]
>>> result = (list_depth(list_, _depth=0))
>>> print(result)
"""
depth_list = [list_depth(item, func=func, _depth=_depth + 1)
for item in list_ if util_type.is_listlike(item)]
if len(depth_list) > 0:
return func(depth_list)
else:
return _depth
|
def _isint ( string ) : return type ( string ) is int or ( isinstance ( string , _binary_type ) or isinstance ( string , _text_type ) ) and _isconvertible ( int , string )
| 0 |
python test if string is an int
|
>>> _isint ( 123 ) True >>> _isint ( 123 . 45 ) False
|
cosqa-train-19347
|
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 is_any_type_set ( sett : Set [ Type ] ) -> bool : return len ( sett ) == 1 and is_any_type ( min ( sett ) )
| 1 |
check if a set is empty in python
|
Helper method to check if a set of types is the { AnyObject } singleton
|
cosqa-train-19348
|
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 csv_to_numpy ( string_like , dtype = None ) : # type: (str) -> np.array stream = StringIO ( string_like ) return np . genfromtxt ( stream , dtype = dtype , delimiter = ',' )
| 1 |
python csv to np array
|
Convert a CSV object to a numpy array .
|
cosqa-train-19349
|
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 stop ( self ) -> None : if self . _stop and not self . _posted_kork : self . _stop ( ) self . _stop = None
| 1 |
stop running function and passing to other variable python
|
Stops the analysis as soon as possible .
|
cosqa-train-19350
|
def stop(self) -> None:
"""Stops the analysis as soon as possible."""
if self._stop and not self._posted_kork:
self._stop()
self._stop = None
|
def proper_round ( n ) : return int ( n ) + ( n / abs ( n ) ) * int ( abs ( n - int ( n ) ) >= 0.5 ) if n != 0 else 0
| 1 |
round to the nearest in python
|
rounds float to closest int : rtype : int : param n : float
|
cosqa-train-19351
|
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
|
def _my_hash ( arg_list ) : # type: (List[Any]) -> int res = 0 for arg in arg_list : res = res * 31 + hash ( arg ) return res
| 1 |
python hash return int number
|
Simple helper hash function
|
cosqa-train-19352
|
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 _check_whitespace ( string ) : if string . count ( ' ' ) + string . count ( '\t' ) + string . count ( '\n' ) > 0 : raise ValueError ( INSTRUCTION_HAS_WHITESPACE )
| 0 |
how to tell if a string holds a whitespace in python
|
Make sure thre is no whitespace in the given string . Will raise a ValueError if whitespace is detected
|
cosqa-train-19353
|
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 proper_round ( n ) : return int ( n ) + ( n / abs ( n ) ) * int ( abs ( n - int ( n ) ) >= 0.5 ) if n != 0 else 0
| 0 |
how to round to the nearest ten in python
|
rounds float to closest int : rtype : int : param n : float
|
cosqa-train-19354
|
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
|
def dtypes ( self ) : return [ ( str ( f . name ) , f . dataType . simpleString ( ) ) for f in self . schema . fields ]
| 0 |
get dtypes of columns python
|
Returns all column names and their data types as a list .
|
cosqa-train-19355
|
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]
|
async def executemany ( self , sql : str , parameters : Iterable [ Iterable [ Any ] ] ) -> None : await self . _execute ( self . _cursor . executemany , sql , parameters )
| 1 |
python 3 executemany many columns
|
Execute the given multiquery .
|
cosqa-train-19356
|
async def executemany(self, sql: str, parameters: Iterable[Iterable[Any]]) -> None:
"""Execute the given multiquery."""
await self._execute(self._cursor.executemany, sql, parameters)
|
def get_domain ( url ) : parse_result = urlparse ( url ) domain = "{schema}://{netloc}" . format ( schema = parse_result . scheme , netloc = parse_result . netloc ) return domain
| 1 |
python urlparse get domain
|
Get domain part of an url .
|
cosqa-train-19357
|
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 pluralize ( word ) : if not word or word . lower ( ) in UNCOUNTABLES : return word else : for rule , replacement in PLURALS : if re . search ( rule , word ) : return re . sub ( rule , replacement , word ) return word
| 0 |
python pattern pluralize word
|
Return the plural form of a word .
|
cosqa-train-19358
|
def pluralize(word):
"""
Return the plural form of a word.
Examples::
>>> pluralize("post")
"posts"
>>> pluralize("octopus")
"octopi"
>>> pluralize("sheep")
"sheep"
>>> pluralize("CamelOctopus")
"CamelOctopi"
"""
if not word or word.lower() in UNCOUNTABLES:
return word
else:
for rule, replacement in PLURALS:
if re.search(rule, word):
return re.sub(rule, replacement, word)
return word
|
def method_caller ( method_name , * args , * * kwargs ) : def call_method ( target ) : func = getattr ( target , method_name ) return func ( * args , * * kwargs ) return call_method
| 1 |
python call built in function using its string name
|
Return a function that will call a named method on the target object with optional positional and keyword arguments .
|
cosqa-train-19359
|
def method_caller(method_name, *args, **kwargs):
"""
Return a function that will call a named method on the
target object with optional positional and keyword
arguments.
>>> lower = method_caller('lower')
>>> lower('MyString')
'mystring'
"""
def call_method(target):
func = getattr(target, method_name)
return func(*args, **kwargs)
return call_method
|
async def parallel_results ( future_map : Sequence [ Tuple ] ) -> Dict : ctx_methods = OrderedDict ( future_map ) fs = list ( ctx_methods . values ( ) ) results = await asyncio . gather ( * fs ) results = { key : results [ idx ] for idx , key in enumerate ( ctx_methods . keys ( ) ) } return results
| 0 |
python future asyncio multiple tbreads
|
Run parallel execution of futures and return mapping of their results to the provided keys . Just a neat shortcut around asyncio . gather ()
|
cosqa-train-19360
|
async def parallel_results(future_map: Sequence[Tuple]) -> Dict:
"""
Run parallel execution of futures and return mapping of their results to the provided keys.
Just a neat shortcut around ``asyncio.gather()``
:param future_map: Keys to futures mapping, e.g.: ( ('nav', get_nav()), ('content, get_content()) )
:return: Dict with futures results mapped to keys {'nav': {1:2}, 'content': 'xyz'}
"""
ctx_methods = OrderedDict(future_map)
fs = list(ctx_methods.values())
results = await asyncio.gather(*fs)
results = {
key: results[idx] for idx, key in enumerate(ctx_methods.keys())
}
return results
|
def positive_int ( val ) : if isinstance ( val , float ) : raise ValueError ( '"{}" must not be a float' . format ( val ) ) val = int ( val ) if val >= 0 : return val raise ValueError ( '"{}" must be positive' . format ( val ) )
| 1 |
how to cast a float as an int in python
|
Parse val into a positive integer .
|
cosqa-train-19361
|
def positive_int(val):
"""Parse `val` into a positive integer."""
if isinstance(val, float):
raise ValueError('"{}" must not be a float'.format(val))
val = int(val)
if val >= 0:
return val
raise ValueError('"{}" must be positive'.format(val))
|
def chars ( string : any ) -> str : return '' . join ( [ c if c . isalpha ( ) else '' for c in str ( string ) ] )
| 0 |
python determine if string is all alpha
|
Return all ( and only ) the chars in the given string .
|
cosqa-train-19362
|
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 branches ( ) : # type: () -> List[str] out = shell . run ( 'git branch' , capture = True , never_pretend = True ) . stdout . strip ( ) return [ x . strip ( '* \t\n' ) for x in out . splitlines ( ) ]
| 1 |
python list git branches
|
Return a list of branches in the current repo .
|
cosqa-train-19363
|
def branches():
# type: () -> List[str]
""" Return a list of branches in the current repo.
Returns:
list[str]: A list of branches in the current repo.
"""
out = shell.run(
'git branch',
capture=True,
never_pretend=True
).stdout.strip()
return [x.strip('* \t\n') for x in out.splitlines()]
|
def genfirstvalues ( cursor : Cursor , arraysize : int = 1000 ) -> Generator [ Any , None , None ] : return ( row [ 0 ] for row in genrows ( cursor , arraysize ) )
| 1 |
python how to select first 100 rows
|
Generate the first value in each row .
|
cosqa-train-19364
|
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 execute ( cur , * args ) : stmt = args [ 0 ] if len ( args ) > 1 : stmt = stmt . replace ( '%' , '%%' ) . replace ( '?' , '%r' ) print ( stmt % ( args [ 1 ] ) ) return cur . execute ( * args )
| 0 |
sql like % in python
|
Utility function to print sqlite queries before executing .
|
cosqa-train-19365
|
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 signed_area ( coords ) : xs , ys = map ( list , zip ( * coords ) ) xs . append ( xs [ 1 ] ) ys . append ( ys [ 1 ] ) return sum ( xs [ i ] * ( ys [ i + 1 ] - ys [ i - 1 ] ) for i in range ( 1 , len ( coords ) ) ) / 2.0
| 0 |
calculate the area under a curve python
|
Return the signed area enclosed by a ring using the linear time algorithm . A value > = 0 indicates a counter - clockwise oriented ring .
|
cosqa-train-19366
|
def signed_area(coords):
"""Return the signed area enclosed by a ring using the linear time
algorithm. A value >= 0 indicates a counter-clockwise oriented ring.
"""
xs, ys = map(list, zip(*coords))
xs.append(xs[1])
ys.append(ys[1])
return sum(xs[i]*(ys[i+1]-ys[i-1]) for i in range(1, len(coords)))/2.0
|
def _cnx_is_empty ( in_file ) : with open ( in_file ) as in_handle : for i , line in enumerate ( in_handle ) : if i > 0 : return False return True
| 1 |
how to check a file is empty in python
|
Check if cnr or cns files are empty ( only have a header )
|
cosqa-train-19367
|
def _cnx_is_empty(in_file):
"""Check if cnr or cns files are empty (only have a header)
"""
with open(in_file) as in_handle:
for i, line in enumerate(in_handle):
if i > 0:
return False
return True
|
def classify_fit ( fqdn , result , * argl , * * argd ) : if len ( argl ) > 2 : #Usually fit is called with fit(machine, Xtrain, ytrain). yP = argl [ 2 ] out = _generic_fit ( fqdn , result , classify_predict , yP , * argl , * * argd ) return out
| 0 |
python keras fit method checkpoints
|
Analyzes the result of a classification algorithm s fitting . See also : func : fit for explanation of arguments .
|
cosqa-train-19368
|
def classify_fit(fqdn, result, *argl, **argd):
"""Analyzes the result of a classification algorithm's fitting. See also
:func:`fit` for explanation of arguments.
"""
if len(argl) > 2:
#Usually fit is called with fit(machine, Xtrain, ytrain).
yP = argl[2]
out = _generic_fit(fqdn, result, classify_predict, yP, *argl, **argd)
return out
|
def thai_to_eng ( text : str ) -> str : return "" . join ( [ TH_EN_KEYB_PAIRS [ ch ] if ( ch in TH_EN_KEYB_PAIRS ) else ch for ch in text ] )
| 1 |
python how to detect english words
|
Correct text in one language that is incorrectly - typed with a keyboard layout in another language . ( type Thai with English keyboard )
|
cosqa-train-19369
|
def thai_to_eng(text: str) -> str:
"""
Correct text in one language that is incorrectly-typed with a keyboard layout in another language. (type Thai with English keyboard)
:param str text: Incorrect input (type English with Thai keyboard)
:return: English text
"""
return "".join(
[TH_EN_KEYB_PAIRS[ch] if (ch in TH_EN_KEYB_PAIRS) else ch for ch in text]
)
|
def file_or_stdin ( ) -> Callable : def parse ( path ) : if path is None or path == "-" : return sys . stdin else : return data_io . smart_open ( path ) return parse
| 0 |
how to receive the path of a file as a user input on python
|
Returns a file descriptor from stdin or opening a file from a given path .
|
cosqa-train-19370
|
def file_or_stdin() -> Callable:
"""
Returns a file descriptor from stdin or opening a file from a given path.
"""
def parse(path):
if path is None or path == "-":
return sys.stdin
else:
return data_io.smart_open(path)
return parse
|
def str_to_time ( time_str : str ) -> datetime . datetime : pieces : Any = [ int ( piece ) for piece in time_str . split ( '-' ) ] return datetime . datetime ( * pieces )
| 1 |
python str to dateal time
|
Convert human readable string to datetime . datetime .
|
cosqa-train-19371
|
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 _run_sync ( self , method : Callable , * args , * * kwargs ) -> Any : if self . loop . is_running ( ) : raise RuntimeError ( "Event loop is already running." ) if not self . is_connected : self . loop . run_until_complete ( self . connect ( ) ) task = asyncio . Task ( method ( * args , * * kwargs ) , loop = self . loop ) result = self . loop . run_until_complete ( task ) self . loop . run_until_complete ( self . quit ( ) ) return result
| 1 |
python async run in
|
Utility method to run commands synchronously for testing .
|
cosqa-train-19372
|
def _run_sync(self, method: Callable, *args, **kwargs) -> Any:
"""
Utility method to run commands synchronously for testing.
"""
if self.loop.is_running():
raise RuntimeError("Event loop is already running.")
if not self.is_connected:
self.loop.run_until_complete(self.connect())
task = asyncio.Task(method(*args, **kwargs), loop=self.loop)
result = self.loop.run_until_complete(task)
self.loop.run_until_complete(self.quit())
return result
|
def file_exists ( fname ) : try : return fname and os . path . exists ( fname ) and os . path . getsize ( fname ) > 0 except OSError : return False
| 0 |
check if a file with certain extension exist in python
|
Check if a file exists and is non - empty .
|
cosqa-train-19373
|
def file_exists(fname):
"""Check if a file exists and is non-empty.
"""
try:
return fname and os.path.exists(fname) and os.path.getsize(fname) > 0
except OSError:
return False
|
def is_relative_url ( url ) : if url . startswith ( "#" ) : return None if url . find ( "://" ) > 0 or url . startswith ( "//" ) : # either 'http(s)://...' or '//cdn...' and therefore absolute return False return True
| 0 |
python determine if path is relative or abso
|
simple method to determine if a url is relative or absolute
|
cosqa-train-19374
|
def is_relative_url(url):
""" simple method to determine if a url is relative or absolute """
if url.startswith("#"):
return None
if url.find("://") > 0 or url.startswith("//"):
# either 'http(s)://...' or '//cdn...' and therefore absolute
return False
return True
|
def most_frequent ( lst ) : lst = lst [ : ] highest_freq = 0 most_freq = None for val in unique ( lst ) : if lst . count ( val ) > highest_freq : most_freq = val highest_freq = lst . count ( val ) return most_freq
| 1 |
python most frequent element in list
|
Returns the item that appears most frequently in the given list .
|
cosqa-train-19375
|
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 arcball_map_to_sphere ( point , center , radius ) : v0 = ( point [ 0 ] - center [ 0 ] ) / radius v1 = ( center [ 1 ] - point [ 1 ] ) / radius n = v0 * v0 + v1 * v1 if n > 1.0 : # position outside of sphere n = math . sqrt ( n ) return numpy . array ( [ v0 / n , v1 / n , 0.0 ] ) else : return numpy . array ( [ v0 , v1 , math . sqrt ( 1.0 - n ) ] )
| 1 |
create sphere through data points in python
|
Return unit sphere coordinates from window coordinates .
|
cosqa-train-19376
|
def arcball_map_to_sphere(point, center, radius):
"""Return unit sphere coordinates from window coordinates."""
v0 = (point[0] - center[0]) / radius
v1 = (center[1] - point[1]) / radius
n = v0*v0 + v1*v1
if n > 1.0:
# position outside of sphere
n = math.sqrt(n)
return numpy.array([v0/n, v1/n, 0.0])
else:
return numpy.array([v0, v1, math.sqrt(1.0 - n)])
|
def _my_hash ( arg_list ) : # type: (List[Any]) -> int res = 0 for arg in arg_list : res = res * 31 + hash ( arg ) return res
| 0 |
python hash a int value
|
Simple helper hash function
|
cosqa-train-19377
|
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 __gt__ ( self , other ) : if isinstance ( other , Address ) : return str ( self ) > str ( other ) raise TypeError
| 0 |
python using greater than with strings
|
Test for greater than .
|
cosqa-train-19378
|
def __gt__(self, other):
"""Test for greater than."""
if isinstance(other, Address):
return str(self) > str(other)
raise TypeError
|
def flatten_list ( x : List [ Any ] ) -> List [ Any ] : # noqa return [ item for sublist in x for item in sublist ]
| 1 |
flatten a list of lists in python irregular simple
|
Converts a list of lists into a flat list . Args : x : list of lists
|
cosqa-train-19379
|
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 mmap ( func , iterable ) : if sys . version_info [ 0 ] > 2 : return [ i for i in map ( func , iterable ) ] else : return map ( func , iterable )
| 0 |
python3 apply function to each list element
|
Wrapper to make map () behave the same on Py2 and Py3 .
|
cosqa-train-19380
|
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 dictlist_wipe_key ( dict_list : Iterable [ Dict ] , key : str ) -> None : for d in dict_list : d . pop ( key , None )
| 1 |
how to delete an element in a python dictionary
|
Process an iterable of dictionaries . For each dictionary d delete d [ key ] if it exists .
|
cosqa-train-19381
|
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 iter_lines ( file_like : Iterable [ str ] ) -> Generator [ str , None , None ] : for line in file_like : line = line . rstrip ( '\r\n' ) if line : yield line
| 0 |
python readlines skip blank lines
|
Helper for iterating only nonempty lines without line breaks
|
cosqa-train-19382
|
def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]:
""" Helper for iterating only nonempty lines without line breaks"""
for line in file_like:
line = line.rstrip('\r\n')
if line:
yield line
|
def rank ( tensor : BKTensor ) -> int : if isinstance ( tensor , np . ndarray ) : return len ( tensor . shape ) return len ( tensor [ 0 ] . size ( ) )
| 0 |
show tensor shape python
|
Return the number of dimensions of a tensor
|
cosqa-train-19383
|
def rank(tensor: BKTensor) -> int:
"""Return the number of dimensions of a tensor"""
if isinstance(tensor, np.ndarray):
return len(tensor.shape)
return len(tensor[0].size())
|
def uppercase_chars ( string : any ) -> str : return '' . join ( [ c if c . isupper ( ) else '' for c in str ( string ) ] )
| 1 |
make string all uppercase python
|
Return all ( and only ) the uppercase chars in the given string .
|
cosqa-train-19384
|
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 to_bytes ( data : Any ) -> bytearray : # noqa if isinstance ( data , int ) : return bytearray ( [ data ] ) return bytearray ( data , encoding = 'latin-1' )
| 0 |
can you cast a python list to a 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-19385
|
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 truncate ( value : Decimal , n_digits : int ) -> Decimal : return Decimal ( math . trunc ( value * ( 10 ** n_digits ) ) ) / ( 10 ** n_digits )
| 1 |
truncate float two decimals python
|
Truncates a value to a number of decimals places
|
cosqa-train-19386
|
def truncate(value: Decimal, n_digits: int) -> Decimal:
"""Truncates a value to a number of decimals places"""
return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)
|
def dictlist_wipe_key ( dict_list : Iterable [ Dict ] , key : str ) -> None : for d in dict_list : d . pop ( key , None )
| 1 |
delete an element from a dictionary python
|
Process an iterable of dictionaries . For each dictionary d delete d [ key ] if it exists .
|
cosqa-train-19387
|
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 flatten_list ( l : List [ list ] ) -> list : return [ v for inner_l in l for v in inner_l ]
| 1 |
python list comprehension flatten
|
takes a list of lists l and returns a flat list
|
cosqa-train-19388
|
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 impose_legend_limit ( limit = 30 , axes = "gca" , * * kwargs ) : if axes == "gca" : axes = _pylab . gca ( ) # make these axes current _pylab . axes ( axes ) # loop over all the lines_pylab. for n in range ( 0 , len ( axes . lines ) ) : if n > limit - 1 and not n == len ( axes . lines ) - 1 : axes . lines [ n ] . set_label ( "_nolegend_" ) if n == limit - 1 and not n == len ( axes . lines ) - 1 : axes . lines [ n ] . set_label ( "..." ) _pylab . legend ( * * kwargs )
| 0 |
how to remove first line from legend matplotlib python
|
This will erase all but say 30 of the legend entries and remake the legend . You ll probably have to move it back into your favorite position at this point .
|
cosqa-train-19389
|
def impose_legend_limit(limit=30, axes="gca", **kwargs):
"""
This will erase all but, say, 30 of the legend entries and remake the legend.
You'll probably have to move it back into your favorite position at this point.
"""
if axes=="gca": axes = _pylab.gca()
# make these axes current
_pylab.axes(axes)
# loop over all the lines_pylab.
for n in range(0,len(axes.lines)):
if n > limit-1 and not n==len(axes.lines)-1: axes.lines[n].set_label("_nolegend_")
if n == limit-1 and not n==len(axes.lines)-1: axes.lines[n].set_label("...")
_pylab.legend(**kwargs)
|
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 |
python argparse script docstring
|
docstring for argparse
|
cosqa-train-19390
|
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 header_status ( header ) : status_line = header [ : header . find ( '\r' ) ] # 'HTTP/1.1 200 OK' -> (200, 'OK') fields = status_line . split ( None , 2 ) return int ( fields [ 1 ] ) , fields [ 2 ]
| 0 |
python parse http status line, header line
|
Parse HTTP status line return status ( int ) and reason .
|
cosqa-train-19391
|
def header_status(header):
"""Parse HTTP status line, return status (int) and reason."""
status_line = header[:header.find('\r')]
# 'HTTP/1.1 200 OK' -> (200, 'OK')
fields = status_line.split(None, 2)
return int(fields[1]), fields[2]
|
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 lambda map
|
Wrapper to make map () behave the same on Py2 and Py3 .
|
cosqa-train-19392
|
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 lower_camel_case_from_underscores ( string ) : components = string . split ( '_' ) string = components [ 0 ] for component in components [ 1 : ] : string += component [ 0 ] . upper ( ) + component [ 1 : ] return string
| 1 |
how does underscore hide in python
|
generate a lower - cased camelCase string from an underscore_string . For example : my_variable_name - > myVariableName
|
cosqa-train-19393
|
def lower_camel_case_from_underscores(string):
"""generate a lower-cased camelCase string from an underscore_string.
For example: my_variable_name -> myVariableName"""
components = string.split('_')
string = components[0]
for component in components[1:]:
string += component[0].upper() + component[1:]
return string
|
def get_keys_of_max_n ( dict_obj , n ) : return sorted ( [ item [ 0 ] for item in sorted ( dict_obj . items ( ) , key = lambda item : item [ 1 ] , reverse = True ) [ : n ] ] )
| 0 |
python top n elements of sorted dictionary
|
Returns the keys that maps to the top n max values in the given dict .
|
cosqa-train-19394
|
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 strtobytes ( input , encoding ) : py_version = sys . version_info [ 0 ] if py_version >= 3 : return _strtobytes_py3 ( input , encoding ) return _strtobytes_py2 ( input , encoding )
| 1 |
python2 python3 bytes strings
|
Take a str and transform it into a byte array .
|
cosqa-train-19395
|
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 months_ago ( date , nb_months = 1 ) : nb_years = nb_months // 12 nb_months = nb_months % 12 month_diff = date . month - nb_months if month_diff > 0 : new_month = month_diff else : new_month = 12 + month_diff nb_years += 1 return date . replace ( day = 1 , month = new_month , year = date . year - nb_years )
| 1 |
subtract months from date python\
|
Return the given date with nb_months substracted from it .
|
cosqa-train-19396
|
def months_ago(date, nb_months=1):
"""
Return the given `date` with `nb_months` substracted from it.
"""
nb_years = nb_months // 12
nb_months = nb_months % 12
month_diff = date.month - nb_months
if month_diff > 0:
new_month = month_diff
else:
new_month = 12 + month_diff
nb_years += 1
return date.replace(day=1, month=new_month, year=date.year - nb_years)
|
def cmd_dot ( conf : Config ) : build_context = BuildContext ( conf ) populate_targets_graph ( build_context , conf ) if conf . output_dot_file is None : write_dot ( build_context , conf , sys . stdout ) else : with open ( conf . output_dot_file , 'w' ) as out_file : write_dot ( build_context , conf , out_file )
| 1 |
graph viz python dot executable
|
Print out a neat targets dependency tree based on requested targets .
|
cosqa-train-19397
|
def cmd_dot(conf: Config):
"""Print out a neat targets dependency tree based on requested targets.
Use graphviz to render the dot file, e.g.:
> ybt dot :foo :bar | dot -Tpng -o graph.png
"""
build_context = BuildContext(conf)
populate_targets_graph(build_context, conf)
if conf.output_dot_file is None:
write_dot(build_context, conf, sys.stdout)
else:
with open(conf.output_dot_file, 'w') as out_file:
write_dot(build_context, conf, out_file)
|
def normalize ( numbers ) : total = float ( sum ( numbers ) ) return [ n / total for n in numbers ]
| 1 |
how to multiply every value in a list by a constant python
|
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-19398
|
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 iter_lines ( file_like : Iterable [ str ] ) -> Generator [ str , None , None ] : for line in file_like : line = line . rstrip ( '\r\n' ) if line : yield line
| 0 |
python readline skip blank line
|
Helper for iterating only nonempty lines without line breaks
|
cosqa-train-19399
|
def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]:
""" Helper for iterating only nonempty lines without line breaks"""
for line in file_like:
line = line.rstrip('\r\n')
if line:
yield line
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.