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 rank ( tensor : BKTensor ) -> int : if isinstance ( tensor , np . ndarray ) : return len ( tensor . shape ) return len ( tensor [ 0 ] . size ( ) )
1
python numpy how to get number of rows of matrix
Return the number of dimensions of a tensor
cosqa-train-19000
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
from string to datetime in python
Convert human readable string to datetime . datetime .
cosqa-train-19001
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 numeric_part ( s ) : m = re_numeric_part . match ( s ) if m : return int ( m . group ( 1 ) ) return None
1
python extract numerical part of string
Returns the leading numeric part of a string .
cosqa-train-19002
def numeric_part(s): """Returns the leading numeric part of a string. >>> numeric_part("20-alpha") 20 >>> numeric_part("foo") >>> numeric_part("16b") 16 """ m = re_numeric_part.match(s) if m: return int(m.group(1)) return None
def random_name_gen ( size = 6 ) : return '' . join ( [ random . choice ( string . ascii_uppercase ) ] + [ random . choice ( string . ascii_uppercase + string . digits ) for i in range ( size - 1 ) ] ) if size > 0 else ''
0
how to make a name randomizer in python
Generate a random python attribute name .
cosqa-train-19003
def random_name_gen(size=6): """Generate a random python attribute name.""" return ''.join( [random.choice(string.ascii_uppercase)] + [random.choice(string.ascii_uppercase + string.digits) for i in range(size - 1)] ) if size > 0 else ''
def count ( args ) : counts = defaultdict ( int ) for arg in args : for item in arg : counts [ item ] = counts [ item ] + 1 return counts
1
count number of ocurrences of a number in a list python
count occurences in a list of lists >>> count ( [[ a b ] [ a ]] ) defaultdict ( int { a : 2 b : 1 } )
cosqa-train-19004
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 looks_like_url ( url ) : if not isinstance ( url , basestring ) : return False if not isinstance ( url , basestring ) or len ( url ) >= 1024 or not cre_url . match ( url ) : return False return True
1
see if something is formatted url properly python
Simplified check to see if the text appears to be a URL .
cosqa-train-19005
def looks_like_url(url): """ Simplified check to see if the text appears to be a URL. Similar to `urlparse` but much more basic. Returns: True if the url str appears to be valid. False otherwise. >>> url = looks_like_url("totalgood.org") >>> bool(url) True """ if not isinstance(url, basestring): return False if not isinstance(url, basestring) or len(url) >= 1024 or not cre_url.match(url): return False return True
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 check if my python is 64 or 32 bit
checks if you are on a 64 bit platform
cosqa-train-19006
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 quoted_or_list ( items : List [ str ] ) -> Optional [ str ] : return or_list ( [ f"'{item}'" for item in items ] )
0
any python list of strings
Given [ A B C ] return A B or C .
cosqa-train-19007
def quoted_or_list(items: List[str]) -> Optional[str]: """Given [A, B, C] return "'A', 'B', or 'C'". Note: We use single quotes here, since these are also used by repr(). """ return or_list([f"'{item}'" for item in items])
def is_line_in_file ( filename : str , line : str ) -> bool : assert "\n" not in line with open ( filename , "r" ) as file : for fileline in file : if fileline == line : return True return False
1
python code to check if line in file exists
Detects whether a line is present within a file .
cosqa-train-19008
def is_line_in_file(filename: str, line: str) -> bool: """ Detects whether a line is present within a file. Args: filename: file to check line: line to search for (as an exact match) """ assert "\n" not in line with open(filename, "r") as file: for fileline in file: if fileline == line: return True return False
def get_timezone ( ) -> Tuple [ datetime . tzinfo , str ] : dt = get_datetime_now ( ) . astimezone ( ) tzstr = dt . strftime ( "%z" ) tzstr = tzstr [ : - 2 ] + ":" + tzstr [ - 2 : ] return dt . tzinfo , tzstr
1
get time zone in python
Discover the current time zone and it s standard string representation ( for source { d } ) .
cosqa-train-19009
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 is_sqlatype_integer ( coltype : Union [ TypeEngine , VisitableType ] ) -> bool : coltype = _coltype_to_typeengine ( coltype ) return isinstance ( coltype , sqltypes . Integer )
1
python sqlalchemy get column type
Is the SQLAlchemy column type an integer type?
cosqa-train-19010
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 _skip_section ( self ) : self . _last = self . _f . readline ( ) while len ( self . _last ) > 0 and len ( self . _last [ 0 ] . strip ( ) ) == 0 : self . _last = self . _f . readline ( )
1
how to skip reading a line python
Skip a section
cosqa-train-19011
def _skip_section(self): """Skip a section""" self._last = self._f.readline() while len(self._last) > 0 and len(self._last[0].strip()) == 0: self._last = self._f.readline()
def 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 dictionary in a dictionary
Load JSON file
cosqa-train-19012
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 is_not_null ( df : DataFrame , col_name : str ) -> bool : if ( isinstance ( df , pd . DataFrame ) and col_name in df . columns and df [ col_name ] . notnull ( ) . any ( ) ) : return True else : return False
1
check if column value 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-19013
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 urljoin ( * args ) : value = "/" . join ( map ( lambda x : str ( x ) . strip ( '/' ) , args ) ) return "/{}" . format ( value )
0
python string concat "a"/"b"
Joins given arguments into a url removing duplicate slashes Thanks http : // stackoverflow . com / a / 11326230 / 1267398
cosqa-train-19014
def urljoin(*args): """ Joins given arguments into a url, removing duplicate slashes Thanks http://stackoverflow.com/a/11326230/1267398 >>> urljoin('/lol', '///lol', '/lol//') '/lol/lol/lol' """ value = "/".join(map(lambda x: str(x).strip('/'), args)) return "/{}".format(value)
def clean_int ( x ) -> int : try : return int ( x ) except ValueError : raise forms . ValidationError ( "Cannot convert to integer: {}" . format ( repr ( x ) ) )
0
python input validation int or sentinal
Returns its parameter as an integer or raises django . forms . ValidationError .
cosqa-train-19015
def clean_int(x) -> int: """ Returns its parameter as an integer, or raises ``django.forms.ValidationError``. """ try: return int(x) except ValueError: raise forms.ValidationError( "Cannot convert to integer: {}".format(repr(x)))
def remove_once ( gset , elem ) : remove = getattr ( gset , 'remove' , None ) if remove is not None : remove ( elem ) else : del gset [ elem ] return elem
1
python delete a element from set
Remove the element from a set lists or dict . >>> L = [ Lucy ] ; S = set ( [ Sky ] ) ; D = { Diamonds : True } ; >>> remove_once ( L Lucy ) ; remove_once ( S Sky ) ; remove_once ( D Diamonds ) ; >>> print L S D [] set ( [] ) {}
cosqa-train-19016
def remove_once(gset, elem): """Remove the element from a set, lists or dict. >>> L = ["Lucy"]; S = set(["Sky"]); D = { "Diamonds": True }; >>> remove_once(L, "Lucy"); remove_once(S, "Sky"); remove_once(D, "Diamonds"); >>> print L, S, D [] set([]) {} Returns the element if it was removed. Raises one of the exceptions in :obj:`RemoveError` otherwise. """ remove = getattr(gset, 'remove', None) if remove is not None: remove(elem) else: del gset[elem] return elem
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.' )
0
cplit a string to list in python
Convert a string to a list with sanitization .
cosqa-train-19017
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 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 last weekday of the month
Get the last weekday in a given month . e . g :
cosqa-train-19018
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 stdev ( self ) : return round ( np . std ( self . array ) , self . precision ) if len ( self . array ) else None
0
python numpy calculate stdev
- > #float : func : numpy . std of the timing intervals
cosqa-train-19019
def stdev(self): """ -> #float :func:numpy.std of the timing intervals """ return round(np.std(self.array), self.precision)\ if len(self.array) else None
def _ ( f , x ) : return { k : v for k , v in x . items ( ) if f ( k , v ) }
0
filter values in a dictionary based on condition python
filter for dict note f should have signature : f :: key - > value - > bool
cosqa-train-19020
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 read_text_from_file ( path : str ) -> str : with open ( path ) as text_file : content = text_file . read ( ) return content
1
python get content of text file
Reads text file contents
cosqa-train-19021
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 genfirstvalues ( cursor : Cursor , arraysize : int = 1000 ) -> Generator [ Any , None , None ] : return ( row [ 0 ] for row in genrows ( cursor , arraysize ) )
1
python first 500 elements of array
Generate the first value in each row .
cosqa-train-19022
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 _cnx_is_empty ( in_file ) : with open ( in_file ) as in_handle : for i , line in enumerate ( in_handle ) : if i > 0 : return False return True
1
how to know if a text file is empty in python
Check if cnr or cns files are empty ( only have a header )
cosqa-train-19023
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 space_list ( line : str ) -> List [ int ] : spaces = [ ] for idx , car in enumerate ( list ( line ) ) : if car == " " : spaces . append ( idx ) return spaces
0
python list of indexes for each newline in string
Given a string return a list of index positions where a blank space occurs .
cosqa-train-19024
def space_list(line: str) -> List[int]: """ Given a string, return a list of index positions where a blank space occurs. :param line: :return: >>> space_list(" abc ") [0, 1, 2, 3, 7] """ spaces = [] for idx, car in enumerate(list(line)): if car == " ": spaces.append(idx) return spaces
def is_not_null ( df : DataFrame , col_name : str ) -> bool : if ( isinstance ( df , pd . DataFrame ) and col_name in df . columns and df [ col_name ] . notnull ( ) . any ( ) ) : return True else : return False
1
python check the column contains null
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-19025
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 rank ( tensor : BKTensor ) -> int : if isinstance ( tensor , np . ndarray ) : return len ( tensor . shape ) return len ( tensor [ 0 ] . size ( ) )
1
how to get column length row length of 2d array in python
Return the number of dimensions of a tensor
cosqa-train-19026
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 get_property ( self , name ) : # type: (str) -> object with self . __properties_lock : return self . __properties . get ( name , os . getenv ( name ) )
1
returns property object instead of its value python
Retrieves a framework or system property . As framework properties don t change while it s running this method don t need to be protected .
cosqa-train-19027
def get_property(self, name): # type: (str) -> object """ Retrieves a framework or system property. As framework properties don't change while it's running, this method don't need to be protected. :param name: The property name """ with self.__properties_lock: return self.__properties.get(name, os.getenv(name))
def genfirstvalues ( cursor : Cursor , arraysize : int = 1000 ) -> Generator [ Any , None , None ] : return ( row [ 0 ] for row in genrows ( cursor , arraysize ) )
1
get every first item of array python
Generate the first value in each row .
cosqa-train-19028
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 is_natural ( x ) : try : is_integer = int ( x ) == x except ( TypeError , ValueError ) : return False return is_integer and x >= 0
1
python compare none with integer
A non - negative integer .
cosqa-train-19029
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 get_period_last_3_months ( ) -> str : today = Datum ( ) today . today ( ) # start_date = today - timedelta(weeks=13) start_date = today . clone ( ) start_date . subtract_months ( 3 ) period = get_period ( start_date . date , today . date ) return period
0
to get last 12 months of data in python
Returns the last week as a period string
cosqa-train-19030
def get_period_last_3_months() -> str: """ Returns the last week as a period string """ today = Datum() today.today() # start_date = today - timedelta(weeks=13) start_date = today.clone() start_date.subtract_months(3) period = get_period(start_date.date, today.date) return period
def argmax ( self , rows : List [ Row ] , column : ComparableColumn ) -> List [ Row ] : if not rows : return [ ] value_row_pairs = [ ( row . values [ column . name ] , row ) for row in rows ] if not value_row_pairs : return [ ] # Returns a list containing the row with the max cell value. return [ sorted ( value_row_pairs , key = lambda x : x [ 0 ] , reverse = True ) [ 0 ] [ 1 ] ]
0
maximum value in a column in python
Takes a list of rows and a column name and returns a list containing a single row ( dict from columns to cells ) that has the maximum numerical value in the given column . We return a list instead of a single dict to be consistent with the return type of select and all_rows .
cosqa-train-19031
def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]: """ Takes a list of rows and a column name and returns a list containing a single row (dict from columns to cells) that has the maximum numerical value in the given column. We return a list instead of a single dict to be consistent with the return type of ``select`` and ``all_rows``. """ if not rows: return [] value_row_pairs = [(row.values[column.name], row) for row in rows] if not value_row_pairs: return [] # Returns a list containing the row with the max cell value. return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]
def most_significant_bit ( lst : np . ndarray ) -> int : return np . argwhere ( np . asarray ( lst ) == 1 ) [ 0 ] [ 0 ]
1
finding least value 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-19032
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 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
check and see if any element in array meets condition python
Returns True if test is True for all array elements . Otherwise returns False .
cosqa-train-19033
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 ( ) ) )
0
strip blank space from string in python
Removes all blank lines in @string
cosqa-train-19034
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 is_builtin_object ( node : astroid . node_classes . NodeNG ) -> bool : return node and node . root ( ) . name == BUILTINS_NAME
0
check if a node is a leaf node python
Returns True if the given node is an object from the __builtin__ module .
cosqa-train-19035
def is_builtin_object(node: astroid.node_classes.NodeNG) -> bool: """Returns True if the given node is an object from the __builtin__ module.""" return node and node.root().name == BUILTINS_NAME
def timeit ( func , * args , * * kwargs ) : start_time = time . time ( ) res = func ( * args , * * kwargs ) timing = time . time ( ) - start_time return res , timing
1
timing a function call python
Time execution of function . Returns ( res seconds ) .
cosqa-train-19036
def timeit(func, *args, **kwargs): """ Time execution of function. Returns (res, seconds). >>> res, timing = timeit(time.sleep, 1) """ start_time = time.time() res = func(*args, **kwargs) timing = time.time() - start_time return res, timing
def _mid ( pt1 , pt2 ) : ( x0 , y0 ) , ( x1 , y1 ) = pt1 , pt2 return 0.5 * ( x0 + x1 ) , 0.5 * ( y0 + y1 )
0
midpoint of two values in python
( Point Point ) - > Point Return the point that lies in between the two input points .
cosqa-train-19037
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 assert_equal ( first , second , msg_fmt = "{msg}" ) : if isinstance ( first , dict ) and isinstance ( second , dict ) : assert_dict_equal ( first , second , msg_fmt ) elif not first == second : msg = "{!r} != {!r}" . format ( first , second ) fail ( msg_fmt . format ( msg = msg , first = first , second = second ) )
0
python assert two values are not the same
Fail unless first equals second as determined by the == operator .
cosqa-train-19038
def assert_equal(first, second, msg_fmt="{msg}"): """Fail unless first equals second, as determined by the '==' operator. >>> assert_equal(5, 5.0) >>> assert_equal("Hello World!", "Goodbye!") Traceback (most recent call last): ... AssertionError: 'Hello World!' != 'Goodbye!' The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument """ if isinstance(first, dict) and isinstance(second, dict): assert_dict_equal(first, second, msg_fmt) elif not first == second: msg = "{!r} != {!r}".format(first, second) fail(msg_fmt.format(msg=msg, first=first, second=second))
def get_language ( query : str ) -> str : query = query . lower ( ) for language in LANGUAGES : if query . endswith ( language ) : return language return ''
0
detect language of a text python
Tries to work out the highlight . js language of a given file name or shebang . Returns an empty string if none match .
cosqa-train-19039
def get_language(query: str) -> str: """Tries to work out the highlight.js language of a given file name or shebang. Returns an empty string if none match. """ query = query.lower() for language in LANGUAGES: if query.endswith(language): return language return ''
def prin ( * args , * * kwargs ) : print >> kwargs . get ( 'out' , None ) , " " . join ( [ str ( arg ) for arg in args ] )
1
how to print python *args
r Like print but a function . I . e . prints out all arguments as print would do . Specify output stream like this ::
cosqa-train-19040
def prin(*args, **kwargs): r"""Like ``print``, but a function. I.e. prints out all arguments as ``print`` would do. Specify output stream like this:: print('ERROR', `out="sys.stderr"``). """ print >> kwargs.get('out',None), " ".join([str(arg) for arg in args])
def post ( self , endpoint : str , * * kwargs ) -> dict : return self . _request ( 'POST' , endpoint , * * kwargs )
0
python call rest service using post
HTTP POST operation to API endpoint .
cosqa-train-19041
def post(self, endpoint: str, **kwargs) -> dict: """HTTP POST operation to API endpoint.""" return self._request('POST', endpoint, **kwargs)
def inverted_dict ( d ) : return dict ( ( force_hashable ( v ) , k ) for ( k , v ) in viewitems ( dict ( d ) ) )
0
using map in python to flip a dictionary
Return a dict with swapped keys and values
cosqa-train-19042
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 debugTreePrint ( node , pfx = "->" ) : print pfx , node . item for c in node . children : debugTreePrint ( c , " " + pfx )
1
implement a tree python
Purely a debugging aid : Ascii - art picture of a tree descended from node
cosqa-train-19043
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 to_bool ( value ) : # type: (Any) -> bool if isinstance ( value , _compat . string_types ) : return value . upper ( ) in ( 'Y' , 'YES' , 'T' , 'TRUE' , '1' , 'OK' ) return bool ( value )
0
python change type from int to boolean
Convert a value into a bool but handle truthy strings eg yes true ok y
cosqa-train-19044
def to_bool(value): # type: (Any) -> bool """ Convert a value into a bool but handle "truthy" strings eg, yes, true, ok, y """ if isinstance(value, _compat.string_types): return value.upper() in ('Y', 'YES', 'T', 'TRUE', '1', 'OK') return bool(value)
def _parse_tuple_string ( argument ) : if isinstance ( argument , str ) : return tuple ( int ( p . strip ( ) ) for p in argument . split ( ',' ) ) return argument
0
python program to unpack a tuple in saveral variable
Return a tuple from parsing a b c d - > ( a b c d )
cosqa-train-19045
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
0
get year from a date in python
Returns the year .
cosqa-train-19046
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 has_synset ( word : str ) -> list : return wn . synsets ( lemmatize ( word , neverstem = True ) )
1
wordnet python get synset
Returns a list of synsets of a word after lemmatization .
cosqa-train-19047
def has_synset(word: str) -> list: """" Returns a list of synsets of a word after lemmatization. """ return wn.synsets(lemmatize(word, neverstem=True))
def version ( ) : OPENJPEG . opj_version . restype = ctypes . c_char_p library_version = OPENJPEG . opj_version ( ) if sys . hexversion >= 0x03000000 : return library_version . decode ( 'utf-8' ) else : return library_version
0
c++ opencv python3 opencv read jpg diffrent
Wrapper for opj_version library routine .
cosqa-train-19048
def version(): """Wrapper for opj_version library routine.""" OPENJPEG.opj_version.restype = ctypes.c_char_p library_version = OPENJPEG.opj_version() if sys.hexversion >= 0x03000000: return library_version.decode('utf-8') else: return library_version
def full ( self ) : return self . maxsize and len ( self . list ) >= self . maxsize or False
1
python queue element stackoverflow
Return True if the queue is full False otherwise ( not reliable! ) .
cosqa-train-19049
def full(self): """Return ``True`` if the queue is full, ``False`` otherwise (not reliable!). Only applicable if :attr:`maxsize` is set. """ return self.maxsize and len(self.list) >= self.maxsize or False
def split ( text : str ) -> List [ str ] : return [ word for word in SEPARATOR . split ( text ) if word . strip ( ' \t' ) ]
1
python split sting to tokens
Split a text into a list of tokens .
cosqa-train-19050
def split(text: str) -> List[str]: """Split a text into a list of tokens. :param text: the text to split :return: tokens """ return [word for word in SEPARATOR.split(text) if word.strip(' \t')]
def tail ( filename , number_of_bytes ) : with open ( filename , "rb" ) as f : if os . stat ( filename ) . st_size > number_of_bytes : f . seek ( - number_of_bytes , 2 ) return f . read ( )
1
python get last x bytes of file
Returns the last number_of_bytes of filename
cosqa-train-19051
def tail(filename, number_of_bytes): """Returns the last number_of_bytes of filename""" with open(filename, "rb") as f: if os.stat(filename).st_size > number_of_bytes: f.seek(-number_of_bytes, 2) return f.read()
def find_editor ( ) -> str : editor = os . environ . get ( 'EDITOR' ) if not editor : if sys . platform [ : 3 ] == 'win' : editor = 'notepad' else : # Favor command-line editors first so we don't leave the terminal to edit for editor in [ 'vim' , 'vi' , 'emacs' , 'nano' , 'pico' , 'gedit' , 'kate' , 'subl' , 'geany' , 'atom' ] : if which ( editor ) : break return editor
1
set default editorfor python scripts windows
Find a reasonable editor to use by default for the system that the cmd2 application is running on .
cosqa-train-19052
def find_editor() -> str: """Find a reasonable editor to use by default for the system that the cmd2 application is running on.""" editor = os.environ.get('EDITOR') if not editor: if sys.platform[:3] == 'win': editor = 'notepad' else: # Favor command-line editors first so we don't leave the terminal to edit for editor in ['vim', 'vi', 'emacs', 'nano', 'pico', 'gedit', 'kate', 'subl', 'geany', 'atom']: if which(editor): break return editor
def position ( self ) -> Position : return Position ( self . _index , self . _lineno , self . _col_offset )
1
get current cursor position python
The current position of the cursor .
cosqa-train-19053
def position(self) -> Position: """The current position of the cursor.""" return Position(self._index, self._lineno, self._col_offset)
def assert_equal ( first , second , msg_fmt = "{msg}" ) : if isinstance ( first , dict ) and isinstance ( second , dict ) : assert_dict_equal ( first , second , msg_fmt ) elif not first == second : msg = "{!r} != {!r}" . format ( first , second ) fail ( msg_fmt . format ( msg = msg , first = first , second = second ) )
0
python assert not equals
Fail unless first equals second as determined by the == operator .
cosqa-train-19054
def assert_equal(first, second, msg_fmt="{msg}"): """Fail unless first equals second, as determined by the '==' operator. >>> assert_equal(5, 5.0) >>> assert_equal("Hello World!", "Goodbye!") Traceback (most recent call last): ... AssertionError: 'Hello World!' != 'Goodbye!' The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument """ if isinstance(first, dict) and isinstance(second, dict): assert_dict_equal(first, second, msg_fmt) elif not first == second: msg = "{!r} != {!r}".format(first, second) fail(msg_fmt.format(msg=msg, first=first, second=second))
def is_not_null ( df : DataFrame , col_name : str ) -> bool : if ( isinstance ( df , pd . DataFrame ) and col_name in df . columns and df [ col_name ] . notnull ( ) . any ( ) ) : return True else : return False
1
to check if there is na value in a column 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-19055
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 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 )
1
python replace multiple value in string
r Replace all ( frm to ) tuples in args in string s .
cosqa-train-19056
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 is_sqlatype_text_over_one_char ( coltype : Union [ TypeEngine , VisitableType ] ) -> bool : coltype = _coltype_to_typeengine ( coltype ) return is_sqlatype_text_of_length_at_least ( coltype , 2 )
0
python sqlalchemy contains string
Is the SQLAlchemy column type a string type that s more than one character long?
cosqa-train-19057
def is_sqlatype_text_over_one_char( coltype: Union[TypeEngine, VisitableType]) -> bool: """ Is the SQLAlchemy column type a string type that's more than one character long? """ coltype = _coltype_to_typeengine(coltype) return is_sqlatype_text_of_length_at_least(coltype, 2)
def uconcatenate ( arrs , axis = 0 ) : v = np . concatenate ( arrs , axis = axis ) v = _validate_numpy_wrapper_units ( v , arrs ) return v
0
python concatenate numpy along axis
Concatenate a sequence of arrays .
cosqa-train-19058
def uconcatenate(arrs, axis=0): """Concatenate a sequence of arrays. This wrapper around numpy.concatenate preserves units. All input arrays must have the same units. See the documentation of numpy.concatenate for full details. Examples -------- >>> from unyt import cm >>> A = [1, 2, 3]*cm >>> B = [2, 3, 4]*cm >>> uconcatenate((A, B)) unyt_array([1, 2, 3, 2, 3, 4], 'cm') """ v = np.concatenate(arrs, axis=axis) v = _validate_numpy_wrapper_units(v, arrs) return v
def try_cast_int ( s ) : try : temp = re . findall ( '\d' , str ( s ) ) temp = '' . join ( temp ) return int ( temp ) except : return s
1
pythonhow covert string on int
( str ) - > int All the digits in a given string are concatenated and converted into a single number .
cosqa-train-19059
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_value ( cls , value : int ) -> bool : return any ( value == item . value for item in cls )
0
enum else if python
True if specified value exists in int enum ; otherwise False .
cosqa-train-19060
def has_value(cls, value: int) -> bool: """True if specified value exists in int enum; otherwise, False.""" return any(value == item.value for item in cls)
def 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
read a file from s3 python
Pull a file directly from S3 .
cosqa-train-19061
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 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
how to call a python file to use in argparse for arguement python
docstring for argparse
cosqa-train-19062
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_trailing_zeros ( self , collection ) : index = len ( collection ) - 1 while index >= 0 and collection [ index ] == 0 : index -= 1 return collection [ : index + 1 ]
0
python truncate leading zeros
Removes trailing zeroes from indexable collection of numbers
cosqa-train-19063
def __remove_trailing_zeros(self, collection): """Removes trailing zeroes from indexable collection of numbers""" index = len(collection) - 1 while index >= 0 and collection[index] == 0: index -= 1 return collection[:index + 1]
def get_case_insensitive_dict_key ( d : Dict , k : str ) -> Optional [ str ] : for key in d . keys ( ) : if k . lower ( ) == key . lower ( ) : return key return None
1
python dictionary get case insensistive key
Within the dictionary d find a key that matches ( in case - insensitive fashion ) the key k and return it ( or None if there isn t one ) .
cosqa-train-19064
def get_case_insensitive_dict_key(d: Dict, k: str) -> Optional[str]: """ Within the dictionary ``d``, find a key that matches (in case-insensitive fashion) the key ``k``, and return it (or ``None`` if there isn't one). """ for key in d.keys(): if k.lower() == key.lower(): return key return None
def get_view_selection ( self ) : if not self . MODEL_STORAGE_ID : return None , None # avoid selection requests on empty tree views -> case warnings in gtk3 if len ( self . store ) == 0 : paths = [ ] else : model , paths = self . _tree_selection . get_selected_rows ( ) # get all related models for selection from respective tree store field selected_model_list = [ ] for path in paths : model = self . store [ path ] [ self . MODEL_STORAGE_ID ] selected_model_list . append ( model ) return self . _tree_selection , selected_model_list
0
select multiple of treeview row python
Get actual tree selection object and all respective models of selected rows
cosqa-train-19065
def get_view_selection(self): """Get actual tree selection object and all respective models of selected rows""" if not self.MODEL_STORAGE_ID: return None, None # avoid selection requests on empty tree views -> case warnings in gtk3 if len(self.store) == 0: paths = [] else: model, paths = self._tree_selection.get_selected_rows() # get all related models for selection from respective tree store field selected_model_list = [] for path in paths: model = self.store[path][self.MODEL_STORAGE_ID] selected_model_list.append(model) return self._tree_selection, selected_model_list
def rate_limited ( max_per_hour : int , * args : Any ) -> Callable [ ... , Any ] : return util . rate_limited ( max_per_hour , * args )
1
callin limit function in python
Rate limit a function .
cosqa-train-19066
def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]: """Rate limit a function.""" return util.rate_limited(max_per_hour, *args)
def _gauss ( mean : int , sigma : int ) -> int : return int ( random . gauss ( mean , sigma ) )
0
how to select a random number from normal distribution in python
Creates a variation from a base value
cosqa-train-19067
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 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
0
check the cores in a processor python multiprocessing
Returns the number of processors on this machine .
cosqa-train-19068
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 zfill ( x , width ) : if not isinstance ( x , basestring ) : x = repr ( x ) return x . zfill ( width )
1
zeropadding to string in python
zfill ( x width ) - > string
cosqa-train-19069
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 is_not_null ( df : DataFrame , col_name : str ) -> bool : if ( isinstance ( df , pd . DataFrame ) and col_name in df . columns and df [ col_name ] . notnull ( ) . any ( ) ) : return True else : return False
1
check 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-19070
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 __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
python replace a char with another in a string
Replaces from a string ** input ** all the occurrences of some symbols according to mapping ** repls ** .
cosqa-train-19071
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 _protected_log ( x1 ) : with np . errstate ( divide = 'ignore' , invalid = 'ignore' ) : return np . where ( np . abs ( x1 ) > 0.001 , np . log ( np . abs ( x1 ) ) , 0. )
0
python math log index 0 is out of bounds for axis 0 with size 0
Closure of log for zero arguments .
cosqa-train-19072
def _protected_log(x1): """Closure of log for zero arguments.""" with np.errstate(divide='ignore', invalid='ignore'): return np.where(np.abs(x1) > 0.001, np.log(np.abs(x1)), 0.)
def remove_once ( gset , elem ) : remove = getattr ( gset , 'remove' , None ) if remove is not None : remove ( elem ) else : del gset [ elem ] return elem
1
delete item from a set python
Remove the element from a set lists or dict . >>> L = [ Lucy ] ; S = set ( [ Sky ] ) ; D = { Diamonds : True } ; >>> remove_once ( L Lucy ) ; remove_once ( S Sky ) ; remove_once ( D Diamonds ) ; >>> print L S D [] set ( [] ) {}
cosqa-train-19073
def remove_once(gset, elem): """Remove the element from a set, lists or dict. >>> L = ["Lucy"]; S = set(["Sky"]); D = { "Diamonds": True }; >>> remove_once(L, "Lucy"); remove_once(S, "Sky"); remove_once(D, "Diamonds"); >>> print L, S, D [] set([]) {} Returns the element if it was removed. Raises one of the exceptions in :obj:`RemoveError` otherwise. """ remove = getattr(gset, 'remove', None) if remove is not None: remove(elem) else: del gset[elem] return elem
def mmap ( func , iterable ) : if sys . version_info [ 0 ] > 2 : return [ i for i in map ( func , iterable ) ] else : return map ( func , iterable )
1
python comprehension for flatmap
Wrapper to make map () behave the same on Py2 and Py3 .
cosqa-train-19074
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 is_string_dtype ( arr_or_dtype ) : # TODO: gh-15585: consider making the checks stricter. def condition ( dtype ) : return dtype . kind in ( 'O' , 'S' , 'U' ) and not is_period_dtype ( dtype ) return _is_dtype ( arr_or_dtype , condition )
1
python how to check dtype
Check whether the provided array or dtype is of the string dtype .
cosqa-train-19075
def is_string_dtype(arr_or_dtype): """ Check whether the provided array or dtype is of the string dtype. Parameters ---------- arr_or_dtype : array-like The array or dtype to check. Returns ------- boolean Whether or not the array or dtype is of the string dtype. Examples -------- >>> is_string_dtype(str) True >>> is_string_dtype(object) True >>> is_string_dtype(int) False >>> >>> is_string_dtype(np.array(['a', 'b'])) True >>> is_string_dtype(pd.Series([1, 2])) False """ # TODO: gh-15585: consider making the checks stricter. def condition(dtype): return dtype.kind in ('O', 'S', 'U') and not is_period_dtype(dtype) return _is_dtype(arr_or_dtype, condition)
def url_host ( url : str ) -> str : from urllib . parse import urlparse res = urlparse ( url ) return res . netloc . split ( ':' ) [ 0 ] if res . netloc else ''
0
python get hostname from url
Parses hostname from URL . : param url : URL : return : hostname
cosqa-train-19076
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 __remove_trailing_zeros ( self , collection ) : index = len ( collection ) - 1 while index >= 0 and collection [ index ] == 0 : index -= 1 return collection [ : index + 1 ]
1
python how to add trailing zeroes
Removes trailing zeroes from indexable collection of numbers
cosqa-train-19077
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 most_significant_bit ( lst : np . ndarray ) -> int : return np . argwhere ( np . asarray ( lst ) == 1 ) [ 0 ] [ 0 ]
1
how to return first number in array of 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-19078
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 expired ( self ) : if self . timeout is None : return False return monotonic ( ) - self . start_time > self . timeout
1
python 3 if action is within a set time do nothing
Boolean property if this action has expired
cosqa-train-19079
def expired(self): """Boolean property if this action has expired """ if self.timeout is None: return False return monotonic() - self.start_time > self.timeout
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 a set is a subset
Report whether another set contains this set .
cosqa-train-19080
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 iprotate ( l , steps = 1 ) : if len ( l ) : steps %= len ( l ) if steps : firstPart = l [ : steps ] del l [ : steps ] l . extend ( firstPart ) return l
1
rotating a list l n times in python
r Like rotate but modifies l in - place .
cosqa-train-19081
def iprotate(l, steps=1): r"""Like rotate, but modifies `l` in-place. >>> l = [1,2,3] >>> iprotate(l) is l True >>> l [2, 3, 1] >>> iprotate(iprotate(l, 2), -3) [1, 2, 3] """ if len(l): steps %= len(l) if steps: firstPart = l[:steps] del l[:steps] l.extend(firstPart) return l
def _extension ( modpath : str ) -> setuptools . Extension : return setuptools . Extension ( modpath , [ modpath . replace ( "." , "/" ) + ".py" ] )
1
python setuptools extension output dir
Make setuptools . Extension .
cosqa-train-19082
def _extension(modpath: str) -> setuptools.Extension: """Make setuptools.Extension.""" return setuptools.Extension(modpath, [modpath.replace(".", "/") + ".py"])
def url_host ( url : str ) -> str : from urllib . parse import urlparse res = urlparse ( url ) return res . netloc . split ( ':' ) [ 0 ] if res . netloc else ''
0
how to get the domain name from netloc in python
Parses hostname from URL . : param url : URL : return : hostname
cosqa-train-19083
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 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 if type of variable is string
Validates that the object itself is some kinda string
cosqa-train-19084
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 to_bytes ( data : Any ) -> bytearray : # noqa if isinstance ( data , int ) : return bytearray ( [ data ] ) return bytearray ( data , encoding = 'latin-1' )
1
python change to bytes
Convert anything to a bytearray . See - http : // stackoverflow . com / questions / 7585435 / best - way - to - convert - string - to - bytes - in - python - 3 - http : // stackoverflow . com / questions / 10459067 / how - to - convert - my - bytearrayb - x9e - x18k - x9a - to - something - like - this - x9e - x1
cosqa-train-19085
def to_bytes(data: Any) -> bytearray: """ Convert anything to a ``bytearray``. See - http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3 - http://stackoverflow.com/questions/10459067/how-to-convert-my-bytearrayb-x9e-x18k-x9a-to-something-like-this-x9e-x1 """ # noqa if isinstance(data, int): return bytearray([data]) return bytearray(data, encoding='latin-1')
def 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
get the last month from python
Returns day number of the last day of the month : param t : datetime : return : int
cosqa-train-19086
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 position ( self ) -> Position : return Position ( self . _index , self . _lineno , self . _col_offset )
0
currnet position of the file cursor pythone
The current position of the cursor .
cosqa-train-19087
def position(self) -> Position: """The current position of the cursor.""" return Position(self._index, self._lineno, self._col_offset)
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.' )
0
how to make a string be a list python
Convert a string to a list with sanitization .
cosqa-train-19088
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 last ( self ) : if self . _last is UNDETERMINED : # not necessarily the last one... self . _last = self . sdat . tseries . index [ - 1 ] return self [ self . _last ]
0
how to get the last element in a series python
Last time step available .
cosqa-train-19089
def last(self): """Last time step available. Example: >>> sdat = StagyyData('path/to/run') >>> assert(sdat.steps.last is sdat.steps[-1]) """ if self._last is UNDETERMINED: # not necessarily the last one... self._last = self.sdat.tseries.index[-1] return self[self._last]
def getIndex ( predicateFn : Callable [ [ T ] , bool ] , items : List [ T ] ) -> int : try : return next ( i for i , v in enumerate ( items ) if predicateFn ( v ) ) except StopIteration : return - 1
0
python get index of element satisfying condition
Finds the index of an item in list which satisfies predicate : param predicateFn : predicate function to run on items of list : param items : list of tuples : return : first index for which predicate function returns True
cosqa-train-19090
def getIndex(predicateFn: Callable[[T], bool], items: List[T]) -> int: """ Finds the index of an item in list, which satisfies predicate :param predicateFn: predicate function to run on items of list :param items: list of tuples :return: first index for which predicate function returns True """ try: return next(i for i, v in enumerate(items) if predicateFn(v)) except StopIteration: return -1
def fib ( n ) : assert n > 0 a , b = 1 , 1 for i in range ( n - 1 ) : a , b = b , a + b return a
0
fibonacci python loops with return
Fibonacci example function
cosqa-train-19091
def fib(n): """Fibonacci example function Args: n (int): integer Returns: int: n-th Fibonacci number """ assert n > 0 a, b = 1, 1 for i in range(n - 1): a, b = b, a + b return a
def suppress_stdout ( ) : save_stdout = sys . stdout sys . stdout = DevNull ( ) yield sys . stdout = save_stdout
0
how to suppress true output in python
Context manager that suppresses stdout .
cosqa-train-19092
def suppress_stdout(): """ Context manager that suppresses stdout. Examples: >>> with suppress_stdout(): ... print('Test print') >>> print('test') test """ save_stdout = sys.stdout sys.stdout = DevNull() yield sys.stdout = save_stdout
def dtypes ( self ) : return [ ( str ( f . name ) , f . dataType . simpleString ( ) ) for f in self . schema . fields ]
1
get types of all python columns
Returns all column names and their data types as a list .
cosqa-train-19093
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 rate_limited ( max_per_hour : int , * args : Any ) -> Callable [ ... , Any ] : return util . rate_limited ( max_per_hour , * args )
1
python limit the execution time of a function call
Rate limit a function .
cosqa-train-19094
def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]: """Rate limit a function.""" return util.rate_limited(max_per_hour, *args)
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
python sample file s3 fetch
Pull a file directly from S3 .
cosqa-train-19095
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 iprotate ( l , steps = 1 ) : if len ( l ) : steps %= len ( l ) if steps : firstPart = l [ : steps ] del l [ : steps ] l . extend ( firstPart ) return l
0
how to rotate items in a list python
r Like rotate but modifies l in - place .
cosqa-train-19096
def iprotate(l, steps=1): r"""Like rotate, but modifies `l` in-place. >>> l = [1,2,3] >>> iprotate(l) is l True >>> l [2, 3, 1] >>> iprotate(iprotate(l, 2), -3) [1, 2, 3] """ if len(l): steps %= len(l) if steps: firstPart = l[:steps] del l[:steps] l.extend(firstPart) return l
def has_key ( cls , * args ) : key = args if len ( args ) > 1 else args [ 0 ] return key in cls . _instances
1
python check if a key exists
Check whether flyweight object with specified key has already been created .
cosqa-train-19097
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 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
1
read a file into a set python
Extract a de - duped collection ( set ) of text from a file . Expected file format is one item per line .
cosqa-train-19098
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 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
ndarray to string python
Format numpy array as a string .
cosqa-train-19099
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)