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 combine_pdf_as_bytes ( pdfs : List [ BytesIO ] ) -> bytes : writer = PdfWriter ( ) for pdf in pdfs : writer . addpages ( PdfReader ( pdf ) . pages ) bio = BytesIO ( ) writer . write ( bio ) bio . seek ( 0 ) output = bio . read ( ) bio . close ( ) return output
1
combine multiple pdfs into one python
Combine PDFs and return a byte - string with the result .
cosqa-train-19600
def combine_pdf_as_bytes(pdfs: List[BytesIO]) -> bytes: """Combine PDFs and return a byte-string with the result. Arguments --------- pdfs A list of BytesIO representations of PDFs """ writer = PdfWriter() for pdf in pdfs: writer.addpages(PdfReader(pdf).pages) bio = BytesIO() writer.write(bio) bio.seek(0) output = bio.read() bio.close() return output
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 number of cpu cores
Returns the number of processors on this machine .
cosqa-train-19601
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 array2string ( arr : numpy . ndarray ) -> str : shape = str ( arr . shape ) [ 1 : - 1 ] if shape . endswith ( "," ) : shape = shape [ : - 1 ] return numpy . array2string ( arr , threshold = 11 ) + "%s[%s]" % ( arr . dtype , shape )
1
python numpy ndarray to string
Format numpy array as a string .
cosqa-train-19602
def array2string(arr: numpy.ndarray) -> str: """Format numpy array as a string.""" shape = str(arr.shape)[1:-1] if shape.endswith(","): shape = shape[:-1] return numpy.array2string(arr, threshold=11) + "%s[%s]" % (arr.dtype, shape)
def to_np ( * args ) : if len ( args ) > 1 : return ( cp . asnumpy ( x ) for x in args ) else : return cp . asnumpy ( args [ 0 ] )
1
python using arrays to return multiple values
convert GPU arras to numpy and return them
cosqa-train-19603
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 is_natural ( x ) : try : is_integer = int ( x ) == x except ( TypeError , ValueError ) : return False return is_integer and x >= 0
1
python if i is not equal to and integer
A non - negative integer .
cosqa-train-19604
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 psutil_phymem_usage ( ) : import psutil # This is needed to avoid a deprecation warning error with # newer psutil versions try : percent = psutil . virtual_memory ( ) . percent except : percent = psutil . phymem_usage ( ) . percent return percent
0
psutil python memory leak
Return physical memory usage ( float ) Requires the cross - platform psutil ( > = v0 . 3 ) library ( https : // github . com / giampaolo / psutil )
cosqa-train-19605
def psutil_phymem_usage(): """ Return physical memory usage (float) Requires the cross-platform psutil (>=v0.3) library (https://github.com/giampaolo/psutil) """ import psutil # This is needed to avoid a deprecation warning error with # newer psutil versions try: percent = psutil.virtual_memory().percent except: percent = psutil.phymem_usage().percent return percent
def integer_partition ( size : int , nparts : int ) -> Iterator [ List [ List [ int ] ] ] : for part in algorithm_u ( range ( size ) , nparts ) : yield part
0
generating integer partitions python
Partition a list of integers into a list of partitions
cosqa-train-19606
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 snake_to_camel ( s : str ) -> str : fragments = s . split ( '_' ) return fragments [ 0 ] + '' . join ( x . title ( ) for x in fragments [ 1 : ] )
1
how to use the capitalize function in python
Convert string from snake case to camel case .
cosqa-train-19607
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 _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 int or not python
>>> _isint ( 123 ) True >>> _isint ( 123 . 45 ) False
cosqa-train-19608
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 valid_date ( x : str ) -> bool : try : if x != dt . datetime . strptime ( x , DATE_FORMAT ) . strftime ( DATE_FORMAT ) : raise ValueError return True except ValueError : return False
1
verify date string yyyymmdd python
Retrun True if x is a valid YYYYMMDD date ; otherwise return False .
cosqa-train-19609
def valid_date(x: str) -> bool: """ Retrun ``True`` if ``x`` is a valid YYYYMMDD date; otherwise return ``False``. """ try: if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT): raise ValueError return True except ValueError: return False
def session_expired ( self ) : if not self . _login_time or ( datetime . datetime . now ( ) - self . _login_time ) . total_seconds ( ) > 12000 : return True
1
python check if date is expired
Returns True if login_time not set or seconds since login time is greater than 200 mins .
cosqa-train-19610
def session_expired(self): """ Returns True if login_time not set or seconds since login time is greater than 200 mins. """ if not self._login_time or (datetime.datetime.now()-self._login_time).total_seconds() > 12000: return True
def top ( self , topn = 10 ) : return [ self [ i ] for i in argsort ( list ( zip ( * self ) ) [ 1 ] ) [ : : - 1 ] [ : topn ] ]
0
return list of top values python
Get a list of the top topn features in this : class : . Feature \ .
cosqa-train-19611
def top(self, topn=10): """ Get a list of the top ``topn`` features in this :class:`.Feature`\. Examples -------- .. code-block:: python >>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)]) >>> myFeature.top(1) [('trapezoid', 5)] Parameters ---------- topn : int Returns ------- list """ return [self[i] for i in argsort(list(zip(*self))[1])[::-1][:topn]]
def 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 random names in python
Generate a random python attribute name .
cosqa-train-19612
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 _parse_tuple_string ( argument ) : if isinstance ( argument , str ) : return tuple ( int ( p . strip ( ) ) for p in argument . split ( ',' ) ) return argument
1
python parse tuple rest
Return a tuple from parsing a b c d - > ( a b c d )
cosqa-train-19613
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 repl_complete ( text : str , state : int ) -> Optional [ str ] : # Can't complete Keywords, Numerals if __NOT_COMPLETEABLE . match ( text ) : return None elif text . startswith ( ":" ) : completions = kw . complete ( text ) else : ns = get_current_ns ( ) completions = ns . complete ( text ) return list ( completions ) [ state ] if completions is not None else None
0
use python to realize auto completion
Completer function for Python s readline / libedit implementation .
cosqa-train-19614
def repl_complete(text: str, state: int) -> Optional[str]: """Completer function for Python's readline/libedit implementation.""" # Can't complete Keywords, Numerals if __NOT_COMPLETEABLE.match(text): return None elif text.startswith(":"): completions = kw.complete(text) else: ns = get_current_ns() completions = ns.complete(text) return list(completions)[state] if completions is not None else None
def clean ( ctx , text ) : text = conversions . to_string ( text , ctx ) return '' . join ( [ c for c in text if ord ( c ) >= 32 ] )
1
python remove all instances of a char
Removes all non - printable characters from a text string
cosqa-train-19615
def clean(ctx, text): """ Removes all non-printable characters from a text string """ text = conversions.to_string(text, ctx) return ''.join([c for c in text if ord(c) >= 32])
def _brief_print_list ( lst , limit = 7 ) : lst = list ( lst ) if len ( lst ) > limit : return _brief_print_list ( lst [ : limit // 2 ] , limit ) + ', ..., ' + _brief_print_list ( lst [ - limit // 2 : ] , limit ) return ', ' . join ( [ "'%s'" % str ( i ) for i in lst ] )
0
how to print few elements from a list in python
Print at most limit elements of list .
cosqa-train-19616
def _brief_print_list(lst, limit=7): """Print at most `limit` elements of list.""" lst = list(lst) if len(lst) > limit: return _brief_print_list(lst[:limit//2], limit) + ', ..., ' + \ _brief_print_list(lst[-limit//2:], limit) return ', '.join(["'%s'"%str(i) for i in lst])
def normalize ( numbers ) : total = float ( sum ( numbers ) ) return [ n / total for n in numbers ]
1
python normalize set of numbers
Multiply each number by a constant such that the sum is 1 . 0 >>> normalize ( [ 1 2 1 ] ) [ 0 . 25 0 . 5 0 . 25 ]
cosqa-train-19617
def normalize(numbers): """Multiply each number by a constant such that the sum is 1.0 >>> normalize([1,2,1]) [0.25, 0.5, 0.25] """ total = float(sum(numbers)) return [n / total for n in numbers]
def validate ( request : Union [ Dict , List ] , schema : dict ) -> Union [ Dict , List ] : jsonschema_validate ( request , schema ) return request
1
rest json schema validation python
Wraps jsonschema . validate returning the same object passed in .
cosqa-train-19618
def validate(request: Union[Dict, List], schema: dict) -> Union[Dict, List]: """ Wraps jsonschema.validate, returning the same object passed in. Args: request: The deserialized-from-json request. schema: The jsonschema schema to validate against. Raises: jsonschema.ValidationError """ jsonschema_validate(request, schema) return request
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 file is empty or not in python
Check if cnr or cns files are empty ( only have a header )
cosqa-train-19619
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 get_keys_of_max_n ( dict_obj , n ) : return sorted ( [ item [ 0 ] for item in sorted ( dict_obj . items ( ) , key = lambda item : item [ 1 ] , reverse = True ) [ : n ] ] )
0
get all max values in dict python
Returns the keys that maps to the top n max values in the given dict .
cosqa-train-19620
def get_keys_of_max_n(dict_obj, n): """Returns the keys that maps to the top n max values in the given dict. Example: -------- >>> dict_obj = {'a':2, 'b':1, 'c':5} >>> get_keys_of_max_n(dict_obj, 2) ['a', 'c'] """ return sorted([ item[0] for item in sorted( dict_obj.items(), key=lambda item: item[1], reverse=True )[:n] ])
def 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
last day of month datetime python
Returns day number of the last day of the month : param t : datetime : return : int
cosqa-train-19621
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 try_cast_int ( s ) : try : temp = re . findall ( '\d' , str ( s ) ) temp = '' . join ( temp ) return int ( temp ) except : return s
0
casting a string to integer python
( str ) - > int All the digits in a given string are concatenated and converted into a single number .
cosqa-train-19622
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 normalize ( numbers ) : total = float ( sum ( numbers ) ) return [ n / total for n in numbers ]
0
how to standardize numbers to between 0 and 1 in python
Multiply each number by a constant such that the sum is 1 . 0 >>> normalize ( [ 1 2 1 ] ) [ 0 . 25 0 . 5 0 . 25 ]
cosqa-train-19623
def normalize(numbers): """Multiply each number by a constant such that the sum is 1.0 >>> normalize([1,2,1]) [0.25, 0.5, 0.25] """ total = float(sum(numbers)) return [n / total for n in numbers]
def clean ( ctx , text ) : text = conversions . to_string ( text , ctx ) return '' . join ( [ c for c in text if ord ( c ) >= 32 ] )
1
strip non latin characters from python text
Removes all non - printable characters from a text string
cosqa-train-19624
def clean(ctx, text): """ Removes all non-printable characters from a text string """ text = conversions.to_string(text, ctx) return ''.join([c for c in text if ord(c) >= 32])
def iter_lines ( file_like : Iterable [ str ] ) -> Generator [ str , None , None ] : for line in file_like : line = line . rstrip ( '\r\n' ) if line : yield line
0
python skip over blank lines while reading
Helper for iterating only nonempty lines without line breaks
cosqa-train-19625
def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]: """ Helper for iterating only nonempty lines without line breaks""" for line in file_like: line = line.rstrip('\r\n') if line: yield line
def clean ( ctx , text ) : text = conversions . to_string ( text , ctx ) return '' . join ( [ c for c in text if ord ( c ) >= 32 ] )
0
remove all encountered char in str python
Removes all non - printable characters from a text string
cosqa-train-19626
def clean(ctx, text): """ Removes all non-printable characters from a text string """ text = conversions.to_string(text, ctx) return ''.join([c for c in text if ord(c) >= 32])
def ranges_to_set ( lst ) : return set ( itertools . chain ( * ( range ( x [ 0 ] , x [ 1 ] + 1 ) for x in lst ) ) )
0
make set of numbers a list python
Convert a list of ranges to a set of numbers ::
cosqa-train-19627
def ranges_to_set(lst): """ Convert a list of ranges to a set of numbers:: >>> ranges = [(1,3), (5,6)] >>> sorted(list(ranges_to_set(ranges))) [1, 2, 3, 5, 6] """ return set(itertools.chain(*(range(x[0], x[1]+1) for x in lst)))
def list_to_str ( list , separator = ',' ) : list = [ str ( x ) for x in list ] return separator . join ( list )
0
python change a list of number to string
>>> list = [ 0 0 7 ] >>> list_to_str ( list ) 0 0 7
cosqa-train-19628
def list_to_str(list, separator=','): """ >>> list = [0, 0, 7] >>> list_to_str(list) '0,0,7' """ list = [str(x) for x in list] return separator.join(list)
def count ( args ) : counts = defaultdict ( int ) for arg in args : for item in arg : counts [ item ] = counts [ item ] + 1 return counts
0
count number of occurrences in a list python
count occurences in a list of lists >>> count ( [[ a b ] [ a ]] ) defaultdict ( int { a : 2 b : 1 } )
cosqa-train-19629
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 make_dep_graph ( depender ) : shutit_global . shutit_global_object . yield_to_draw ( ) digraph = '' for dependee_id in depender . depends_on : digraph = ( digraph + '"' + depender . module_id + '"->"' + dependee_id + '";\n' ) return digraph
1
python create code dependecy graph
Returns a digraph string fragment based on the passed - in module
cosqa-train-19630
def make_dep_graph(depender): """Returns a digraph string fragment based on the passed-in module """ shutit_global.shutit_global_object.yield_to_draw() digraph = '' for dependee_id in depender.depends_on: digraph = (digraph + '"' + depender.module_id + '"->"' + dependee_id + '";\n') return digraph
def quaternion_imag ( quaternion ) : return numpy . array ( quaternion [ 1 : 4 ] , dtype = numpy . float64 , copy = True )
0
get single col python 2d array
Return imaginary part of quaternion .
cosqa-train-19631
def quaternion_imag(quaternion): """Return imaginary part of quaternion. >>> quaternion_imag([3, 0, 1, 2]) array([ 0., 1., 2.]) """ return numpy.array(quaternion[1:4], dtype=numpy.float64, copy=True)
def multiple_replace ( string , replacements ) : # type: (str, Dict[str,str]) -> str pattern = re . compile ( "|" . join ( [ re . escape ( k ) for k in sorted ( replacements , key = len , reverse = True ) ] ) , flags = re . DOTALL ) return pattern . sub ( lambda x : replacements [ x . group ( 0 ) ] , string )
0
how to replace multiple strings with one string in python 3
Simultaneously replace multiple strigns in a string
cosqa-train-19632
def multiple_replace(string, replacements): # type: (str, Dict[str,str]) -> str """Simultaneously replace multiple strigns in a string Args: string (str): Input string replacements (Dict[str,str]): Replacements dictionary Returns: str: String with replacements """ pattern = re.compile("|".join([re.escape(k) for k in sorted(replacements, key=len, reverse=True)]), flags=re.DOTALL) return pattern.sub(lambda x: replacements[x.group(0)], string)
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
python code to check if file is empty
Check if cnr or cns files are empty ( only have a header )
cosqa-train-19633
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 _read_section ( self ) : lines = [ self . _last [ self . _last . find ( ":" ) + 1 : ] ] self . _last = self . _f . readline ( ) while len ( self . _last ) > 0 and len ( self . _last [ 0 ] . strip ( ) ) == 0 : lines . append ( self . _last ) self . _last = self . _f . readline ( ) return lines
0
python read last lines
Read and return an entire section
cosqa-train-19634
def _read_section(self): """Read and return an entire section""" lines = [self._last[self._last.find(":")+1:]] self._last = self._f.readline() while len(self._last) > 0 and len(self._last[0].strip()) == 0: lines.append(self._last) self._last = self._f.readline() return lines
def get_tokens ( line : str ) -> Iterator [ str ] : for token in line . rstrip ( ) . split ( ) : if len ( token ) > 0 : yield token
1
python parse a line into tokens
Yields tokens from input string .
cosqa-train-19635
def get_tokens(line: str) -> Iterator[str]: """ Yields tokens from input string. :param line: Input string. :return: Iterator over tokens. """ for token in line.rstrip().split(): if len(token) > 0: yield token
def list_to_str ( lst ) : if len ( lst ) == 1 : str_ = lst [ 0 ] elif len ( lst ) == 2 : str_ = ' and ' . join ( lst ) elif len ( lst ) > 2 : str_ = ', ' . join ( lst [ : - 1 ] ) str_ += ', and {0}' . format ( lst [ - 1 ] ) else : raise ValueError ( 'List of length 0 provided.' ) return str_
0
python join list to string by comma
Turn a list into a comma - and / or and - separated string .
cosqa-train-19636
def list_to_str(lst): """ Turn a list into a comma- and/or and-separated string. Parameters ---------- lst : :obj:`list` A list of strings to join into a single string. Returns ------- str_ : :obj:`str` A string with commas and/or ands separating th elements from ``lst``. """ if len(lst) == 1: str_ = lst[0] elif len(lst) == 2: str_ = ' and '.join(lst) elif len(lst) > 2: str_ = ', '.join(lst[:-1]) str_ += ', and {0}'.format(lst[-1]) else: raise ValueError('List of length 0 provided.') return str_
def returned ( n ) : ## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk for pos in randwalk ( ) >> drop ( 1 ) >> takei ( xrange ( n - 1 ) ) : if pos == Origin : return True return False
0
python how to make randomwalk work
Generate a random walk and return True if the walker has returned to the origin after taking n steps .
cosqa-train-19637
def returned(n): """Generate a random walk and return True if the walker has returned to the origin after taking `n` steps. """ ## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk for pos in randwalk() >> drop(1) >> takei(xrange(n-1)): if pos == Origin: return True return False
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 )
1
python get the maximum length of string objects in a list
Returns the longest string size for a string entry across data .
cosqa-train-19638
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 most_significant_bit ( lst : np . ndarray ) -> int : return np . argwhere ( np . asarray ( lst ) == 1 ) [ 0 ] [ 0 ]
0
how to store the smallest number in array in 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-19639
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 fib ( n ) : assert n > 0 a , b = 1 , 1 for i in range ( n - 1 ) : a , b = b , a + b return a
1
fibonacci sequence upto 8 python
Fibonacci example function
cosqa-train-19640
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 __rmatmul__ ( self , other ) : return self . T . dot ( np . transpose ( other ) ) . T
1
multiply matrix with different constant in python
Matrix multiplication using binary
cosqa-train-19641
def __rmatmul__(self, other): """ Matrix multiplication using binary `@` operator in Python>=3.5. """ return self.T.dot(np.transpose(other)).T
def enum_mark_last ( iterable , start = 0 ) : it = iter ( iterable ) count = start try : last = next ( it ) except StopIteration : return for val in it : yield count , False , last last = val count += 1 yield count , True , last
0
python for enumerate last item
Returns a generator over iterable that tells whether the current item is the last one . Usage : >>> iterable = range ( 10 ) >>> for index is_last item in enum_mark_last ( iterable ) : >>> print ( index item end = \ n if is_last else )
cosqa-train-19642
def enum_mark_last(iterable, start=0): """ Returns a generator over iterable that tells whether the current item is the last one. Usage: >>> iterable = range(10) >>> for index, is_last, item in enum_mark_last(iterable): >>> print(index, item, end='\n' if is_last else ', ') """ it = iter(iterable) count = start try: last = next(it) except StopIteration: return for val in it: yield count, False, last last = val count += 1 yield count, True, last
def most_frequent ( lst ) : lst = lst [ : ] highest_freq = 0 most_freq = None for val in unique ( lst ) : if lst . count ( val ) > highest_freq : most_freq = val highest_freq = lst . count ( val ) return most_freq
0
python code to calculate the most frequent
Returns the item that appears most frequently in the given list .
cosqa-train-19643
def most_frequent(lst): """ Returns the item that appears most frequently in the given list. """ lst = lst[:] highest_freq = 0 most_freq = None for val in unique(lst): if lst.count(val) > highest_freq: most_freq = val highest_freq = lst.count(val) return most_freq
def command ( self , cmd , * args ) : self . _serial_interface . command ( cmd ) if len ( args ) > 0 : self . _serial_interface . data ( list ( args ) )
1
serial python send commands
Sends a command and an ( optional ) sequence of arguments through to the delegated serial interface . Note that the arguments are passed through as data .
cosqa-train-19644
def command(self, cmd, *args): """ Sends a command and an (optional) sequence of arguments through to the delegated serial interface. Note that the arguments are passed through as data. """ self._serial_interface.command(cmd) if len(args) > 0: self._serial_interface.data(list(args))
def clean_map ( obj : Mapping [ Any , Any ] ) -> Mapping [ Any , Any ] : return { k : v for k , v in obj . items ( ) if v is not None }
0
remove all the items from the dictionary in python
Return a new copied dictionary without the keys with None values from the given Mapping object .
cosqa-train-19645
def clean_map(obj: Mapping[Any, Any]) -> Mapping[Any, Any]: """ Return a new copied dictionary without the keys with ``None`` values from the given Mapping object. """ return {k: v for k, v in obj.items() if v is not None}
def is_sqlatype_integer ( coltype : Union [ TypeEngine , VisitableType ] ) -> bool : coltype = _coltype_to_typeengine ( coltype ) return isinstance ( coltype , sqltypes . Integer )
0
python sqlalchemy set data type
Is the SQLAlchemy column type an integer type?
cosqa-train-19646
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 non_increasing ( values ) : return all ( x >= y for x , y in zip ( values , values [ 1 : ] ) )
0
python how to check if any two variables are greater than zero
True if values are not increasing .
cosqa-train-19647
def non_increasing(values): """True if values are not increasing.""" return all(x >= y for x, y in zip(values, values[1:]))
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
get window dimensions python
gets the dimensions depending on python version and os
cosqa-train-19648
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 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
get last 5 months on a date column in python
Returns the last week as a period string
cosqa-train-19649
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 to_0d_array ( value : Any ) -> np . ndarray : if np . isscalar ( value ) or ( isinstance ( value , np . ndarray ) and value . ndim == 0 ) : return np . array ( value ) else : return to_0d_object_array ( value )
1
initialize a 2d array in python without numpy
Given a value wrap it in a 0 - D numpy . ndarray .
cosqa-train-19650
def to_0d_array(value: Any) -> np.ndarray: """Given a value, wrap it in a 0-D numpy.ndarray. """ if np.isscalar(value) or (isinstance(value, np.ndarray) and value.ndim == 0): return np.array(value) else: return to_0d_object_array(value)
def 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
how to test if a set is a subset of another in python
Report whether another set contains this set .
cosqa-train-19651
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 repl_complete ( text : str , state : int ) -> Optional [ str ] : # Can't complete Keywords, Numerals if __NOT_COMPLETEABLE . match ( text ) : return None elif text . startswith ( ":" ) : completions = kw . complete ( text ) else : ns = get_current_ns ( ) completions = ns . complete ( text ) return list ( completions ) [ state ] if completions is not None else None
1
python semantic completion youcompleteme
Completer function for Python s readline / libedit implementation .
cosqa-train-19652
def repl_complete(text: str, state: int) -> Optional[str]: """Completer function for Python's readline/libedit implementation.""" # Can't complete Keywords, Numerals if __NOT_COMPLETEABLE.match(text): return None elif text.startswith(":"): completions = kw.complete(text) else: ns = get_current_ns() completions = ns.complete(text) return list(completions)[state] if completions is not None else None
def fprint ( expr , print_ascii = False ) : if print_ascii : pprint ( expr , use_unicode = False , num_columns = 120 ) else : return expr
0
showing hypthsis symbols in python
r This function chooses whether to use ascii characters to represent a symbolic expression in the notebook or to use sympy s pprint .
cosqa-train-19653
def fprint(expr, print_ascii=False): r"""This function chooses whether to use ascii characters to represent a symbolic expression in the notebook or to use sympy's pprint. >>> from sympy import cos >>> omega=Symbol("omega") >>> fprint(cos(omega),print_ascii=True) cos(omega) """ if print_ascii: pprint(expr, use_unicode=False, num_columns=120) else: return expr
def astensor ( array : TensorLike ) -> BKTensor : tensor = tf . convert_to_tensor ( value = array , dtype = CTYPE ) return tensor
1
python array to torch tensor
Covert numpy array to tensorflow tensor
cosqa-train-19654
def astensor(array: TensorLike) -> BKTensor: """Covert numpy array to tensorflow tensor""" tensor = tf.convert_to_tensor(value=array, dtype=CTYPE) return tensor
def _check_whitespace ( string ) : if string . count ( ' ' ) + string . count ( '\t' ) + string . count ( '\n' ) > 0 : raise ValueError ( INSTRUCTION_HAS_WHITESPACE )
1
to check if a particular string is whitespace python
Make sure thre is no whitespace in the given string . Will raise a ValueError if whitespace is detected
cosqa-train-19655
def _check_whitespace(string): """ Make sure thre is no whitespace in the given string. Will raise a ValueError if whitespace is detected """ if string.count(' ') + string.count('\t') + string.count('\n') > 0: raise ValueError(INSTRUCTION_HAS_WHITESPACE)
def get_property_as_float ( self , name : str ) -> float : return float ( self . __instrument . get_property ( name ) )
1
python'float' object has no attribute 'getvalue'
Return the value of a float property .
cosqa-train-19656
def get_property_as_float(self, name: str) -> float: """Return the value of a float property. :return: The property value (float). Raises exception if property with name doesn't exist. .. versionadded:: 1.0 Scriptable: Yes """ return float(self.__instrument.get_property(name))
def get_triangles ( graph : DiGraph ) -> SetOfNodeTriples : return { tuple ( sorted ( [ a , b , c ] , key = str ) ) for a , b in graph . edges ( ) for c in graph . successors ( b ) if graph . has_edge ( c , a ) }
0
print all cycles in a directed graph in python
Get a set of triples representing the 3 - cycles from a directional graph .
cosqa-train-19657
def get_triangles(graph: DiGraph) -> SetOfNodeTriples: """Get a set of triples representing the 3-cycles from a directional graph. Each 3-cycle is returned once, with nodes in sorted order. """ return { tuple(sorted([a, b, c], key=str)) for a, b in graph.edges() for c in graph.successors(b) if graph.has_edge(c, a) }
def valid_file ( path : str ) -> bool : path = Path ( path ) . expanduser ( ) log . debug ( "checking if %s is a valid file" , path ) return path . exists ( ) and path . is_file ( )
1
check if a path is a file or a directory in python
Verifies that a string path actually exists and is a file
cosqa-train-19658
def valid_file(path: str) -> bool: """ Verifies that a string path actually exists and is a file :param path: The path to verify :return: **True** if path exist and is a file """ path = Path(path).expanduser() log.debug("checking if %s is a valid file", path) return path.exists() and path.is_file()
def rmglob ( pattern : str ) -> None : for f in glob . glob ( pattern ) : os . remove ( f )
1
python remove file using wildcard
Deletes all files whose filename matches the glob pattern ( via : func : glob . glob ) .
cosqa-train-19659
def rmglob(pattern: str) -> None: """ Deletes all files whose filename matches the glob ``pattern`` (via :func:`glob.glob`). """ for f in glob.glob(pattern): os.remove(f)
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 a 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-19660
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 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 check if line exists in file
Detects whether a line is present within a file .
cosqa-train-19661
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 after_third_friday ( day = None ) : day = day if day is not None else datetime . datetime . now ( ) now = day . replace ( day = 1 , hour = 16 , minute = 0 , second = 0 , microsecond = 0 ) now += relativedelta . relativedelta ( weeks = 2 , weekday = relativedelta . FR ) return day > now
1
python third friday of month
check if day is after month s 3rd friday
cosqa-train-19662
def after_third_friday(day=None): """ check if day is after month's 3rd friday """ day = day if day is not None else datetime.datetime.now() now = day.replace(day=1, hour=16, minute=0, second=0, microsecond=0) now += relativedelta.relativedelta(weeks=2, weekday=relativedelta.FR) return day > now
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 )
1
python limit duration function execution metadata
Print execution time of the function . For quick n dirty profiling .
cosqa-train-19663
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 bfx ( value , msb , lsb ) : mask = bitmask ( ( msb , lsb ) ) return ( value & mask ) >> lsb
0
bit mask funtion in python
!
cosqa-train-19664
def bfx(value, msb, lsb): """! @brief Extract a value from a bitfield.""" mask = bitmask((msb, lsb)) return (value & mask) >> lsb
def assert_in ( first , second , msg_fmt = "{msg}" ) : if first not in second : msg = "{!r} not in {!r}" . format ( first , second ) fail ( msg_fmt . format ( msg = msg , first = first , second = second ) )
0
assert in or assertcontain in python
Fail if first is not in collection second .
cosqa-train-19665
def assert_in(first, second, msg_fmt="{msg}"): """Fail if first is not in collection second. >>> assert_in("foo", [4, "foo", {}]) >>> assert_in("bar", [4, "foo", {}]) Traceback (most recent call last): ... AssertionError: 'bar' not in [4, 'foo', {}] The following msg_fmt arguments are supported: * msg - the default error message * first - the element looked for * second - the container looked in """ if first not in second: msg = "{!r} not in {!r}".format(first, second) fail(msg_fmt.format(msg=msg, first=first, second=second))
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
0
are python dictionaries case sensitive
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-19666
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 _check_whitespace ( string ) : if string . count ( ' ' ) + string . count ( '\t' ) + string . count ( '\n' ) > 0 : raise ValueError ( INSTRUCTION_HAS_WHITESPACE )
1
python code to check for whitespaces
Make sure thre is no whitespace in the given string . Will raise a ValueError if whitespace is detected
cosqa-train-19667
def _check_whitespace(string): """ Make sure thre is no whitespace in the given string. Will raise a ValueError if whitespace is detected """ if string.count(' ') + string.count('\t') + string.count('\n') > 0: raise ValueError(INSTRUCTION_HAS_WHITESPACE)
def maybe_infer_dtype_type ( element ) : tipo = None if hasattr ( element , 'dtype' ) : tipo = element . dtype elif is_list_like ( element ) : element = np . asarray ( element ) tipo = element . dtype return tipo
1
how to determine an object's data type python
Try to infer an object s dtype for use in arithmetic ops
cosqa-train-19668
def maybe_infer_dtype_type(element): """Try to infer an object's dtype, for use in arithmetic ops Uses `element.dtype` if that's available. Objects implementing the iterator protocol are cast to a NumPy array, and from there the array's type is used. Parameters ---------- element : object Possibly has a `.dtype` attribute, and possibly the iterator protocol. Returns ------- tipo : type Examples -------- >>> from collections import namedtuple >>> Foo = namedtuple("Foo", "dtype") >>> maybe_infer_dtype_type(Foo(np.dtype("i8"))) numpy.int64 """ tipo = None if hasattr(element, 'dtype'): tipo = element.dtype elif is_list_like(element): element = np.asarray(element) tipo = element.dtype return tipo
def do_quit ( self , _ : argparse . Namespace ) -> bool : self . _should_quit = True return self . _STOP_AND_EXIT
0
python break or exit command
Exit this application
cosqa-train-19669
def do_quit(self, _: argparse.Namespace) -> bool: """Exit this application""" self._should_quit = True return self._STOP_AND_EXIT
def flatten_list ( l : List [ list ] ) -> list : return [ v for inner_l in l for v in inner_l ]
1
python flatten list inside list
takes a list of lists l and returns a flat list
cosqa-train-19670
def flatten_list(l: List[list]) -> list: """ takes a list of lists, l and returns a flat list """ return [v for inner_l in l for v in inner_l]
def dictfetchall ( cursor : Cursor ) -> List [ Dict [ str , Any ] ] : columns = get_fieldnames_from_cursor ( cursor ) return [ OrderedDict ( zip ( columns , row ) ) for row in cursor . fetchall ( ) ]
1
python return ordereddict from db cursor
Return all rows from a cursor as a list of : class : OrderedDict objects .
cosqa-train-19671
def dictfetchall(cursor: Cursor) -> List[Dict[str, Any]]: """ Return all rows from a cursor as a list of :class:`OrderedDict` objects. Args: cursor: the cursor Returns: a list (one item per row) of :class:`OrderedDict` objects whose key are column names and whose values are the row values """ columns = get_fieldnames_from_cursor(cursor) return [ OrderedDict(zip(columns, row)) for row in cursor.fetchall() ]
def count ( args ) : counts = defaultdict ( int ) for arg in args : for item in arg : counts [ item ] = counts [ item ] + 1 return counts
1
write a function that counts the number of times an element appears in a list python
count occurences in a list of lists >>> count ( [[ a b ] [ a ]] ) defaultdict ( int { a : 2 b : 1 } )
cosqa-train-19672
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 get_domain ( url ) : parse_result = urlparse ( url ) domain = "{schema}://{netloc}" . format ( schema = parse_result . scheme , netloc = parse_result . netloc ) return domain
0
python get url from just a domain name
Get domain part of an url .
cosqa-train-19673
def get_domain(url): """ Get domain part of an url. For example: https://www.python.org/doc/ -> https://www.python.org """ parse_result = urlparse(url) domain = "{schema}://{netloc}".format( schema=parse_result.scheme, netloc=parse_result.netloc) return domain
def _request ( self , method : str , endpoint : str , params : dict = None , data : dict = None , headers : dict = None ) -> dict :
1
how to pass an http request in python
HTTP request method of interface implementation .
cosqa-train-19674
def _request(self, method: str, endpoint: str, params: dict = None, data: dict = None, headers: dict = None) -> dict: """HTTP request method of interface implementation."""
def is_natural ( x ) : try : is_integer = int ( x ) == x except ( TypeError , ValueError ) : return False return is_integer and x >= 0
1
comparison to see if it is non numerical value in python
A non - negative integer .
cosqa-train-19675
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 _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
python skip for new line in file
Skip a section
cosqa-train-19676
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 read_text_from_file ( path : str ) -> str : with open ( path ) as text_file : content = text_file . read ( ) return content
1
how display contents of a text file in python
Reads text file contents
cosqa-train-19677
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 encode_list ( key , list_ ) : # type: (str, Iterable) -> Dict[str, str] if not list_ : return { } return { key : " " . join ( str ( i ) for i in list_ ) }
1
python create dictionary given list of values and list of keys
Converts a list into a space - separated string and puts it in a dictionary
cosqa-train-19678
def encode_list(key, list_): # type: (str, Iterable) -> Dict[str, str] """ Converts a list into a space-separated string and puts it in a dictionary :param key: Dictionary key to store the list :param list_: A list of objects :return: A dictionary key->string or an empty dictionary """ if not list_: return {} return {key: " ".join(str(i) for i in list_)}
def backspace ( self ) : if self . _cx + self . _cw >= 0 : self . erase ( ) self . _cx -= self . _cw self . flush ( )
0
move to new row after every space python
Moves the cursor one place to the left erasing the character at the current position . Cannot move beyond column zero nor onto the previous line .
cosqa-train-19679
def backspace(self): """ Moves the cursor one place to the left, erasing the character at the current position. Cannot move beyond column zero, nor onto the previous line. """ if self._cx + self._cw >= 0: self.erase() self._cx -= self._cw self.flush()
def get_valid_filename ( s ) : s = str ( s ) . strip ( ) . replace ( ' ' , '_' ) return re . sub ( r'(?u)[^-\w.]' , '' , s )
0
python make sure string is a valid filename
Shamelessly taken from Django . https : // github . com / django / django / blob / master / django / utils / text . py
cosqa-train-19680
def get_valid_filename(s): """ Shamelessly taken from Django. https://github.com/django/django/blob/master/django/utils/text.py Return the given string converted to a string that can be used for a clean filename. Remove leading and trailing spaces; convert other spaces to underscores; and remove anything that is not an alphanumeric, dash, underscore, or dot. >>> get_valid_filename("john's portrait in 2004.jpg") 'johns_portrait_in_2004.jpg' """ s = str(s).strip().replace(' ', '_') return re.sub(r'(?u)[^-\w.]', '', s)
def timeit ( func , * args , * * kwargs ) : start_time = time . time ( ) res = func ( * args , * * kwargs ) timing = time . time ( ) - start_time return res , timing
1
timing a python function
Time execution of function . Returns ( res seconds ) .
cosqa-train-19681
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 strings_to_integers ( strings : Iterable [ str ] ) -> Iterable [ int ] : return strings_to_ ( strings , lambda x : int ( float ( x ) ) )
0
python conver list of strings to int
Convert a list of strings to a list of integers .
cosqa-train-19682
def strings_to_integers(strings: Iterable[str]) -> Iterable[int]: """ Convert a list of strings to a list of integers. :param strings: a list of string :return: a list of converted integers .. doctest:: >>> strings_to_integers(['1', '1.0', '-0.2']) [1, 1, 0] """ return strings_to_(strings, lambda x: int(float(x)))
def is_natural ( x ) : try : is_integer = int ( x ) == x except ( TypeError , ValueError ) : return False return is_integer and x >= 0
1
comparing int to none python
A non - negative integer .
cosqa-train-19683
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 _parse_tuple_string ( argument ) : if isinstance ( argument , str ) : return tuple ( int ( p . strip ( ) ) for p in argument . split ( ',' ) ) return argument
0
python 3 extract tuple
Return a tuple from parsing a b c d - > ( a b c d )
cosqa-train-19684
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 snake_to_camel ( s : str ) -> str : fragments = s . split ( '_' ) return fragments [ 0 ] + '' . join ( x . title ( ) for x in fragments [ 1 : ] )
0
python to capitalize alternate
Convert string from snake case to camel case .
cosqa-train-19685
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 array2string ( arr : numpy . ndarray ) -> str : shape = str ( arr . shape ) [ 1 : - 1 ] if shape . endswith ( "," ) : shape = shape [ : - 1 ] return numpy . array2string ( arr , threshold = 11 ) + "%s[%s]" % ( arr . dtype , shape )
0
how to remove numpy array to make string python
Format numpy array as a string .
cosqa-train-19686
def array2string(arr: numpy.ndarray) -> str: """Format numpy array as a string.""" shape = str(arr.shape)[1:-1] if shape.endswith(","): shape = shape[:-1] return numpy.array2string(arr, threshold=11) + "%s[%s]" % (arr.dtype, shape)
def lowercase_chars ( string : any ) -> str : return '' . join ( [ c if c . islower ( ) else '' for c in str ( string ) ] )
1
case sensitive in string in python
Return all ( and only ) the lowercase chars in the given string .
cosqa-train-19687
def lowercase_chars(string: any) -> str: """Return all (and only) the lowercase chars in the given string.""" return ''.join([c if c.islower() else '' for c in str(string)])
def from_file ( file_path ) -> dict : with io . open ( file_path , 'r' , encoding = 'utf-8' ) as json_stream : return Json . parse ( json_stream , True )
1
how to read json file into a python dictionary
Load JSON file
cosqa-train-19688
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
python identify if there are any nulls in column
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-19689
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 _rindex ( mylist : Sequence [ T ] , x : T ) -> int : return len ( mylist ) - mylist [ : : - 1 ] . index ( x ) - 1
0
how to return the last index calue python\
Index of the last occurrence of x in the sequence .
cosqa-train-19690
def _rindex(mylist: Sequence[T], x: T) -> int: """Index of the last occurrence of x in the sequence.""" return len(mylist) - mylist[::-1].index(x) - 1
def bfx ( value , msb , lsb ) : mask = bitmask ( ( msb , lsb ) ) return ( value & mask ) >> lsb
0
python best way to store bit field
!
cosqa-train-19691
def bfx(value, msb, lsb): """! @brief Extract a value from a bitfield.""" mask = bitmask((msb, lsb)) return (value & mask) >> lsb
def try_cast_int ( s ) : try : temp = re . findall ( '\d' , str ( s ) ) temp = '' . join ( temp ) return int ( temp ) except : return s
1
forceing a string into a number python comand
( str ) - > int All the digits in a given string are concatenated and converted into a single number .
cosqa-train-19692
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 fetchallfirstvalues ( self , sql : str , * args ) -> List [ Any ] : rows = self . fetchall ( sql , * args ) return [ row [ 0 ] for row in rows ]
0
python get first column of table
Executes SQL ; returns list of first values of each row .
cosqa-train-19693
def fetchallfirstvalues(self, sql: str, *args) -> List[Any]: """Executes SQL; returns list of first values of each row.""" rows = self.fetchall(sql, *args) return [row[0] for row in rows]
def snake_to_camel ( s : str ) -> str : fragments = s . split ( '_' ) return fragments [ 0 ] + '' . join ( x . title ( ) for x in fragments [ 1 : ] )
0
python capitalize letters in string
Convert string from snake case to camel case .
cosqa-train-19694
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 to_json ( self ) -> Mapping : return { str ( x ) : str ( y ) for x , y in self . items ( ) }
0
jquery serialize to python dict
Return the properties of this : class : Sample as JSON serializable .
cosqa-train-19695
def to_json(self) -> Mapping: """Return the properties of this :class:`Sample` as JSON serializable. """ return {str(x): str(y) for x, y in self.items()}
def uppercase_chars ( string : any ) -> str : return '' . join ( [ c if c . isupper ( ) else '' for c in str ( string ) ] )
1
how to make letters obtained from strings uppercase in python
Return all ( and only ) the uppercase chars in the given string .
cosqa-train-19696
def uppercase_chars(string: any) -> str: """Return all (and only) the uppercase chars in the given string.""" return ''.join([c if c.isupper() else '' for c in str(string)])
def fib ( n ) : assert n > 0 a , b = 1 , 1 for i in range ( n - 1 ) : a , b = b , a + b return a
0
python generate fibanacci using lambda
Fibonacci example function
cosqa-train-19697
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 read ( self , start_position : int , size : int ) -> memoryview : return memoryview ( self . _bytes ) [ start_position : start_position + size ]
0
python variable index range in memoryview
Return a view into the memory
cosqa-train-19698
def read(self, start_position: int, size: int) -> memoryview: """ Return a view into the memory """ return memoryview(self._bytes)[start_position:start_position + size]
def 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
howto read file from s3 directly by path in python
Pull a file directly from S3 .
cosqa-train-19699
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)