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 inverted_dict ( d ) : return dict ( ( force_hashable ( v ) , k ) for ( k , v ) in viewitems ( dict ( d ) ) )
| 1 |
python how to inverse a dictionary
|
Return a dict with swapped keys and values
|
cosqa-train-17300
|
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 iterate_items ( dictish ) : if hasattr ( dictish , 'iteritems' ) : return dictish . iteritems ( ) if hasattr ( dictish , 'items' ) : return dictish . items ( ) return dictish
| 0 |
iterable items from dict python
|
Return a consistent ( key value ) iterable on dict - like objects including lists of tuple pairs .
|
cosqa-train-17301
|
def iterate_items(dictish):
""" Return a consistent (key, value) iterable on dict-like objects,
including lists of tuple pairs.
Example:
>>> list(iterate_items({'a': 1}))
[('a', 1)]
>>> list(iterate_items([('a', 1), ('b', 2)]))
[('a', 1), ('b', 2)]
"""
if hasattr(dictish, 'iteritems'):
return dictish.iteritems()
if hasattr(dictish, 'items'):
return dictish.items()
return dictish
|
def closest_values ( L ) : assert len ( L ) >= 2 L . sort ( ) valmin , argmin = min ( ( L [ i ] - L [ i - 1 ] , i ) for i in range ( 1 , len ( L ) ) ) return L [ argmin - 1 ] , L [ argmin ]
| 1 |
finding 2 closest items in 2 lists in python
|
Closest values
|
cosqa-train-17302
|
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 toStringArray ( name , a , width = 0 ) : string = name + ": " cnt = 0 for i in a : string += "%4.2f " % i if width > 0 and ( cnt + 1 ) % width == 0 : string += '\n' cnt += 1 return string
| 0 |
how to fill an array with str in python
|
Returns an array ( any sequence of floats really ) as a string .
|
cosqa-train-17303
|
def toStringArray(name, a, width = 0):
"""
Returns an array (any sequence of floats, really) as a string.
"""
string = name + ": "
cnt = 0
for i in a:
string += "%4.2f " % i
if width > 0 and (cnt + 1) % width == 0:
string += '\n'
cnt += 1
return string
|
def _isint ( string ) : return type ( string ) is int or ( isinstance ( string , _binary_type ) or isinstance ( string , _text_type ) ) and _isconvertible ( int , string )
| 1 |
python detect if int
|
>>> _isint ( 123 ) True >>> _isint ( 123 . 45 ) False
|
cosqa-train-17304
|
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 psutil_phymem_usage ( ) : import psutil # This is needed to avoid a deprecation warning error with
# newer psutil versions
try : percent = psutil . virtual_memory ( ) . percent except : percent = psutil . phymem_usage ( ) . percent return percent
| 1 |
how to track ram usage in python
|
Return physical memory usage ( float ) Requires the cross - platform psutil ( > = v0 . 3 ) library ( https : // github . com / giampaolo / psutil )
|
cosqa-train-17305
|
def psutil_phymem_usage():
"""
Return physical memory usage (float)
Requires the cross-platform psutil (>=v0.3) library
(https://github.com/giampaolo/psutil)
"""
import psutil
# This is needed to avoid a deprecation warning error with
# newer psutil versions
try:
percent = psutil.virtual_memory().percent
except:
percent = psutil.phymem_usage().percent
return percent
|
def text_coords ( string , position ) : line_start = string . rfind ( '\n' , 0 , position ) + 1 line_end = string . find ( '\n' , position ) lineno = string . count ( '\n' , 0 , position ) columnno = position - line_start line = string [ line_start : line_end ] return ( lineno , columnno , line )
| 1 |
how to get string positions in python 3
|
r Transform a simple index into a human - readable position in a string .
|
cosqa-train-17306
|
def text_coords(string, position):
r"""
Transform a simple index into a human-readable position in a string.
This function accepts a string and an index, and will return a triple of
`(lineno, columnno, line)` representing the position through the text. It's
useful for displaying a string index in a human-readable way::
>>> s = "abcdef\nghijkl\nmnopqr\nstuvwx\nyz"
>>> text_coords(s, 0)
(0, 0, 'abcdef')
>>> text_coords(s, 4)
(0, 4, 'abcdef')
>>> text_coords(s, 6)
(0, 6, 'abcdef')
>>> text_coords(s, 7)
(1, 0, 'ghijkl')
>>> text_coords(s, 11)
(1, 4, 'ghijkl')
>>> text_coords(s, 15)
(2, 1, 'mnopqr')
"""
line_start = string.rfind('\n', 0, position) + 1
line_end = string.find('\n', position)
lineno = string.count('\n', 0, position)
columnno = position - line_start
line = string[line_start:line_end]
return (lineno, columnno, line)
|
def highlight ( text : str , color_code : int , bold : bool = False ) -> str : return '{}\033[{}m{}\033[0m' . format ( '\033[1m' if bold else '' , color_code , text , )
| 1 |
how to change color of highlight variable in python
|
Wraps the given string with terminal color codes .
|
cosqa-train-17307
|
def highlight(text: str, color_code: int, bold: bool=False) -> str:
"""Wraps the given string with terminal color codes.
Args:
text: The content to highlight.
color_code: The color to highlight with, e.g. 'shelltools.RED'.
bold: Whether to bold the content in addition to coloring.
Returns:
The highlighted string.
"""
return '{}\033[{}m{}\033[0m'.format(
'\033[1m' if bold else '',
color_code,
text,)
|
def assign_parent ( node : astroid . node_classes . NodeNG ) -> astroid . node_classes . NodeNG : while node and isinstance ( node , ( astroid . AssignName , astroid . Tuple , astroid . List ) ) : node = node . parent return node
| 0 |
get the parent node of a node using python
|
return the higher parent which is not an AssignName Tuple or List node
|
cosqa-train-17308
|
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 stretch ( iterable , n = 2 ) : times = range ( n ) for item in iterable : for i in times : yield item
| 0 |
python how to repeat a list a set amount of times
|
r Repeat each item in iterable n times .
|
cosqa-train-17309
|
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 excel_datetime ( timestamp , epoch = None ) : if epoch is None : epoch = datetime . datetime . fromordinal ( 693594 ) return epoch + datetime . timedelta ( timestamp )
| 0 |
excel numeric dates to python timestamp
|
Return datetime object from timestamp in Excel serial format .
|
cosqa-train-17310
|
def excel_datetime(timestamp, epoch=None):
"""Return datetime object from timestamp in Excel serial format.
Convert LSM time stamps.
>>> excel_datetime(40237.029999999795)
datetime.datetime(2010, 2, 28, 0, 43, 11, 999982)
"""
if epoch is None:
epoch = datetime.datetime.fromordinal(693594)
return epoch + datetime.timedelta(timestamp)
|
def callable_validator ( v : Any ) -> AnyCallable : if callable ( v ) : return v raise errors . CallableError ( value = v )
| 0 |
invalid callable given python
|
Perform a simple check if the value is callable .
|
cosqa-train-17311
|
def callable_validator(v: Any) -> AnyCallable:
"""
Perform a simple check if the value is callable.
Note: complete matching of argument type hints and return types is not performed
"""
if callable(v):
return v
raise errors.CallableError(value=v)
|
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 |
how efficient are python bitmasks
|
Crunch a 64 - bit int ( 8 bool bytes ) into a bitfield .
|
cosqa-train-17312
|
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 enum_mark_last ( iterable , start = 0 ) : it = iter ( iterable ) count = start try : last = next ( it ) except StopIteration : return for val in it : yield count , False , last last = val count += 1 yield count , True , last
| 0 |
detect the last element in a python 'for' loop
|
Returns a generator over iterable that tells whether the current item is the last one . Usage : >>> iterable = range ( 10 ) >>> for index is_last item in enum_mark_last ( iterable ) : >>> print ( index item end = \ n if is_last else )
|
cosqa-train-17313
|
def enum_mark_last(iterable, start=0):
"""
Returns a generator over iterable that tells whether the current item is the last one.
Usage:
>>> iterable = range(10)
>>> for index, is_last, item in enum_mark_last(iterable):
>>> print(index, item, end='\n' if is_last else ', ')
"""
it = iter(iterable)
count = start
try:
last = next(it)
except StopIteration:
return
for val in it:
yield count, False, last
last = val
count += 1
yield count, True, last
|
def csv_to_numpy ( string_like , dtype = None ) : # type: (str) -> np.array stream = StringIO ( string_like ) return np . genfromtxt ( stream , dtype = dtype , delimiter = ',' )
| 1 |
python read from csv into numpy array
|
Convert a CSV object to a numpy array .
|
cosqa-train-17314
|
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 genfirstvalues ( cursor : Cursor , arraysize : int = 1000 ) -> Generator [ Any , None , None ] : return ( row [ 0 ] for row in genrows ( cursor , arraysize ) )
| 1 |
python dataset get first 50 rows
|
Generate the first value in each row .
|
cosqa-train-17315
|
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 pack_bits ( longbits ) : byte = longbits & ( 0x0101010101010101 ) byte = ( byte | ( byte >> 7 ) ) & ( 0x0003000300030003 ) byte = ( byte | ( byte >> 14 ) ) & ( 0x0000000f0000000f ) byte = ( byte | ( byte >> 28 ) ) & ( 0x00000000000000ff ) return byte
| 1 |
long number of bits python
|
Crunch a 64 - bit int ( 8 bool bytes ) into a bitfield .
|
cosqa-train-17316
|
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 to_iso_string ( self ) -> str : assert isinstance ( self . value , datetime ) return datetime . isoformat ( self . value )
| 1 |
python datetime enter date in isoformat
|
Returns full ISO string for the given date
|
cosqa-train-17317
|
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 _brief_print_list ( lst , limit = 7 ) : lst = list ( lst ) if len ( lst ) > limit : return _brief_print_list ( lst [ : limit // 2 ] , limit ) + ', ..., ' + _brief_print_list ( lst [ - limit // 2 : ] , limit ) return ', ' . join ( [ "'%s'" % str ( i ) for i in lst ] )
| 0 |
how to print each item in a list until a certain limit is reached python
|
Print at most limit elements of list .
|
cosqa-train-17318
|
def _brief_print_list(lst, limit=7):
"""Print at most `limit` elements of list."""
lst = list(lst)
if len(lst) > limit:
return _brief_print_list(lst[:limit//2], limit) + ', ..., ' + \
_brief_print_list(lst[-limit//2:], limit)
return ', '.join(["'%s'"%str(i) for i in lst])
|
def get_period_last_3_months ( ) -> str : today = Datum ( ) today . today ( ) # start_date = today - timedelta(weeks=13) start_date = today . clone ( ) start_date . subtract_months ( 3 ) period = get_period ( start_date . date , today . date ) return period
| 0 |
python get last months business day end
|
Returns the last week as a period string
|
cosqa-train-17319
|
def get_period_last_3_months() -> str:
""" Returns the last week as a period string """
today = Datum()
today.today()
# start_date = today - timedelta(weeks=13)
start_date = today.clone()
start_date.subtract_months(3)
period = get_period(start_date.date, today.date)
return period
|
def truncate ( value : Decimal , n_digits : int ) -> Decimal : return Decimal ( math . trunc ( value * ( 10 ** n_digits ) ) ) / ( 10 ** n_digits )
| 0 |
python truncate to number of decimals
|
Truncates a value to a number of decimals places
|
cosqa-train-17320
|
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 timeit ( func , * args , * * kwargs ) : start_time = time . time ( ) res = func ( * args , * * kwargs ) timing = time . time ( ) - start_time return res , timing
| 0 |
python time a func timeit
|
Time execution of function . Returns ( res seconds ) .
|
cosqa-train-17321
|
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 is_sqlatype_string ( coltype : Union [ TypeEngine , VisitableType ] ) -> bool : coltype = _coltype_to_typeengine ( coltype ) return isinstance ( coltype , sqltypes . String )
| 0 |
python check the data type of a column
|
Is the SQLAlchemy column type a string type?
|
cosqa-train-17322
|
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 snake_to_camel ( s : str ) -> str : fragments = s . split ( '_' ) return fragments [ 0 ] + '' . join ( x . title ( ) for x in fragments [ 1 : ] )
| 0 |
how to do capitalize strings in python
|
Convert string from snake case to camel case .
|
cosqa-train-17323
|
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 list_to_str ( list , separator = ',' ) : list = [ str ( x ) for x in list ] return separator . join ( list )
| 1 |
python from list make a string with separator
|
>>> list = [ 0 0 7 ] >>> list_to_str ( list ) 0 0 7
|
cosqa-train-17324
|
def list_to_str(list, separator=','):
"""
>>> list = [0, 0, 7]
>>> list_to_str(list)
'0,0,7'
"""
list = [str(x) for x in list]
return separator.join(list)
|
def output_dir ( self , * args ) -> str : return os . path . join ( self . project_dir , 'output' , * args )
| 1 |
speicify directory for output file python
|
Directory where to store output
|
cosqa-train-17325
|
def output_dir(self, *args) -> str:
""" Directory where to store output """
return os.path.join(self.project_dir, 'output', *args)
|
def writable_stream ( handle ) : if isinstance ( handle , io . IOBase ) and sys . version_info >= ( 3 , 5 ) : return handle . writable ( ) try : handle . write ( b'' ) except ( io . UnsupportedOperation , IOError ) : return False else : return True
| 1 |
python check bytesio is empty
|
Test whether a stream can be written to .
|
cosqa-train-17326
|
def writable_stream(handle):
"""Test whether a stream can be written to.
"""
if isinstance(handle, io.IOBase) and sys.version_info >= (3, 5):
return handle.writable()
try:
handle.write(b'')
except (io.UnsupportedOperation, IOError):
return False
else:
return True
|
def strtobytes ( input , encoding ) : py_version = sys . version_info [ 0 ] if py_version >= 3 : return _strtobytes_py3 ( input , encoding ) return _strtobytes_py2 ( input , encoding )
| 0 |
python3 str to byte string
|
Take a str and transform it into a byte array .
|
cosqa-train-17327
|
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 contains ( self , token : str ) -> bool : self . _validate_token ( token ) return token in self
| 0 |
how to check if a token is in a list python
|
Return if the token is in the list or not .
|
cosqa-train-17328
|
def contains(self, token: str) -> bool:
"""Return if the token is in the list or not."""
self._validate_token(token)
return token in self
|
def detect_model_num ( string ) : match = re . match ( MODEL_NUM_REGEX , string ) if match : return int ( match . group ( ) ) return None
| 0 |
extrac t model number from a string python
|
Takes a string related to a model name and extract its model number .
|
cosqa-train-17329
|
def detect_model_num(string):
"""Takes a string related to a model name and extract its model number.
For example:
'000000-bootstrap.index' => 0
"""
match = re.match(MODEL_NUM_REGEX, string)
if match:
return int(match.group())
return None
|
def get_column_names ( engine : Engine , tablename : str ) -> List [ str ] : return [ info . name for info in gen_columns_info ( engine , tablename ) ]
| 0 |
how to get columns for table in python
|
Get all the database column names for the specified table .
|
cosqa-train-17330
|
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 uppercase_chars ( string : any ) -> str : return '' . join ( [ c if c . isupper ( ) else '' for c in str ( string ) ] )
| 1 |
make variable all uppercase in python
|
Return all ( and only ) the uppercase chars in the given string .
|
cosqa-train-17331
|
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 is_line_in_file ( filename : str , line : str ) -> bool : assert "\n" not in line with open ( filename , "r" ) as file : for fileline in file : if fileline == line : return True return False
| 0 |
check if line is not in text file in python
|
Detects whether a line is present within a file .
|
cosqa-train-17332
|
def is_line_in_file(filename: str, line: str) -> bool:
"""
Detects whether a line is present within a file.
Args:
filename: file to check
line: line to search for (as an exact match)
"""
assert "\n" not in line
with open(filename, "r") as file:
for fileline in file:
if fileline == line:
return True
return False
|
def shape ( self ) -> Tuple [ int , ... ] : return tuple ( bins . bin_count for bins in self . _binnings )
| 0 |
bin width in histogram python
|
Shape of histogram s data .
|
cosqa-train-17333
|
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 is_sqlatype_integer ( coltype : Union [ TypeEngine , VisitableType ] ) -> bool : coltype = _coltype_to_typeengine ( coltype ) return isinstance ( coltype , sqltypes . Integer )
| 1 |
python sqlalchemy column enum
|
Is the SQLAlchemy column type an integer type?
|
cosqa-train-17334
|
def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type an integer type?
"""
coltype = _coltype_to_typeengine(coltype)
return isinstance(coltype, sqltypes.Integer)
|
def _ ( f , x ) : return { k : v for k , v in x . items ( ) if f ( k , v ) }
| 0 |
python filter dictionary and output subset
|
filter for dict note f should have signature : f :: key - > value - > bool
|
cosqa-train-17335
|
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 most_frequent ( lst ) : lst = lst [ : ] highest_freq = 0 most_freq = None for val in unique ( lst ) : if lst . count ( val ) > highest_freq : most_freq = val highest_freq = lst . count ( val ) return most_freq
| 0 |
how to return 10 most frequent occurances in a list with python
|
Returns the item that appears most frequently in the given list .
|
cosqa-train-17336
|
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 simple_eq ( one : Instance , two : Instance , attrs : List [ str ] ) -> bool : return all ( getattr ( one , a ) == getattr ( two , a ) for a in attrs )
| 1 |
python best way to compare attributes of an object to other objects
|
Test if two objects are equal based on a comparison of the specified attributes attrs .
|
cosqa-train-17337
|
def simple_eq(one: Instance, two: Instance, attrs: List[str]) -> bool:
"""
Test if two objects are equal, based on a comparison of the specified
attributes ``attrs``.
"""
return all(getattr(one, a) == getattr(two, a) for a in attrs)
|
def split ( text : str ) -> List [ str ] : return [ word for word in SEPARATOR . split ( text ) if word . strip ( ' \t' ) ]
| 0 |
python split on spaces but also tokenize punctuation
|
Split a text into a list of tokens .
|
cosqa-train-17338
|
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 to_int64 ( a ) : # build new dtype and replace i4 --> i8 def promote_i4 ( typestr ) : if typestr [ 1 : ] == 'i4' : typestr = typestr [ 0 ] + 'i8' return typestr dtype = [ ( name , promote_i4 ( typestr ) ) for name , typestr in a . dtype . descr ] return a . astype ( dtype )
| 1 |
change dtype to int in python
|
Return view of the recarray with all int32 cast to int64 .
|
cosqa-train-17339
|
def to_int64(a):
"""Return view of the recarray with all int32 cast to int64."""
# build new dtype and replace i4 --> i8
def promote_i4(typestr):
if typestr[1:] == 'i4':
typestr = typestr[0]+'i8'
return typestr
dtype = [(name, promote_i4(typestr)) for name,typestr in a.dtype.descr]
return a.astype(dtype)
|
def imt2tup ( string ) : s = string . strip ( ) if not s . endswith ( ')' ) : # no parenthesis, PGA is considered the same as PGA() return ( s , ) name , rest = s . split ( '(' , 1 ) return ( name , ) + tuple ( float ( x ) for x in ast . literal_eval ( rest [ : - 1 ] + ',' ) )
| 0 |
python conver a string to a tup
|
>>> imt2tup ( PGA ) ( PGA ) >>> imt2tup ( SA ( 1 . 0 ) ) ( SA 1 . 0 ) >>> imt2tup ( SA ( 1 ) ) ( SA 1 . 0 )
|
cosqa-train-17340
|
def imt2tup(string):
"""
>>> imt2tup('PGA')
('PGA',)
>>> imt2tup('SA(1.0)')
('SA', 1.0)
>>> imt2tup('SA(1)')
('SA', 1.0)
"""
s = string.strip()
if not s.endswith(')'):
# no parenthesis, PGA is considered the same as PGA()
return (s,)
name, rest = s.split('(', 1)
return (name,) + tuple(float(x) for x in ast.literal_eval(rest[:-1] + ','))
|
def read ( self , count = 0 ) : return self . f . read ( count ) if count > 0 else self . f . read ( )
| 1 |
python does read or readline return an empty string
|
Read
|
cosqa-train-17341
|
def read(self, count=0):
""" Read """
return self.f.read(count) if count > 0 else self.f.read()
|
def list_to_str ( lst ) : if len ( lst ) == 1 : str_ = lst [ 0 ] elif len ( lst ) == 2 : str_ = ' and ' . join ( lst ) elif len ( lst ) > 2 : str_ = ', ' . join ( lst [ : - 1 ] ) str_ += ', and {0}' . format ( lst [ - 1 ] ) else : raise ValueError ( 'List of length 0 provided.' ) return str_
| 1 |
python list of string to one string comma delimitted
|
Turn a list into a comma - and / or and - separated string .
|
cosqa-train-17342
|
def list_to_str(lst):
"""
Turn a list into a comma- and/or and-separated string.
Parameters
----------
lst : :obj:`list`
A list of strings to join into a single string.
Returns
-------
str_ : :obj:`str`
A string with commas and/or ands separating th elements from ``lst``.
"""
if len(lst) == 1:
str_ = lst[0]
elif len(lst) == 2:
str_ = ' and '.join(lst)
elif len(lst) > 2:
str_ = ', '.join(lst[:-1])
str_ += ', and {0}'.format(lst[-1])
else:
raise ValueError('List of length 0 provided.')
return str_
|
def _store_helper ( model : Action , session : Optional [ Session ] = None ) -> None : if session is None : session = _make_session ( ) session . add ( model ) session . commit ( ) session . close ( )
| 0 |
python sqlalchemy execute store procedure
|
Help store an action .
|
cosqa-train-17343
|
def _store_helper(model: Action, session: Optional[Session] = None) -> None:
"""Help store an action."""
if session is None:
session = _make_session()
session.add(model)
session.commit()
session.close()
|
def valid_date ( x : str ) -> bool : try : if x != dt . datetime . strptime ( x , DATE_FORMAT ) . strftime ( DATE_FORMAT ) : raise ValueError return True except ValueError : return False
| 1 |
check if a date is valid python
|
Retrun True if x is a valid YYYYMMDD date ; otherwise return False .
|
cosqa-train-17344
|
def valid_date(x: str) -> bool:
"""
Retrun ``True`` if ``x`` is a valid YYYYMMDD date;
otherwise return ``False``.
"""
try:
if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):
raise ValueError
return True
except ValueError:
return False
|
def _cursorLeft ( self ) : if self . cursorPos > 0 : self . cursorPos -= 1 sys . stdout . write ( console . CURSOR_LEFT ) sys . stdout . flush ( )
| 0 |
place the cursor on the next line after print python
|
Handles cursor left events
|
cosqa-train-17345
|
def _cursorLeft(self):
""" Handles "cursor left" events """
if self.cursorPos > 0:
self.cursorPos -= 1
sys.stdout.write(console.CURSOR_LEFT)
sys.stdout.flush()
|
def has_key ( cls , * args ) : key = args if len ( args ) > 1 else args [ 0 ] return key in cls . _instances
| 1 |
python if key exist complexity
|
Check whether flyweight object with specified key has already been created .
|
cosqa-train-17346
|
def has_key(cls, *args):
"""
Check whether flyweight object with specified key has already been created.
Returns:
bool: True if already created, False if not
"""
key = args if len(args) > 1 else args[0]
return key in cls._instances
|
def strtobytes ( input , encoding ) : py_version = sys . version_info [ 0 ] if py_version >= 3 : return _strtobytes_py3 ( input , encoding ) return _strtobytes_py2 ( input , encoding )
| 0 |
python 3 codecs decode
|
Take a str and transform it into a byte array .
|
cosqa-train-17347
|
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 get_last_weekday_in_month ( year , month , weekday ) : day = date ( year , month , monthrange ( year , month ) [ 1 ] ) while True : if day . weekday ( ) == weekday : break day = day - timedelta ( days = 1 ) return day
| 1 |
python is last day in month
|
Get the last weekday in a given month . e . g :
|
cosqa-train-17348
|
def get_last_weekday_in_month(year, month, weekday):
"""Get the last weekday in a given month. e.g:
>>> # the last monday in Jan 2013
>>> Calendar.get_last_weekday_in_month(2013, 1, MON)
datetime.date(2013, 1, 28)
"""
day = date(year, month, monthrange(year, month)[1])
while True:
if day.weekday() == weekday:
break
day = day - timedelta(days=1)
return day
|
def camel_to_snake_case ( string ) : s = _1 . sub ( r'\1_\2' , string ) return _2 . sub ( r'\1_\2' , s ) . lower ( )
| 0 |
python change string value in variable to lower case
|
Converts string presented in camel case to snake case .
|
cosqa-train-17349
|
def camel_to_snake_case(string):
"""Converts 'string' presented in camel case to snake case.
e.g.: CamelCase => snake_case
"""
s = _1.sub(r'\1_\2', string)
return _2.sub(r'\1_\2', s).lower()
|
def get_keys_of_max_n ( dict_obj , n ) : return sorted ( [ item [ 0 ] for item in sorted ( dict_obj . items ( ) , key = lambda item : item [ 1 ] , reverse = True ) [ : n ] ] )
| 1 |
how to get top 5 key values in python dictionary
|
Returns the keys that maps to the top n max values in the given dict .
|
cosqa-train-17350
|
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 flatten_list ( x : List [ Any ] ) -> List [ Any ] : # noqa return [ item for sublist in x for item in sublist ]
| 1 |
flatten python list of list
|
Converts a list of lists into a flat list . Args : x : list of lists
|
cosqa-train-17351
|
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 datetime_from_isoformat ( value : str ) : if sys . version_info >= ( 3 , 7 ) : return datetime . fromisoformat ( value ) return datetime . strptime ( value , '%Y-%m-%dT%H:%M:%S.%f' )
| 1 |
read python datetime from isoformat
|
Return a datetime object from an isoformat string .
|
cosqa-train-17352
|
def datetime_from_isoformat(value: str):
"""Return a datetime object from an isoformat string.
Args:
value (str): Datetime string in isoformat.
"""
if sys.version_info >= (3, 7):
return datetime.fromisoformat(value)
return datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f')
|
def get_domain ( url ) : parse_result = urlparse ( url ) domain = "{schema}://{netloc}" . format ( schema = parse_result . scheme , netloc = parse_result . netloc ) return domain
| 0 |
domain specific language for python
|
Get domain part of an url .
|
cosqa-train-17353
|
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 argmax ( self , rows : List [ Row ] , column : ComparableColumn ) -> List [ Row ] : if not rows : return [ ] value_row_pairs = [ ( row . values [ column . name ] , row ) for row in rows ] if not value_row_pairs : return [ ] # Returns a list containing the row with the max cell value. return [ sorted ( value_row_pairs , key = lambda x : x [ 0 ] , reverse = True ) [ 0 ] [ 1 ] ]
| 0 |
how to return max value in column 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-17354
|
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 tanimoto_set_similarity ( x : Iterable [ X ] , y : Iterable [ X ] ) -> float : a , b = set ( x ) , set ( y ) union = a | b if not union : return 0.0 return len ( a & b ) / len ( union )
| 1 |
looking for similarity between 2 lists in python
|
Calculate the tanimoto set similarity .
|
cosqa-train-17355
|
def tanimoto_set_similarity(x: Iterable[X], y: Iterable[X]) -> float:
"""Calculate the tanimoto set similarity."""
a, b = set(x), set(y)
union = a | b
if not union:
return 0.0
return len(a & b) / len(union)
|
def reverse_mapping ( mapping ) : keys , values = zip ( * mapping . items ( ) ) return dict ( zip ( values , keys ) )
| 1 |
how do do opposite mapping in python
|
For every key value pair return the mapping for the equivalent value key pair
|
cosqa-train-17356
|
def reverse_mapping(mapping):
"""
For every key, value pair, return the mapping for the
equivalent value, key pair
>>> reverse_mapping({'a': 'b'}) == {'b': 'a'}
True
"""
keys, values = zip(*mapping.items())
return dict(zip(values, keys))
|
def exponential_backoff ( attempt : int , cap : int = 1200 ) -> timedelta : base = 3 temp = min ( base * 2 ** attempt , cap ) return timedelta ( seconds = temp / 2 + random . randint ( 0 , temp / 2 ) )
| 0 |
python retry after 30 seconds
|
Calculate a delay to retry using an exponential backoff algorithm .
|
cosqa-train-17357
|
def exponential_backoff(attempt: int, cap: int=1200) -> timedelta:
"""Calculate a delay to retry using an exponential backoff algorithm.
It is an exponential backoff with random jitter to prevent failures
from being retried at the same time. It is a good fit for most
applications.
:arg attempt: the number of attempts made
:arg cap: maximum delay, defaults to 20 minutes
"""
base = 3
temp = min(base * 2 ** attempt, cap)
return timedelta(seconds=temp / 2 + random.randint(0, temp / 2))
|
def get_table_names_from_metadata ( metadata : MetaData ) -> List [ str ] : return [ table . name for table in metadata . tables . values ( ) ]
| 1 |
python load oracle database tabls in sql alchemy metadata
|
Returns all database table names found in an SQLAlchemy : class : MetaData object .
|
cosqa-train-17358
|
def get_table_names_from_metadata(metadata: MetaData) -> List[str]:
"""
Returns all database table names found in an SQLAlchemy :class:`MetaData`
object.
"""
return [table.name for table in metadata.tables.values()]
|
def 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 remove all dictionary values equal to none
|
Return a new copied dictionary without the keys with None values from the given Mapping object .
|
cosqa-train-17359
|
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 dtypes ( self ) : return [ ( str ( f . name ) , f . dataType . simpleString ( ) ) for f in self . schema . fields ]
| 0 |
get datatype of columns in python
|
Returns all column names and their data types as a list .
|
cosqa-train-17360
|
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 is_integer ( value : Any ) -> bool : return ( isinstance ( value , int ) and not isinstance ( value , bool ) ) or ( isinstance ( value , float ) and isfinite ( value ) and int ( value ) == value )
| 0 |
python is list or float
|
Return true if a value is an integer number .
|
cosqa-train-17361
|
def is_integer(value: Any) -> bool:
"""Return true if a value is an integer number."""
return (isinstance(value, int) and not isinstance(value, bool)) or (
isinstance(value, float) and isfinite(value) and int(value) == value
)
|
def flatten_multidict ( multidict ) : return dict ( [ ( key , value if len ( value ) > 1 else value [ 0 ] ) for ( key , value ) in multidict . iterlists ( ) ] )
| 0 |
python flatten a dictionary of dictionaries
|
Return flattened dictionary from MultiDict .
|
cosqa-train-17362
|
def flatten_multidict(multidict):
"""Return flattened dictionary from ``MultiDict``."""
return dict([(key, value if len(value) > 1 else value[0])
for (key, value) in multidict.iterlists()])
|
def dict_to_enum_fn ( d : Dict [ str , Any ] , enum_class : Type [ Enum ] ) -> Enum : return enum_class [ d [ 'name' ] ]
| 0 |
create enum object from value python
|
Converts an dict to a Enum .
|
cosqa-train-17363
|
def dict_to_enum_fn(d: Dict[str, Any], enum_class: Type[Enum]) -> Enum:
"""
Converts an ``dict`` to a ``Enum``.
"""
return enum_class[d['name']]
|
def almost_hermitian ( gate : Gate ) -> bool : return np . allclose ( asarray ( gate . asoperator ( ) ) , asarray ( gate . H . asoperator ( ) ) )
| 0 |
how to check if a matrix is hermitian python
|
Return true if gate tensor is ( almost ) Hermitian
|
cosqa-train-17364
|
def almost_hermitian(gate: Gate) -> bool:
"""Return true if gate tensor is (almost) Hermitian"""
return np.allclose(asarray(gate.asoperator()),
asarray(gate.H.asoperator()))
|
def recClearTag ( element ) : children = element . getchildren ( ) if len ( children ) > 0 : for child in children : recClearTag ( child ) element . tag = clearTag ( element . tag )
| 0 |
python xml elementtree remove node
|
Applies maspy . xml . clearTag () to the tag attribute of the element and recursively to all child elements .
|
cosqa-train-17365
|
def recClearTag(element):
"""Applies maspy.xml.clearTag() to the tag attribute of the "element" and
recursively to all child elements.
:param element: an :instance:`xml.etree.Element`
"""
children = element.getchildren()
if len(children) > 0:
for child in children:
recClearTag(child)
element.tag = clearTag(element.tag)
|
def sample_normal ( mean , var , rng ) : ret = numpy . sqrt ( var ) * rng . randn ( * mean . shape ) + mean return ret
| 1 |
normal distribution with n samples python
|
Sample from independent normal distributions
|
cosqa-train-17366
|
def sample_normal(mean, var, rng):
"""Sample from independent normal distributions
Each element is an independent normal distribution.
Parameters
----------
mean : numpy.ndarray
Means of the normal distribution. Shape --> (batch_num, sample_dim)
var : numpy.ndarray
Variance of the normal distribution. Shape --> (batch_num, sample_dim)
rng : numpy.random.RandomState
Returns
-------
ret : numpy.ndarray
The sampling result. Shape --> (batch_num, sample_dim)
"""
ret = numpy.sqrt(var) * rng.randn(*mean.shape) + mean
return ret
|
def _my_hash ( arg_list ) : # type: (List[Any]) -> int res = 0 for arg in arg_list : res = res * 31 + hash ( arg ) return res
| 1 |
how to quickly ad hash to python
|
Simple helper hash function
|
cosqa-train-17367
|
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 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 |
reading a 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-17368
|
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 timeit ( func , * args , * * kwargs ) : start_time = time . time ( ) res = func ( * args , * * kwargs ) timing = time . time ( ) - start_time return res , timing
| 1 |
pass function variable in timeit python
|
Time execution of function . Returns ( res seconds ) .
|
cosqa-train-17369
|
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 to_int64 ( a ) : # build new dtype and replace i4 --> i8 def promote_i4 ( typestr ) : if typestr [ 1 : ] == 'i4' : typestr = typestr [ 0 ] + 'i8' return typestr dtype = [ ( name , promote_i4 ( typestr ) ) for name , typestr in a . dtype . descr ] return a . astype ( dtype )
| 0 |
convrt dtypes to int in python
|
Return view of the recarray with all int32 cast to int64 .
|
cosqa-train-17370
|
def to_int64(a):
"""Return view of the recarray with all int32 cast to int64."""
# build new dtype and replace i4 --> i8
def promote_i4(typestr):
if typestr[1:] == 'i4':
typestr = typestr[0]+'i8'
return typestr
dtype = [(name, promote_i4(typestr)) for name,typestr in a.dtype.descr]
return a.astype(dtype)
|
def fetchvalue ( self , sql : str , * args ) -> Optional [ Any ] : row = self . fetchone ( sql , * args ) if row is None : return None return row [ 0 ]
| 1 |
how to fetch one value from one row from mysql query in python
|
Executes SQL ; returns the first value of the first row or None .
|
cosqa-train-17371
|
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 inject_nulls ( data : Mapping , field_names ) -> dict : record = dict ( ) for field in field_names : record [ field ] = data . get ( field , None ) return record
| 0 |
python null value dictionary
|
Insert None as value for missing fields .
|
cosqa-train-17372
|
def inject_nulls(data: Mapping, field_names) -> dict:
"""Insert None as value for missing fields."""
record = dict()
for field in field_names:
record[field] = data.get(field, None)
return record
|
def clean_column_names ( df : DataFrame ) -> DataFrame : f = df . copy ( ) f . columns = [ col . strip ( ) for col in f . columns ] return f
| 0 |
how to remove columns from python data frame
|
Strip the whitespace from all column names in the given DataFrame and return the result .
|
cosqa-train-17373
|
def clean_column_names(df: DataFrame) -> DataFrame:
"""
Strip the whitespace from all column names in the given DataFrame
and return the result.
"""
f = df.copy()
f.columns = [col.strip() for col in f.columns]
return f
|
def bytes_hack ( buf ) : ub = None if sys . version_info > ( 3 , ) : ub = buf else : ub = bytes ( buf ) return ub
| 0 |
update stale python 3 bytecode
|
Hacky workaround for old installs of the library on systems without python - future that were keeping the 2to3 update from working after auto - update .
|
cosqa-train-17374
|
def bytes_hack(buf):
"""
Hacky workaround for old installs of the library on systems without python-future that were
keeping the 2to3 update from working after auto-update.
"""
ub = None
if sys.version_info > (3,):
ub = buf
else:
ub = bytes(buf)
return ub
|
def chars ( string : any ) -> str : return '' . join ( [ c if c . isalpha ( ) else '' for c in str ( string ) ] )
| 1 |
finding all non alphanumeric characters in a string python
|
Return all ( and only ) the chars in the given string .
|
cosqa-train-17375
|
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 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 read lines from file until next blank line
|
Helper for iterating only nonempty lines without line breaks
|
cosqa-train-17376
|
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 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 path is valid
|
Verifies that a string path actually exists and is a file
|
cosqa-train-17377
|
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 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 )
| 0 |
python pass argparse to main
|
docstring for argparse
|
cosqa-train-17378
|
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 pack_bits ( longbits ) : byte = longbits & ( 0x0101010101010101 ) byte = ( byte | ( byte >> 7 ) ) & ( 0x0003000300030003 ) byte = ( byte | ( byte >> 14 ) ) & ( 0x0000000f0000000f ) byte = ( byte | ( byte >> 28 ) ) & ( 0x00000000000000ff ) return byte
| 1 |
setting bit fields with python
|
Crunch a 64 - bit int ( 8 bool bytes ) into a bitfield .
|
cosqa-train-17379
|
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 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 ''
| 0 |
python if string matches return next lines
|
Very simple grep that returns the first matching line in a file . String matching only does not do REs as currently implemented .
|
cosqa-train-17380
|
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 flatten_list ( l : List [ list ] ) -> list : return [ v for inner_l in l for v in inner_l ]
| 0 |
how to flatten a list in a list in python
|
takes a list of lists l and returns a flat list
|
cosqa-train-17381
|
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 get_deprecation_reason ( node : Union [ EnumValueDefinitionNode , FieldDefinitionNode ] ) -> Optional [ str ] : from . . execution import get_directive_values deprecated = get_directive_values ( GraphQLDeprecatedDirective , node ) return deprecated [ "reason" ] if deprecated else None
| 1 |
python how to mark as deprecated
|
Given a field or enum value node get deprecation reason as string .
|
cosqa-train-17382
|
def get_deprecation_reason(
node: Union[EnumValueDefinitionNode, FieldDefinitionNode]
) -> Optional[str]:
"""Given a field or enum value node, get deprecation reason as string."""
from ..execution import get_directive_values
deprecated = get_directive_values(GraphQLDeprecatedDirective, node)
return deprecated["reason"] if deprecated else None
|
def dtypes ( self ) : return [ ( str ( f . name ) , f . dataType . simpleString ( ) ) for f in self . schema . fields ]
| 1 |
data type of python columns
|
Returns all column names and their data types as a list .
|
cosqa-train-17383
|
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 _prm_get_longest_stringsize ( string_list ) : maxlength = 1 for stringar in string_list : if isinstance ( stringar , np . ndarray ) : if stringar . ndim > 0 : for string in stringar . ravel ( ) : maxlength = max ( len ( string ) , maxlength ) else : maxlength = max ( len ( stringar . tolist ( ) ) , maxlength ) else : maxlength = max ( len ( stringar ) , maxlength ) # Make the string Col longer than needed in order to allow later on slightly larger strings return int ( maxlength * 1.5 )
| 0 |
return max length of string for list of strings python
|
Returns the longest string size for a string entry across data .
|
cosqa-train-17384
|
def _prm_get_longest_stringsize(string_list):
""" Returns the longest string size for a string entry across data."""
maxlength = 1
for stringar in string_list:
if isinstance(stringar, np.ndarray):
if stringar.ndim > 0:
for string in stringar.ravel():
maxlength = max(len(string), maxlength)
else:
maxlength = max(len(stringar.tolist()), maxlength)
else:
maxlength = max(len(stringar), maxlength)
# Make the string Col longer than needed in order to allow later on slightly larger strings
return int(maxlength * 1.5)
|
def first_location_of_maximum ( x ) : if not isinstance ( x , ( np . ndarray , pd . Series ) ) : x = np . asarray ( x ) return np . argmax ( x ) / len ( x ) if len ( x ) > 0 else np . NaN
| 1 |
max value in a series in python
|
Returns the first location of the maximum value of x . The position is calculated relatively to the length of x .
|
cosqa-train-17385
|
def first_location_of_maximum(x):
"""
Returns the first location of the maximum value of x.
The position is calculated relatively to the length of x.
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
if not isinstance(x, (np.ndarray, pd.Series)):
x = np.asarray(x)
return np.argmax(x) / len(x) if len(x) > 0 else np.NaN
|
def astensor ( array : TensorLike ) -> BKTensor : tensor = tf . convert_to_tensor ( value = array , dtype = CTYPE ) return tensor
| 1 |
to covert matrix to tensorflow in python
|
Covert numpy array to tensorflow tensor
|
cosqa-train-17386
|
def astensor(array: TensorLike) -> BKTensor:
"""Covert numpy array to tensorflow tensor"""
tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)
return tensor
|
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 |
visualize dot file python
|
Print out a neat targets dependency tree based on requested targets .
|
cosqa-train-17387
|
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 has_value ( cls , value : int ) -> bool : return any ( value == item . value for item in cls )
| 0 |
python check if a value is in an enum
|
True if specified value exists in int enum ; otherwise False .
|
cosqa-train-17388
|
def has_value(cls, value: int) -> bool:
"""True if specified value exists in int enum; otherwise, False."""
return any(value == item.value for item in cls)
|
def _rindex ( mylist : Sequence [ T ] , x : T ) -> int : return len ( mylist ) - mylist [ : : - 1 ] . index ( x ) - 1
| 1 |
how to get the last index of something python
|
Index of the last occurrence of x in the sequence .
|
cosqa-train-17389
|
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 _skip_section ( self ) : self . _last = self . _f . readline ( ) while len ( self . _last ) > 0 and len ( self . _last [ 0 ] . strip ( ) ) == 0 : self . _last = self . _f . readline ( )
| 0 |
how to manually skip a line in python
|
Skip a section
|
cosqa-train-17390
|
def _skip_section(self):
"""Skip a section"""
self._last = self._f.readline()
while len(self._last) > 0 and len(self._last[0].strip()) == 0:
self._last = self._f.readline()
|
def post ( self , endpoint : str , * * kwargs ) -> dict : return self . _request ( 'POST' , endpoint , * * kwargs )
| 1 |
python call post api data dict data
|
HTTP POST operation to API endpoint .
|
cosqa-train-17391
|
def post(self, endpoint: str, **kwargs) -> dict:
"""HTTP POST operation to API endpoint."""
return self._request('POST', endpoint, **kwargs)
|
def auto_up ( self , count = 1 , go_to_start_of_line_if_history_changes = False ) : if self . complete_state : self . complete_previous ( count = count ) elif self . document . cursor_position_row > 0 : self . cursor_up ( count = count ) elif not self . selection_state : self . history_backward ( count = count ) # Go to the start of the line? if go_to_start_of_line_if_history_changes : self . cursor_position += self . document . get_start_of_line_position ( )
| 0 |
how to go back to the previous line in python
|
If we re not on the first line ( of a multiline input ) go a line up otherwise go back in history . ( If nothing is selected . )
|
cosqa-train-17392
|
def auto_up(self, count=1, go_to_start_of_line_if_history_changes=False):
"""
If we're not on the first line (of a multiline input) go a line up,
otherwise go back in history. (If nothing is selected.)
"""
if self.complete_state:
self.complete_previous(count=count)
elif self.document.cursor_position_row > 0:
self.cursor_up(count=count)
elif not self.selection_state:
self.history_backward(count=count)
# Go to the start of the line?
if go_to_start_of_line_if_history_changes:
self.cursor_position += self.document.get_start_of_line_position()
|
def to_0d_array ( value : Any ) -> np . ndarray : if np . isscalar ( value ) or ( isinstance ( value , np . ndarray ) and value . ndim == 0 ) : return np . array ( value ) else : return to_0d_object_array ( value )
| 0 |
python ndarray make zero array
|
Given a value wrap it in a 0 - D numpy . ndarray .
|
cosqa-train-17393
|
def to_0d_array(value: Any) -> np.ndarray:
"""Given a value, wrap it in a 0-D numpy.ndarray.
"""
if np.isscalar(value) or (isinstance(value, np.ndarray) and
value.ndim == 0):
return np.array(value)
else:
return to_0d_object_array(value)
|
def gcd_float ( numbers , tol = 1e-8 ) : def pair_gcd_tol ( a , b ) : """Calculate the Greatest Common Divisor of a and b.
Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive).
""" while b > tol : a , b = b , a % b return a n = numbers [ 0 ] for i in numbers : n = pair_gcd_tol ( n , i ) return n
| 1 |
greatest common divisor function in python
|
Returns the greatest common divisor for a sequence of numbers . Uses a numerical tolerance so can be used on floats
|
cosqa-train-17394
|
def gcd_float(numbers, tol=1e-8):
"""
Returns the greatest common divisor for a sequence of numbers.
Uses a numerical tolerance, so can be used on floats
Args:
numbers: Sequence of numbers.
tol: Numerical tolerance
Returns:
(int) Greatest common divisor of numbers.
"""
def pair_gcd_tol(a, b):
"""Calculate the Greatest Common Divisor of a and b.
Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive).
"""
while b > tol:
a, b = b, a % b
return a
n = numbers[0]
for i in numbers:
n = pair_gcd_tol(n, i)
return 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 generate hash from list
|
Simple helper hash function
|
cosqa-train-17395
|
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 astensor ( array : TensorLike ) -> BKTensor : tensor = tf . convert_to_tensor ( value = array , dtype = CTYPE ) return tensor
| 0 |
array to tensor tf python
|
Covert numpy array to tensorflow tensor
|
cosqa-train-17396
|
def astensor(array: TensorLike) -> BKTensor:
"""Covert numpy array to tensorflow tensor"""
tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)
return tensor
|
def is_not_null ( df : DataFrame , col_name : str ) -> bool : if ( isinstance ( df , pd . DataFrame ) and col_name in df . columns and df [ col_name ] . notnull ( ) . any ( ) ) : return True else : return False
| 1 |
how do you check if a data frame has null values 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-17397
|
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 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 )
| 0 |
python main function argparse
|
docstring for argparse
|
cosqa-train-17398
|
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 dotproduct ( X , Y ) : return sum ( [ x * y for x , y in zip ( X , Y ) ] )
| 1 |
python elementwise product vector and matrix
|
Return the sum of the element - wise product of vectors x and y . >>> dotproduct ( [ 1 2 3 ] [ 1000 100 10 ] ) 1230
|
cosqa-train-17399
|
def dotproduct(X, Y):
"""Return the sum of the element-wise product of vectors x and y.
>>> dotproduct([1, 2, 3], [1000, 100, 10])
1230
"""
return sum([x * y for x, y in zip(X, Y)])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.