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 count ( self , elem ) : return self . _left_list . count ( elem ) + self . _right_list . count ( elem )
0
length of a deque python
Return the number of elements equal to elem present in the queue
cosqa-train-19200
def count(self, elem): """ Return the number of elements equal to elem present in the queue >>> pdeque([1, 2, 1]).count(1) 2 """ return self._left_list.count(elem) + self._right_list.count(elem)
def _close ( self ) : self . _usb_handle . releaseInterface ( ) try : # If we're using PyUSB >= 1.0 we can re-attach the kernel driver here. self . _usb_handle . dev . attach_kernel_driver ( 0 ) except : pass self . _usb_int = None self . _usb_handle = None return True
0
python usb core no backend
Release the USB interface again .
cosqa-train-19201
def _close(self): """ Release the USB interface again. """ self._usb_handle.releaseInterface() try: # If we're using PyUSB >= 1.0 we can re-attach the kernel driver here. self._usb_handle.dev.attach_kernel_driver(0) except: pass self._usb_int = None self._usb_handle = None return True
def long_substr ( data ) : substr = '' if len ( data ) > 1 and len ( data [ 0 ] ) > 0 : for i in range ( len ( data [ 0 ] ) ) : for j in range ( len ( data [ 0 ] ) - i + 1 ) : if j > len ( substr ) and all ( data [ 0 ] [ i : i + j ] in x for x in data ) : substr = data [ 0 ] [ i : i + j ] elif len ( data ) == 1 : substr = data [ 0 ] return substr
1
longest substring no repeating python
Return the longest common substring in a list of strings . Credit : http : // stackoverflow . com / questions / 2892931 / longest - common - substring - from - more - than - two - strings - python
cosqa-train-19202
def long_substr(data): """Return the longest common substring in a list of strings. Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python """ substr = '' if len(data) > 1 and len(data[0]) > 0: for i in range(len(data[0])): for j in range(len(data[0])-i+1): if j > len(substr) and all(data[0][i:i+j] in x for x in data): substr = data[0][i:i+j] elif len(data) == 1: substr = data[0] return substr
def mmap ( func , iterable ) : if sys . version_info [ 0 ] > 2 : return [ i for i in map ( func , iterable ) ] else : return map ( func , iterable )
1
python3 for each in map
Wrapper to make map () behave the same on Py2 and Py3 .
cosqa-train-19203
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 dag_longest_path ( graph , source , target ) : if source == target : return [ source ] allpaths = nx . all_simple_paths ( graph , source , target ) longest_path = [ ] for l in allpaths : if len ( l ) > len ( longest_path ) : longest_path = l return longest_path
1
python networkx longest path directed acyclic graph
Finds the longest path in a dag between two nodes
cosqa-train-19204
def dag_longest_path(graph, source, target): """ Finds the longest path in a dag between two nodes """ if source == target: return [source] allpaths = nx.all_simple_paths(graph, source, target) longest_path = [] for l in allpaths: if len(l) > len(longest_path): longest_path = l return longest_path
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 run spyder with multiple python versions
Get version information for components used by Spyder
cosqa-train-19205
def get_versions(reporev=True): """Get version information for components used by Spyder""" import sys import platform import qtpy import qtpy.QtCore revision = None if reporev: from spyder.utils import vcs revision, branch = vcs.get_git_revision(os.path.dirname(__dir__)) if not sys.platform == 'darwin': # To avoid a crash with our Mac app system = platform.system() else: system = 'Darwin' return { 'spyder': __version__, 'python': platform.python_version(), # "2.7.3" 'bitness': 64 if sys.maxsize > 2**32 else 32, 'qt': qtpy.QtCore.__version__, 'qt_api': qtpy.API_NAME, # PyQt5 'qt_api_ver': qtpy.PYQT_VERSION, 'system': system, # Linux, Windows, ... 'release': platform.release(), # XP, 10.6, 2.2.0, etc. 'revision': revision, # '9fdf926eccce' }
def read32 ( bytestream ) : dt = np . dtype ( np . uint32 ) . newbyteorder ( '>' ) return np . frombuffer ( bytestream . read ( 4 ) , dtype = dt ) [ 0 ]
0
python conver to unsigned int
Read 4 bytes from bytestream as an unsigned 32 - bit integer .
cosqa-train-19206
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 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
0
how to tell if link is relative python
simple method to determine if a url is relative or absolute
cosqa-train-19207
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 to_np ( * args ) : if len ( args ) > 1 : return ( cp . asnumpy ( x ) for x in args ) else : return cp . asnumpy ( args [ 0 ] )
0
how to evaluate each element of an array in a function python
convert GPU arras to numpy and return them
cosqa-train-19208
def to_np(*args): """ convert GPU arras to numpy and return them""" if len(args) > 1: return (cp.asnumpy(x) for x in args) else: return cp.asnumpy(args[0])
def remove_blank_spaces ( syllables : List [ str ] ) -> List [ str ] : cleaned = [ ] for syl in syllables : if syl == " " or syl == '' : pass else : cleaned . append ( syl ) return cleaned
0
how to remove blank spaces from lists python
Given a list of letters remove any blank spaces or empty strings .
cosqa-train-19209
def remove_blank_spaces(syllables: List[str]) -> List[str]: """ Given a list of letters, remove any blank spaces or empty strings. :param syllables: :return: >>> remove_blank_spaces(['', 'a', ' ', 'b', ' ', 'c', '']) ['a', 'b', 'c'] """ cleaned = [] for syl in syllables: if syl == " " or syl == '': pass else: cleaned.append(syl) return cleaned
def dict_to_ddb ( item ) : # type: (Dict[str, Any]) -> Dict[str, Any] # TODO: narrow these types down serializer = TypeSerializer ( ) return { key : serializer . serialize ( value ) for key , value in item . items ( ) }
1
python dict to sqlalchemy item
Converts a native Python dictionary to a raw DynamoDB item .
cosqa-train-19210
def dict_to_ddb(item): # type: (Dict[str, Any]) -> Dict[str, Any] # TODO: narrow these types down """Converts a native Python dictionary to a raw DynamoDB item. :param dict item: Native item :returns: DynamoDB item :rtype: dict """ serializer = TypeSerializer() return {key: serializer.serialize(value) for key, value in item.items()}
def _isint ( string ) : return type ( string ) is int or ( isinstance ( string , _binary_type ) or isinstance ( string , _text_type ) ) and _isconvertible ( int , string )
0
how to check if a string is an int python
>>> _isint ( 123 ) True >>> _isint ( 123 . 45 ) False
cosqa-train-19211
def _isint(string): """ >>> _isint("123") True >>> _isint("123.45") False """ return type(string) is int or \ (isinstance(string, _binary_type) or isinstance(string, _text_type)) and \ _isconvertible(int, string)
def non_increasing ( values ) : return all ( x >= y for x , y in zip ( values , values [ 1 : ] ) )
1
python not equal to a set of values
True if values are not increasing .
cosqa-train-19212
def non_increasing(values): """True if values are not increasing.""" return all(x >= y for x, y in zip(values, values[1:]))
def input ( prompt = "" ) : string = stdin_decode ( raw_input ( prompt ) ) caller_frame = sys . _getframe ( 1 ) globals = caller_frame . f_globals locals = caller_frame . f_locals return eval ( string , globals , locals )
0
prompt user in python eval(
input ( [ prompt ] ) - > value
cosqa-train-19213
def input(prompt=""): """input([prompt]) -> value Equivalent to eval(raw_input(prompt)).""" string = stdin_decode(raw_input(prompt)) caller_frame = sys._getframe(1) globals = caller_frame.f_globals locals = caller_frame.f_locals return eval(string, globals, locals)
def suppress_stdout ( ) : save_stdout = sys . stdout sys . stdout = DevNull ( ) yield sys . stdout = save_stdout
0
python hide certain output
Context manager that suppresses stdout .
cosqa-train-19214
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 convert_to_int ( x : Any , default : int = None ) -> int : try : return int ( x ) except ( TypeError , ValueError ) : return default
0
python input default int
Transforms its input into an integer or returns default .
cosqa-train-19215
def convert_to_int(x: Any, default: int = None) -> int: """ Transforms its input into an integer, or returns ``default``. """ try: return int(x) except (TypeError, ValueError): return default
def filter_bool ( n : Node , query : str ) -> bool : return _scalariter2item ( n , query , bool )
1
python filter function return a series, but expected a scalar bool
Filter and ensure that the returned value is of type bool .
cosqa-train-19216
def filter_bool(n: Node, query: str) -> bool: """ Filter and ensure that the returned value is of type bool. """ return _scalariter2item(n, query, bool)
def ask_bool ( question : str , default : bool = True ) -> bool : default_q = "Y/n" if default else "y/N" answer = input ( "{0} [{1}]: " . format ( question , default_q ) ) lower = answer . lower ( ) if not lower : return default return lower == "y"
0
python how to ask a true or false question
Asks a question yes no style
cosqa-train-19217
def ask_bool(question: str, default: bool = True) -> bool: """Asks a question yes no style""" default_q = "Y/n" if default else "y/N" answer = input("{0} [{1}]: ".format(question, default_q)) lower = answer.lower() if not lower: return default return lower == "y"
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 last month from python
Returns day number of the last day of the month : param t : datetime : return : int
cosqa-train-19218
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 indexes_equal ( a : Index , b : Index ) -> bool : return str ( a ) == str ( b )
0
check if two strings are equal python
Are two indexes equal? Checks by comparing str () versions of them . ( AM UNSURE IF THIS IS ENOUGH . )
cosqa-train-19219
def indexes_equal(a: Index, b: Index) -> bool: """ Are two indexes equal? Checks by comparing ``str()`` versions of them. (AM UNSURE IF THIS IS ENOUGH.) """ return str(a) == str(b)
def to_bool ( value : Any ) -> bool : return bool ( strtobool ( value ) if isinstance ( value , str ) else value )
0
python turn true and false into logical
Convert string or other Python object to boolean .
cosqa-train-19220
def to_bool(value: Any) -> bool: """Convert string or other Python object to boolean. **Rationalle** Passing flags is one of the most common cases of using environment vars and as values are strings we need to have an easy way to convert them to boolean Python value. Without this function int or float string values can be converted as false positives, e.g. ``bool('0') => True``, but using this function ensure that digit flag be properly converted to boolean value. :param value: String or other value. """ return bool(strtobool(value) if isinstance(value, str) else value)
def page_align_content_length ( length ) : # type: (int) -> int mod = length % _PAGEBLOB_BOUNDARY if mod != 0 : return length + ( _PAGEBLOB_BOUNDARY - mod ) return length
1
python calc page align
Compute page boundary alignment : param int length : content length : rtype : int : return : aligned byte boundary
cosqa-train-19221
def page_align_content_length(length): # type: (int) -> int """Compute page boundary alignment :param int length: content length :rtype: int :return: aligned byte boundary """ mod = length % _PAGEBLOB_BOUNDARY if mod != 0: return length + (_PAGEBLOB_BOUNDARY - mod) return length
def split ( text : str ) -> List [ str ] : return [ word for word in SEPARATOR . split ( text ) if word . strip ( ' \t' ) ]
0
how to split sentence based on delimeter using python
Split a text into a list of tokens .
cosqa-train-19222
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 post ( self , endpoint : str , * * kwargs ) -> dict : return self . _request ( 'POST' , endpoint , * * kwargs )
0
python rest api posting json request
HTTP POST operation to API endpoint .
cosqa-train-19223
def post(self, endpoint: str, **kwargs) -> dict: """HTTP POST operation to API endpoint.""" return self._request('POST', endpoint, **kwargs)
def cpu_count ( ) -> int : if multiprocessing is None : return 1 try : return multiprocessing . cpu_count ( ) except NotImplementedError : pass try : return os . sysconf ( "SC_NPROCESSORS_CONF" ) except ( AttributeError , ValueError ) : pass gen_log . error ( "Could not detect number of processors; assuming 1" ) return 1
1
python get the number of cpu cores
Returns the number of processors on this machine .
cosqa-train-19224
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 _request ( self , method : str , endpoint : str , params : dict = None , data : dict = None , headers : dict = None ) -> dict :
1
python method object pass in
HTTP request method of interface implementation .
cosqa-train-19225
def _request(self, method: str, endpoint: str, params: dict = None, data: dict = None, headers: dict = None) -> dict: """HTTP request method of interface implementation."""
def rank ( tensor : BKTensor ) -> int : if isinstance ( tensor , np . ndarray ) : return len ( tensor . shape ) return len ( tensor [ 0 ] . size ( ) )
0
python length of element in matrix
Return the number of dimensions of a tensor
cosqa-train-19226
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 from_buffer ( buffer , mime = False ) : m = _get_magic_type ( mime ) return m . from_buffer ( buffer )
1
pythondetermine file format from binary
Accepts a binary string and returns the detected filetype . Return value is the mimetype if mime = True otherwise a human readable name .
cosqa-train-19227
def from_buffer(buffer, mime=False): """ Accepts a binary string and returns the detected filetype. Return value is the mimetype if mime=True, otherwise a human readable name. >>> magic.from_buffer(open("testdata/test.pdf").read(1024)) 'PDF document, version 1.2' """ m = _get_magic_type(mime) return m.from_buffer(buffer)
def url_concat ( url , args ) : if not args : return url if url [ - 1 ] not in ( '?' , '&' ) : url += '&' if ( '?' in url ) else '?' return url + urllib . urlencode ( args )
0
python adding query string to url
Concatenate url and argument dictionary regardless of whether url has existing query parameters .
cosqa-train-19228
def url_concat(url, args): """Concatenate url and argument dictionary regardless of whether url has existing query parameters. >>> url_concat("http://example.com/foo?a=b", dict(c="d")) 'http://example.com/foo?a=b&c=d' """ if not args: return url if url[-1] not in ('?', '&'): url += '&' if ('?' in url) else '?' return url + urllib.urlencode(args)
def getVectorFromType ( self , dtype ) -> Union [ bool , None , Tuple [ int , int ] ] : if dtype == BIT : return False elif isinstance ( dtype , Bits ) : return [ evalParam ( dtype . width ) - 1 , hInt ( 0 ) ]
0
python unsupported operand type for nonetype
: see : doc of method on parent class
cosqa-train-19229
def getVectorFromType(self, dtype) -> Union[bool, None, Tuple[int, int]]: """ :see: doc of method on parent class """ if dtype == BIT: return False elif isinstance(dtype, Bits): return [evalParam(dtype.width) - 1, hInt(0)]
def get_from_gnucash26_date ( date_str : str ) -> date : date_format = "%Y%m%d" result = datetime . strptime ( date_str , date_format ) . date ( ) return result
0
get a date from string python
Creates a datetime from GnuCash 2 . 6 date string
cosqa-train-19230
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 strtobytes ( input , encoding ) : py_version = sys . version_info [ 0 ] if py_version >= 3 : return _strtobytes_py3 ( input , encoding ) return _strtobytes_py2 ( input , encoding )
1
python 3 string to byte encoding
Take a str and transform it into a byte array .
cosqa-train-19231
def strtobytes(input, encoding): """Take a str and transform it into a byte array.""" py_version = sys.version_info[0] if py_version >= 3: return _strtobytes_py3(input, encoding) return _strtobytes_py2(input, encoding)
def _ ( f , x ) : return { k : v for k , v in x . items ( ) if f ( k , v ) }
1
how do i filter a python dictionary by its values
filter for dict note f should have signature : f :: key - > value - > bool
cosqa-train-19232
def _(f, x): """ filter for dict, note `f` should have signature: `f::key->value->bool` """ return {k: v for k, v in x.items() if f(k, v)}
def get_day_name ( self ) -> str : weekday = self . value . isoweekday ( ) - 1 return calendar . day_name [ weekday ]
1
python how to get day of week name
Returns the day name
cosqa-train-19233
def get_day_name(self) -> str: """ Returns the day name """ weekday = self.value.isoweekday() - 1 return calendar.day_name[weekday]
def use_kwargs ( self , * args , * * kwargs ) -> typing . Callable : return super ( ) . use_kwargs ( * args , * * kwargs )
1
python receive **kwargs pass on **kwargs
Decorator that injects parsed arguments into a view function or method .
cosqa-train-19234
def use_kwargs(self, *args, **kwargs) -> typing.Callable: """Decorator that injects parsed arguments into a view function or method. Receives the same arguments as `webargs.core.Parser.use_kwargs`. """ return super().use_kwargs(*args, **kwargs)
def convert_camel_case_string ( name : str ) -> str : string = re . sub ( "(.)([A-Z][a-z]+)" , r"\1_\2" , name ) return re . sub ( "([a-z0-9])([A-Z])" , r"\1_\2" , string ) . lower ( )
1
python force string to camel case
Convert camel case string to snake case
cosqa-train-19235
def convert_camel_case_string(name: str) -> str: """Convert camel case string to snake case""" string = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name) return re.sub("([a-z0-9])([A-Z])", r"\1_\2", string).lower()
def _cnx_is_empty ( in_file ) : with open ( in_file ) as in_handle : for i , line in enumerate ( in_handle ) : if i > 0 : return False return True
0
how to see if a text file is empty in python
Check if cnr or cns files are empty ( only have a header )
cosqa-train-19236
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 do_quit ( self , _ : argparse . Namespace ) -> bool : self . _should_quit = True return self . _STOP_AND_EXIT
1
python user input to exit
Exit this application
cosqa-train-19237
def do_quit(self, _: argparse.Namespace) -> bool: """Exit this application""" self._should_quit = True return self._STOP_AND_EXIT
def distinct_permutations ( iterable ) : def make_new_permutations ( permutations , e ) : """Internal helper function. The output permutations are built up by adding element *e* to the current *permutations* at every possible position. The key idea is to keep repeated elements (reverse) ordered: if e1 == e2 and e1 is before e2 in the iterable, then all permutations with e1 before e2 are ignored. """ for permutation in permutations : for j in range ( len ( permutation ) ) : yield permutation [ : j ] + [ e ] + permutation [ j : ] if permutation [ j ] == e : break else : yield permutation + [ e ] permutations = [ [ ] ] for e in iterable : permutations = make_new_permutations ( permutations , e ) return ( tuple ( t ) for t in permutations )
1
python how to generate only half of the permutations
Yield successive distinct permutations of the elements in * iterable * .
cosqa-train-19238
def distinct_permutations(iterable): """Yield successive distinct permutations of the elements in *iterable*. >>> sorted(distinct_permutations([1, 0, 1])) [(0, 1, 1), (1, 0, 1), (1, 1, 0)] Equivalent to ``set(permutations(iterable))``, except duplicates are not generated and thrown away. For larger input sequences this is much more efficient. Duplicate permutations arise when there are duplicated elements in the input iterable. The number of items returned is `n! / (x_1! * x_2! * ... * x_n!)`, where `n` is the total number of items input, and each `x_i` is the count of a distinct item in the input sequence. """ def make_new_permutations(permutations, e): """Internal helper function. The output permutations are built up by adding element *e* to the current *permutations* at every possible position. The key idea is to keep repeated elements (reverse) ordered: if e1 == e2 and e1 is before e2 in the iterable, then all permutations with e1 before e2 are ignored. """ for permutation in permutations: for j in range(len(permutation)): yield permutation[:j] + [e] + permutation[j:] if permutation[j] == e: break else: yield permutation + [e] permutations = [[]] for e in iterable: permutations = make_new_permutations(permutations, e) return (tuple(t) for t in permutations)
def text_alignment ( x , y ) : if x == 0 : ha = "center" elif x > 0 : ha = "left" else : ha = "right" if y == 0 : va = "center" elif y > 0 : va = "bottom" else : va = "top" return ha , va
1
how to get horizontal alignment on python
Align text labels based on the x - and y - axis coordinate values .
cosqa-train-19239
def text_alignment(x, y): """ Align text labels based on the x- and y-axis coordinate values. This function is used for computing the appropriate alignment of the text label. For example, if the text is on the "right" side of the plot, we want it to be left-aligned. If the text is on the "top" side of the plot, we want it to be bottom-aligned. :param x, y: (`int` or `float`) x- and y-axis coordinate respectively. :returns: A 2-tuple of strings, the horizontal and vertical alignments respectively. """ if x == 0: ha = "center" elif x > 0: ha = "left" else: ha = "right" if y == 0: va = "center" elif y > 0: va = "bottom" else: va = "top" return ha, va
def _validate_image_rank ( self , img_array ) : if img_array . ndim == 1 or img_array . ndim > 3 : msg = "{0}D imagery is not allowed." . format ( img_array . ndim ) raise IOError ( msg )
1
invalid dimensions for image data in python
Images must be either 2D or 3D .
cosqa-train-19240
def _validate_image_rank(self, img_array): """ Images must be either 2D or 3D. """ if img_array.ndim == 1 or img_array.ndim > 3: msg = "{0}D imagery is not allowed.".format(img_array.ndim) raise IOError(msg)
def _request ( self , method : str , endpoint : str , params : dict = None , data : dict = None , headers : dict = None ) -> dict :
0
get and post methods for python server
HTTP request method of interface implementation .
cosqa-train-19241
def _request(self, method: str, endpoint: str, params: dict = None, data: dict = None, headers: dict = None) -> dict: """HTTP request method of interface implementation."""
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 check if a file is empty using python
Check if cnr or cns files are empty ( only have a header )
cosqa-train-19242
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 _kbhit_unix ( ) -> bool : dr , dw , de = select . select ( [ sys . stdin ] , [ ] , [ ] , 0 ) return dr != [ ]
1
python linux detect keypress
Under UNIX : is a keystroke available?
cosqa-train-19243
def _kbhit_unix() -> bool: """ Under UNIX: is a keystroke available? """ dr, dw, de = select.select([sys.stdin], [], [], 0) return dr != []
def lint ( fmt = 'colorized' ) : if fmt == 'html' : outfile = 'pylint_report.html' local ( 'pylint -f %s davies > %s || true' % ( fmt , outfile ) ) local ( 'open %s' % outfile ) else : local ( 'pylint -f %s davies || true' % fmt )
0
auto pylint python 2
Run verbose PyLint on source . Optionally specify fmt = html for HTML output .
cosqa-train-19244
def lint(fmt='colorized'): """Run verbose PyLint on source. Optionally specify fmt=html for HTML output.""" if fmt == 'html': outfile = 'pylint_report.html' local('pylint -f %s davies > %s || true' % (fmt, outfile)) local('open %s' % outfile) else: local('pylint -f %s davies || true' % fmt)
def _hash_the_file ( hasher , filename ) : BUF_SIZE = 65536 with open ( filename , 'rb' ) as f : buf = f . read ( BUF_SIZE ) while len ( buf ) > 0 : hasher . update ( buf ) buf = f . read ( BUF_SIZE ) return hasher
1
python hash for a file
Helper function for creating hash functions .
cosqa-train-19245
def _hash_the_file(hasher, filename): """Helper function for creating hash functions. See implementation of :func:`dtoolcore.filehasher.shasum` for more usage details. """ BUF_SIZE = 65536 with open(filename, 'rb') as f: buf = f.read(BUF_SIZE) while len(buf) > 0: hasher.update(buf) buf = f.read(BUF_SIZE) return hasher
def normalize_column_names ( df ) : columns = df . columns if hasattr ( df , 'columns' ) else df columns = [ c . lower ( ) . replace ( ' ' , '_' ) for c in columns ] return columns
1
remove special characters from column names in python
r Clean up whitespace in column names . See better version at pugnlp . clean_columns
cosqa-train-19246
def normalize_column_names(df): r""" Clean up whitespace in column names. See better version at `pugnlp.clean_columns` >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=['Hello World', 'not here']) >>> normalize_column_names(df) ['hello_world', 'not_here'] """ columns = df.columns if hasattr(df, 'columns') else df columns = [c.lower().replace(' ', '_') for c in columns] return columns
def hsv2rgb_spectrum ( hsv ) : h , s , v = hsv return hsv2rgb_raw ( ( ( h * 192 ) >> 8 , s , v ) )
0
python hsv 2 rgb
Generates RGB values from HSV values in line with a typical light spectrum .
cosqa-train-19247
def hsv2rgb_spectrum(hsv): """Generates RGB values from HSV values in line with a typical light spectrum.""" h, s, v = hsv return hsv2rgb_raw(((h * 192) >> 8, s, v))
def read_text_from_file ( path : str ) -> str : with open ( path ) as text_file : content = text_file . read ( ) return content
1
how to read the contents of a text file in python
Reads text file contents
cosqa-train-19248
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 snake_to_camel ( s : str ) -> str : fragments = s . split ( '_' ) return fragments [ 0 ] + '' . join ( x . title ( ) for x in fragments [ 1 : ] )
0
how to titlecase words in python
Convert string from snake case to camel case .
cosqa-train-19249
def snake_to_camel(s: str) -> str: """Convert string from snake case to camel case.""" fragments = s.split('_') return fragments[0] + ''.join(x.title() for x in fragments[1:])
def list_adb_devices_by_usb_id ( ) : out = adb . AdbProxy ( ) . devices ( [ '-l' ] ) clean_lines = new_str ( out , 'utf-8' ) . strip ( ) . split ( '\n' ) results = [ ] for line in clean_lines : tokens = line . strip ( ) . split ( ) if len ( tokens ) > 2 and tokens [ 1 ] == 'device' : results . append ( tokens [ 2 ] ) return results
1
python read adb devices
List the usb id of all android devices connected to the computer that are detected by adb .
cosqa-train-19250
def list_adb_devices_by_usb_id(): """List the usb id of all android devices connected to the computer that are detected by adb. Returns: A list of strings that are android device usb ids. Empty if there's none. """ out = adb.AdbProxy().devices(['-l']) clean_lines = new_str(out, 'utf-8').strip().split('\n') results = [] for line in clean_lines: tokens = line.strip().split() if len(tokens) > 2 and tokens[1] == 'device': results.append(tokens[2]) return results
def pack_bits ( longbits ) : byte = longbits & ( 0x0101010101010101 ) byte = ( byte | ( byte >> 7 ) ) & ( 0x0003000300030003 ) byte = ( byte | ( byte >> 14 ) ) & ( 0x0000000f0000000f ) byte = ( byte | ( byte >> 28 ) ) & ( 0x00000000000000ff ) return byte
1
python3 how to correct print out bit data
Crunch a 64 - bit int ( 8 bool bytes ) into a bitfield .
cosqa-train-19251
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 camel_to_snake ( s : str ) -> str : return CAMEL_CASE_RE . sub ( r'_\1' , s ) . strip ( ) . lower ( )
0
python change column name from camel to snake
Convert string from camel case to snake case .
cosqa-train-19252
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 get_window_dim ( ) : version = sys . version_info if version >= ( 3 , 3 ) : return _size_36 ( ) if platform . system ( ) == 'Windows' : return _size_windows ( ) return _size_27 ( )
0
python get desktop size from linux
gets the dimensions depending on python version and os
cosqa-train-19253
def get_window_dim(): """ gets the dimensions depending on python version and os""" version = sys.version_info if version >= (3, 3): return _size_36() if platform.system() == 'Windows': return _size_windows() return _size_27()
def _prm_get_longest_stringsize ( string_list ) : maxlength = 1 for stringar in string_list : if isinstance ( stringar , np . ndarray ) : if stringar . ndim > 0 : for string in stringar . ravel ( ) : maxlength = max ( len ( string ) , maxlength ) else : maxlength = max ( len ( stringar . tolist ( ) ) , maxlength ) else : maxlength = max ( len ( stringar ) , maxlength ) # Make the string Col longer than needed in order to allow later on slightly larger strings return int ( maxlength * 1.5 )
0
python length longest string in array
Returns the longest string size for a string entry across data .
cosqa-train-19254
def _prm_get_longest_stringsize(string_list): """ Returns the longest string size for a string entry across data.""" maxlength = 1 for stringar in string_list: if isinstance(stringar, np.ndarray): if stringar.ndim > 0: for string in stringar.ravel(): maxlength = max(len(string), maxlength) else: maxlength = max(len(stringar.tolist()), maxlength) else: maxlength = max(len(stringar), maxlength) # Make the string Col longer than needed in order to allow later on slightly larger strings return int(maxlength * 1.5)
def try_cast_int ( s ) : try : temp = re . findall ( '\d' , str ( s ) ) temp = '' . join ( temp ) return int ( temp ) except : return s
1
changing string to int with python
( str ) - > int All the digits in a given string are concatenated and converted into a single number .
cosqa-train-19255
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 count ( args ) : counts = defaultdict ( int ) for arg in args : for item in arg : counts [ item ] = counts [ item ] + 1 return counts
0
python count appearances in a list
count occurences in a list of lists >>> count ( [[ a b ] [ a ]] ) defaultdict ( int { a : 2 b : 1 } )
cosqa-train-19256
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 cpu_count ( ) -> int : if multiprocessing is None : return 1 try : return multiprocessing . cpu_count ( ) except NotImplementedError : pass try : return os . sysconf ( "SC_NPROCESSORS_CONF" ) except ( AttributeError , ValueError ) : pass gen_log . error ( "Could not detect number of processors; assuming 1" ) return 1
1
how to detect number of cpu cores in python
Returns the number of processors on this machine .
cosqa-train-19257
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 _kbhit_unix ( ) -> bool : dr , dw , de = select . select ( [ sys . stdin ] , [ ] , [ ] , 0 ) return dr != [ ]
1
python windows check for keypress
Under UNIX : is a keystroke available?
cosqa-train-19258
def _kbhit_unix() -> bool: """ Under UNIX: is a keystroke available? """ dr, dw, de = select.select([sys.stdin], [], [], 0) return dr != []
def astensor ( array : TensorLike ) -> BKTensor : tensor = tf . convert_to_tensor ( value = array , dtype = CTYPE ) return tensor
0
tensorflow compatible with python
Covert numpy array to tensorflow tensor
cosqa-train-19259
def astensor(array: TensorLike) -> BKTensor: """Covert numpy array to tensorflow tensor""" tensor = tf.convert_to_tensor(value=array, dtype=CTYPE) return tensor
def has_value ( cls , value : int ) -> bool : return any ( value == item . value for item in cls )
0
enum int comparison python
True if specified value exists in int enum ; otherwise False .
cosqa-train-19260
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 fast_median ( a ) : a = checkma ( a ) #return scoreatpercentile(a.compressed(), 50) if a . count ( ) > 0 : out = np . percentile ( a . compressed ( ) , 50 ) else : out = np . ma . masked return out
0
median without numpy python
Fast median operation for masked array using 50th - percentile
cosqa-train-19261
def fast_median(a): """Fast median operation for masked array using 50th-percentile """ a = checkma(a) #return scoreatpercentile(a.compressed(), 50) if a.count() > 0: out = np.percentile(a.compressed(), 50) else: out = np.ma.masked return out
def timeit ( func , log , limit ) : def newfunc ( * args , * * kwargs ) : """Execute function and print execution time.""" t = time . time ( ) res = func ( * args , * * kwargs ) duration = time . time ( ) - t if duration > limit : print ( func . __name__ , "took %0.2f seconds" % duration , file = log ) print ( args , file = log ) print ( kwargs , file = log ) return res return update_func_meta ( newfunc , func )
0
python execute function after specific ammount of time
Print execution time of the function . For quick n dirty profiling .
cosqa-train-19262
def timeit (func, log, limit): """Print execution time of the function. For quick'n'dirty profiling.""" def newfunc (*args, **kwargs): """Execute function and print execution time.""" t = time.time() res = func(*args, **kwargs) duration = time.time() - t if duration > limit: print(func.__name__, "took %0.2f seconds" % duration, file=log) print(args, file=log) print(kwargs, file=log) return res return update_func_meta(newfunc, func)
def last_location_of_minimum ( x ) : x = np . asarray ( x ) return 1.0 - np . argmin ( x [ : : - 1 ] ) / len ( x ) if len ( x ) > 0 else np . NaN
1
how to compute the minimum value of a tensor in python
Returns the last location of the minimal value of x . The position is calculated relatively to the length of x .
cosqa-train-19263
def last_location_of_minimum(x): """ Returns the last location of the minimal value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ x = np.asarray(x) return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN
def find_duplicates ( l : list ) -> set : return set ( [ x for x in l if l . count ( x ) > 1 ] )
1
function to count duplicates in list in python
Return the duplicates in a list .
cosqa-train-19264
def find_duplicates(l: list) -> set: """ Return the duplicates in a list. The function relies on https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-a-list . Parameters ---------- l : list Name Returns ------- set Duplicated values >>> find_duplicates([1,2,3]) set() >>> find_duplicates([1,2,1]) {1} """ return set([x for x in l if l.count(x) > 1])
def 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
return index for a certain value python
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-19265
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 execute ( cur , * args ) : stmt = args [ 0 ] if len ( args ) > 1 : stmt = stmt . replace ( '%' , '%%' ) . replace ( '?' , '%r' ) print ( stmt % ( args [ 1 ] ) ) return cur . execute ( * args )
1
question 3 what method do you call in an sqlite cursor object in python to run an sql command
Utility function to print sqlite queries before executing .
cosqa-train-19266
def execute(cur, *args): """Utility function to print sqlite queries before executing. Use instead of cur.execute(). First argument is cursor. cur.execute(stmt) becomes util.execute(cur, stmt) """ stmt = args[0] if len(args) > 1: stmt = stmt.replace('%', '%%').replace('?', '%r') print(stmt % (args[1])) return cur.execute(*args)
def file_exists ( fname ) : try : return fname and os . path . exists ( fname ) and os . path . getsize ( fname ) > 0 except OSError : return False
0
check if file is blank in python
Check if a file exists and is non - empty .
cosqa-train-19267
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 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 spyder to python 3
Get version information for components used by Spyder
cosqa-train-19268
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 chars ( string : any ) -> str : return '' . join ( [ c if c . isalpha ( ) else '' for c in str ( string ) ] )
0
python any letter in string
Return all ( and only ) the chars in the given string .
cosqa-train-19269
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 _isbool ( string ) : return isinstance ( string , _bool_type ) or ( isinstance ( string , ( _binary_type , _text_type ) ) and string in ( "True" , "False" ) )
1
python boolean and or not
>>> _isbool ( True ) True >>> _isbool ( False ) True >>> _isbool ( 1 ) False
cosqa-train-19270
def _isbool(string): """ >>> _isbool(True) True >>> _isbool("False") True >>> _isbool(1) False """ return isinstance(string, _bool_type) or\ (isinstance(string, (_binary_type, _text_type)) and string in ("True", "False"))
def bfx ( value , msb , lsb ) : mask = bitmask ( ( msb , lsb ) ) return ( value & mask ) >> lsb
1
python operate on a single bit
!
cosqa-train-19271
def bfx(value, msb, lsb): """! @brief Extract a value from a bitfield.""" mask = bitmask((msb, lsb)) return (value & mask) >> lsb
def callable_validator ( v : Any ) -> AnyCallable : if callable ( v ) : return v raise errors . CallableError ( value = v )
1
check if callable python
Perform a simple check if the value is callable .
cosqa-train-19272
def callable_validator(v: Any) -> AnyCallable: """ Perform a simple check if the value is callable. Note: complete matching of argument type hints and return types is not performed """ if callable(v): return v raise errors.CallableError(value=v)
def 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 shared cache
Setup the flask - cache on a flask app
cosqa-train-19273
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 file_exists ( fname ) : try : return fname and os . path . exists ( fname ) and os . path . getsize ( fname ) > 0 except OSError : return False
0
python if os file doesn't exist
Check if a file exists and is non - empty .
cosqa-train-19274
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 __gt__ ( self , other ) : if not isinstance ( other , Key ) : return NotImplemented return self . __tuple ( ) > other . __tuple ( )
0
python merge greater than
Greater than ordering .
cosqa-train-19275
def __gt__(self, other): """Greater than ordering.""" if not isinstance(other, Key): return NotImplemented return self.__tuple() > other.__tuple()
def strictly_positive_int_or_none ( val ) : val = positive_int_or_none ( val ) if val is None or val > 0 : return val raise ValueError ( '"{}" must be strictly positive' . format ( val ) )
0
how to check int null value in python
Parse val into either None or a strictly positive integer .
cosqa-train-19276
def strictly_positive_int_or_none(val): """Parse `val` into either `None` or a strictly positive integer.""" val = positive_int_or_none(val) if val is None or val > 0: return val raise ValueError('"{}" must be strictly positive'.format(val))
def has_key ( cls , * args ) : key = args if len ( args ) > 1 else args [ 0 ] return key in cls . _instances
0
python check to see if a key exists
Check whether flyweight object with specified key has already been created .
cosqa-train-19277
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 numpy_to_yaml ( representer : Representer , data : np . ndarray ) -> Sequence [ Any ] : return representer . represent_sequence ( "!numpy_array" , data . tolist ( ) )
1
python np array yaml
Write a numpy array to YAML .
cosqa-train-19278
def numpy_to_yaml(representer: Representer, data: np.ndarray) -> Sequence[Any]: """ Write a numpy array to YAML. It registers the array under the tag ``!numpy_array``. Use with: .. code-block:: python >>> yaml = ruamel.yaml.YAML() >>> yaml.representer.add_representer(np.ndarray, yaml.numpy_to_yaml) Note: We cannot use ``yaml.register_class`` because it won't register the proper type. (It would register the type of the class, rather than of `numpy.ndarray`). Instead, we use the above approach to register this method explicitly with the representer. """ return representer.represent_sequence( "!numpy_array", data.tolist() )
def sections ( self ) -> list : self . config . read ( self . filepath ) return self . config . sections ( )
1
python config parser get list of sections
List of sections .
cosqa-train-19279
def sections(self) -> list: """List of sections.""" self.config.read(self.filepath) return self.config.sections()
def obj_in_list_always ( target_list , obj ) : for item in set ( target_list ) : if item is not obj : return False return True
1
how to chk that an item is not in a list in python
>>> l = [ 1 1 1 ] >>> obj_in_list_always ( l 1 ) True >>> l . append ( 2 ) >>> obj_in_list_always ( l 1 ) False
cosqa-train-19280
def obj_in_list_always(target_list, obj): """ >>> l = [1,1,1] >>> obj_in_list_always(l, 1) True >>> l.append(2) >>> obj_in_list_always(l, 1) False """ for item in set(target_list): if item is not obj: return False return True
def integer_partition ( size : int , nparts : int ) -> Iterator [ List [ List [ int ] ] ] : for part in algorithm_u ( range ( size ) , nparts ) : yield part
0
itertools get all partitions into 2 sets python
Partition a list of integers into a list of partitions
cosqa-train-19281
def integer_partition(size: int, nparts: int) -> Iterator[List[List[int]]]: """ Partition a list of integers into a list of partitions """ for part in algorithm_u(range(size), nparts): yield part
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 3 speed up for loop with map
Wrapper to make map () behave the same on Py2 and Py3 .
cosqa-train-19282
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 assert_raises ( ex_type , func , * args , * * kwargs ) : try : func ( * args , * * kwargs ) except Exception as ex : assert isinstance ( ex , ex_type ) , ( 'Raised %r but type should have been %r' % ( ex , ex_type ) ) return True else : raise AssertionError ( 'No error was raised' )
0
how to throw an assertion error in python
r Checks that a function raises an error when given specific arguments .
cosqa-train-19283
def assert_raises(ex_type, func, *args, **kwargs): r""" Checks that a function raises an error when given specific arguments. Args: ex_type (Exception): exception type func (callable): live python function CommandLine: python -m utool.util_assert assert_raises --show Example: >>> # ENABLE_DOCTEST >>> from utool.util_assert import * # NOQA >>> import utool as ut >>> ex_type = AssertionError >>> func = len >>> # Check that this raises an error when something else does not >>> assert_raises(ex_type, assert_raises, ex_type, func, []) >>> # Check this does not raise an error when something else does >>> assert_raises(ValueError, [].index, 0) """ try: func(*args, **kwargs) except Exception as ex: assert isinstance(ex, ex_type), ( 'Raised %r but type should have been %r' % (ex, ex_type)) return True else: raise AssertionError('No error was raised')
def uuid2buid ( value ) : if six . PY3 : # pragma: no cover return urlsafe_b64encode ( value . bytes ) . decode ( 'utf-8' ) . rstrip ( '=' ) else : return six . text_type ( urlsafe_b64encode ( value . bytes ) . rstrip ( '=' ) )
0
uuid to str python 3
Convert a UUID object to a 22 - char BUID string
cosqa-train-19284
def uuid2buid(value): """ Convert a UUID object to a 22-char BUID string >>> u = uuid.UUID('33203dd2-f2ef-422f-aeb0-058d6f5f7089') >>> uuid2buid(u) 'MyA90vLvQi-usAWNb19wiQ' """ if six.PY3: # pragma: no cover return urlsafe_b64encode(value.bytes).decode('utf-8').rstrip('=') else: return six.text_type(urlsafe_b64encode(value.bytes).rstrip('='))
def debugTreePrint ( node , pfx = "->" ) : print pfx , node . item for c in node . children : debugTreePrint ( c , " " + pfx )
1
python print nodes binary tree
Purely a debugging aid : Ascii - art picture of a tree descended from node
cosqa-train-19285
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 indexes_equal ( a : Index , b : Index ) -> bool : return str ( a ) == str ( b )
0
checking if 2 strings are equal in python
Are two indexes equal? Checks by comparing str () versions of them . ( AM UNSURE IF THIS IS ENOUGH . )
cosqa-train-19286
def indexes_equal(a: Index, b: Index) -> bool: """ Are two indexes equal? Checks by comparing ``str()`` versions of them. (AM UNSURE IF THIS IS ENOUGH.) """ return str(a) == str(b)
def get_window_dim ( ) : version = sys . version_info if version >= ( 3 , 3 ) : return _size_36 ( ) if platform . system ( ) == 'Windows' : return _size_windows ( ) return _size_27 ( )
1
how to get the size of desktop using python
gets the dimensions depending on python version and os
cosqa-train-19287
def get_window_dim(): """ gets the dimensions depending on python version and os""" version = sys.version_info if version >= (3, 3): return _size_36() if platform.system() == 'Windows': return _size_windows() return _size_27()
def login ( self , user : str , passwd : str ) -> None : self . context . login ( user , passwd )
1
instagram login python requests
Log in to instagram with given username and password and internally store session object .
cosqa-train-19288
def login(self, user: str, passwd: str) -> None: """Log in to instagram with given username and password and internally store session object. :raises InvalidArgumentException: If the provided username does not exist. :raises BadCredentialsException: If the provided password is wrong. :raises ConnectionException: If connection to Instagram failed. :raises TwoFactorAuthRequiredException: First step of 2FA login done, now call :meth:`Instaloader.two_factor_login`.""" self.context.login(user, passwd)
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
use requests with python asyncio
Utility method to run commands synchronously for testing .
cosqa-train-19289
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 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
set maximum string length python
Truncate string values .
cosqa-train-19290
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 has_synset ( word : str ) -> list : return wn . synsets ( lemmatize ( word , neverstem = True ) )
1
split python wordnet synosym
Returns a list of synsets of a word after lemmatization .
cosqa-train-19291
def has_synset(word: str) -> list: """" Returns a list of synsets of a word after lemmatization. """ return wn.synsets(lemmatize(word, neverstem=True))
def dag_longest_path ( graph , source , target ) : if source == target : return [ source ] allpaths = nx . all_simple_paths ( graph , source , target ) longest_path = [ ] for l in allpaths : if len ( l ) > len ( longest_path ) : longest_path = l return longest_path
0
compute shortest path in graph python
Finds the longest path in a dag between two nodes
cosqa-train-19292
def dag_longest_path(graph, source, target): """ Finds the longest path in a dag between two nodes """ if source == target: return [source] allpaths = nx.all_simple_paths(graph, source, target) longest_path = [] for l in allpaths: if len(l) > len(longest_path): longest_path = l return longest_path
def _numbers_units ( N ) : lst = range ( 1 , N + 1 ) return "" . join ( list ( map ( lambda i : str ( i % 10 ) , lst ) ) )
1
how to make a string of numbers n python
>>> _numbers_units ( 45 ) 123456789012345678901234567890123456789012345
cosqa-train-19293
def _numbers_units(N): """ >>> _numbers_units(45) '123456789012345678901234567890123456789012345' """ lst = range(1, N + 1) return "".join(list(map(lambda i: str(i % 10), lst)))
def _duplicates ( list_ ) : item_indices = { } for i , item in enumerate ( list_ ) : try : item_indices [ item ] . append ( i ) except KeyError : # First time seen item_indices [ item ] = [ i ] return item_indices
0
python get duplicate index
Return dict mapping item - > indices .
cosqa-train-19294
def _duplicates(list_): """Return dict mapping item -> indices.""" item_indices = {} for i, item in enumerate(list_): try: item_indices[item].append(i) except KeyError: # First time seen item_indices[item] = [i] return item_indices
def put ( self , endpoint : str , * * kwargs ) -> dict : return self . _request ( 'PUT' , endpoint , * * kwargs )
1
python restful post put
HTTP PUT operation to API endpoint .
cosqa-train-19295
def put(self, endpoint: str, **kwargs) -> dict: """HTTP PUT operation to API endpoint.""" return self._request('PUT', endpoint, **kwargs)
def inverted_dict ( d ) : return dict ( ( force_hashable ( v ) , k ) for ( k , v ) in viewitems ( dict ( d ) ) )
1
how to you inverse a dictionary in python
Return a dict with swapped keys and values
cosqa-train-19296
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 clean_column_names ( df : DataFrame ) -> DataFrame : f = df . copy ( ) f . columns = [ col . strip ( ) for col in f . columns ] return f
0
how to drop ( ) in python column names
Strip the whitespace from all column names in the given DataFrame and return the result .
cosqa-train-19297
def clean_column_names(df: DataFrame) -> DataFrame: """ Strip the whitespace from all column names in the given DataFrame and return the result. """ f = df.copy() f.columns = [col.strip() for col in f.columns] return f
def to_int64 ( a ) : # build new dtype and replace i4 --> i8 def promote_i4 ( typestr ) : if typestr [ 1 : ] == 'i4' : typestr = typestr [ 0 ] + 'i8' return typestr dtype = [ ( name , promote_i4 ( typestr ) ) for name , typestr in a . dtype . descr ] return a . astype ( dtype )
0
how to change dtype in python to int
Return view of the recarray with all int32 cast to int64 .
cosqa-train-19298
def to_int64(a): """Return view of the recarray with all int32 cast to int64.""" # build new dtype and replace i4 --> i8 def promote_i4(typestr): if typestr[1:] == 'i4': typestr = typestr[0]+'i8' return typestr dtype = [(name, promote_i4(typestr)) for name,typestr in a.dtype.descr] return a.astype(dtype)
def 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
python open iterate remove newline
Helper for iterating only nonempty lines without line breaks
cosqa-train-19299
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