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 get_case_insensitive_dict_key ( d : Dict , k : str ) -> Optional [ str ] : for key in d . keys ( ) : if k . lower ( ) == key . lower ( ) : return key return None
| 0 |
case independent lookup in python dictionary
|
Within the dictionary d find a key that matches ( in case - insensitive fashion ) the key k and return it ( or None if there isn t one ) .
|
cosqa-train-17900
|
def get_case_insensitive_dict_key(d: Dict, k: str) -> Optional[str]:
"""
Within the dictionary ``d``, find a key that matches (in case-insensitive
fashion) the key ``k``, and return it (or ``None`` if there isn't one).
"""
for key in d.keys():
if k.lower() == key.lower():
return key
return None
|
def find_index ( segmentation , stroke_id ) : for i , symbol in enumerate ( segmentation ) : for sid in symbol : if sid == stroke_id : return i return - 1
| 1 |
python retrive list index based on its content
|
>>> find_index ( [[ 0 1 2 ] [ 3 4 ] [ 5 6 7 ]] 0 ) 0 >>> find_index ( [[ 0 1 2 ] [ 3 4 ] [ 5 6 7 ]] 1 ) 0 >>> find_index ( [[ 0 1 2 ] [ 3 4 ] [ 5 6 7 ]] 5 ) 2 >>> find_index ( [[ 0 1 2 ] [ 3 4 ] [ 5 6 7 ]] 6 ) 2
|
cosqa-train-17901
|
def find_index(segmentation, stroke_id):
"""
>>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 0)
0
>>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 1)
0
>>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 5)
2
>>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 6)
2
"""
for i, symbol in enumerate(segmentation):
for sid in symbol:
if sid == stroke_id:
return i
return -1
|
def from_file ( file_path ) -> dict : with io . open ( file_path , 'r' , encoding = 'utf-8' ) as json_stream : return Json . parse ( json_stream , True )
| 0 |
python read json from file into dictionary
|
Load JSON file
|
cosqa-train-17902
|
def from_file(file_path) -> dict:
""" Load JSON file """
with io.open(file_path, 'r', encoding='utf-8') as json_stream:
return Json.parse(json_stream, True)
|
def inverted_dict ( d ) : return dict ( ( force_hashable ( v ) , k ) for ( k , v ) in viewitems ( dict ( d ) ) )
| 0 |
python how to make an inverted dictionary
|
Return a dict with swapped keys and values
|
cosqa-train-17903
|
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 most_significant_bit ( lst : np . ndarray ) -> int : return np . argwhere ( np . asarray ( lst ) == 1 ) [ 0 ] [ 0 ]
| 1 |
get index of first true in array python
|
A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s i . e . the first position where a 1 appears reading left to right .
|
cosqa-train-17904
|
def most_significant_bit(lst: np.ndarray) -> int:
"""
A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,
i.e. the first position where a 1 appears, reading left to right.
:param lst: a 1d array of 0s and 1s with at least one 1
:return: the first position in lst that a 1 appears
"""
return np.argwhere(np.asarray(lst) == 1)[0][0]
|
def pack_bits ( longbits ) : byte = longbits & ( 0x0101010101010101 ) byte = ( byte | ( byte >> 7 ) ) & ( 0x0003000300030003 ) byte = ( byte | ( byte >> 14 ) ) & ( 0x0000000f0000000f ) byte = ( byte | ( byte >> 28 ) ) & ( 0x00000000000000ff ) return byte
| 0 |
truncate first 32 bits in python
|
Crunch a 64 - bit int ( 8 bool bytes ) into a bitfield .
|
cosqa-train-17905
|
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 check_oneof ( * * kwargs ) : # Sanity check: If no keyword arguments were sent, this is fine. if not kwargs : return None not_nones = [ val for val in kwargs . values ( ) if val is not None ] if len ( not_nones ) > 1 : raise ValueError ( 'Only one of {fields} should be set.' . format ( fields = ', ' . join ( sorted ( kwargs . keys ( ) ) ) , ) )
| 0 |
python check if kargs empty
|
Raise ValueError if more than one keyword argument is not none .
|
cosqa-train-17906
|
def check_oneof(**kwargs):
"""Raise ValueError if more than one keyword argument is not none.
Args:
kwargs (dict): The keyword arguments sent to the function.
Returns: None
Raises:
ValueError: If more than one entry in kwargs is not none.
"""
# Sanity check: If no keyword arguments were sent, this is fine.
if not kwargs:
return None
not_nones = [val for val in kwargs.values() if val is not None]
if len(not_nones) > 1:
raise ValueError('Only one of {fields} should be set.'.format(
fields=', '.join(sorted(kwargs.keys())),
))
|
def check_lengths ( * arrays ) : lengths = [ len ( array ) for array in arrays ] if len ( np . unique ( lengths ) ) > 1 : raise ValueError ( 'Inconsistent data lengths: {}' . format ( lengths ) )
| 1 |
python check if certain length of input equals something
|
tool to ensure input and output data have the same number of samples
|
cosqa-train-17907
|
def check_lengths(*arrays):
"""
tool to ensure input and output data have the same number of samples
Parameters
----------
*arrays : iterable of arrays to be checked
Returns
-------
None
"""
lengths = [len(array) for array in arrays]
if len(np.unique(lengths)) > 1:
raise ValueError('Inconsistent data lengths: {}'.format(lengths))
|
def grep ( pattern , filename ) : try : # for line in file # if line matches pattern: # return line return next ( ( L for L in open ( filename ) if L . find ( pattern ) >= 0 ) ) except StopIteration : return ''
| 1 |
in python how do you use grep in a file
|
Very simple grep that returns the first matching line in a file . String matching only does not do REs as currently implemented .
|
cosqa-train-17908
|
def grep(pattern, filename):
"""Very simple grep that returns the first matching line in a file.
String matching only, does not do REs as currently implemented.
"""
try:
# for line in file
# if line matches pattern:
# return line
return next((L for L in open(filename) if L.find(pattern) >= 0))
except StopIteration:
return ''
|
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 code in strings in python
|
Utility function to print sqlite queries before executing .
|
cosqa-train-17909
|
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 butlast ( iterable ) : iterable = iter ( iterable ) try : first = next ( iterable ) except StopIteration : return for second in iterable : yield first first = second
| 0 |
python code for last in list
|
Yield all items from iterable except the last one .
|
cosqa-train-17910
|
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 prin ( * args , * * kwargs ) : print >> kwargs . get ( 'out' , None ) , " " . join ( [ str ( arg ) for arg in args ] )
| 1 |
python print *args keys
|
r Like print but a function . I . e . prints out all arguments as print would do . Specify output stream like this ::
|
cosqa-train-17911
|
def prin(*args, **kwargs):
r"""Like ``print``, but a function. I.e. prints out all arguments as
``print`` would do. Specify output stream like this::
print('ERROR', `out="sys.stderr"``).
"""
print >> kwargs.get('out',None), " ".join([str(arg) for arg in args])
|
def camelize ( key ) : return '' . join ( x . capitalize ( ) if i > 0 else x for i , x in enumerate ( key . split ( '_' ) ) )
| 0 |
capitalizing the first letter of a variable in python
|
Convert a python_style_variable_name to lowerCamelCase .
|
cosqa-train-17912
|
def camelize(key):
"""Convert a python_style_variable_name to lowerCamelCase.
Examples
--------
>>> camelize('variable_name')
'variableName'
>>> camelize('variableName')
'variableName'
"""
return ''.join(x.capitalize() if i > 0 else x
for i, x in enumerate(key.split('_')))
|
def mmap ( func , iterable ) : if sys . version_info [ 0 ] > 2 : return [ i for i in map ( func , iterable ) ] else : return map ( func , iterable )
| 0 |
map function between python2 and python3
|
Wrapper to make map () behave the same on Py2 and Py3 .
|
cosqa-train-17913
|
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 __init__ ( self , enum_obj : Any ) -> None : if enum_obj : self . name = enum_obj self . items = ', ' . join ( [ str ( i ) for i in enum_obj ] ) else : self . items = ''
| 0 |
enum python print name instead of object by default
|
Initialize attributes for informative output .
|
cosqa-train-17914
|
def __init__(self, enum_obj: Any) -> None:
"""Initialize attributes for informative output.
:param enum_obj: Enum object.
"""
if enum_obj:
self.name = enum_obj
self.items = ', '.join([str(i) for i in enum_obj])
else:
self.items = ''
|
def fast_median ( a ) : a = checkma ( a ) #return scoreatpercentile(a.compressed(), 50) if a . count ( ) > 0 : out = np . percentile ( a . compressed ( ) , 50 ) else : out = np . ma . masked return out
| 0 |
python scikit median of array
|
Fast median operation for masked array using 50th - percentile
|
cosqa-train-17915
|
def fast_median(a):
"""Fast median operation for masked array using 50th-percentile
"""
a = checkma(a)
#return scoreatpercentile(a.compressed(), 50)
if a.count() > 0:
out = np.percentile(a.compressed(), 50)
else:
out = np.ma.masked
return out
|
def dtypes ( self ) : return [ ( str ( f . name ) , f . dataType . simpleString ( ) ) for f in self . schema . fields ]
| 1 |
how to get the datatypes in python
|
Returns all column names and their data types as a list .
|
cosqa-train-17916
|
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 _groups_of_size ( iterable , n , fillvalue = None ) : # _groups_of_size('ABCDEFG', 3, 'x') --> ABC DEF Gxx args = [ iter ( iterable ) ] * n return zip_longest ( fillvalue = fillvalue , * args )
| 0 |
maximum size of iterable python
|
Collect data into fixed - length chunks or blocks .
|
cosqa-train-17917
|
def _groups_of_size(iterable, n, fillvalue=None):
"""Collect data into fixed-length chunks or blocks."""
# _groups_of_size('ABCDEFG', 3, 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return zip_longest(fillvalue=fillvalue, *args)
|
def get_versions ( reporev = True ) : import sys import platform import qtpy import qtpy . QtCore revision = None if reporev : from spyder . utils import vcs revision , branch = vcs . get_git_revision ( os . path . dirname ( __dir__ ) ) if not sys . platform == 'darwin' : # To avoid a crash with our Mac app system = platform . system ( ) else : system = 'Darwin' return { 'spyder' : __version__ , 'python' : platform . python_version ( ) , # "2.7.3" 'bitness' : 64 if sys . maxsize > 2 ** 32 else 32 , 'qt' : qtpy . QtCore . __version__ , 'qt_api' : qtpy . API_NAME , # PyQt5 'qt_api_ver' : qtpy . PYQT_VERSION , 'system' : system , # Linux, Windows, ... 'release' : platform . release ( ) , # XP, 10.6, 2.2.0, etc. 'revision' : revision , # '9fdf926eccce' }
| 0 |
spyder change from python 2 to 2
|
Get version information for components used by Spyder
|
cosqa-train-17918
|
def get_versions(reporev=True):
"""Get version information for components used by Spyder"""
import sys
import platform
import qtpy
import qtpy.QtCore
revision = None
if reporev:
from spyder.utils import vcs
revision, branch = vcs.get_git_revision(os.path.dirname(__dir__))
if not sys.platform == 'darwin': # To avoid a crash with our Mac app
system = platform.system()
else:
system = 'Darwin'
return {
'spyder': __version__,
'python': platform.python_version(), # "2.7.3"
'bitness': 64 if sys.maxsize > 2**32 else 32,
'qt': qtpy.QtCore.__version__,
'qt_api': qtpy.API_NAME, # PyQt5
'qt_api_ver': qtpy.PYQT_VERSION,
'system': system, # Linux, Windows, ...
'release': platform.release(), # XP, 10.6, 2.2.0, etc.
'revision': revision, # '9fdf926eccce'
}
|
def long_substring ( str_a , str_b ) : data = [ str_a , str_b ] substr = '' if len ( data ) > 1 and len ( data [ 0 ] ) > 0 : for i in range ( len ( data [ 0 ] ) ) : for j in range ( len ( data [ 0 ] ) - i + 1 ) : if j > len ( substr ) and all ( data [ 0 ] [ i : i + j ] in x for x in data ) : substr = data [ 0 ] [ i : i + j ] return substr . strip ( )
| 0 |
finding the similar part of two strings in python
|
Looks for a longest common string between any two given strings passed : param str_a : str : param str_b : str
|
cosqa-train-17919
|
def long_substring(str_a, str_b):
"""
Looks for a longest common string between any two given strings passed
:param str_a: str
:param str_b: str
Big Thanks to Pulkit Kathuria(@kevincobain2000) for the function
The function is derived from jProcessing toolkit suite
"""
data = [str_a, str_b]
substr = ''
if len(data) > 1 and len(data[0]) > 0:
for i in range(len(data[0])):
for j in range(len(data[0])-i+1):
if j > len(substr) and all(data[0][i:i+j] in x for x in data):
substr = data[0][i:i+j]
return substr.strip()
|
def is_finite ( value : Any ) -> bool : return isinstance ( value , int ) or ( isinstance ( value , float ) and isfinite ( value ) )
| 0 |
how to say if not isnumeric in python
|
Return true if a value is a finite number .
|
cosqa-train-17920
|
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 squash ( self , a , b ) : return ( ( '' . join ( x ) if isinstance ( x , tuple ) else x ) for x in itertools . product ( a , b ) )
| 0 |
all combinations of two iterables python list comprhension
|
Returns a generator that squashes two iterables into one .
|
cosqa-train-17921
|
def squash(self, a, b):
"""
Returns a generator that squashes two iterables into one.
```
['this', 'that'], [[' and', ' or']] => ['this and', 'this or', 'that and', 'that or']
```
"""
return ((''.join(x) if isinstance(x, tuple) else x) for x in itertools.product(a, b))
|
def SetCursorPos ( x : int , y : int ) -> bool : return bool ( ctypes . windll . user32 . SetCursorPos ( x , y ) )
| 1 |
python win32api mouse position
|
SetCursorPos from Win32 . Set mouse cursor to point x y . x : int . y : int . Return bool True if succeed otherwise False .
|
cosqa-train-17922
|
def SetCursorPos(x: int, y: int) -> bool:
"""
SetCursorPos from Win32.
Set mouse cursor to point x, y.
x: int.
y: int.
Return bool, True if succeed otherwise False.
"""
return bool(ctypes.windll.user32.SetCursorPos(x, y))
|
def uppercase_chars ( string : any ) -> str : return '' . join ( [ c if c . isupper ( ) else '' for c in str ( string ) ] )
| 1 |
who check upper case in python
|
Return all ( and only ) the uppercase chars in the given string .
|
cosqa-train-17923
|
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 normalize ( numbers ) : total = float ( sum ( numbers ) ) return [ n / total for n in numbers ]
| 1 |
how to normalize numbers with 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-17924
|
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 clean_map ( obj : Mapping [ Any , Any ] ) -> Mapping [ Any , Any ] : return { k : v for k , v in obj . items ( ) if v is not None }
| 0 |
python dictionary delete key with empty value
|
Return a new copied dictionary without the keys with None values from the given Mapping object .
|
cosqa-train-17925
|
def clean_map(obj: Mapping[Any, Any]) -> Mapping[Any, Any]:
"""
Return a new copied dictionary without the keys with ``None`` values from
the given Mapping object.
"""
return {k: v for k, v in obj.items() if v is not None}
|
def is_unicode ( string ) : str_type = str ( type ( string ) ) if str_type . find ( 'str' ) > 0 or str_type . find ( 'unicode' ) > 0 : return True return False
| 1 |
python check variable type is string
|
Validates that the object itself is some kinda string
|
cosqa-train-17926
|
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 pack_bits ( longbits ) : byte = longbits & ( 0x0101010101010101 ) byte = ( byte | ( byte >> 7 ) ) & ( 0x0003000300030003 ) byte = ( byte | ( byte >> 14 ) ) & ( 0x0000000f0000000f ) byte = ( byte | ( byte >> 28 ) ) & ( 0x00000000000000ff ) return byte
| 1 |
extract bits from large numbers python
|
Crunch a 64 - bit int ( 8 bool bytes ) into a bitfield .
|
cosqa-train-17927
|
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 wipe_table ( self , table : str ) -> int : sql = "DELETE FROM " + self . delimit ( table ) return self . db_exec ( sql )
| 1 |
python delete all rows from table sql
|
Delete all records from a table . Use caution!
|
cosqa-train-17928
|
def wipe_table(self, table: str) -> int:
"""Delete all records from a table. Use caution!"""
sql = "DELETE FROM " + self.delimit(table)
return self.db_exec(sql)
|
def year ( date ) : try : fmt = '%m/%d/%Y' return datetime . strptime ( date , fmt ) . timetuple ( ) . tm_year except ValueError : return 0
| 0 |
python return year from a date string
|
Returns the year .
|
cosqa-train-17929
|
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 _interface_exists ( self , interface ) : ios_cfg = self . _get_running_config ( ) parse = HTParser ( ios_cfg ) itfcs_raw = parse . find_lines ( "^interface " + interface ) return len ( itfcs_raw ) > 0
| 1 |
python detect interface existance
|
Check whether interface exists .
|
cosqa-train-17930
|
def _interface_exists(self, interface):
"""Check whether interface exists."""
ios_cfg = self._get_running_config()
parse = HTParser(ios_cfg)
itfcs_raw = parse.find_lines("^interface " + interface)
return len(itfcs_raw) > 0
|
def templategetter ( tmpl ) : tmpl = tmpl . replace ( '{' , '%(' ) tmpl = tmpl . replace ( '}' , ')s' ) return lambda data : tmpl % data
| 1 |
use template string in python to replcae later
|
This is a dirty little template function generator that turns single - brace Mustache - style template strings into functions that interpolate dict keys :
|
cosqa-train-17931
|
def templategetter(tmpl):
"""
This is a dirty little template function generator that turns single-brace
Mustache-style template strings into functions that interpolate dict keys:
>>> get_name = templategetter("{first} {last}")
>>> get_name({'first': 'Shawn', 'last': 'Allen'})
'Shawn Allen'
"""
tmpl = tmpl.replace('{', '%(')
tmpl = tmpl.replace('}', ')s')
return lambda data: tmpl % data
|
def timeit ( func , * args , * * kwargs ) : start_time = time . time ( ) res = func ( * args , * * kwargs ) timing = time . time ( ) - start_time return res , timing
| 0 |
calculating the time of a function python
|
Time execution of function . Returns ( res seconds ) .
|
cosqa-train-17932
|
def timeit(func, *args, **kwargs):
"""
Time execution of function. Returns (res, seconds).
>>> res, timing = timeit(time.sleep, 1)
"""
start_time = time.time()
res = func(*args, **kwargs)
timing = time.time() - start_time
return res, timing
|
def iprotate ( l , steps = 1 ) : if len ( l ) : steps %= len ( l ) if steps : firstPart = l [ : steps ] del l [ : steps ] l . extend ( firstPart ) return l
| 0 |
how to rotate list left in python3
|
r Like rotate but modifies l in - place .
|
cosqa-train-17933
|
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 is_unicode ( string ) : str_type = str ( type ( string ) ) if str_type . find ( 'str' ) > 0 or str_type . find ( 'unicode' ) > 0 : return True return False
| 1 |
python check is valuie is str
|
Validates that the object itself is some kinda string
|
cosqa-train-17934
|
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 |
call post api from python
|
HTTP POST operation to API endpoint .
|
cosqa-train-17935
|
def post(self, endpoint: str, **kwargs) -> dict:
"""HTTP POST operation to API endpoint."""
return self._request('POST', endpoint, **kwargs)
|
def get_window_dim ( ) : version = sys . version_info if version >= ( 3 , 3 ) : return _size_36 ( ) if platform . system ( ) == 'Windows' : return _size_windows ( ) return _size_27 ( )
| 0 |
python get chrome size
|
gets the dimensions depending on python version and os
|
cosqa-train-17936
|
def get_window_dim():
""" gets the dimensions depending on python version and os"""
version = sys.version_info
if version >= (3, 3):
return _size_36()
if platform.system() == 'Windows':
return _size_windows()
return _size_27()
|
def GetAllPixelColors ( self ) -> ctypes . Array : return self . GetPixelColorsOfRect ( 0 , 0 , self . Width , self . Height )
| 1 |
python ctypes array of arrays
|
Return ctypes . Array an iterable array of int values in argb .
|
cosqa-train-17937
|
def GetAllPixelColors(self) -> ctypes.Array:
"""
Return `ctypes.Array`, an iterable array of int values in argb.
"""
return self.GetPixelColorsOfRect(0, 0, self.Width, self.Height)
|
def gen_lower ( x : Iterable [ str ] ) -> Generator [ str , None , None ] : for string in x : yield string . lower ( )
| 0 |
python lambda filter lowercase string
|
Args : x : iterable of strings
|
cosqa-train-17938
|
def gen_lower(x: Iterable[str]) -> Generator[str, None, None]:
"""
Args:
x: iterable of strings
Yields:
each string in lower case
"""
for string in x:
yield string.lower()
|
def calculate_fft ( data , tbin ) : if len ( np . shape ( data ) ) > 1 : n = len ( data [ 0 ] ) return np . fft . fftfreq ( n , tbin * 1e-3 ) , np . fft . fft ( data , axis = 1 ) else : n = len ( data ) return np . fft . fftfreq ( n , tbin * 1e-3 ) , np . fft . fft ( data )
| 1 |
python calculate fft for wave form
|
Function to calculate the Fourier transform of data . Parameters ---------- data : numpy . ndarray 1D or 2D array containing time series . tbin : float Bin size of time series ( in ms ) . Returns ------- freqs : numpy . ndarray Frequency axis of signal in Fourier space . fft : numpy . ndarray Signal in Fourier space .
|
cosqa-train-17939
|
def calculate_fft(data, tbin):
"""
Function to calculate the Fourier transform of data.
Parameters
----------
data : numpy.ndarray
1D or 2D array containing time series.
tbin : float
Bin size of time series (in ms).
Returns
-------
freqs : numpy.ndarray
Frequency axis of signal in Fourier space.
fft : numpy.ndarray
Signal in Fourier space.
"""
if len(np.shape(data)) > 1:
n = len(data[0])
return np.fft.fftfreq(n, tbin * 1e-3), np.fft.fft(data, axis=1)
else:
n = len(data)
return np.fft.fftfreq(n, tbin * 1e-3), np.fft.fft(data)
|
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 |
finding max 3 out of a dictionary in python
|
Returns the keys that maps to the top n max values in the given dict .
|
cosqa-train-17940
|
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 assign_parent ( node : astroid . node_classes . NodeNG ) -> astroid . node_classes . NodeNG : while node and isinstance ( node , ( astroid . AssignName , astroid . Tuple , astroid . List ) ) : node = node . parent return node
| 1 |
python ast visit get parent node
|
return the higher parent which is not an AssignName Tuple or List node
|
cosqa-train-17941
|
def assign_parent(node: astroid.node_classes.NodeNG) -> astroid.node_classes.NodeNG:
"""return the higher parent which is not an AssignName, Tuple or List node
"""
while node and isinstance(node, (astroid.AssignName, astroid.Tuple, astroid.List)):
node = node.parent
return node
|
def get_commits_modified_file ( self , filepath : str ) -> List [ str ] : path = str ( Path ( filepath ) ) commits = [ ] try : commits = self . git . log ( "--follow" , "--format=%H" , path ) . split ( '\n' ) except GitCommandError : logger . debug ( "Could not find information of file %s" , path ) return commits
| 0 |
get files changed using commitid using gitpython
|
Given a filepath returns all the commits that modified this file ( following renames ) .
|
cosqa-train-17942
|
def get_commits_modified_file(self, filepath: str) -> List[str]:
"""
Given a filepath, returns all the commits that modified this file
(following renames).
:param str filepath: path to the file
:return: the list of commits' hash
"""
path = str(Path(filepath))
commits = []
try:
commits = self.git.log("--follow", "--format=%H", path).split('\n')
except GitCommandError:
logger.debug("Could not find information of file %s", path)
return commits
|
async def executemany ( self , sql : str , parameters : Iterable [ Iterable [ Any ] ] ) -> None : await self . _execute ( self . _cursor . executemany , sql , parameters )
| 0 |
python sqlite3 executemany %
|
Execute the given multiquery .
|
cosqa-train-17943
|
async def executemany(self, sql: str, parameters: Iterable[Iterable[Any]]) -> None:
"""Execute the given multiquery."""
await self._execute(self._cursor.executemany, sql, parameters)
|
def __remove_trailing_zeros ( self , collection ) : index = len ( collection ) - 1 while index >= 0 and collection [ index ] == 0 : index -= 1 return collection [ : index + 1 ]
| 1 |
remove leading zeros python
|
Removes trailing zeroes from indexable collection of numbers
|
cosqa-train-17944
|
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_day_name ( self ) -> str : weekday = self . value . isoweekday ( ) - 1 return calendar . day_name [ weekday ]
| 1 |
print the full name of the day of the week python
|
Returns the day name
|
cosqa-train-17945
|
def get_day_name(self) -> str:
""" Returns the day name """
weekday = self.value.isoweekday() - 1
return calendar.day_name[weekday]
|
def fib ( n ) : assert n > 0 a , b = 1 , 1 for i in range ( n - 1 ) : a , b = b , a + b return a
| 1 |
python fibonacci user input
|
Fibonacci example function
|
cosqa-train-17946
|
def fib(n):
"""Fibonacci example function
Args:
n (int): integer
Returns:
int: n-th Fibonacci number
"""
assert n > 0
a, b = 1, 1
for i in range(n - 1):
a, b = b, a + b
return a
|
def get_language ( ) : from parler import appsettings language = dj_get_language ( ) if language is None and appsettings . PARLER_DEFAULT_ACTIVATE : return appsettings . PARLER_DEFAULT_LANGUAGE_CODE else : return language
| 0 |
how to detect language in python
|
Wrapper around Django s get_language utility . For Django > = 1 . 8 get_language returns None in case no translation is activate . Here we patch this behavior e . g . for back - end functionality requiring access to translated fields
|
cosqa-train-17947
|
def get_language():
"""
Wrapper around Django's `get_language` utility.
For Django >= 1.8, `get_language` returns None in case no translation is activate.
Here we patch this behavior e.g. for back-end functionality requiring access to translated fields
"""
from parler import appsettings
language = dj_get_language()
if language is None and appsettings.PARLER_DEFAULT_ACTIVATE:
return appsettings.PARLER_DEFAULT_LANGUAGE_CODE
else:
return language
|
def _kbhit_unix ( ) -> bool : dr , dw , de = select . select ( [ sys . stdin ] , [ ] , [ ] , 0 ) return dr != [ ]
| 0 |
how to check if a key was pressed with curses python
|
Under UNIX : is a keystroke available?
|
cosqa-train-17948
|
def _kbhit_unix() -> bool:
"""
Under UNIX: is a keystroke available?
"""
dr, dw, de = select.select([sys.stdin], [], [], 0)
return dr != []
|
def __gt__ ( self , other ) : if isinstance ( other , Address ) : return str ( self ) > str ( other ) raise TypeError
| 0 |
python if a is greater than b
|
Test for greater than .
|
cosqa-train-17949
|
def __gt__(self, other):
"""Test for greater than."""
if isinstance(other, Address):
return str(self) > str(other)
raise TypeError
|
def similarity ( word1 : str , word2 : str ) -> float : return _MODEL . similarity ( word1 , word2 )
| 0 |
python similarities between two strings word2vec
|
Get cosine similarity between two words . If a word is not in the vocabulary KeyError will be raised .
|
cosqa-train-17950
|
def similarity(word1: str, word2: str) -> float:
"""
Get cosine similarity between two words.
If a word is not in the vocabulary, KeyError will be raised.
:param string word1: first word
:param string word2: second word
:return: the cosine similarity between the two word vectors
"""
return _MODEL.similarity(word1, word2)
|
def snake_case ( a_string ) : partial = re . sub ( '(.)([A-Z][a-z]+)' , r'\1_\2' , a_string ) return re . sub ( '([a-z0-9])([A-Z])' , r'\1_\2' , partial ) . lower ( )
| 0 |
lower case string in python
|
Returns a snake cased version of a string .
|
cosqa-train-17951
|
def snake_case(a_string):
"""Returns a snake cased version of a string.
:param a_string: any :class:`str` object.
Usage:
>>> snake_case('FooBar')
"foo_bar"
"""
partial = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', a_string)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', partial).lower()
|
def get_default_bucket_key ( buckets : List [ Tuple [ int , int ] ] ) -> Tuple [ int , int ] : return max ( buckets )
| 0 |
get key with max value python
|
Returns the default bucket from a list of buckets i . e . the largest bucket .
|
cosqa-train-17952
|
def get_default_bucket_key(buckets: List[Tuple[int, int]]) -> Tuple[int, int]:
"""
Returns the default bucket from a list of buckets, i.e. the largest bucket.
:param buckets: List of buckets.
:return: The largest bucket in the list.
"""
return max(buckets)
|
def __remove_method ( m : lmap . Map , key : T ) -> lmap . Map : return m . dissoc ( key )
| 0 |
python map remove key
|
Swap the methods atom to remove method with key .
|
cosqa-train-17953
|
def __remove_method(m: lmap.Map, key: T) -> lmap.Map:
"""Swap the methods atom to remove method with key."""
return m.dissoc(key)
|
def rate_limited ( max_per_hour : int , * args : Any ) -> Callable [ ... , Any ] : return util . rate_limited ( max_per_hour , * args )
| 0 |
how to implement a rate limiter in python
|
Rate limit a function .
|
cosqa-train-17954
|
def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:
"""Rate limit a function."""
return util.rate_limited(max_per_hour, *args)
|
def product ( * args , * * kwargs ) : p = [ [ ] ] for iterable in map ( tuple , args ) * kwargs . get ( "repeat" , 1 ) : p = [ x + [ y ] for x in p for y in iterable ] for p in p : yield tuple ( p )
| 1 |
permutations in python with three arguements
|
Yields all permutations with replacement : list ( product ( cat repeat = 2 )) = > [ ( c c ) ( c a ) ( c t ) ( a c ) ( a a ) ( a t ) ( t c ) ( t a ) ( t t ) ]
|
cosqa-train-17955
|
def product(*args, **kwargs):
""" Yields all permutations with replacement:
list(product("cat", repeat=2)) =>
[("c", "c"),
("c", "a"),
("c", "t"),
("a", "c"),
("a", "a"),
("a", "t"),
("t", "c"),
("t", "a"),
("t", "t")]
"""
p = [[]]
for iterable in map(tuple, args) * kwargs.get("repeat", 1):
p = [x + [y] for x in p for y in iterable]
for p in p:
yield tuple(p)
|
def __gt__ ( self , other ) : if isinstance ( other , Address ) : return str ( self ) > str ( other ) raise TypeError
| 1 |
python greater than string
|
Test for greater than .
|
cosqa-train-17956
|
def __gt__(self, other):
"""Test for greater than."""
if isinstance(other, Address):
return str(self) > str(other)
raise TypeError
|
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
| 1 |
how to pass a file to stdin in python
|
Returns a file descriptor from stdin or opening a file from a given path .
|
cosqa-train-17957
|
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 inverted_dict ( d ) : return dict ( ( force_hashable ( v ) , k ) for ( k , v ) in viewitems ( dict ( d ) ) )
| 0 |
invert dictionary python 3
|
Return a dict with swapped keys and values
|
cosqa-train-17958
|
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 _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 list index by identity
|
Return dict mapping item - > indices .
|
cosqa-train-17959
|
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 fetchvalue ( self , sql : str , * args ) -> Optional [ Any ] : row = self . fetchone ( sql , * args ) if row is None : return None return row [ 0 ]
| 1 |
how to get only one row in sql database python using flask
|
Executes SQL ; returns the first value of the first row or None .
|
cosqa-train-17960
|
def fetchvalue(self, sql: str, *args) -> Optional[Any]:
"""Executes SQL; returns the first value of the first row, or None."""
row = self.fetchone(sql, *args)
if row is None:
return None
return row[0]
|
def get_column_names ( engine : Engine , tablename : str ) -> List [ str ] : return [ info . name for info in gen_columns_info ( engine , tablename ) ]
| 0 |
python get columns names in a list
|
Get all the database column names for the specified table .
|
cosqa-train-17961
|
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 _mid ( pt1 , pt2 ) : ( x0 , y0 ) , ( x1 , y1 ) = pt1 , pt2 return 0.5 * ( x0 + x1 ) , 0.5 * ( y0 + y1 )
| 1 |
calculate mid points between numbers python
|
( Point Point ) - > Point Return the point that lies in between the two input points .
|
cosqa-train-17962
|
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 most_significant_bit ( lst : np . ndarray ) -> int : return np . argwhere ( np . asarray ( lst ) == 1 ) [ 0 ] [ 0 ]
| 0 |
how to get the index of elements with max value in array python
|
A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s i . e . the first position where a 1 appears reading left to right .
|
cosqa-train-17963
|
def most_significant_bit(lst: np.ndarray) -> int:
"""
A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,
i.e. the first position where a 1 appears, reading left to right.
:param lst: a 1d array of 0s and 1s with at least one 1
:return: the first position in lst that a 1 appears
"""
return np.argwhere(np.asarray(lst) == 1)[0][0]
|
def dictlist_wipe_key ( dict_list : Iterable [ Dict ] , key : str ) -> None : for d in dict_list : d . pop ( key , None )
| 1 |
python remove key from dictionary if exist
|
Process an iterable of dictionaries . For each dictionary d delete d [ key ] if it exists .
|
cosqa-train-17964
|
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 string ( value ) -> str : return system_json . dumps ( Json ( value ) . safe_object ( ) , ensure_ascii = False )
| 1 |
python json value as string
|
string dict / object / value to JSON
|
cosqa-train-17965
|
def string(value) -> str:
""" string dict/object/value to JSON """
return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)
|
def _rindex ( mylist : Sequence [ T ] , x : T ) -> int : return len ( mylist ) - mylist [ : : - 1 ] . index ( x ) - 1
| 0 |
return last index in python
|
Index of the last occurrence of x in the sequence .
|
cosqa-train-17966
|
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 |
python histogram get number of bins
|
Shape of histogram s data .
|
cosqa-train-17967
|
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 split ( text : str ) -> List [ str ] : return [ word for word in SEPARATOR . split ( text ) if word . strip ( ' \t' ) ]
| 1 |
how to split sentence in python with delimiter
|
Split a text into a list of tokens .
|
cosqa-train-17968
|
def split(text: str) -> List[str]:
"""Split a text into a list of tokens.
:param text: the text to split
:return: tokens
"""
return [word for word in SEPARATOR.split(text) if word.strip(' \t')]
|
def Exit ( msg , code = 1 ) : print >> sys . stderr , msg sys . exit ( code )
| 1 |
exit function in python not defined
|
Exit execution with return code and message : param msg : Message displayed prior to exit : param code : code returned upon exiting
|
cosqa-train-17969
|
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 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 call from code
|
docstring for argparse
|
cosqa-train-17970
|
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 argmax ( self , rows : List [ Row ] , column : ComparableColumn ) -> List [ Row ] : if not rows : return [ ] value_row_pairs = [ ( row . values [ column . name ] , row ) for row in rows ] if not value_row_pairs : return [ ] # Returns a list containing the row with the max cell value. return [ sorted ( value_row_pairs , key = lambda x : x [ 0 ] , reverse = True ) [ 0 ] [ 1 ] ]
| 1 |
get column with max value python
|
Takes a list of rows and a column name and returns a list containing a single row ( dict from columns to cells ) that has the maximum numerical value in the given column . We return a list instead of a single dict to be consistent with the return type of select and all_rows .
|
cosqa-train-17971
|
def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:
"""
Takes a list of rows and a column name and returns a list containing a single row (dict from
columns to cells) that has the maximum numerical value in the given column. We return a list
instead of a single dict to be consistent with the return type of ``select`` and
``all_rows``.
"""
if not rows:
return []
value_row_pairs = [(row.values[column.name], row) for row in rows]
if not value_row_pairs:
return []
# Returns a list containing the row with the max cell value.
return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]
|
def running_containers ( name_filter : str ) -> List [ str ] : return [ container . short_id for container in docker_client . containers . list ( filters = { "name" : name_filter } ) ]
| 1 |
docker container ls not listing python
|
: raises docker . exceptions . APIError
|
cosqa-train-17972
|
def running_containers(name_filter: str) -> List[str]:
"""
:raises docker.exceptions.APIError
"""
return [container.short_id for container in
docker_client.containers.list(filters={"name": name_filter})]
|
def remove_empty_text ( utterances : List [ Utterance ] ) -> List [ Utterance ] : return [ utter for utter in utterances if utter . text . strip ( ) != "" ]
| 1 |
remove words of string in list of stringpython
|
Remove empty utterances from a list of utterances Args : utterances : The list of utterance we are processing
|
cosqa-train-17973
|
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 _isint ( string ) : return type ( string ) is int or ( isinstance ( string , _binary_type ) or isinstance ( string , _text_type ) ) and _isconvertible ( int , string )
| 1 |
how to test if a str is an int python
|
>>> _isint ( 123 ) True >>> _isint ( 123 . 45 ) False
|
cosqa-train-17974
|
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 bfx ( value , msb , lsb ) : mask = bitmask ( ( msb , lsb ) ) return ( value & mask ) >> lsb
| 0 |
python calculating bitwise differently
|
!
|
cosqa-train-17975
|
def bfx(value, msb, lsb):
"""! @brief Extract a value from a bitfield."""
mask = bitmask((msb, lsb))
return (value & mask) >> lsb
|
def indexes_equal ( a : Index , b : Index ) -> bool : return str ( a ) == str ( b )
| 1 |
testing if two strings are equal in python
|
Are two indexes equal? Checks by comparing str () versions of them . ( AM UNSURE IF THIS IS ENOUGH . )
|
cosqa-train-17976
|
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 __as_list ( value : List [ JsonObjTypes ] ) -> List [ JsonTypes ] : return [ e . _as_dict if isinstance ( e , JsonObj ) else e for e in value ]
| 0 |
python3 flask jsonify unhashable type list
|
Return a json array as a list
|
cosqa-train-17977
|
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 cookies ( self ) -> Dict [ str , str ] : cookies = SimpleCookie ( ) cookies . load ( self . headers . get ( 'Cookie' , '' ) ) return { key : cookie . value for key , cookie in cookies . items ( ) }
| 1 |
how to get all cookies from python request
|
The parsed cookies attached to this request .
|
cosqa-train-17978
|
def cookies(self) -> Dict[str, str]:
"""The parsed cookies attached to this request."""
cookies = SimpleCookie()
cookies.load(self.headers.get('Cookie', ''))
return {key: cookie.value for key, cookie in cookies.items()}
|
def count ( args ) : counts = defaultdict ( int ) for arg in args : for item in arg : counts [ item ] = counts [ item ] + 1 return counts
| 1 |
how to count in lists without the sum command python
|
count occurences in a list of lists >>> count ( [[ a b ] [ a ]] ) defaultdict ( int { a : 2 b : 1 } )
|
cosqa-train-17979
|
def count(args):
""" count occurences in a list of lists
>>> count([['a','b'],['a']])
defaultdict(int, {'a' : 2, 'b' : 1})
"""
counts = defaultdict(int)
for arg in args:
for item in arg:
counts[item] = counts[item] + 1
return counts
|
def to_bytes ( data : Any ) -> bytearray : # noqa if isinstance ( data , int ) : return bytearray ( [ data ] ) return bytearray ( data , encoding = 'latin-1' )
| 1 |
how to converta string into bytes in python
|
Convert anything to a bytearray . See - http : // stackoverflow . com / questions / 7585435 / best - way - to - convert - string - to - bytes - in - python - 3 - http : // stackoverflow . com / questions / 10459067 / how - to - convert - my - bytearrayb - x9e - x18k - x9a - to - something - like - this - x9e - x1
|
cosqa-train-17980
|
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 zfill ( x , width ) : if not isinstance ( x , basestring ) : x = repr ( x ) return x . zfill ( width )
| 1 |
python str number zero pad left and right
|
zfill ( x width ) - > string
|
cosqa-train-17981
|
def zfill(x, width):
"""zfill(x, width) -> string
Pad a numeric string x with zeros on the left, to fill a field
of the specified width. The string x is never truncated.
"""
if not isinstance(x, basestring):
x = repr(x)
return x.zfill(width)
|
def position ( self ) -> Position : return Position ( self . _index , self . _lineno , self . _col_offset )
| 1 |
python 3 cursor position
|
The current position of the cursor .
|
cosqa-train-17982
|
def position(self) -> Position:
"""The current position of the cursor."""
return Position(self._index, self._lineno, self._col_offset)
|
def de_duplicate ( items ) : result = [ ] for item in items : if item not in result : result . append ( item ) return result
| 0 |
how to delete duplicates in a list python panda
|
Remove any duplicate item preserving order
|
cosqa-train-17983
|
def de_duplicate(items):
"""Remove any duplicate item, preserving order
>>> de_duplicate([1, 2, 1, 2])
[1, 2]
"""
result = []
for item in items:
if item not in result:
result.append(item)
return result
|
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 |
how to get bottom n lowestkey value pair from the dictionary in python
|
Returns the keys that maps to the top n max values in the given dict .
|
cosqa-train-17984
|
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 get_last_day_of_month ( t : datetime ) -> int : tn = t + timedelta ( days = 32 ) tn = datetime ( year = tn . year , month = tn . month , day = 1 ) tt = tn - timedelta ( hours = 1 ) return tt . day
| 1 |
is last day of month python
|
Returns day number of the last day of the month : param t : datetime : return : int
|
cosqa-train-17985
|
def get_last_day_of_month(t: datetime) -> int:
"""
Returns day number of the last day of the month
:param t: datetime
:return: int
"""
tn = t + timedelta(days=32)
tn = datetime(year=tn.year, month=tn.month, day=1)
tt = tn - timedelta(hours=1)
return tt.day
|
def get_default_bucket_key ( buckets : List [ Tuple [ int , int ] ] ) -> Tuple [ int , int ] : return max ( buckets )
| 1 |
get key of maximum value in python
|
Returns the default bucket from a list of buckets i . e . the largest bucket .
|
cosqa-train-17986
|
def get_default_bucket_key(buckets: List[Tuple[int, int]]) -> Tuple[int, int]:
"""
Returns the default bucket from a list of buckets, i.e. the largest bucket.
:param buckets: List of buckets.
:return: The largest bucket in the list.
"""
return max(buckets)
|
def docker_environment ( env ) : return ' ' . join ( [ "-e \"%s=%s\"" % ( key , value . replace ( "$" , "\\$" ) . replace ( "\"" , "\\\"" ) . replace ( "`" , "\\`" ) ) for key , value in env . items ( ) ] )
| 0 |
python docker configuration passing environment varialbes
|
Transform dictionary of environment variables into Docker - e parameters .
|
cosqa-train-17987
|
def docker_environment(env):
"""
Transform dictionary of environment variables into Docker -e parameters.
>>> result = docker_environment({'param1': 'val1', 'param2': 'val2'})
>>> result in ['-e "param1=val1" -e "param2=val2"', '-e "param2=val2" -e "param1=val1"']
True
"""
return ' '.join(
["-e \"%s=%s\"" % (key, value.replace("$", "\\$").replace("\"", "\\\"").replace("`", "\\`"))
for key, value in env.items()])
|
def call_api ( self , resource_path , method , path_params = None , query_params = None , header_params = None , body = None , post_params = None , files = None , response_type = None , auth_settings = None , asynchronous = None , _return_http_data_only = None , collection_formats = None , _preload_content = True , _request_timeout = None ) : if not asynchronous : return self . __call_api ( resource_path , method , path_params , query_params , header_params , body , post_params , files , response_type , auth_settings , _return_http_data_only , collection_formats , _preload_content , _request_timeout ) else : thread = self . pool . apply_async ( self . __call_api , ( resource_path , method , path_params , query_params , header_params , body , post_params , files , response_type , auth_settings , _return_http_data_only , collection_formats , _preload_content , _request_timeout ) ) return thread
| 0 |
python http request synchronous or asynchronous
|
Makes the HTTP request ( synchronous ) and return the deserialized data . To make an async request set the asynchronous parameter .
|
cosqa-train-17988
|
def call_api(self, resource_path, method,
path_params=None, query_params=None, header_params=None,
body=None, post_params=None, files=None,
response_type=None, auth_settings=None, asynchronous=None,
_return_http_data_only=None, collection_formats=None, _preload_content=True,
_request_timeout=None):
"""
Makes the HTTP request (synchronous) and return the deserialized data.
To make an async request, set the asynchronous parameter.
:param resource_path: Path to method endpoint.
:param method: Method to call.
:param path_params: Path parameters in the url.
:param query_params: Query parameters in the url.
:param header_params: Header parameters to be
placed in the request header.
:param body: Request body.
:param post_params dict: Request post form parameters,
for `application/x-www-form-urlencoded`, `multipart/form-data`.
:param auth_settings list: Auth Settings names for the request.
:param response: Response data type.
:param files dict: key -> filename, value -> filepath,
for `multipart/form-data`.
:param asynchronous bool: execute request asynchronously
:param _return_http_data_only: response data without head status code and headers
:param collection_formats: dict of collection formats for path, query,
header, and post parameters.
:param _preload_content: if False, the urllib3.HTTPResponse object will be returned without
reading/decoding response data. Default is True.
:param _request_timeout: timeout setting for this request. If one number provided, it will be total request
timeout. It can also be a pair (tuple) of (connection, read) timeouts.
:return:
If asynchronous parameter is True,
the request will be called asynchronously.
The method will return the request thread.
If parameter asynchronous is False or missing,
then the method will return the response directly.
"""
if not asynchronous:
return self.__call_api(resource_path, method,
path_params, query_params, header_params,
body, post_params, files,
response_type, auth_settings,
_return_http_data_only, collection_formats, _preload_content, _request_timeout)
else:
thread = self.pool.apply_async(self.__call_api, (resource_path, method,
path_params, query_params,
header_params, body,
post_params, files,
response_type, auth_settings,
_return_http_data_only,
collection_formats, _preload_content, _request_timeout))
return thread
|
def snake_to_camel ( value ) : camel = "" . join ( word . title ( ) for word in value . split ( "_" ) ) return value [ : 1 ] . lower ( ) + camel [ 1 : ]
| 0 |
lowercase letter numbers in python
|
Converts a snake_case_string to a camelCaseString .
|
cosqa-train-17989
|
def snake_to_camel(value):
"""
Converts a snake_case_string to a camelCaseString.
>>> snake_to_camel("foo_bar_baz")
'fooBarBaz'
"""
camel = "".join(word.title() for word in value.split("_"))
return value[:1].lower() + camel[1:]
|
def camelize ( key ) : return '' . join ( x . capitalize ( ) if i > 0 else x for i , x in enumerate ( key . split ( '_' ) ) )
| 1 |
how to uppercase string element python
|
Convert a python_style_variable_name to lowerCamelCase .
|
cosqa-train-17990
|
def camelize(key):
"""Convert a python_style_variable_name to lowerCamelCase.
Examples
--------
>>> camelize('variable_name')
'variableName'
>>> camelize('variableName')
'variableName'
"""
return ''.join(x.capitalize() if i > 0 else x
for i, x in enumerate(key.split('_')))
|
def is_natural ( x ) : try : is_integer = int ( x ) == x except ( TypeError , ValueError ) : return False return is_integer and x >= 0
| 0 |
how to make check digit even or odd python
|
A non - negative integer .
|
cosqa-train-17991
|
def is_natural(x):
"""A non-negative integer."""
try:
is_integer = int(x) == x
except (TypeError, ValueError):
return False
return is_integer and x >= 0
|
def parsehttpdate ( string_ ) : try : t = time . strptime ( string_ , "%a, %d %b %Y %H:%M:%S %Z" ) except ValueError : return None return datetime . datetime ( * t [ : 6 ] )
| 1 |
date time string python http
|
Parses an HTTP date into a datetime object .
|
cosqa-train-17992
|
def parsehttpdate(string_):
"""
Parses an HTTP date into a datetime object.
>>> parsehttpdate('Thu, 01 Jan 1970 01:01:01 GMT')
datetime.datetime(1970, 1, 1, 1, 1, 1)
"""
try:
t = time.strptime(string_, "%a, %d %b %Y %H:%M:%S %Z")
except ValueError:
return None
return datetime.datetime(*t[:6])
|
def count ( self , elem ) : return self . _left_list . count ( elem ) + self . _right_list . count ( elem )
| 0 |
how to get length of deque in python
|
Return the number of elements equal to elem present in the queue
|
cosqa-train-17993
|
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 check_key ( self , key : str ) -> bool : keys = self . get_keys ( ) return key in keys
| 1 |
python how to check if key exists + haskeys
|
Checks if key exists in datastore . True if yes False if no .
|
cosqa-train-17994
|
def check_key(self, key: str) -> bool:
"""
Checks if key exists in datastore. True if yes, False if no.
:param: SHA512 hash key
:return: whether or key not exists in datastore
"""
keys = self.get_keys()
return key in keys
|
def find_duplicates ( l : list ) -> set : return set ( [ x for x in l if l . count ( x ) > 1 ] )
| 1 |
python checking for duplicates in a list
|
Return the duplicates in a list .
|
cosqa-train-17995
|
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 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
| 0 |
check if df is not null in 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-17996
|
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 pack_bits ( longbits ) : byte = longbits & ( 0x0101010101010101 ) byte = ( byte | ( byte >> 7 ) ) & ( 0x0003000300030003 ) byte = ( byte | ( byte >> 14 ) ) & ( 0x0000000f0000000f ) byte = ( byte | ( byte >> 28 ) ) & ( 0x00000000000000ff ) return byte
| 1 |
python keep bits byte aligned
|
Crunch a 64 - bit int ( 8 bool bytes ) into a bitfield .
|
cosqa-train-17997
|
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 year ( date ) : try : fmt = '%m/%d/%Y' return datetime . strptime ( date , fmt ) . timetuple ( ) . tm_year except ValueError : return 0
| 1 |
how to get the year of the date in python
|
Returns the year .
|
cosqa-train-17998
|
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 argmax ( self , rows : List [ Row ] , column : ComparableColumn ) -> List [ Row ] : if not rows : return [ ] value_row_pairs = [ ( row . values [ column . name ] , row ) for row in rows ] if not value_row_pairs : return [ ] # Returns a list containing the row with the max cell value. return [ sorted ( value_row_pairs , key = lambda x : x [ 0 ] , reverse = True ) [ 0 ] [ 1 ] ]
| 1 |
pick up a row having a maximum value in a column in python
|
Takes a list of rows and a column name and returns a list containing a single row ( dict from columns to cells ) that has the maximum numerical value in the given column . We return a list instead of a single dict to be consistent with the return type of select and all_rows .
|
cosqa-train-17999
|
def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:
"""
Takes a list of rows and a column name and returns a list containing a single row (dict from
columns to cells) that has the maximum numerical value in the given column. We return a list
instead of a single dict to be consistent with the return type of ``select`` and
``all_rows``.
"""
if not rows:
return []
value_row_pairs = [(row.values[column.name], row) for row in rows]
if not value_row_pairs:
return []
# Returns a list containing the row with the max cell value.
return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.