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 _mid ( pt1 , pt2 ) : ( x0 , y0 ) , ( x1 , y1 ) = pt1 , pt2 return 0.5 * ( x0 + x1 ) , 0.5 * ( y0 + y1 )
1
calculate mid of two points from lat long python
( Point Point ) - > Point Return the point that lies in between the two input points .
cosqa-train-17500
def _mid(pt1, pt2): """ (Point, Point) -> Point Return the point that lies in between the two input points. """ (x0, y0), (x1, y1) = pt1, pt2 return 0.5 * (x0 + x1), 0.5 * (y0 + y1)
def 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 know the data type of an element in python
Try to infer an object s dtype for use in arithmetic ops
cosqa-train-17501
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 _parse_date ( string : str ) -> datetime . date : return datetime . datetime . strptime ( string , '%Y-%m-%d' ) . date ( )
1
extract date object from a string in python
Parse an ISO format date ( YYYY - mm - dd ) .
cosqa-train-17502
def _parse_date(string: str) -> datetime.date: """Parse an ISO format date (YYYY-mm-dd). >>> _parse_date('1990-01-02') datetime.date(1990, 1, 2) """ return datetime.datetime.strptime(string, '%Y-%m-%d').date()
def hash_file ( fileobj ) : hasher = hashlib . md5 ( ) buf = fileobj . read ( 65536 ) while len ( buf ) > 0 : hasher . update ( buf ) buf = fileobj . read ( 65536 ) return hasher . hexdigest ( )
1
python file hash md5
: param fileobj : a file object : return : a hash of the file content
cosqa-train-17503
def hash_file(fileobj): """ :param fileobj: a file object :return: a hash of the file content """ hasher = hashlib.md5() buf = fileobj.read(65536) while len(buf) > 0: hasher.update(buf) buf = fileobj.read(65536) return hasher.hexdigest()
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 how to ndarray string to one string
Format numpy array as a string .
cosqa-train-17504
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 remove_empty_text ( utterances : List [ Utterance ] ) -> List [ Utterance ] : return [ utter for utter in utterances if utter . text . strip ( ) != "" ]
0
python filter list not equal to space
Remove empty utterances from a list of utterances Args : utterances : The list of utterance we are processing
cosqa-train-17505
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 setup_cache ( app : Flask , cache_config ) -> Optional [ Cache ] : if cache_config and cache_config . get ( 'CACHE_TYPE' ) != 'null' : return Cache ( app , config = cache_config ) return None
0
python flask cache per request
Setup the flask - cache on a flask app
cosqa-train-17506
def setup_cache(app: Flask, cache_config) -> Optional[Cache]: """Setup the flask-cache on a flask app""" if cache_config and cache_config.get('CACHE_TYPE') != 'null': return Cache(app, config=cache_config) return None
def read32 ( bytestream ) : dt = np . dtype ( np . uint32 ) . newbyteorder ( '>' ) return np . frombuffer ( bytestream . read ( 4 ) , dtype = dt ) [ 0 ]
0
python 3 unsignedchar 8bit data
Read 4 bytes from bytestream as an unsigned 32 - bit integer .
cosqa-train-17507
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 flatten_list ( x : List [ Any ] ) -> List [ Any ] : # noqa return [ item for sublist in x for item in sublist ]
0
how to make a flat list within list in python
Converts a list of lists into a flat list . Args : x : list of lists
cosqa-train-17508
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 camel_to_snake ( s : str ) -> str : return CAMEL_CASE_RE . sub ( r'_\1' , s ) . strip ( ) . lower ( )
0
detect string is camel python
Convert string from camel case to snake case .
cosqa-train-17509
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 mmap ( func , iterable ) : if sys . version_info [ 0 ] > 2 : return [ i for i in map ( func , iterable ) ] else : return map ( func , iterable )
0
python using the map function with a constant and a list
Wrapper to make map () behave the same on Py2 and Py3 .
cosqa-train-17510
def mmap(func, iterable): """Wrapper to make map() behave the same on Py2 and Py3.""" if sys.version_info[0] > 2: return [i for i in map(func, iterable)] else: return map(func, iterable)
def find_first_in_list ( txt : str , str_list : [ str ] ) -> int : # type: ignore start = len ( txt ) + 1 for item in str_list : if start > txt . find ( item ) > - 1 : start = txt . find ( item ) return start if len ( txt ) + 1 > start > - 1 else - 1
0
finding the last occurrence of a character in a string in python
Returns the index of the earliest occurence of an item from a list in a string
cosqa-train-17511
def find_first_in_list(txt: str, str_list: [str]) -> int: # type: ignore """ Returns the index of the earliest occurence of an item from a list in a string Ex: find_first_in_list('foobar', ['bar', 'fin']) -> 3 """ start = len(txt) + 1 for item in str_list: if start > txt.find(item) > -1: start = txt.find(item) return start if len(txt) + 1 > start > -1 else -1
def stretch ( iterable , n = 2 ) : times = range ( n ) for item in iterable : for i in times : yield item
0
iterate a specific number of times in python
r Repeat each item in iterable n times .
cosqa-train-17512
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 string ( value ) -> str : return system_json . dumps ( Json ( value ) . safe_object ( ) , ensure_ascii = False )
1
python variable in a json string
string dict / object / value to JSON
cosqa-train-17513
def string(value) -> str: """ string dict/object/value to JSON """ return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)
def butlast ( iterable ) : iterable = iter ( iterable ) try : first = next ( iterable ) except StopIteration : return for second in iterable : yield first first = second
0
python iterate list last element
Yield all items from iterable except the last one .
cosqa-train-17514
def butlast(iterable): """Yield all items from ``iterable`` except the last one. >>> list(butlast(['spam', 'eggs', 'ham'])) ['spam', 'eggs'] >>> list(butlast(['spam'])) [] >>> list(butlast([])) [] """ iterable = iter(iterable) try: first = next(iterable) except StopIteration: return for second in iterable: yield first first = second
def inverted_dict ( d ) : return dict ( ( force_hashable ( v ) , k ) for ( k , v ) in viewitems ( dict ( d ) ) )
1
how to get inverse dict in python
Return a dict with swapped keys and values
cosqa-train-17515
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 in_transaction ( self ) : if not hasattr ( self . local , 'tx' ) : return False return len ( self . local . tx ) > 0
1
python this transaction is inactive
Check if this database is in a transactional context .
cosqa-train-17516
def in_transaction(self): """Check if this database is in a transactional context.""" if not hasattr(self.local, 'tx'): return False return len(self.local.tx) > 0
def score_small_straight_yatzy ( dice : List [ int ] ) -> int : dice_set = set ( dice ) if _are_two_sets_equal ( { 1 , 2 , 3 , 4 , 5 } , dice_set ) : return sum ( dice ) return 0
0
the final score for fantasy teaam based on the selected coding using python
Small straight scoring according to yatzy rules
cosqa-train-17517
def score_small_straight_yatzy(dice: List[int]) -> int: """ Small straight scoring according to yatzy rules """ dice_set = set(dice) if _are_two_sets_equal({1, 2, 3, 4, 5}, dice_set): return sum(dice) return 0
def _str_to_list ( value , separator ) : value_list = [ item . strip ( ) for item in value . split ( separator ) ] value_list_sanitized = builtins . list ( filter ( None , value_list ) ) if len ( value_list_sanitized ) > 0 : return value_list_sanitized else : raise ValueError ( 'Invalid list variable.' )
1
python build a list from a string delimited by space
Convert a string to a list with sanitization .
cosqa-train-17518
def _str_to_list(value, separator): """Convert a string to a list with sanitization.""" value_list = [item.strip() for item in value.split(separator)] value_list_sanitized = builtins.list(filter(None, value_list)) if len(value_list_sanitized) > 0: return value_list_sanitized else: raise ValueError('Invalid list variable.')
def 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
most frequent item in list python
Returns the item that appears most frequently in the given list .
cosqa-train-17519
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 remove_empty_text ( utterances : List [ Utterance ] ) -> List [ Utterance ] : return [ utter for utter in utterances if utter . text . strip ( ) != "" ]
1
strip a list of string python
Remove empty utterances from a list of utterances Args : utterances : The list of utterance we are processing
cosqa-train-17520
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 read32 ( bytestream ) : dt = np . dtype ( np . uint32 ) . newbyteorder ( '>' ) return np . frombuffer ( bytestream . read ( 4 ) , dtype = dt ) [ 0 ]
0
python not recognizing numpy uint8 as integer
Read 4 bytes from bytestream as an unsigned 32 - bit integer .
cosqa-train-17521
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 dtypes ( self ) : return [ ( str ( f . name ) , f . dataType . simpleString ( ) ) for f in self . schema . fields ]
1
get datatypes columns python
Returns all column names and their data types as a list .
cosqa-train-17522
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 clean ( ctx , text ) : text = conversions . to_string ( text , ctx ) return '' . join ( [ c for c in text if ord ( c ) >= 32 ] )
1
remove a set of characters in python
Removes all non - printable characters from a text string
cosqa-train-17523
def clean(ctx, text): """ Removes all non-printable characters from a text string """ text = conversions.to_string(text, ctx) return ''.join([c for c in text if ord(c) >= 32])
def process_literal_param ( self , value : Optional [ List [ int ] ] , dialect : Dialect ) -> str : retval = self . _intlist_to_dbstr ( value ) return retval
0
python mongodb int to str
Convert things on the way from Python to the database .
cosqa-train-17524
def process_literal_param(self, value: Optional[List[int]], dialect: Dialect) -> str: """Convert things on the way from Python to the database.""" retval = self._intlist_to_dbstr(value) return retval
def label_from_bin ( buf ) : mpls_label = type_desc . Int3 . to_user ( six . binary_type ( buf ) ) return mpls_label >> 4 , mpls_label & 1
1
python protobuf parsefromstring get int value
Converts binary representation label to integer .
cosqa-train-17525
def label_from_bin(buf): """ Converts binary representation label to integer. :param buf: Binary representation of label. :return: MPLS Label and BoS bit. """ mpls_label = type_desc.Int3.to_user(six.binary_type(buf)) return mpls_label >> 4, mpls_label & 1
def truncate ( value : Decimal , n_digits : int ) -> Decimal : return Decimal ( math . trunc ( value * ( 10 ** n_digits ) ) ) / ( 10 ** n_digits )
1
how to cut off a calculated number to two decimals in python
Truncates a value to a number of decimals places
cosqa-train-17526
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 has_table ( self , name ) : return len ( self . sql ( "SELECT name FROM sqlite_master WHERE type='table' AND name=?" , parameters = ( name , ) , asrecarray = False , cache = False ) ) > 0
1
sqllite python entry exist
Return True if the table * name * exists in the database .
cosqa-train-17527
def has_table(self, name): """Return ``True`` if the table *name* exists in the database.""" return len(self.sql("SELECT name FROM sqlite_master WHERE type='table' AND name=?", parameters=(name,), asrecarray=False, cache=False)) > 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
python how to evaluate if a variable is equal to an integer
Return true if a value is an integer number .
cosqa-train-17528
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 get_from_gnucash26_date ( date_str : str ) -> date : date_format = "%Y%m%d" result = datetime . strptime ( date_str , date_format ) . date ( ) return result
1
using string to generate datetime date in python
Creates a datetime from GnuCash 2 . 6 date string
cosqa-train-17529
def get_from_gnucash26_date(date_str: str) -> date: """ Creates a datetime from GnuCash 2.6 date string """ date_format = "%Y%m%d" result = datetime.strptime(date_str, date_format).date() return result
def flatten_list ( l : List [ list ] ) -> list : return [ v for inner_l in l for v in inner_l ]
1
turn list of lists into one list in python
takes a list of lists l and returns a flat list
cosqa-train-17530
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 __remove_trailing_zeros ( self , collection ) : index = len ( collection ) - 1 while index >= 0 and collection [ index ] == 0 : index -= 1 return collection [ : index + 1 ]
0
remove leading zeroes python
Removes trailing zeroes from indexable collection of numbers
cosqa-train-17531
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 rl_get_point ( ) -> int : # pragma: no cover if rl_type == RlType . GNU : return ctypes . c_int . in_dll ( readline_lib , "rl_point" ) . value elif rl_type == RlType . PYREADLINE : return readline . rl . mode . l_buffer . point else : return 0
1
python ctype get cursor position
Returns the offset of the current cursor position in rl_line_buffer
cosqa-train-17532
def rl_get_point() -> int: # pragma: no cover """ Returns the offset of the current cursor position in rl_line_buffer """ if rl_type == RlType.GNU: return ctypes.c_int.in_dll(readline_lib, "rl_point").value elif rl_type == RlType.PYREADLINE: return readline.rl.mode.l_buffer.point else: return 0
def top ( self , topn = 10 ) : return [ self [ i ] for i in argsort ( list ( zip ( * self ) ) [ 1 ] ) [ : : - 1 ] [ : topn ] ]
0
top n value in last dimension python
Get a list of the top topn features in this : class : . Feature \ .
cosqa-train-17533
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 camel_to_snake ( s : str ) -> str : return CAMEL_CASE_RE . sub ( r'_\1' , s ) . strip ( ) . lower ( )
0
python camel case to snake
Convert string from camel case to snake case .
cosqa-train-17534
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 try_cast_int ( s ) : try : temp = re . findall ( '\d' , str ( s ) ) temp = '' . join ( temp ) return int ( temp ) except : return s
1
python how to cast a string char to an int
( str ) - > int All the digits in a given string are concatenated and converted into a single number .
cosqa-train-17535
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 has_key ( cls , * args ) : key = args if len ( args ) > 1 else args [ 0 ] return key in cls . _instances
0
how to test for a key being used in python
Check whether flyweight object with specified key has already been created .
cosqa-train-17536
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 isarray ( array , test , dim = 2 ) : if dim > 1 : return all ( isarray ( array [ i ] , test , dim - 1 ) for i in range ( len ( array ) ) ) return all ( test ( i ) for i in array )
1
python if element in array meets conditions
Returns True if test is True for all array elements . Otherwise returns False .
cosqa-train-17537
def isarray(array, test, dim=2): """Returns True if test is True for all array elements. Otherwise, returns False. """ if dim > 1: return all(isarray(array[i], test, dim - 1) for i in range(len(array))) return all(test(i) for i in array)
def remove_blank_lines ( string ) : return "\n" . join ( line for line in string . split ( "\n" ) if len ( line . strip ( ) ) )
1
python strip if stirng is not empty
Removes all blank lines in @string
cosqa-train-17538
def remove_blank_lines(string): """ Removes all blank lines in @string -> #str without blank lines """ return "\n".join(line for line in string.split("\n") if len(line.strip()))
def dict_of_sets_add ( dictionary , key , value ) : # type: (DictUpperBound, Any, Any) -> None set_objs = dictionary . get ( key , set ( ) ) set_objs . add ( value ) dictionary [ key ] = set_objs
0
how to add an item to a set in python
Add value to a set in a dictionary by key
cosqa-train-17539
def dict_of_sets_add(dictionary, key, value): # type: (DictUpperBound, Any, Any) -> None """Add value to a set in a dictionary by key Args: dictionary (DictUpperBound): Dictionary to which to add values key (Any): Key within dictionary value (Any): Value to add to set in dictionary Returns: None """ set_objs = dictionary.get(key, set()) set_objs.add(value) dictionary[key] = set_objs
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
retrieve s3 file from python
Pull a file directly from S3 .
cosqa-train-17540
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 read_text_from_file ( path : str ) -> str : with open ( path ) as text_file : content = text_file . read ( ) return content
1
how to read content of text file from python
Reads text file contents
cosqa-train-17541
def read_text_from_file(path: str) -> str: """ Reads text file contents """ with open(path) as text_file: content = text_file.read() return content
def _check_whitespace ( string ) : if string . count ( ' ' ) + string . count ( '\t' ) + string . count ( '\n' ) > 0 : raise ValueError ( INSTRUCTION_HAS_WHITESPACE )
0
python what checks string characters for whitespaces
Make sure thre is no whitespace in the given string . Will raise a ValueError if whitespace is detected
cosqa-train-17542
def _check_whitespace(string): """ Make sure thre is no whitespace in the given string. Will raise a ValueError if whitespace is detected """ if string.count(' ') + string.count('\t') + string.count('\n') > 0: raise ValueError(INSTRUCTION_HAS_WHITESPACE)
def 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 in windows
Discover the current time zone and it s standard string representation ( for source { d } ) .
cosqa-train-17543
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 clean ( ctx , text ) : text = conversions . to_string ( text , ctx ) return '' . join ( [ c for c in text if ord ( c ) >= 32 ] )
1
remove all instance of char in string python
Removes all non - printable characters from a text string
cosqa-train-17544
def clean(ctx, text): """ Removes all non-printable characters from a text string """ text = conversions.to_string(text, ctx) return ''.join([c for c in text if ord(c) >= 32])
def is_unicode ( string ) : str_type = str ( type ( string ) ) if str_type . find ( 'str' ) > 0 or str_type . find ( 'unicode' ) > 0 : return True return False
1
python check type as string
Validates that the object itself is some kinda string
cosqa-train-17545
def is_unicode(string): """Validates that the object itself is some kinda string""" str_type = str(type(string)) if str_type.find('str') > 0 or str_type.find('unicode') > 0: return True return False
def rate_limited ( max_per_hour : int , * args : Any ) -> Callable [ ... , Any ] : return util . rate_limited ( max_per_hour , * args )
0
python variable limit in a function
Rate limit a function .
cosqa-train-17546
def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]: """Rate limit a function.""" return util.rate_limited(max_per_hour, *args)
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
0
how to check if current day is last day of month in python
Get the last weekday in a given month . e . g :
cosqa-train-17547
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 is_unitary ( matrix : np . ndarray ) -> bool : rows , cols = matrix . shape if rows != cols : return False return np . allclose ( np . eye ( rows ) , matrix . dot ( matrix . T . conj ( ) ) )
0
testing if a matrix is an upper triangle python
A helper function that checks if a matrix is unitary .
cosqa-train-17548
def is_unitary(matrix: np.ndarray) -> bool: """ A helper function that checks if a matrix is unitary. :param matrix: a matrix to test unitarity of :return: true if and only if matrix is unitary """ rows, cols = matrix.shape if rows != cols: return False return np.allclose(np.eye(rows), matrix.dot(matrix.T.conj()))
def SGT ( self , a , b ) : # http://gavwood.com/paper.pdf s0 , s1 = to_signed ( a ) , to_signed ( b ) return Operators . ITEBV ( 256 , s0 > s1 , 1 , 0 )
0
two greater than signs python
Signed greater - than comparison
cosqa-train-17549
def SGT(self, a, b): """Signed greater-than comparison""" # http://gavwood.com/paper.pdf s0, s1 = to_signed(a), to_signed(b) return Operators.ITEBV(256, s0 > s1, 1, 0)
def snake_to_camel ( s : str ) -> str : fragments = s . split ( '_' ) return fragments [ 0 ] + '' . join ( x . title ( ) for x in fragments [ 1 : ] )
1
how to capitalize first letter input python
Convert string from snake case to camel case .
cosqa-train-17550
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 find_first_in_list ( txt : str , str_list : [ str ] ) -> int : # type: ignore start = len ( txt ) + 1 for item in str_list : if start > txt . find ( item ) > - 1 : start = txt . find ( item ) return start if len ( txt ) + 1 > start > - 1 else - 1
0
how to check forfirst index python string
Returns the index of the earliest occurence of an item from a list in a string
cosqa-train-17551
def find_first_in_list(txt: str, str_list: [str]) -> int: # type: ignore """ Returns the index of the earliest occurence of an item from a list in a string Ex: find_first_in_list('foobar', ['bar', 'fin']) -> 3 """ start = len(txt) + 1 for item in str_list: if start > txt.find(item) > -1: start = txt.find(item) return start if len(txt) + 1 > start > -1 else -1
def replaceStrs ( s , * args ) : if args == ( ) : return s mapping = dict ( ( frm , to ) for frm , to in args ) return re . sub ( "|" . join ( map ( re . escape , mapping . keys ( ) ) ) , lambda match : mapping [ match . group ( 0 ) ] , s )
0
python substitute values in string
r Replace all ( frm to ) tuples in args in string s .
cosqa-train-17552
def replaceStrs(s, *args): r"""Replace all ``(frm, to)`` tuples in `args` in string `s`. >>> replaceStrs("nothing is better than warm beer", ... ('nothing','warm beer'), ('warm beer','nothing')) 'warm beer is better than nothing' """ if args == (): return s mapping = dict((frm, to) for frm, to in args) return re.sub("|".join(map(re.escape, mapping.keys())), lambda match:mapping[match.group(0)], s)
def chars ( string : any ) -> str : return '' . join ( [ c if c . isalpha ( ) else '' for c in str ( string ) ] )
1
how to test if a string in python is all letters
Return all ( and only ) the chars in the given string .
cosqa-train-17553
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 file_exists ( fname ) : try : return fname and os . path . exists ( fname ) and os . path . getsize ( fname ) > 0 except OSError : return False
0
check if the dirctionary is null or empty python
Check if a file exists and is non - empty .
cosqa-train-17554
def file_exists(fname): """Check if a file exists and is non-empty. """ try: return fname and os.path.exists(fname) and os.path.getsize(fname) > 0 except OSError: return False
def 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
calling arg parse file from python
docstring for argparse
cosqa-train-17555
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
how to shuffle the items in a matrix python
Reshuffle the indicies of a bipartite matrix A [ ij kl ] - > A [ lj ki ] .
cosqa-train-17556
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 remove_falsy_values ( counter : Mapping [ Any , int ] ) -> Mapping [ Any , int ] : return { label : count for label , count in counter . items ( ) if count }
1
remove all nan values from dictionary python
Remove all values that are zero .
cosqa-train-17557
def remove_falsy_values(counter: Mapping[Any, int]) -> Mapping[Any, int]: """Remove all values that are zero.""" return { label: count for label, count in counter.items() if count }
async def executemany ( self , sql : str , parameters : Iterable [ Iterable [ Any ] ] ) -> None : await self . _execute ( self . _cursor . executemany , sql , parameters )
1
python pyobc cursor executemany
Execute the given multiquery .
cosqa-train-17558
async def executemany(self, sql: str, parameters: Iterable[Iterable[Any]]) -> None: """Execute the given multiquery.""" await self._execute(self._cursor.executemany, sql, parameters)
def normcdf ( x , log = False ) : y = np . atleast_1d ( x ) . copy ( ) flib . normcdf ( y ) if log : if ( y > 0 ) . all ( ) : return np . log ( y ) return - np . inf return y
1
continuous normalizing with cdf with python
Normal cumulative density function .
cosqa-train-17559
def normcdf(x, log=False): """Normal cumulative density function.""" y = np.atleast_1d(x).copy() flib.normcdf(y) if log: if (y>0).all(): return np.log(y) return -np.inf return y
def pack_bits ( longbits ) : byte = longbits & ( 0x0101010101010101 ) byte = ( byte | ( byte >> 7 ) ) & ( 0x0003000300030003 ) byte = ( byte | ( byte >> 14 ) ) & ( 0x0000000f0000000f ) byte = ( byte | ( byte >> 28 ) ) & ( 0x00000000000000ff ) return byte
0
reduce bit depth to 8 from 24 in python
Crunch a 64 - bit int ( 8 bool bytes ) into a bitfield .
cosqa-train-17560
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 _parse_date ( string : str ) -> datetime . date : return datetime . datetime . strptime ( string , '%Y-%m-%d' ) . date ( )
1
how to parse string into date python
Parse an ISO format date ( YYYY - mm - dd ) .
cosqa-train-17561
def _parse_date(string: str) -> datetime.date: """Parse an ISO format date (YYYY-mm-dd). >>> _parse_date('1990-01-02') datetime.date(1990, 1, 2) """ return datetime.datetime.strptime(string, '%Y-%m-%d').date()
def is_relative_url ( url ) : if url . startswith ( "#" ) : return None if url . find ( "://" ) > 0 or url . startswith ( "//" ) : # either 'http(s)://...' or '//cdn...' and therefore absolute return False return True
1
determine if url is absolute or relative in python
simple method to determine if a url is relative or absolute
cosqa-train-17562
def is_relative_url(url): """ simple method to determine if a url is relative or absolute """ if url.startswith("#"): return None if url.find("://") > 0 or url.startswith("//"): # either 'http(s)://...' or '//cdn...' and therefore absolute return False return True
def inverted_dict ( d ) : return dict ( ( force_hashable ( v ) , k ) for ( k , v ) in viewitems ( dict ( d ) ) )
1
reversing a dictionary in python
Return a dict with swapped keys and values
cosqa-train-17563
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 normalize ( numbers ) : total = float ( sum ( numbers ) ) return [ n / total for n in numbers ]
1
python normalize sum 1
Multiply each number by a constant such that the sum is 1 . 0 >>> normalize ( [ 1 2 1 ] ) [ 0 . 25 0 . 5 0 . 25 ]
cosqa-train-17564
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 zlib_compress ( data ) : if PY3K : if isinstance ( data , str ) : return zlib . compress ( bytes ( data , 'utf-8' ) ) return zlib . compress ( data ) return zlib . compress ( data )
0
python 3 dealing with gzipped json
Compress things in a py2 / 3 safe fashion >>> json_str = { test : 1 } >>> blob = zlib_compress ( json_str )
cosqa-train-17565
def zlib_compress(data): """ Compress things in a py2/3 safe fashion >>> json_str = '{"test": 1}' >>> blob = zlib_compress(json_str) """ if PY3K: if isinstance(data, str): return zlib.compress(bytes(data, 'utf-8')) return zlib.compress(data) return zlib.compress(data)
def _run_sync ( self , method : Callable , * args , * * kwargs ) -> Any : if self . loop . is_running ( ) : raise RuntimeError ( "Event loop is already running." ) if not self . is_connected : self . loop . run_until_complete ( self . connect ( ) ) task = asyncio . Task ( method ( * args , * * kwargs ) , loop = self . loop ) result = self . loop . run_until_complete ( task ) self . loop . run_until_complete ( self . quit ( ) ) return result
0
asyncio not working python
Utility method to run commands synchronously for testing .
cosqa-train-17566
def _run_sync(self, method: Callable, *args, **kwargs) -> Any: """ Utility method to run commands synchronously for testing. """ if self.loop.is_running(): raise RuntimeError("Event loop is already running.") if not self.is_connected: self.loop.run_until_complete(self.connect()) task = asyncio.Task(method(*args, **kwargs), loop=self.loop) result = self.loop.run_until_complete(task) self.loop.run_until_complete(self.quit()) return result
def get_cursor ( self ) : x , y = self . _cursor width , height = self . parent . get_size ( ) while x >= width : x -= width y += 1 if y >= height and self . scrollMode == 'scroll' : y = height - 1 return x , y
0
how to get hover position of cursor python
Return the virtual cursor position .
cosqa-train-17567
def get_cursor(self): """Return the virtual cursor position. The cursor can be moved with the :any:`move` method. Returns: Tuple[int, int]: The (x, y) coordinate of where :any:`print_str` will continue from. .. seealso:: :any:move` """ x, y = self._cursor width, height = self.parent.get_size() while x >= width: x -= width y += 1 if y >= height and self.scrollMode == 'scroll': y = height - 1 return x, y
def file_lines ( bblfile : str ) -> iter : with open ( bblfile ) as fd : yield from ( line . rstrip ( ) for line in fd if line . rstrip ( ) )
0
python3 how to read and filter lines from a file
Yield lines found in given file
cosqa-train-17568
def file_lines(bblfile:str) -> iter: """Yield lines found in given file""" with open(bblfile) as fd: yield from (line.rstrip() for line in fd if line.rstrip())
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
1
how to skip blank lines in python
Helper for iterating only nonempty lines without line breaks
cosqa-train-17569
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 _tree_line ( self , no_type : bool = False ) -> str : return self . _tree_line_prefix ( ) + " " + self . iname ( )
1
how to represent tree in python
Return the receiver s contribution to tree diagram .
cosqa-train-17570
def _tree_line(self, no_type: bool = False) -> str: """Return the receiver's contribution to tree diagram.""" return self._tree_line_prefix() + " " + self.iname()
def issubset ( self , other ) : if len ( self ) > len ( other ) : # Fast check for obvious cases return False return all ( item in other for item in self )
0
python check if set is subset of another
Report whether another set contains this set .
cosqa-train-17571
def issubset(self, other): """ Report whether another set contains this set. Example: >>> OrderedSet([1, 2, 3]).issubset({1, 2}) False >>> OrderedSet([1, 2, 3]).issubset({1, 2, 3, 4}) True >>> OrderedSet([1, 2, 3]).issubset({1, 4, 3, 5}) False """ if len(self) > len(other): # Fast check for obvious cases return False return all(item in other for item in self)
def getRandomBinaryTreeLeafNode ( binaryTree ) : if binaryTree . internal == True : if random . random ( ) > 0.5 : return getRandomBinaryTreeLeafNode ( binaryTree . left ) else : return getRandomBinaryTreeLeafNode ( binaryTree . right ) else : return binaryTree
1
how to generate random binary tree in python
Get random binary tree node .
cosqa-train-17572
def getRandomBinaryTreeLeafNode(binaryTree): """Get random binary tree node. """ if binaryTree.internal == True: if random.random() > 0.5: return getRandomBinaryTreeLeafNode(binaryTree.left) else: return getRandomBinaryTreeLeafNode(binaryTree.right) else: return binaryTree
def get_domain ( url ) : parse_result = urlparse ( url ) domain = "{schema}://{netloc}" . format ( schema = parse_result . scheme , netloc = parse_result . netloc ) return domain
1
python3 urllib urlparse domain
Get domain part of an url .
cosqa-train-17573
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 is_natural ( x ) : try : is_integer = int ( x ) == x except ( TypeError , ValueError ) : return False return is_integer and x >= 0
0
how to check for real number python
A non - negative integer .
cosqa-train-17574
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 fcast ( value : float ) -> TensorLike : newvalue = tf . cast ( value , FTYPE ) if DEVICE == 'gpu' : newvalue = newvalue . gpu ( ) # Why is this needed? # pragma: no cover return newvalue
1
python tensorflow casting int to float
Cast to float tensor
cosqa-train-17575
def fcast(value: float) -> TensorLike: """Cast to float tensor""" newvalue = tf.cast(value, FTYPE) if DEVICE == 'gpu': newvalue = newvalue.gpu() # Why is this needed? # pragma: no cover return newvalue
def proper_round ( n ) : return int ( n ) + ( n / abs ( n ) ) * int ( abs ( n - int ( n ) ) >= 0.5 ) if n != 0 else 0
0
round float to nearest whole python
rounds float to closest int : rtype : int : param n : float
cosqa-train-17576
def proper_round(n): """ rounds float to closest int :rtype: int :param n: float """ return int(n) + (n / abs(n)) * int(abs(n - int(n)) >= 0.5) if n != 0 else 0
def url_host ( url : str ) -> str : from urllib . parse import urlparse res = urlparse ( url ) return res . netloc . split ( ':' ) [ 0 ] if res . netloc else ''
1
python3 extract host from url
Parses hostname from URL . : param url : URL : return : hostname
cosqa-train-17577
def url_host(url: str) -> str: """ Parses hostname from URL. :param url: URL :return: hostname """ from urllib.parse import urlparse res = urlparse(url) return res.netloc.split(':')[0] if res.netloc else ''
def count ( args ) : counts = defaultdict ( int ) for arg in args : for item in arg : counts [ item ] = counts [ item ] + 1 return counts
1
python count occurrences in a list
count occurences in a list of lists >>> count ( [[ a b ] [ a ]] ) defaultdict ( int { a : 2 b : 1 } )
cosqa-train-17578
def count(args): """ count occurences in a list of lists >>> count([['a','b'],['a']]) defaultdict(int, {'a' : 2, 'b' : 1}) """ counts = defaultdict(int) for arg in args: for item in arg: counts[item] = counts[item] + 1 return counts
def stretch ( iterable , n = 2 ) : times = range ( n ) for item in iterable : for i in times : yield item
1
python repeat n times in list
r Repeat each item in iterable n times .
cosqa-train-17579
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 _gauss ( mean : int , sigma : int ) -> int : return int ( random . gauss ( mean , sigma ) )
0
gaussian random variable in python
Creates a variation from a base value
cosqa-train-17580
def _gauss(mean: int, sigma: int) -> int: """ Creates a variation from a base value Args: mean: base value sigma: gaussian sigma Returns: random value """ return int(random.gauss(mean, sigma))
def get_keys_of_max_n ( dict_obj , n ) : return sorted ( [ item [ 0 ] for item in sorted ( dict_obj . items ( ) , key = lambda item : item [ 1 ] , reverse = True ) [ : n ] ] )
0
how to select the top 5 in a sorted dictionary python
Returns the keys that maps to the top n max values in the given dict .
cosqa-train-17581
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_multidict ( multidict ) : return dict ( [ ( key , value if len ( value ) > 1 else value [ 0 ] ) for ( key , value ) in multidict . iterlists ( ) ] )
0
python flatten dict of dicts
Return flattened dictionary from MultiDict .
cosqa-train-17582
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 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 forcing the immediate release of memory
Release lock on compilation directory .
cosqa-train-17583
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 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 )
1
access files in s3 with python
Pull a file directly from S3 .
cosqa-train-17584
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 normalize ( numbers ) : total = float ( sum ( numbers ) ) return [ n / total for n in numbers ]
1
normalize to 1 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-17585
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 _find_conda ( ) : if 'CONDA_EXE' in os . environ : conda = os . environ [ 'CONDA_EXE' ] else : conda = util . which ( 'conda' ) return conda
0
conda activate "python" is not recognized as an internal or external
Find the conda executable robustly across conda versions .
cosqa-train-17586
def _find_conda(): """Find the conda executable robustly across conda versions. Returns ------- conda : str Path to the conda executable. Raises ------ IOError If the executable cannot be found in either the CONDA_EXE environment variable or in the PATH. Notes ----- In POSIX platforms in conda >= 4.4, conda can be set up as a bash function rather than an executable. (This is to enable the syntax ``conda activate env-name``.) In this case, the environment variable ``CONDA_EXE`` contains the path to the conda executable. In other cases, we use standard search for the appropriate name in the PATH. See https://github.com/airspeed-velocity/asv/issues/645 for more details. """ if 'CONDA_EXE' in os.environ: conda = os.environ['CONDA_EXE'] else: conda = util.which('conda') return conda
def strings_to_integers ( strings : Iterable [ str ] ) -> Iterable [ int ] : return strings_to_ ( strings , lambda x : int ( float ( x ) ) )
1
turn list of str to int python
Convert a list of strings to a list of integers .
cosqa-train-17587
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 truncate_string ( value , max_width = None ) : if isinstance ( value , text_type ) and max_width is not None and len ( value ) > max_width : return value [ : max_width ] return value
0
max length limit of string python
Truncate string values .
cosqa-train-17588
def truncate_string(value, max_width=None): """Truncate string values.""" if isinstance(value, text_type) and max_width is not None and len(value) > max_width: return value[:max_width] return value
def check_key ( self , key : str ) -> bool : keys = self . get_keys ( ) return key in keys
1
python check if hash key exists
Checks if key exists in datastore . True if yes False if no .
cosqa-train-17589
def check_key(self, key: str) -> bool: """ Checks if key exists in datastore. True if yes, False if no. :param: SHA512 hash key :return: whether or key not exists in datastore """ keys = self.get_keys() return key in keys
def split_unit ( value ) : r = re . search ( '^(\-?[\d\.]+)(.*)$' , str ( value ) ) return r . groups ( ) if r else ( '' , '' )
1
separate a number and units in python using regular expressions
Split a number from its unit 1px - > ( q px ) Args : value ( str ) : input returns : tuple
cosqa-train-17590
def split_unit(value): """ Split a number from its unit 1px -> (q, 'px') Args: value (str): input returns: tuple """ r = re.search('^(\-?[\d\.]+)(.*)$', str(value)) return r.groups() if r else ('', '')
def dict_of_sets_add ( dictionary , key , value ) : # type: (DictUpperBound, Any, Any) -> None set_objs = dictionary . get ( key , set ( ) ) set_objs . add ( value ) dictionary [ key ] = set_objs
1
add values to a set in python
Add value to a set in a dictionary by key
cosqa-train-17591
def dict_of_sets_add(dictionary, key, value): # type: (DictUpperBound, Any, Any) -> None """Add value to a set in a dictionary by key Args: dictionary (DictUpperBound): Dictionary to which to add values key (Any): Key within dictionary value (Any): Value to add to set in dictionary Returns: None """ set_objs = dictionary.get(key, set()) set_objs.add(value) dictionary[key] = set_objs
def get_versions ( reporev = True ) : import sys import platform import qtpy import qtpy . QtCore revision = None if reporev : from spyder . utils import vcs revision , branch = vcs . get_git_revision ( os . path . dirname ( __dir__ ) ) if not sys . platform == 'darwin' : # To avoid a crash with our Mac app system = platform . system ( ) else : system = 'Darwin' return { 'spyder' : __version__ , 'python' : platform . python_version ( ) , # "2.7.3" 'bitness' : 64 if sys . maxsize > 2 ** 32 else 32 , 'qt' : qtpy . QtCore . __version__ , 'qt_api' : qtpy . API_NAME , # PyQt5 'qt_api_ver' : qtpy . PYQT_VERSION , 'system' : system , # Linux, Windows, ... 'release' : platform . release ( ) , # XP, 10.6, 2.2.0, etc. 'revision' : revision , # '9fdf926eccce' }
0
how to change python versions in spyder
Get version information for components used by Spyder
cosqa-train-17592
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 _find_conda ( ) : if 'CONDA_EXE' in os . environ : conda = os . environ [ 'CONDA_EXE' ] else : conda = util . which ( 'conda' ) return conda
1
using python from conda path in windows
Find the conda executable robustly across conda versions .
cosqa-train-17593
def _find_conda(): """Find the conda executable robustly across conda versions. Returns ------- conda : str Path to the conda executable. Raises ------ IOError If the executable cannot be found in either the CONDA_EXE environment variable or in the PATH. Notes ----- In POSIX platforms in conda >= 4.4, conda can be set up as a bash function rather than an executable. (This is to enable the syntax ``conda activate env-name``.) In this case, the environment variable ``CONDA_EXE`` contains the path to the conda executable. In other cases, we use standard search for the appropriate name in the PATH. See https://github.com/airspeed-velocity/asv/issues/645 for more details. """ if 'CONDA_EXE' in os.environ: conda = os.environ['CONDA_EXE'] else: conda = util.which('conda') return conda
def remove_falsy_values ( counter : Mapping [ Any , int ] ) -> Mapping [ Any , int ] : return { label : count for label , count in counter . items ( ) if count }
1
eliminate nan from dictionary as values python
Remove all values that are zero .
cosqa-train-17594
def remove_falsy_values(counter: Mapping[Any, int]) -> Mapping[Any, int]: """Remove all values that are zero.""" return { label: count for label, count in counter.items() if count }
def rms ( x ) : try : return ( np . array ( x ) ** 2 ) . mean ( ) ** 0.5 except : x = np . array ( dropna ( x ) ) invN = 1.0 / len ( x ) return ( sum ( invN * ( x_i ** 2 ) for x_i in x ) ) ** .5
1
how to write code for an rms average equation in python
Root Mean Square
cosqa-train-17595
def rms(x): """"Root Mean Square" Arguments: x (seq of float): A sequence of numerical values Returns: The square root of the average of the squares of the values math.sqrt(sum(x_i**2 for x_i in x) / len(x)) or return (np.array(x) ** 2).mean() ** 0.5 >>> rms([0, 2, 4, 4]) 3.0 """ try: return (np.array(x) ** 2).mean() ** 0.5 except: x = np.array(dropna(x)) invN = 1.0 / len(x) return (sum(invN * (x_i ** 2) for x_i in x)) ** .5
def templategetter ( tmpl ) : tmpl = tmpl . replace ( '{' , '%(' ) tmpl = tmpl . replace ( '}' , ')s' ) return lambda data : tmpl % data
0
does python have template literals
This is a dirty little template function generator that turns single - brace Mustache - style template strings into functions that interpolate dict keys :
cosqa-train-17596
def templategetter(tmpl): """ This is a dirty little template function generator that turns single-brace Mustache-style template strings into functions that interpolate dict keys: >>> get_name = templategetter("{first} {last}") >>> get_name({'first': 'Shawn', 'last': 'Allen'}) 'Shawn Allen' """ tmpl = tmpl.replace('{', '%(') tmpl = tmpl.replace('}', ')s') return lambda data: tmpl % data
def flatten_list ( x : List [ Any ] ) -> List [ Any ] : # noqa return [ item for sublist in x for item in sublist ]
1
make a list of multiple lists into one list python3
Converts a list of lists into a flat list . Args : x : list of lists
cosqa-train-17597
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 to_clipboard ( self , excel = True , sep = None , * * kwargs ) : from pandas . io import clipboards clipboards . to_clipboard ( self , excel = excel , sep = sep , * * kwargs )
1
select an copy to clipboard a column to clipboard in excel python
r Copy object to the system clipboard .
cosqa-train-17598
def to_clipboard(self, excel=True, sep=None, **kwargs): r""" Copy object to the system clipboard. Write a text representation of object to the system clipboard. This can be pasted into Excel, for example. Parameters ---------- excel : bool, default True - True, use the provided separator, writing in a csv format for allowing easy pasting into excel. - False, write a string representation of the object to the clipboard. sep : str, default ``'\t'`` Field delimiter. **kwargs These parameters will be passed to DataFrame.to_csv. See Also -------- DataFrame.to_csv : Write a DataFrame to a comma-separated values (csv) file. read_clipboard : Read text from clipboard and pass to read_table. Notes ----- Requirements for your platform. - Linux : `xclip`, or `xsel` (with `gtk` or `PyQt4` modules) - Windows : none - OS X : none Examples -------- Copy the contents of a DataFrame to the clipboard. >>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=['A', 'B', 'C']) >>> df.to_clipboard(sep=',') ... # Wrote the following to the system clipboard: ... # ,A,B,C ... # 0,1,2,3 ... # 1,4,5,6 We can omit the the index by passing the keyword `index` and setting it to false. >>> df.to_clipboard(sep=',', index=False) ... # Wrote the following to the system clipboard: ... # A,B,C ... # 1,2,3 ... # 4,5,6 """ from pandas.io import clipboards clipboards.to_clipboard(self, excel=excel, sep=sep, **kwargs)
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
python set bits off
Crunch a 64 - bit int ( 8 bool bytes ) into a bitfield .
cosqa-train-17599
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