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 last_commit ( self ) -> Tuple : from libs . repos import git return git . get_last_commit ( repo_path = self . path )
| 1 |
how to load commits in order python from gitlog
|
Returns a tuple ( hash and commit object )
|
cosqa-train-17000
|
def last_commit(self) -> Tuple:
"""Returns a tuple (hash, and commit object)"""
from libs.repos import git
return git.get_last_commit(repo_path=self.path)
|
def indexes_equal ( a : Index , b : Index ) -> bool : return str ( a ) == str ( b )
| 0 |
how do i determine 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-17001
|
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 dictlist_wipe_key ( dict_list : Iterable [ Dict ] , key : str ) -> None : for d in dict_list : d . pop ( key , None )
| 1 |
how to delete an entry in a python dictionary
|
Process an iterable of dictionaries . For each dictionary d delete d [ key ] if it exists .
|
cosqa-train-17002
|
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 lower_camel_case_from_underscores ( string ) : components = string . split ( '_' ) string = components [ 0 ] for component in components [ 1 : ] : string += component [ 0 ] . upper ( ) + component [ 1 : ] return string
| 0 |
local variables with underscore python
|
generate a lower - cased camelCase string from an underscore_string . For example : my_variable_name - > myVariableName
|
cosqa-train-17003
|
def lower_camel_case_from_underscores(string):
"""generate a lower-cased camelCase string from an underscore_string.
For example: my_variable_name -> myVariableName"""
components = string.split('_')
string = components[0]
for component in components[1:]:
string += component[0].upper() + component[1:]
return string
|
def has_synset ( word : str ) -> list : return wn . synsets ( lemmatize ( word , neverstem = True ) )
| 1 |
wordnet synsets implementation in python
|
Returns a list of synsets of a word after lemmatization .
|
cosqa-train-17004
|
def has_synset(word: str) -> list:
"""" Returns a list of synsets of a word after lemmatization. """
return wn.synsets(lemmatize(word, neverstem=True))
|
def is_sqlatype_string ( coltype : Union [ TypeEngine , VisitableType ] ) -> bool : coltype = _coltype_to_typeengine ( coltype ) return isinstance ( coltype , sqltypes . String )
| 0 |
how to conveert data type of a column using python
|
Is the SQLAlchemy column type a string type?
|
cosqa-train-17005
|
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 list_to_str ( lst ) : if len ( lst ) == 1 : str_ = lst [ 0 ] elif len ( lst ) == 2 : str_ = ' and ' . join ( lst ) elif len ( lst ) > 2 : str_ = ', ' . join ( lst [ : - 1 ] ) str_ += ', and {0}' . format ( lst [ - 1 ] ) else : raise ValueError ( 'List of length 0 provided.' ) return str_
| 0 |
python join list to string comma separated
|
Turn a list into a comma - and / or and - separated string .
|
cosqa-train-17006
|
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 from_file ( file_path ) -> dict : with io . open ( file_path , 'r' , encoding = 'utf-8' ) as json_stream : return Json . parse ( json_stream , True )
| 1 |
read json file and turn into dictionary using python
|
Load JSON file
|
cosqa-train-17007
|
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 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 lambda parsing arg
|
docstring for argparse
|
cosqa-train-17008
|
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 remove_empty_text ( utterances : List [ Utterance ] ) -> List [ Utterance ] : return [ utter for utter in utterances if utter . text . strip ( ) != "" ]
| 1 |
python remove words from sentences in a list
|
Remove empty utterances from a list of utterances Args : utterances : The list of utterance we are processing
|
cosqa-train-17009
|
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 chars ( string : any ) -> str : return '' . join ( [ c if c . isalpha ( ) else '' for c in str ( string ) ] )
| 0 |
check all letters in a string in python
|
Return all ( and only ) the chars in the given string .
|
cosqa-train-17010
|
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 SetCursorPos ( x : int , y : int ) -> bool : return bool ( ctypes . windll . user32 . SetCursorPos ( x , y ) )
| 0 |
how to move curser using pywin32 in python code
|
SetCursorPos from Win32 . Set mouse cursor to point x y . x : int . y : int . Return bool True if succeed otherwise False .
|
cosqa-train-17011
|
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 try_cast_int ( s ) : try : temp = re . findall ( '\d' , str ( s ) ) temp = '' . join ( temp ) return int ( temp ) except : return s
| 1 |
python string deciaml to int
|
( str ) - > int All the digits in a given string are concatenated and converted into a single number .
|
cosqa-train-17012
|
def try_cast_int(s):
"""(str) -> int
All the digits in a given string are concatenated and converted into a single number.
"""
try:
temp = re.findall('\d', str(s))
temp = ''.join(temp)
return int(temp)
except:
return s
|
def inverted_dict ( d ) : return dict ( ( force_hashable ( v ) , k ) for ( k , v ) in viewitems ( dict ( d ) ) )
| 0 |
python how to invert a dictionary
|
Return a dict with swapped keys and values
|
cosqa-train-17013
|
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 is_natural ( x ) : try : is_integer = int ( x ) == x except ( TypeError , ValueError ) : return False return is_integer and x >= 0
| 1 |
python 3 none compare with int
|
A non - negative integer .
|
cosqa-train-17014
|
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 most_significant_bit ( lst : np . ndarray ) -> int : return np . argwhere ( np . asarray ( lst ) == 1 ) [ 0 ] [ 0 ]
| 0 |
python code to print out index of largest element in numpy array
|
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-17015
|
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 rank ( tensor : BKTensor ) -> int : if isinstance ( tensor , np . ndarray ) : return len ( tensor . shape ) return len ( tensor [ 0 ] . size ( ) )
| 0 |
length of a vector (1,1) in python
|
Return the number of dimensions of a tensor
|
cosqa-train-17016
|
def rank(tensor: BKTensor) -> int:
"""Return the number of dimensions of a tensor"""
if isinstance(tensor, np.ndarray):
return len(tensor.shape)
return len(tensor[0].size())
|
def str_to_time ( time_str : str ) -> datetime . datetime : pieces : Any = [ int ( piece ) for piece in time_str . split ( '-' ) ] return datetime . datetime ( * pieces )
| 0 |
python string list to datetime
|
Convert human readable string to datetime . datetime .
|
cosqa-train-17017
|
def str_to_time(time_str: str) -> datetime.datetime:
"""
Convert human readable string to datetime.datetime.
"""
pieces: Any = [int(piece) for piece in time_str.split('-')]
return datetime.datetime(*pieces)
|
def remove_nans_1D ( * args ) -> tuple : vals = np . isnan ( args [ 0 ] ) for a in args : vals |= np . isnan ( a ) return tuple ( np . array ( a ) [ ~ vals ] for a in args )
| 0 |
filter non nan numpy python
|
Remove nans in a set of 1D arrays .
|
cosqa-train-17018
|
def remove_nans_1D(*args) -> tuple:
"""Remove nans in a set of 1D arrays.
Removes indicies in all arrays if any array is nan at that index.
All input arrays must have the same size.
Parameters
----------
args : 1D arrays
Returns
-------
tuple
Tuple of 1D arrays in same order as given, with nan indicies removed.
"""
vals = np.isnan(args[0])
for a in args:
vals |= np.isnan(a)
return tuple(np.array(a)[~vals] for a in args)
|
def has_key ( cls , * args ) : key = args if len ( args ) > 1 else args [ 0 ] return key in cls . _instances
| 0 |
how do i ask if key exists python
|
Check whether flyweight object with specified key has already been created .
|
cosqa-train-17019
|
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 snake_to_camel ( s : str ) -> str : fragments = s . split ( '_' ) return fragments [ 0 ] + '' . join ( x . title ( ) for x in fragments [ 1 : ] )
| 1 |
how to make the secon character to capitalize in python
|
Convert string from snake case to camel case .
|
cosqa-train-17020
|
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 _latex_format ( obj : Any ) -> str : if isinstance ( obj , float ) : try : return sympy . latex ( symbolize ( obj ) ) except ValueError : return "{0:.4g}" . format ( obj ) return str ( obj )
| 0 |
how to type in latex in python
|
Format an object as a latex string .
|
cosqa-train-17021
|
def _latex_format(obj: Any) -> str:
"""Format an object as a latex string."""
if isinstance(obj, float):
try:
return sympy.latex(symbolize(obj))
except ValueError:
return "{0:.4g}".format(obj)
return str(obj)
|
def is_empty_shape ( sh : ShExJ . Shape ) -> bool : return sh . closed is None and sh . expression is None and sh . extra is None and sh . semActs is None
| 0 |
check if object is empty python
|
Determine whether sh has any value
|
cosqa-train-17022
|
def is_empty_shape(sh: ShExJ.Shape) -> bool:
""" Determine whether sh has any value """
return sh.closed is None and sh.expression is None and sh.extra is None and \
sh.semActs is None
|
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 |
python create a set containing all the unique characters in the string read from the text file
|
Extract a de - duped collection ( set ) of text from a file . Expected file format is one item per line .
|
cosqa-train-17023
|
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 indexes_equal ( a : Index , b : Index ) -> bool : return str ( a ) == str ( b )
| 0 |
see if 2 strings are equal python
|
Are two indexes equal? Checks by comparing str () versions of them . ( AM UNSURE IF THIS IS ENOUGH . )
|
cosqa-train-17024
|
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 extend ( a : dict , b : dict ) -> dict : res = a . copy ( ) res . update ( b ) return res
| 1 |
create new dictionary from two dictionaries python
|
Merge two dicts and return a new dict . Much like subclassing works .
|
cosqa-train-17025
|
def extend(a: dict, b: dict) -> dict:
"""Merge two dicts and return a new dict. Much like subclassing works."""
res = a.copy()
res.update(b)
return res
|
def pmon ( month ) : year , month = month . split ( '-' ) return '{month_name}, {year}' . format ( month_name = calendar . month_name [ int ( month ) ] , year = year , )
| 0 |
printing the month name from a month number in python
|
P the month
|
cosqa-train-17026
|
def pmon(month):
"""
P the month
>>> print(pmon('2012-08'))
August, 2012
"""
year, month = month.split('-')
return '{month_name}, {year}'.format(
month_name=calendar.month_name[int(month)],
year=year,
)
|
def recClearTag ( element ) : children = element . getchildren ( ) if len ( children ) > 0 : for child in children : recClearTag ( child ) element . tag = clearTag ( element . tag )
| 0 |
delete xml element python
|
Applies maspy . xml . clearTag () to the tag attribute of the element and recursively to all child elements .
|
cosqa-train-17027
|
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 _lower ( string ) : if not string : return "" new_string = [ string [ 0 ] . lower ( ) ] for char in string [ 1 : ] : if char . isupper ( ) : new_string . append ( "_" ) new_string . append ( char . lower ( ) ) return "" . join ( new_string )
| 0 |
python extend the same list in lower case
|
Custom lower string function . Examples : FooBar - > foo_bar
|
cosqa-train-17028
|
def _lower(string):
"""Custom lower string function.
Examples:
FooBar -> foo_bar
"""
if not string:
return ""
new_string = [string[0].lower()]
for char in string[1:]:
if char.isupper():
new_string.append("_")
new_string.append(char.lower())
return "".join(new_string)
|
def iterate_items ( dictish ) : if hasattr ( dictish , 'iteritems' ) : return dictish . iteritems ( ) if hasattr ( dictish , 'items' ) : return dictish . items ( ) return dictish
| 0 |
python 3 dictionary comprehension multiple iterators
|
Return a consistent ( key value ) iterable on dict - like objects including lists of tuple pairs .
|
cosqa-train-17029
|
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 area ( self ) : area = 0.0 for segment in self . segments ( ) : area += ( ( segment . p . x * segment . q . y ) - ( segment . q . x * segment . p . y ) ) / 2 return area
| 0 |
area of a polygon in python
|
area () - > number
|
cosqa-train-17030
|
def area (self):
"""area() -> number
Returns the area of this Polygon.
"""
area = 0.0
for segment in self.segments():
area += ((segment.p.x * segment.q.y) - (segment.q.x * segment.p.y))/2
return area
|
def get_day_name ( self ) -> str : weekday = self . value . isoweekday ( ) - 1 return calendar . day_name [ weekday ]
| 1 |
get name of day of week python
|
Returns the day name
|
cosqa-train-17031
|
def get_day_name(self) -> str:
""" Returns the day name """
weekday = self.value.isoweekday() - 1
return calendar.day_name[weekday]
|
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 of words return a dictionary mapping each unique word to an index
|
Return dict mapping item - > indices .
|
cosqa-train-17032
|
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 recall_score ( y_true , y_pred , average = 'micro' , suffix = False ) : true_entities = set ( get_entities ( y_true , suffix ) ) pred_entities = set ( get_entities ( y_pred , suffix ) ) nb_correct = len ( true_entities & pred_entities ) nb_true = len ( true_entities ) score = nb_correct / nb_true if nb_true > 0 else 0 return score
| 0 |
accuracy and precision recall in python
|
Compute the recall .
|
cosqa-train-17033
|
def recall_score(y_true, y_pred, average='micro', suffix=False):
"""Compute the recall.
The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of
true positives and ``fn`` the number of false negatives. The recall is
intuitively the ability of the classifier to find all the positive samples.
The best value is 1 and the worst value is 0.
Args:
y_true : 2d array. Ground truth (correct) target values.
y_pred : 2d array. Estimated targets as returned by a tagger.
Returns:
score : float.
Example:
>>> from seqeval.metrics import recall_score
>>> y_true = [['O', 'O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
>>> y_pred = [['O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
>>> recall_score(y_true, y_pred)
0.50
"""
true_entities = set(get_entities(y_true, suffix))
pred_entities = set(get_entities(y_pred, suffix))
nb_correct = len(true_entities & pred_entities)
nb_true = len(true_entities)
score = nb_correct / nb_true if nb_true > 0 else 0
return score
|
def is_any_type_set ( sett : Set [ Type ] ) -> bool : return len ( sett ) == 1 and is_any_type ( min ( sett ) )
| 1 |
list of objects, how to tell if none of them have a value python
|
Helper method to check if a set of types is the { AnyObject } singleton
|
cosqa-train-17034
|
def is_any_type_set(sett: Set[Type]) -> bool:
"""
Helper method to check if a set of types is the {AnyObject} singleton
:param sett:
:return:
"""
return len(sett) == 1 and is_any_type(min(sett))
|
def unzoom_all ( self , event = None ) : if len ( self . conf . zoom_lims ) > 0 : self . conf . zoom_lims = [ self . conf . zoom_lims [ 0 ] ] self . unzoom ( event )
| 0 |
spider python zoom out
|
zoom out full data range
|
cosqa-train-17035
|
def unzoom_all(self, event=None):
""" zoom out full data range """
if len(self.conf.zoom_lims) > 0:
self.conf.zoom_lims = [self.conf.zoom_lims[0]]
self.unzoom(event)
|
def write_text ( filename : str , text : str ) -> None : with open ( filename , 'w' ) as f : # type: TextIO print ( text , file = f )
| 0 |
how to write to a text file in python
|
Writes text to a file .
|
cosqa-train-17036
|
def write_text(filename: str, text: str) -> None:
"""
Writes text to a file.
"""
with open(filename, 'w') as f: # type: TextIO
print(text, file=f)
|
def right_replace ( string , old , new , count = 1 ) : if not string : return string return new . join ( string . rsplit ( old , count ) )
| 0 |
python string replace last occurance
|
Right replaces count occurrences of old with new in string . For example ::
|
cosqa-train-17037
|
def right_replace(string, old, new, count=1):
"""
Right replaces ``count`` occurrences of ``old`` with ``new`` in ``string``.
For example::
right_replace('one_two_two', 'two', 'three') -> 'one_two_three'
"""
if not string:
return string
return new.join(string.rsplit(old, count))
|
def unzoom_all ( self , event = None ) : if len ( self . conf . zoom_lims ) > 0 : self . conf . zoom_lims = [ self . conf . zoom_lims [ 0 ] ] self . unzoom ( event )
| 1 |
python matplotlib how to zoom out
|
zoom out full data range
|
cosqa-train-17038
|
def unzoom_all(self, event=None):
""" zoom out full data range """
if len(self.conf.zoom_lims) > 0:
self.conf.zoom_lims = [self.conf.zoom_lims[0]]
self.unzoom(event)
|
def debugTreePrint ( node , pfx = "->" ) : print pfx , node . item for c in node . children : debugTreePrint ( c , " " + pfx )
| 0 |
python recursive print a tree networkx
|
Purely a debugging aid : Ascii - art picture of a tree descended from node
|
cosqa-train-17039
|
def debugTreePrint(node,pfx="->"):
"""Purely a debugging aid: Ascii-art picture of a tree descended from node"""
print pfx,node.item
for c in node.children:
debugTreePrint(c," "+pfx)
|
def exclude ( self , * args , * * kwargs ) -> "QuerySet" : return self . _filter_or_exclude ( negate = True , * args , * * kwargs )
| 0 |
python filter not none
|
Same as . filter () but with appends all args with NOT
|
cosqa-train-17040
|
def exclude(self, *args, **kwargs) -> "QuerySet":
"""
Same as .filter(), but with appends all args with NOT
"""
return self._filter_or_exclude(negate=True, *args, **kwargs)
|
def camel_to_snake ( s : str ) -> str : return CAMEL_CASE_RE . sub ( r'_\1' , s ) . strip ( ) . lower ( )
| 0 |
string is camel python
|
Convert string from camel case to snake case .
|
cosqa-train-17041
|
def camel_to_snake(s: str) -> str:
"""Convert string from camel case to snake case."""
return CAMEL_CASE_RE.sub(r'_\1', s).strip().lower()
|
def is_sqlatype_integer ( coltype : Union [ TypeEngine , VisitableType ] ) -> bool : coltype = _coltype_to_typeengine ( coltype ) return isinstance ( coltype , sqltypes . Integer )
| 1 |
python sqlalchemy different column different dtype
|
Is the SQLAlchemy column type an integer type?
|
cosqa-train-17042
|
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 get_timezone ( ) -> Tuple [ datetime . tzinfo , str ] : dt = get_datetime_now ( ) . astimezone ( ) tzstr = dt . strftime ( "%z" ) tzstr = tzstr [ : - 2 ] + ":" + tzstr [ - 2 : ] return dt . tzinfo , tzstr
| 0 |
python get timezone info
|
Discover the current time zone and it s standard string representation ( for source { d } ) .
|
cosqa-train-17043
|
def get_timezone() -> Tuple[datetime.tzinfo, str]:
"""Discover the current time zone and it's standard string representation (for source{d})."""
dt = get_datetime_now().astimezone()
tzstr = dt.strftime("%z")
tzstr = tzstr[:-2] + ":" + tzstr[-2:]
return dt.tzinfo, tzstr
|
def zfill ( x , width ) : if not isinstance ( x , basestring ) : x = repr ( x ) return x . zfill ( width )
| 0 |
how to pad zeros to string in python
|
zfill ( x width ) - > string
|
cosqa-train-17044
|
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 most_frequent ( lst ) : lst = lst [ : ] highest_freq = 0 most_freq = None for val in unique ( lst ) : if lst . count ( val ) > highest_freq : most_freq = val highest_freq = lst . count ( val ) return most_freq
| 1 |
python return most frequency of list
|
Returns the item that appears most frequently in the given list .
|
cosqa-train-17045
|
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 normalize ( numbers ) : total = float ( sum ( numbers ) ) return [ n / total for n in numbers ]
| 1 |
normalize percentage per row in 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-17046
|
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 attrname_to_colname_dict ( cls ) -> Dict [ str , str ] : attr_col = { } # type: Dict[str, str] for attrname , column in gen_columns ( cls ) : attr_col [ attrname ] = column . name return attr_col
| 1 |
get colunmn names in python
|
Asks an SQLAlchemy class how its attribute names correspond to database column names .
|
cosqa-train-17047
|
def attrname_to_colname_dict(cls) -> Dict[str, str]:
"""
Asks an SQLAlchemy class how its attribute names correspond to database
column names.
Args:
cls: SQLAlchemy ORM class
Returns:
a dictionary mapping attribute names to database column names
"""
attr_col = {} # type: Dict[str, str]
for attrname, column in gen_columns(cls):
attr_col[attrname] = column.name
return attr_col
|
async def parallel_results ( future_map : Sequence [ Tuple ] ) -> Dict : ctx_methods = OrderedDict ( future_map ) fs = list ( ctx_methods . values ( ) ) results = await asyncio . gather ( * fs ) results = { key : results [ idx ] for idx , key in enumerate ( ctx_methods . keys ( ) ) } return results
| 0 |
python asyncio 'bare yield'
|
Run parallel execution of futures and return mapping of their results to the provided keys . Just a neat shortcut around asyncio . gather ()
|
cosqa-train-17048
|
async def parallel_results(future_map: Sequence[Tuple]) -> Dict:
"""
Run parallel execution of futures and return mapping of their results to the provided keys.
Just a neat shortcut around ``asyncio.gather()``
:param future_map: Keys to futures mapping, e.g.: ( ('nav', get_nav()), ('content, get_content()) )
:return: Dict with futures results mapped to keys {'nav': {1:2}, 'content': 'xyz'}
"""
ctx_methods = OrderedDict(future_map)
fs = list(ctx_methods.values())
results = await asyncio.gather(*fs)
results = {
key: results[idx] for idx, key in enumerate(ctx_methods.keys())
}
return results
|
def __remove_trailing_zeros ( self , collection ) : index = len ( collection ) - 1 while index >= 0 and collection [ index ] == 0 : index -= 1 return collection [ : index + 1 ]
| 1 |
how to keep leading zeroes in python
|
Removes trailing zeroes from indexable collection of numbers
|
cosqa-train-17049
|
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 __replace_all ( repls : dict , input : str ) -> str : return re . sub ( '|' . join ( re . escape ( key ) for key in repls . keys ( ) ) , lambda k : repls [ k . group ( 0 ) ] , input )
| 0 |
replace all occurences of char in a string python
|
Replaces from a string ** input ** all the occurrences of some symbols according to mapping ** repls ** .
|
cosqa-train-17050
|
def __replace_all(repls: dict, input: str) -> str:
""" Replaces from a string **input** all the occurrences of some
symbols according to mapping **repls**.
:param dict repls: where #key is the old character and
#value is the one to substitute with;
:param str input: original string where to apply the
replacements;
:return: *(str)* the string with the desired characters replaced
"""
return re.sub('|'.join(re.escape(key) for key in repls.keys()),
lambda k: repls[k.group(0)], input)
|
def maybe_infer_dtype_type ( element ) : tipo = None if hasattr ( element , 'dtype' ) : tipo = element . dtype elif is_list_like ( element ) : element = np . asarray ( element ) tipo = element . dtype return tipo
| 0 |
how to determine what data type something is in python
|
Try to infer an object s dtype for use in arithmetic ops
|
cosqa-train-17051
|
def maybe_infer_dtype_type(element):
"""Try to infer an object's dtype, for use in arithmetic ops
Uses `element.dtype` if that's available.
Objects implementing the iterator protocol are cast to a NumPy array,
and from there the array's type is used.
Parameters
----------
element : object
Possibly has a `.dtype` attribute, and possibly the iterator
protocol.
Returns
-------
tipo : type
Examples
--------
>>> from collections import namedtuple
>>> Foo = namedtuple("Foo", "dtype")
>>> maybe_infer_dtype_type(Foo(np.dtype("i8")))
numpy.int64
"""
tipo = None
if hasattr(element, 'dtype'):
tipo = element.dtype
elif is_list_like(element):
element = np.asarray(element)
tipo = element.dtype
return tipo
|
def bytes_hack ( buf ) : ub = None if sys . version_info > ( 3 , ) : ub = buf else : ub = bytes ( buf ) return ub
| 0 |
python3 biopython bytes object expected
|
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-17052
|
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 top ( self , topn = 10 ) : return [ self [ i ] for i in argsort ( list ( zip ( * self ) ) [ 1 ] ) [ : : - 1 ] [ : topn ] ]
| 1 |
top values in list python
|
Get a list of the top topn features in this : class : . Feature \ .
|
cosqa-train-17053
|
def top(self, topn=10):
"""
Get a list of the top ``topn`` features in this :class:`.Feature`\.
Examples
--------
.. code-block:: python
>>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)])
>>> myFeature.top(1)
[('trapezoid', 5)]
Parameters
----------
topn : int
Returns
-------
list
"""
return [self[i] for i in argsort(list(zip(*self))[1])[::-1][:topn]]
|
def get_prop_value ( name , props , default = None ) : # type: (str, Dict[str, Any], Any) -> Any if not props : return default try : return props [ name ] except KeyError : return default
| 1 |
python property get with default
|
Returns the value of a property or the default one
|
cosqa-train-17054
|
def get_prop_value(name, props, default=None):
# type: (str, Dict[str, Any], Any) -> Any
"""
Returns the value of a property or the default one
:param name: Name of a property
:param props: Dictionary of properties
:param default: Default value
:return: The value of the property or the default one
"""
if not props:
return default
try:
return props[name]
except KeyError:
return default
|
def _my_hash ( arg_list ) : # type: (List[Any]) -> int res = 0 for arg in arg_list : res = res * 31 + hash ( arg ) return res
| 1 |
generate the hash values using perfect hash function in python
|
Simple helper hash function
|
cosqa-train-17055
|
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 most_significant_bit ( lst : np . ndarray ) -> int : return np . argwhere ( np . asarray ( lst ) == 1 ) [ 0 ] [ 0 ]
| 1 |
python largest index in array true
|
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-17056
|
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 create_pie_chart ( self , snapshot , filename = '' ) : try : from pylab import figure , title , pie , axes , savefig from pylab import sum as pylab_sum except ImportError : return self . nopylab_msg % ( "pie_chart" ) # Don't bother illustrating a pie without pieces. if not snapshot . tracked_total : return '' classlist = [ ] sizelist = [ ] for k , v in list ( snapshot . classes . items ( ) ) : if v [ 'pct' ] > 3.0 : classlist . append ( k ) sizelist . append ( v [ 'sum' ] ) sizelist . insert ( 0 , snapshot . asizeof_total - pylab_sum ( sizelist ) ) classlist . insert ( 0 , 'Other' ) #sizelist = [x*0.01 for x in sizelist] title ( "Snapshot (%s) Memory Distribution" % ( snapshot . desc ) ) figure ( figsize = ( 8 , 8 ) ) axes ( [ 0.1 , 0.1 , 0.8 , 0.8 ] ) pie ( sizelist , labels = classlist ) savefig ( filename , dpi = 50 ) return self . chart_tag % ( self . relative_path ( filename ) )
| 1 |
how to make a pie chart in python matplotlib
|
Create a pie chart that depicts the distribution of the allocated memory for a given snapshot . The chart is saved to filename .
|
cosqa-train-17057
|
def create_pie_chart(self, snapshot, filename=''):
"""
Create a pie chart that depicts the distribution of the allocated memory
for a given `snapshot`. The chart is saved to `filename`.
"""
try:
from pylab import figure, title, pie, axes, savefig
from pylab import sum as pylab_sum
except ImportError:
return self.nopylab_msg % ("pie_chart")
# Don't bother illustrating a pie without pieces.
if not snapshot.tracked_total:
return ''
classlist = []
sizelist = []
for k, v in list(snapshot.classes.items()):
if v['pct'] > 3.0:
classlist.append(k)
sizelist.append(v['sum'])
sizelist.insert(0, snapshot.asizeof_total - pylab_sum(sizelist))
classlist.insert(0, 'Other')
#sizelist = [x*0.01 for x in sizelist]
title("Snapshot (%s) Memory Distribution" % (snapshot.desc))
figure(figsize=(8,8))
axes([0.1, 0.1, 0.8, 0.8])
pie(sizelist, labels=classlist)
savefig(filename, dpi=50)
return self.chart_tag % (self.relative_path(filename))
|
def strings_to_integers ( strings : Iterable [ str ] ) -> Iterable [ int ] : return strings_to_ ( strings , lambda x : int ( float ( x ) ) )
| 1 |
python turn list of str to int
|
Convert a list of strings to a list of integers .
|
cosqa-train-17058
|
def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:
"""
Convert a list of strings to a list of integers.
:param strings: a list of string
:return: a list of converted integers
.. doctest::
>>> strings_to_integers(['1', '1.0', '-0.2'])
[1, 1, 0]
"""
return strings_to_(strings, lambda x: int(float(x)))
|
def _ ( f , x ) : return { k : v for k , v in x . items ( ) if f ( k , v ) }
| 0 |
python filter dictionary lambda key value
|
filter for dict note f should have signature : f :: key - > value - > bool
|
cosqa-train-17059
|
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 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 |
python datetime get last month number
|
Returns day number of the last day of the month : param t : datetime : return : int
|
cosqa-train-17060
|
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 samefile ( a : str , b : str ) -> bool : try : return os . path . samefile ( a , b ) except OSError : return os . path . normpath ( a ) == os . path . normpath ( b )
| 0 |
python check two file path equal
|
Check if two pathes represent the same file .
|
cosqa-train-17061
|
def samefile(a: str, b: str) -> bool:
"""Check if two pathes represent the same file."""
try:
return os.path.samefile(a, b)
except OSError:
return os.path.normpath(a) == os.path.normpath(b)
|
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 json file reader
|
Load JSON file
|
cosqa-train-17062
|
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 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' }
| 1 |
python downgrade got rid of spyder
|
Get version information for components used by Spyder
|
cosqa-train-17063
|
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 read32 ( bytestream ) : dt = np . dtype ( np . uint32 ) . newbyteorder ( '>' ) return np . frombuffer ( bytestream . read ( 4 ) , dtype = dt ) [ 0 ]
| 1 |
how to read image in python uint8
|
Read 4 bytes from bytestream as an unsigned 32 - bit integer .
|
cosqa-train-17064
|
def read32(bytestream):
"""Read 4 bytes from bytestream as an unsigned 32-bit integer."""
dt = np.dtype(np.uint32).newbyteorder('>')
return np.frombuffer(bytestream.read(4), dtype=dt)[0]
|
def do_quit ( self , _ : argparse . Namespace ) -> bool : self . _should_quit = True return self . _STOP_AND_EXIT
| 0 |
python force stop event
|
Exit this application
|
cosqa-train-17065
|
def do_quit(self, _: argparse.Namespace) -> bool:
"""Exit this application"""
self._should_quit = True
return self._STOP_AND_EXIT
|
def astensor ( array : TensorLike ) -> BKTensor : tensor = tf . convert_to_tensor ( value = array , dtype = CTYPE ) return tensor
| 0 |
python transform a vector to a tensor
|
Covert numpy array to tensorflow tensor
|
cosqa-train-17066
|
def astensor(array: TensorLike) -> BKTensor:
"""Covert numpy array to tensorflow tensor"""
tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)
return tensor
|
def genfirstvalues ( cursor : Cursor , arraysize : int = 1000 ) -> Generator [ Any , None , None ] : return ( row [ 0 ] for row in genrows ( cursor , arraysize ) )
| 0 |
get first 50 rows python
|
Generate the first value in each row .
|
cosqa-train-17067
|
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 array2string ( arr : numpy . ndarray ) -> str : shape = str ( arr . shape ) [ 1 : - 1 ] if shape . endswith ( "," ) : shape = shape [ : - 1 ] return numpy . array2string ( arr , threshold = 11 ) + "%s[%s]" % ( arr . dtype , shape )
| 0 |
python format string for all entries in numpy array
|
Format numpy array as a string .
|
cosqa-train-17068
|
def array2string(arr: numpy.ndarray) -> str:
"""Format numpy array as a string."""
shape = str(arr.shape)[1:-1]
if shape.endswith(","):
shape = shape[:-1]
return numpy.array2string(arr, threshold=11) + "%s[%s]" % (arr.dtype, shape)
|
def 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 function
|
docstring for argparse
|
cosqa-train-17069
|
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 _reshuffle ( mat , shape ) : return np . reshape ( np . transpose ( np . reshape ( mat , shape ) , ( 3 , 1 , 2 , 0 ) ) , ( shape [ 3 ] * shape [ 1 ] , shape [ 0 ] * shape [ 2 ] ) )
| 1 |
python shuffle columns of a matrix
|
Reshuffle the indicies of a bipartite matrix A [ ij kl ] - > A [ lj ki ] .
|
cosqa-train-17070
|
def _reshuffle(mat, shape):
"""Reshuffle the indicies of a bipartite matrix A[ij,kl] -> A[lj,ki]."""
return np.reshape(
np.transpose(np.reshape(mat, shape), (3, 1, 2, 0)),
(shape[3] * shape[1], shape[0] * shape[2]))
|
def cpu_count ( ) -> int : if multiprocessing is None : return 1 try : return multiprocessing . cpu_count ( ) except NotImplementedError : pass try : return os . sysconf ( "SC_NPROCESSORS_CONF" ) except ( AttributeError , ValueError ) : pass gen_log . error ( "Could not detect number of processors; assuming 1" ) return 1
| 1 |
get number of cpu cores used python 3
|
Returns the number of processors on this machine .
|
cosqa-train-17071
|
def cpu_count() -> int:
"""Returns the number of processors on this machine."""
if multiprocessing is None:
return 1
try:
return multiprocessing.cpu_count()
except NotImplementedError:
pass
try:
return os.sysconf("SC_NPROCESSORS_CONF")
except (AttributeError, ValueError):
pass
gen_log.error("Could not detect number of processors; assuming 1")
return 1
|
def mouse_event ( dwFlags : int , dx : int , dy : int , dwData : int , dwExtraInfo : int ) -> None : ctypes . windll . user32 . mouse_event ( dwFlags , dx , dy , dwData , dwExtraInfo )
| 0 |
python pywin32 mouse events
|
mouse_event from Win32 .
|
cosqa-train-17072
|
def mouse_event(dwFlags: int, dx: int, dy: int, dwData: int, dwExtraInfo: int) -> None:
"""mouse_event from Win32."""
ctypes.windll.user32.mouse_event(dwFlags, dx, dy, dwData, dwExtraInfo)
|
def array2string ( arr : numpy . ndarray ) -> str : shape = str ( arr . shape ) [ 1 : - 1 ] if shape . endswith ( "," ) : shape = shape [ : - 1 ] return numpy . array2string ( arr , threshold = 11 ) + "%s[%s]" % ( arr . dtype , shape )
| 0 |
numpy array to string with no bracket in python
|
Format numpy array as a string .
|
cosqa-train-17073
|
def array2string(arr: numpy.ndarray) -> str:
"""Format numpy array as a string."""
shape = str(arr.shape)[1:-1]
if shape.endswith(","):
shape = shape[:-1]
return numpy.array2string(arr, threshold=11) + "%s[%s]" % (arr.dtype, shape)
|
def _izip ( * iterables ) : # This izip routine is from itertools # izip('ABCD', 'xy') --> Ax By iterators = map ( iter , iterables ) while iterators : yield tuple ( map ( next , iterators ) )
| 0 |
make an array from iterator in python
|
Iterate through multiple lists or arrays of equal size
|
cosqa-train-17074
|
def _izip(*iterables):
""" Iterate through multiple lists or arrays of equal size """
# This izip routine is from itertools
# izip('ABCD', 'xy') --> Ax By
iterators = map(iter, iterables)
while iterators:
yield tuple(map(next, iterators))
|
def extend ( a : dict , b : dict ) -> dict : res = a . copy ( ) res . update ( b ) return res
| 0 |
python create new dict from two
|
Merge two dicts and return a new dict . Much like subclassing works .
|
cosqa-train-17075
|
def extend(a: dict, b: dict) -> dict:
"""Merge two dicts and return a new dict. Much like subclassing works."""
res = a.copy()
res.update(b)
return res
|
def s3_get ( url : str , temp_file : IO ) -> None : s3_resource = boto3 . resource ( "s3" ) bucket_name , s3_path = split_s3_path ( url ) s3_resource . Bucket ( bucket_name ) . download_fileobj ( s3_path , temp_file )
| 0 |
python fetch file from s3
|
Pull a file directly from S3 .
|
cosqa-train-17076
|
def s3_get(url: str, temp_file: IO) -> None:
"""Pull a file directly from S3."""
s3_resource = boto3.resource("s3")
bucket_name, s3_path = split_s3_path(url)
s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)
|
def decode_value ( stream ) : length = decode_length ( stream ) ( value , ) = unpack_value ( ">{:d}s" . format ( length ) , stream ) return value
| 1 |
how to extract data from stream in python
|
Decode the contents of a value from a serialized stream .
|
cosqa-train-17077
|
def decode_value(stream):
"""Decode the contents of a value from a serialized stream.
:param stream: Source data stream
:type stream: io.BytesIO
:returns: Decoded value
:rtype: bytes
"""
length = decode_length(stream)
(value,) = unpack_value(">{:d}s".format(length), stream)
return value
|
async def executemany ( self , sql : str , parameters : Iterable [ Iterable [ Any ] ] ) -> None : await self . _execute ( self . _cursor . executemany , sql , parameters )
| 1 |
python pysql send multiple queries
|
Execute the given multiquery .
|
cosqa-train-17078
|
async def executemany(self, sql: str, parameters: Iterable[Iterable[Any]]) -> None:
"""Execute the given multiquery."""
await self._execute(self._cursor.executemany, sql, parameters)
|
def flatten_list ( x : List [ Any ] ) -> List [ Any ] : # noqa return [ item for sublist in x for item in sublist ]
| 0 |
python 3 flatten list of lists with list comprehension
|
Converts a list of lists into a flat list . Args : x : list of lists
|
cosqa-train-17079
|
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 try_cast_int ( s ) : try : temp = re . findall ( '\d' , str ( s ) ) temp = '' . join ( temp ) return int ( temp ) except : return s
| 1 |
turn string into int in python
|
( str ) - > int All the digits in a given string are concatenated and converted into a single number .
|
cosqa-train-17080
|
def try_cast_int(s):
"""(str) -> int
All the digits in a given string are concatenated and converted into a single number.
"""
try:
temp = re.findall('\d', str(s))
temp = ''.join(temp)
return int(temp)
except:
return s
|
def 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 value in column is null 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-17081
|
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 release_lock ( ) : get_lock . n_lock -= 1 assert get_lock . n_lock >= 0 # Only really release lock once all lock requests have ended. if get_lock . lock_is_enabled and get_lock . n_lock == 0 : get_lock . start_time = None get_lock . unlocker . unlock ( )
| 1 |
python unblock lock acquire
|
Release lock on compilation directory .
|
cosqa-train-17082
|
def release_lock():
"""Release lock on compilation directory."""
get_lock.n_lock -= 1
assert get_lock.n_lock >= 0
# Only really release lock once all lock requests have ended.
if get_lock.lock_is_enabled and get_lock.n_lock == 0:
get_lock.start_time = None
get_lock.unlocker.unlock()
|
def uppercase_chars ( string : any ) -> str : return '' . join ( [ c if c . isupper ( ) else '' for c in str ( string ) ] )
| 1 |
any way to make all of the characters in a string uppercase? python
|
Return all ( and only ) the uppercase chars in the given string .
|
cosqa-train-17083
|
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 read ( self , start_position : int , size : int ) -> memoryview : return memoryview ( self . _bytes ) [ start_position : start_position + size ]
| 1 |
python memoryview contact buffer fragment
|
Return a view into the memory
|
cosqa-train-17084
|
def read(self, start_position: int, size: int) -> memoryview:
"""
Return a view into the memory
"""
return memoryview(self._bytes)[start_position:start_position + size]
|
def min ( self ) : res = self . _qexec ( "min(%s)" % self . _name ) if len ( res ) > 0 : self . _min = res [ 0 ] [ 0 ] return self . _min
| 1 |
get minimum value of column python
|
: returns the minimum of the column
|
cosqa-train-17085
|
def min(self):
"""
:returns the minimum of the column
"""
res = self._qexec("min(%s)" % self._name)
if len(res) > 0:
self._min = res[0][0]
return self._min
|
def most_significant_bit ( lst : np . ndarray ) -> int : return np . argwhere ( np . asarray ( lst ) == 1 ) [ 0 ] [ 0 ]
| 0 |
how to return smallest magnitude vector in an 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-17086
|
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 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 )
| 1 |
check if input is an integer or boolean python
|
Return true if a value is an integer number .
|
cosqa-train-17087
|
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 append_num_column ( self , text : str , index : int ) : width = self . columns [ index ] [ "width" ] return f"{text:>{width}}"
| 0 |
python formating the width of a column
|
Add value to the output row width based on index
|
cosqa-train-17088
|
def append_num_column(self, text: str, index: int):
""" Add value to the output row, width based on index """
width = self.columns[index]["width"]
return f"{text:>{width}}"
|
def check64bit ( current_system = "python" ) : if current_system == "python" : return sys . maxsize > 2147483647 elif current_system == "os" : import platform pm = platform . machine ( ) if pm != ".." and pm . endswith ( '64' ) : # recent Python (not Iron) return True else : if 'PROCESSOR_ARCHITEW6432' in os . environ : return True # 32 bit program running on 64 bit Windows try : # 64 bit Windows 64 bit program return os . environ [ 'PROCESSOR_ARCHITECTURE' ] . endswith ( '64' ) except IndexError : pass # not Windows try : # this often works in Linux return '64' in platform . architecture ( ) [ 0 ] except Exception : # is an older version of Python, assume also an older os@ # (best we can guess) return False
| 1 |
how to tell if running 64 bit python
|
checks if you are on a 64 bit platform
|
cosqa-train-17089
|
def check64bit(current_system="python"):
"""checks if you are on a 64 bit platform"""
if current_system == "python":
return sys.maxsize > 2147483647
elif current_system == "os":
import platform
pm = platform.machine()
if pm != ".." and pm.endswith('64'): # recent Python (not Iron)
return True
else:
if 'PROCESSOR_ARCHITEW6432' in os.environ:
return True # 32 bit program running on 64 bit Windows
try:
# 64 bit Windows 64 bit program
return os.environ['PROCESSOR_ARCHITECTURE'].endswith('64')
except IndexError:
pass # not Windows
try:
# this often works in Linux
return '64' in platform.architecture()[0]
except Exception:
# is an older version of Python, assume also an older os@
# (best we can guess)
return False
|
def _kbhit_unix ( ) -> bool : dr , dw , de = select . select ( [ sys . stdin ] , [ ] , [ ] , 0 ) return dr != [ ]
| 0 |
python key press exist
|
Under UNIX : is a keystroke available?
|
cosqa-train-17090
|
def _kbhit_unix() -> bool:
"""
Under UNIX: is a keystroke available?
"""
dr, dw, de = select.select([sys.stdin], [], [], 0)
return dr != []
|
def array2string ( arr : numpy . ndarray ) -> str : shape = str ( arr . shape ) [ 1 : - 1 ] if shape . endswith ( "," ) : shape = shape [ : - 1 ] return numpy . array2string ( arr , threshold = 11 ) + "%s[%s]" % ( arr . dtype , shape )
| 1 |
python print numpy array with string
|
Format numpy array as a string .
|
cosqa-train-17091
|
def array2string(arr: numpy.ndarray) -> str:
"""Format numpy array as a string."""
shape = str(arr.shape)[1:-1]
if shape.endswith(","):
shape = shape[:-1]
return numpy.array2string(arr, threshold=11) + "%s[%s]" % (arr.dtype, shape)
|
def 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 lastworking day of month
|
Get the last weekday in a given month . e . g :
|
cosqa-train-17092
|
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 _gaussian_function ( self , datalength : int , values : np . ndarray , height : int , index : int ) -> np . ndarray : return height * np . exp ( - ( 1 / ( self . spread_number * datalength ) ) * ( values - ( ( datalength / self . function_number ) * index ) ) ** 2 )
| 0 |
python range step of gaussian distribtuion
|
i th Regression Model Gaussian
|
cosqa-train-17093
|
def _gaussian_function(self, datalength: int, values: np.ndarray,
height: int, index: int) -> np.ndarray:
"""
i'th Regression Model Gaussian
:param: len(x)
:param: x values
:param: height of gaussian
:param: position of gaussian
:return: gaussian bumps over domain
"""
return height * np.exp(-(1 / (self.spread_number * datalength)) *
(values - ((datalength / self.function_number) * index)) ** 2)
|
def _parse_tuple_string ( argument ) : if isinstance ( argument , str ) : return tuple ( int ( p . strip ( ) ) for p in argument . split ( ',' ) ) return argument
| 0 |
python tuple string element without quotation marks
|
Return a tuple from parsing a b c d - > ( a b c d )
|
cosqa-train-17094
|
def _parse_tuple_string(argument):
""" Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) """
if isinstance(argument, str):
return tuple(int(p.strip()) for p in argument.split(','))
return argument
|
def 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 from a dat in python
|
Returns the year .
|
cosqa-train-17095
|
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 SvcStop ( self ) -> None : # tell the SCM we're shutting down # noinspection PyUnresolvedReferences self . ReportServiceStatus ( win32service . SERVICE_STOP_PENDING ) # fire the stop event win32event . SetEvent ( self . h_stop_event )
| 1 |
python stop service windows
|
Called when the service is being shut down .
|
cosqa-train-17096
|
def SvcStop(self) -> None:
"""
Called when the service is being shut down.
"""
# tell the SCM we're shutting down
# noinspection PyUnresolvedReferences
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
# fire the stop event
win32event.SetEvent(self.h_stop_event)
|
def strings_to_integers ( strings : Iterable [ str ] ) -> Iterable [ int ] : return strings_to_ ( strings , lambda x : int ( float ( x ) ) )
| 0 |
python translate a list of strings into int
|
Convert a list of strings to a list of integers .
|
cosqa-train-17097
|
def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:
"""
Convert a list of strings to a list of integers.
:param strings: a list of string
:return: a list of converted integers
.. doctest::
>>> strings_to_integers(['1', '1.0', '-0.2'])
[1, 1, 0]
"""
return strings_to_(strings, lambda x: int(float(x)))
|
def _cnx_is_empty ( in_file ) : with open ( in_file ) as in_handle : for i , line in enumerate ( in_handle ) : if i > 0 : return False return True
| 0 |
python how to check a file for an empty line
|
Check if cnr or cns files are empty ( only have a header )
|
cosqa-train-17098
|
def _cnx_is_empty(in_file):
"""Check if cnr or cns files are empty (only have a header)
"""
with open(in_file) as in_handle:
for i, line in enumerate(in_handle):
if i > 0:
return False
return True
|
def 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 |
how to obtain several matched strings from a single file in python
|
Very simple grep that returns the first matching line in a file . String matching only does not do REs as currently implemented .
|
cosqa-train-17099
|
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 ''
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.