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 text_coords ( string , position ) : line_start = string . rfind ( '\n' , 0 , position ) + 1 line_end = string . find ( '\n' , position ) lineno = string . count ( '\n' , 0 , position ) columnno = position - line_start line = string [ line_start : line_end ] return ( lineno , columnno , line )
0
how to index through a string to get certain positions python
r Transform a simple index into a human - readable position in a string .
cosqa-train-18900
def text_coords(string, position): r""" Transform a simple index into a human-readable position in a string. This function accepts a string and an index, and will return a triple of `(lineno, columnno, line)` representing the position through the text. It's useful for displaying a string index in a human-readable way:: >>> s = "abcdef\nghijkl\nmnopqr\nstuvwx\nyz" >>> text_coords(s, 0) (0, 0, 'abcdef') >>> text_coords(s, 4) (0, 4, 'abcdef') >>> text_coords(s, 6) (0, 6, 'abcdef') >>> text_coords(s, 7) (1, 0, 'ghijkl') >>> text_coords(s, 11) (1, 4, 'ghijkl') >>> text_coords(s, 15) (2, 1, 'mnopqr') """ line_start = string.rfind('\n', 0, position) + 1 line_end = string.find('\n', position) lineno = string.count('\n', 0, position) columnno = position - line_start line = string[line_start:line_end] return (lineno, columnno, line)
def csv_to_numpy ( string_like , dtype = None ) : # type: (str) -> np.array stream = StringIO ( string_like ) return np . genfromtxt ( stream , dtype = dtype , delimiter = ',' )
1
python read csv data to numpy array
Convert a CSV object to a numpy array .
cosqa-train-18901
def csv_to_numpy(string_like, dtype=None): # type: (str) -> np.array """Convert a CSV object to a numpy array. Args: string_like (str): CSV string. dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the contents of each column, individually. This argument can only be used to 'upcast' the array. For downcasting, use the .astype(t) method. Returns: (np.array): numpy array """ stream = StringIO(string_like) return np.genfromtxt(stream, dtype=dtype, delimiter=',')
def has_key ( cls , * args ) : key = args if len ( args ) > 1 else args [ 0 ] return key in cls . _instances
0
python check existance of key
Check whether flyweight object with specified key has already been created .
cosqa-train-18902
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 _isint ( string ) : return type ( string ) is int or ( isinstance ( string , _binary_type ) or isinstance ( string , _text_type ) ) and _isconvertible ( int , string )
1
python test if string an int
>>> _isint ( 123 ) True >>> _isint ( 123 . 45 ) False
cosqa-train-18903
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 build ( ctx ) : return_code = run_sphinx ( ctx . obj [ 'root_dir' ] ) if return_code > 0 : sys . exit ( return_code )
1
sphinx how to show python code
Build documentation as HTML .
cosqa-train-18904
def build(ctx): """Build documentation as HTML. The build HTML site is located in the ``doc/_build/html`` directory of the package. """ return_code = run_sphinx(ctx.obj['root_dir']) if return_code > 0: sys.exit(return_code)
def pack_bits ( longbits ) : byte = longbits & ( 0x0101010101010101 ) byte = ( byte | ( byte >> 7 ) ) & ( 0x0003000300030003 ) byte = ( byte | ( byte >> 14 ) ) & ( 0x0000000f0000000f ) byte = ( byte | ( byte >> 28 ) ) & ( 0x00000000000000ff ) return byte
0
bits of a value python
Crunch a 64 - bit int ( 8 bool bytes ) into a bitfield .
cosqa-train-18905
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 rate_limited ( max_per_hour : int , * args : Any ) -> Callable [ ... , Any ] : return util . rate_limited ( max_per_hour , * args )
0
how to limit the function's executing time python
Rate limit a function .
cosqa-train-18906
def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]: """Rate limit a function.""" return util.rate_limited(max_per_hour, *args)
def memory_full ( ) : current_process = psutil . Process ( os . getpid ( ) ) return ( current_process . memory_percent ( ) > config . MAXIMUM_CACHE_MEMORY_PERCENTAGE )
1
how to make sure python stay in memory limit
Check if the memory is too full for further caching .
cosqa-train-18907
def memory_full(): """Check if the memory is too full for further caching.""" current_process = psutil.Process(os.getpid()) return (current_process.memory_percent() > config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)
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
1
is asyncio thread safe python
Utility method to run commands synchronously for testing .
cosqa-train-18908
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 find_duplicates ( l : list ) -> set : return set ( [ x for x in l if l . count ( x ) > 1 ] )
0
finding duplicate words in a list python
Return the duplicates in a list .
cosqa-train-18909
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 _parse_tuple_string ( argument ) : if isinstance ( argument , str ) : return tuple ( int ( p . strip ( ) ) for p in argument . split ( ',' ) ) return argument
1
how to delete quotes in python so taht the string will turn into a tuple
Return a tuple from parsing a b c d - > ( a b c d )
cosqa-train-18910
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 __getattr__ ( self , item : str ) -> Callable : return functools . partial ( self . call_action , item )
1
python how to call methods dynamically
Get a callable that sends the actual API request internally .
cosqa-train-18911
def __getattr__(self, item: str) -> Callable: """Get a callable that sends the actual API request internally.""" return functools.partial(self.call_action, item)
def fetchallfirstvalues ( self , sql : str , * args ) -> List [ Any ] : rows = self . fetchall ( sql , * args ) return [ row [ 0 ] for row in rows ]
1
python select first columns
Executes SQL ; returns list of first values of each row .
cosqa-train-18912
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 memory_full ( ) : current_process = psutil . Process ( os . getpid ( ) ) return ( current_process . memory_percent ( ) > config . MAXIMUM_CACHE_MEMORY_PERCENTAGE )
0
python process memory leak
Check if the memory is too full for further caching .
cosqa-train-18913
def memory_full(): """Check if the memory is too full for further caching.""" current_process = psutil.Process(os.getpid()) return (current_process.memory_percent() > config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)
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
how to format a string into a date with python
Creates a datetime from GnuCash 2 . 6 date string
cosqa-train-18914
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 remove_empty_text ( utterances : List [ Utterance ] ) -> List [ Utterance ] : return [ utter for utter in utterances if utter . text . strip ( ) != "" ]
0
python strip a list of string
Remove empty utterances from a list of utterances Args : utterances : The list of utterance we are processing
cosqa-train-18915
def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]: """Remove empty utterances from a list of utterances Args: utterances: The list of utterance we are processing """ return [utter for utter in utterances if utter.text.strip() != ""]
def 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
0
python how to get index of smallest value in a series
Returns the last location of the minimal value of x . The position is calculated relatively to the length of x .
cosqa-train-18916
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 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
python numpy get dtype of array
Try to infer an object s dtype for use in arithmetic ops
cosqa-train-18917
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 memory_full ( ) : current_process = psutil . Process ( os . getpid ( ) ) return ( current_process . memory_percent ( ) > config . MAXIMUM_CACHE_MEMORY_PERCENTAGE )
1
python to limit memory usage
Check if the memory is too full for further caching .
cosqa-train-18918
def memory_full(): """Check if the memory is too full for further caching.""" current_process = psutil.Process(os.getpid()) return (current_process.memory_percent() > config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)
def timeit ( func , * args , * * kwargs ) : start_time = time . time ( ) res = func ( * args , * * kwargs ) timing = time . time ( ) - start_time return res , timing
0
python how to time a function run
Time execution of function . Returns ( res seconds ) .
cosqa-train-18919
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 method_caller ( method_name , * args , * * kwargs ) : def call_method ( target ) : func = getattr ( target , method_name ) return func ( * args , * * kwargs ) return call_method
0
python keyword for same method name
Return a function that will call a named method on the target object with optional positional and keyword arguments .
cosqa-train-18920
def method_caller(method_name, *args, **kwargs): """ Return a function that will call a named method on the target object with optional positional and keyword arguments. >>> lower = method_caller('lower') >>> lower('MyString') 'mystring' """ def call_method(target): func = getattr(target, method_name) return func(*args, **kwargs) return call_method
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
1
python check memory usage in a process
Return physical memory usage ( float ) Requires the cross - platform psutil ( > = v0 . 3 ) library ( https : // github . com / giampaolo / psutil )
cosqa-train-18921
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 zfill ( x , width ) : if not isinstance ( x , basestring ) : x = repr ( x ) return x . zfill ( width )
1
python pad string with zeros to a certain length
zfill ( x width ) - > string
cosqa-train-18922
def zfill(x, width): """zfill(x, width) -> string Pad a numeric string x with zeros on the left, to fill a field of the specified width. The string x is never truncated. """ if not isinstance(x, basestring): x = repr(x) return x.zfill(width)
def 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
python get last weeks time
Returns the last week as a period string
cosqa-train-18923
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 block_diag ( * blocks : np . ndarray ) -> np . ndarray : for b in blocks : if b . shape [ 0 ] != b . shape [ 1 ] : raise ValueError ( 'Blocks must be square.' ) if not blocks : return np . zeros ( ( 0 , 0 ) , dtype = np . complex128 ) n = sum ( b . shape [ 0 ] for b in blocks ) dtype = functools . reduce ( _merge_dtypes , ( b . dtype for b in blocks ) ) result = np . zeros ( shape = ( n , n ) , dtype = dtype ) i = 0 for b in blocks : j = i + b . shape [ 0 ] result [ i : j , i : j ] = b i = j return result
1
python create diagnol block matrix
Concatenates blocks into a block diagonal matrix .
cosqa-train-18924
def block_diag(*blocks: np.ndarray) -> np.ndarray: """Concatenates blocks into a block diagonal matrix. Args: *blocks: Square matrices to place along the diagonal of the result. Returns: A block diagonal matrix with the given blocks along its diagonal. Raises: ValueError: A block isn't square. """ for b in blocks: if b.shape[0] != b.shape[1]: raise ValueError('Blocks must be square.') if not blocks: return np.zeros((0, 0), dtype=np.complex128) n = sum(b.shape[0] for b in blocks) dtype = functools.reduce(_merge_dtypes, (b.dtype for b in blocks)) result = np.zeros(shape=(n, n), dtype=dtype) i = 0 for b in blocks: j = i + b.shape[0] result[i:j, i:j] = b i = j return result
def get_column_names ( engine : Engine , tablename : str ) -> List [ str ] : return [ info . name for info in gen_columns_info ( engine , tablename ) ]
1
python list out all column names
Get all the database column names for the specified table .
cosqa-train-18925
def get_column_names(engine: Engine, tablename: str) -> List[str]: """ Get all the database column names for the specified table. """ return [info.name for info in gen_columns_info(engine, tablename)]
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
python json file into dict
Load JSON file
cosqa-train-18926
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_finite ( value : Any ) -> bool : return isinstance ( value , int ) or ( isinstance ( value , float ) and isfinite ( value ) )
0
check if float has no decimal python
Return true if a value is a finite number .
cosqa-train-18927
def is_finite(value: Any) -> bool: """Return true if a value is a finite number.""" return isinstance(value, int) or (isinstance(value, float) and isfinite(value))
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
python delete false keys from dict
Return a new copied dictionary without the keys with None values from the given Mapping object .
cosqa-train-18928
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 dictlist_replace ( dict_list : Iterable [ Dict ] , key : str , value : Any ) -> None : for d in dict_list : d [ key ] = value
1
python change dictioinary values in place
Process an iterable of dictionaries . For each dictionary d change ( in place ) d [ key ] to value .
cosqa-train-18929
def dictlist_replace(dict_list: Iterable[Dict], key: str, value: Any) -> None: """ Process an iterable of dictionaries. For each dictionary ``d``, change (in place) ``d[key]`` to ``value``. """ for d in dict_list: d[key] = value
def average_arrays ( arrays : List [ mx . nd . NDArray ] ) -> mx . nd . NDArray : if not arrays : raise ValueError ( "arrays is empty." ) if len ( arrays ) == 1 : return arrays [ 0 ] check_condition ( all ( arrays [ 0 ] . shape == a . shape for a in arrays ) , "nd array shapes do not match" ) return mx . nd . add_n ( * arrays ) / len ( arrays )
0
average of 2d array python
Take a list of arrays of the same shape and take the element wise average .
cosqa-train-18930
def average_arrays(arrays: List[mx.nd.NDArray]) -> mx.nd.NDArray: """ Take a list of arrays of the same shape and take the element wise average. :param arrays: A list of NDArrays with the same shape that will be averaged. :return: The average of the NDArrays in the same context as arrays[0]. """ if not arrays: raise ValueError("arrays is empty.") if len(arrays) == 1: return arrays[0] check_condition(all(arrays[0].shape == a.shape for a in arrays), "nd array shapes do not match") return mx.nd.add_n(*arrays) / len(arrays)
def read_text_from_file ( path : str ) -> str : with open ( path ) as text_file : content = text_file . read ( ) return content
1
how to read contents in a text file python
Reads text file contents
cosqa-train-18931
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 is_not_null ( df : DataFrame , col_name : str ) -> bool : if ( isinstance ( df , pd . DataFrame ) and col_name in df . columns and df [ col_name ] . notnull ( ) . any ( ) ) : return True else : return False
0
check whether a column has null values or not in 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-18932
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 get_domain ( url ) : parse_result = urlparse ( url ) domain = "{schema}://{netloc}" . format ( schema = parse_result . scheme , netloc = parse_result . netloc ) return domain
1
python urlparse strip to domain
Get domain part of an url .
cosqa-train-18933
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 write_text ( filename : str , text : str ) -> None : with open ( filename , 'w' ) as f : # type: TextIO print ( text , file = f )
0
how to write text in a file through python
Writes text to a file .
cosqa-train-18934
def write_text(filename: str, text: str) -> None: """ Writes text to a file. """ with open(filename, 'w') as f: # type: TextIO print(text, file=f)
def isarray ( array , test , dim = 2 ) : if dim > 1 : return all ( isarray ( array [ i ] , test , dim - 1 ) for i in range ( len ( array ) ) ) return all ( test ( i ) for i in array )
1
how to logically and an array in python
Returns True if test is True for all array elements . Otherwise returns False .
cosqa-train-18935
def isarray(array, test, dim=2): """Returns True if test is True for all array elements. Otherwise, returns False. """ if dim > 1: return all(isarray(array[i], test, dim - 1) for i in range(len(array))) return all(test(i) for i in array)
def 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
0
python identify the third friday of a month
check if day is after month s 3rd friday
cosqa-train-18936
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 stretch ( iterable , n = 2 ) : times = range ( n ) for item in iterable : for i in times : yield item
0
iterate for loop a fixed number of times python
r Repeat each item in iterable n times .
cosqa-train-18937
def stretch(iterable, n=2): r"""Repeat each item in `iterable` `n` times. Example: >>> list(stretch(range(3), 2)) [0, 0, 1, 1, 2, 2] """ times = range(n) for item in iterable: for i in times: yield item
def debugTreePrint ( node , pfx = "->" ) : print pfx , node . item for c in node . children : debugTreePrint ( c , " " + pfx )
0
python code to print tree in reverse
Purely a debugging aid : Ascii - art picture of a tree descended from node
cosqa-train-18938
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 memory_full ( ) : current_process = psutil . Process ( os . getpid ( ) ) return ( current_process . memory_percent ( ) > config . MAXIMUM_CACHE_MEMORY_PERCENTAGE )
1
how to limit memory usage in python programes
Check if the memory is too full for further caching .
cosqa-train-18939
def memory_full(): """Check if the memory is too full for further caching.""" current_process = psutil.Process(os.getpid()) return (current_process.memory_percent() > config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)
def get_account_id_by_fullname ( self , fullname : str ) -> str : account = self . get_by_fullname ( fullname ) return account . guid
0
get name by user id python
Locates the account by fullname
cosqa-train-18940
def get_account_id_by_fullname(self, fullname: str) -> str: """ Locates the account by fullname """ account = self.get_by_fullname(fullname) return account.guid
def get_timezone ( ) -> Tuple [ datetime . tzinfo , str ] : dt = get_datetime_now ( ) . astimezone ( ) tzstr = dt . strftime ( "%z" ) tzstr = tzstr [ : - 2 ] + ":" + tzstr [ - 2 : ] return dt . tzinfo , tzstr
1
python get specific timezone name
Discover the current time zone and it s standard string representation ( for source { d } ) .
cosqa-train-18941
def get_timezone() -> Tuple[datetime.tzinfo, str]: """Discover the current time zone and it's standard string representation (for source{d}).""" dt = get_datetime_now().astimezone() tzstr = dt.strftime("%z") tzstr = tzstr[:-2] + ":" + tzstr[-2:] return dt.tzinfo, tzstr
def dtypes ( self ) : return [ ( str ( f . name ) , f . dataType . simpleString ( ) ) for f in self . schema . fields ]
1
data types of columns in python
Returns all column names and their data types as a list .
cosqa-train-18942
def dtypes(self): """Returns all column names and their data types as a list. >>> df.dtypes [('age', 'int'), ('name', 'string')] """ return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]
def _reshuffle ( mat , shape ) : return np . reshape ( np . transpose ( np . reshape ( mat , shape ) , ( 3 , 1 , 2 , 0 ) ) , ( shape [ 3 ] * shape [ 1 ] , shape [ 0 ] * shape [ 2 ] ) )
0
reshape shuffle matrix python
Reshuffle the indicies of a bipartite matrix A [ ij kl ] - > A [ lj ki ] .
cosqa-train-18943
def _reshuffle(mat, shape): """Reshuffle the indicies of a bipartite matrix A[ij,kl] -> A[lj,ki].""" return np.reshape( np.transpose(np.reshape(mat, shape), (3, 1, 2, 0)), (shape[3] * shape[1], shape[0] * shape[2]))
def get_column_names ( engine : Engine , tablename : str ) -> List [ str ] : return [ info . name for info in gen_columns_info ( engine , tablename ) ]
0
to get all the column names in python
Get all the database column names for the specified table .
cosqa-train-18944
def get_column_names(engine: Engine, tablename: str) -> List[str]: """ Get all the database column names for the specified table. """ return [info.name for info in gen_columns_info(engine, tablename)]
def butlast ( iterable ) : iterable = iter ( iterable ) try : first = next ( iterable ) except StopIteration : return for second in iterable : yield first first = second
0
python select last items in list
Yield all items from iterable except the last one .
cosqa-train-18945
def butlast(iterable): """Yield all items from ``iterable`` except the last one. >>> list(butlast(['spam', 'eggs', 'ham'])) ['spam', 'eggs'] >>> list(butlast(['spam'])) [] >>> list(butlast([])) [] """ iterable = iter(iterable) try: first = next(iterable) except StopIteration: return for second in iterable: yield first first = second
def read_text_from_file ( path : str ) -> str : with open ( path ) as text_file : content = text_file . read ( ) return content
1
python display contents of a text file
Reads text file contents
cosqa-train-18946
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 isFull ( self ) : return ( ( self . _pageSize > 0 and self . _numElements >= self . _pageSize ) or ( self . _bufferSize >= self . _maxBufferSize ) )
0
python test if pageobject is empty
Returns True if the response buffer is full and False otherwise . The buffer is full if either ( 1 ) the number of items in the value list is > = pageSize or ( 2 ) the total length of the serialised elements in the page is > = maxBufferSize .
cosqa-train-18947
def isFull(self): """ Returns True if the response buffer is full, and False otherwise. The buffer is full if either (1) the number of items in the value list is >= pageSize or (2) the total length of the serialised elements in the page is >= maxBufferSize. If page_size or max_response_length were not set in the request then they're not checked. """ return ( (self._pageSize > 0 and self._numElements >= self._pageSize) or (self._bufferSize >= self._maxBufferSize) )
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
0
python whether today is 3rd wendesday
check if day is after month s 3rd friday
cosqa-train-18948
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 callable_validator ( v : Any ) -> AnyCallable : if callable ( v ) : return v raise errors . CallableError ( value = v )
0
python test if callable
Perform a simple check if the value is callable .
cosqa-train-18949
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 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 file contains line
Detects whether a line is present within a file .
cosqa-train-18950
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 snake_to_camel ( s : str ) -> str : fragments = s . split ( '_' ) return fragments [ 0 ] + '' . join ( x . title ( ) for x in fragments [ 1 : ] )
0
capitalize letter in python string
Convert string from snake case to camel case .
cosqa-train-18951
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 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
python minimum in a column
Returns the last location of the minimal value of x . The position is calculated relatively to the length of x .
cosqa-train-18952
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 camel_to_snake_case ( string ) : s = _1 . sub ( r'\1_\2' , string ) return _2 . sub ( r'\1_\2' , s ) . lower ( )
0
python string to lowercast
Converts string presented in camel case to snake case .
cosqa-train-18953
def camel_to_snake_case(string): """Converts 'string' presented in camel case to snake case. e.g.: CamelCase => snake_case """ s = _1.sub(r'\1_\2', string) return _2.sub(r'\1_\2', s).lower()
def _isint ( string ) : return type ( string ) is int or ( isinstance ( string , _binary_type ) or isinstance ( string , _text_type ) ) and _isconvertible ( int , string )
0
python check if is an int
>>> _isint ( 123 ) True >>> _isint ( 123 . 45 ) False
cosqa-train-18954
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 lower_camel_case_from_underscores ( string ) : components = string . split ( '_' ) string = components [ 0 ] for component in components [ 1 : ] : string += component [ 0 ] . upper ( ) + component [ 1 : ] return string
0
python underscore in for loop
generate a lower - cased camelCase string from an underscore_string . For example : my_variable_name - > myVariableName
cosqa-train-18955
def lower_camel_case_from_underscores(string): """generate a lower-cased camelCase string from an underscore_string. For example: my_variable_name -> myVariableName""" components = string.split('_') string = components[0] for component in components[1:]: string += component[0].upper() + component[1:] return string
def is_sqlatype_integer ( coltype : Union [ TypeEngine , VisitableType ] ) -> bool : coltype = _coltype_to_typeengine ( coltype ) return isinstance ( coltype , sqltypes . Integer )
0
python sqlalchemy column data types
Is the SQLAlchemy column type an integer type?
cosqa-train-18956
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 _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 ] )
1
how to print values in list greater than 5 python
Print at most limit elements of list .
cosqa-train-18957
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 has_table ( self , name ) : return len ( self . sql ( "SELECT name FROM sqlite_master WHERE type='table' AND name=?" , parameters = ( name , ) , asrecarray = False , cache = False ) ) > 0
1
ironpython check if data table exists
Return True if the table * name * exists in the database .
cosqa-train-18958
def has_table(self, name): """Return ``True`` if the table *name* exists in the database.""" return len(self.sql("SELECT name FROM sqlite_master WHERE type='table' AND name=?", parameters=(name,), asrecarray=False, cache=False)) > 0
def proper_round ( n ) : return int ( n ) + ( n / abs ( n ) ) * int ( abs ( n - int ( n ) ) >= 0.5 ) if n != 0 else 0
0
round float up to int python
rounds float to closest int : rtype : int : param n : float
cosqa-train-18959
def proper_round(n): """ rounds float to closest int :rtype: int :param n: float """ return int(n) + (n / abs(n)) * int(abs(n - int(n)) >= 0.5) if n != 0 else 0
def count ( args ) : counts = defaultdict ( int ) for arg in args : for item in arg : counts [ item ] = counts [ item ] + 1 return counts
0
how to count the number of times a value appears in a list in functions python
count occurences in a list of lists >>> count ( [[ a b ] [ a ]] ) defaultdict ( int { a : 2 b : 1 } )
cosqa-train-18960
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 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
0
python longest substring of same char
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-18961
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 suppress_stdout ( ) : save_stdout = sys . stdout sys . stdout = DevNull ( ) yield sys . stdout = save_stdout
1
clear output in python 3
Context manager that suppresses stdout .
cosqa-train-18962
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 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
limit execution time of a python function
Print execution time of the function . For quick n dirty profiling .
cosqa-train-18963
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 cli_run ( ) : parser = argparse . ArgumentParser ( description = 'Stupidly simple code answers from StackOverflow' ) parser . add_argument ( 'query' , help = "What's the problem ?" , type = str , nargs = '+' ) parser . add_argument ( '-t' , '--tags' , help = 'semicolon separated tags -> python;lambda' ) args = parser . parse_args ( ) main ( args )
0
command line python pass argparse to function
docstring for argparse
cosqa-train-18964
def cli_run(): """docstring for argparse""" parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow') parser.add_argument('query', help="What's the problem ?", type=str, nargs='+') parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda') args = parser.parse_args() main(args)
def pack_bits ( longbits ) : byte = longbits & ( 0x0101010101010101 ) byte = ( byte | ( byte >> 7 ) ) & ( 0x0003000300030003 ) byte = ( byte | ( byte >> 14 ) ) & ( 0x0000000f0000000f ) byte = ( byte | ( byte >> 28 ) ) & ( 0x00000000000000ff ) return byte
0
python manipulate bits 32 bit ints
Crunch a 64 - bit int ( 8 bool bytes ) into a bitfield .
cosqa-train-18965
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 date_to_datetime ( d ) : if not isinstance ( d , datetime ) : d = datetime . combine ( d , datetime . min . time ( ) ) return d
0
python add min to datetime
>>> date_to_datetime ( date ( 2000 1 2 )) datetime . datetime ( 2000 1 2 0 0 ) >>> date_to_datetime ( datetime ( 2000 1 2 3 4 5 )) datetime . datetime ( 2000 1 2 3 4 5 )
cosqa-train-18966
def date_to_datetime(d): """ >>> date_to_datetime(date(2000, 1, 2)) datetime.datetime(2000, 1, 2, 0, 0) >>> date_to_datetime(datetime(2000, 1, 2, 3, 4, 5)) datetime.datetime(2000, 1, 2, 3, 4, 5) """ if not isinstance(d, datetime): d = datetime.combine(d, datetime.min.time()) return d
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
how to read file from s3 using python using boto
Pull a file directly from S3 .
cosqa-train-18967
def s3_get(url: str, temp_file: IO) -> None: """Pull a file directly from S3.""" s3_resource = boto3.resource("s3") bucket_name, s3_path = split_s3_path(url) s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)
def str_to_time ( time_str : str ) -> datetime . datetime : pieces : Any = [ int ( piece ) for piece in time_str . split ( '-' ) ] return datetime . datetime ( * pieces )
1
turn a timestring in to a date time python
Convert human readable string to datetime . datetime .
cosqa-train-18968
def str_to_time(time_str: str) -> datetime.datetime: """ Convert human readable string to datetime.datetime. """ pieces: Any = [int(piece) for piece in time_str.split('-')] return datetime.datetime(*pieces)
def find_duplicates ( l : list ) -> set : return set ( [ x for x in l if l . count ( x ) > 1 ] )
0
function for checking duplicates in lists python
Return the duplicates in a list .
cosqa-train-18969
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 encode_list ( key , list_ ) : # type: (str, Iterable) -> Dict[str, str] if not list_ : return { } return { key : " " . join ( str ( i ) for i in list_ ) }
0
python make dict from key list
Converts a list into a space - separated string and puts it in a dictionary
cosqa-train-18970
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 dtypes ( self ) : return [ ( str ( f . name ) , f . dataType . simpleString ( ) ) for f in self . schema . fields ]
1
get data type columns python
Returns all column names and their data types as a list .
cosqa-train-18971
def dtypes(self): """Returns all column names and their data types as a list. >>> df.dtypes [('age', 'int'), ('name', 'string')] """ return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]
def strtobytes ( input , encoding ) : py_version = sys . version_info [ 0 ] if py_version >= 3 : return _strtobytes_py3 ( input , encoding ) return _strtobytes_py2 ( input , encoding )
0
python binary without string
Take a str and transform it into a byte array .
cosqa-train-18972
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 s3_get ( url : str , temp_file : IO ) -> None : s3_resource = boto3 . resource ( "s3" ) bucket_name , s3_path = split_s3_path ( url ) s3_resource . Bucket ( bucket_name ) . download_fileobj ( s3_path , temp_file )
0
get file from s3 python
Pull a file directly from S3 .
cosqa-train-18973
def s3_get(url: str, temp_file: IO) -> None: """Pull a file directly from S3.""" s3_resource = boto3.resource("s3") bucket_name, s3_path = split_s3_path(url) s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)
def wipe_table ( self , table : str ) -> int : sql = "DELETE FROM " + self . delimit ( table ) return self . db_exec ( sql )
1
python sql alchemy delete sql table
Delete all records from a table . Use caution!
cosqa-train-18974
def wipe_table(self, table: str) -> int: """Delete all records from a table. Use caution!""" sql = "DELETE FROM " + self.delimit(table) return self.db_exec(sql)
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 entries from a python dictionary
Return a new copied dictionary without the keys with None values from the given Mapping object .
cosqa-train-18975
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 zip_with_index ( rdd ) : starts = [ 0 ] if rdd . getNumPartitions ( ) > 1 : nums = rdd . mapPartitions ( lambda it : [ sum ( 1 for _ in it ) ] ) . collect ( ) count = sum ( nums ) for i in range ( len ( nums ) - 1 ) : starts . append ( starts [ - 1 ] + nums [ i ] ) else : count = rdd . count ( ) def func ( k , it ) : for i , v in enumerate ( it , starts [ k ] ) : yield v , i return count , rdd . mapPartitionsWithIndex ( func )
0
how can i get the rdd index python
Alternate version of Spark s zipWithIndex that eagerly returns count .
cosqa-train-18976
def zip_with_index(rdd): """ Alternate version of Spark's zipWithIndex that eagerly returns count. """ starts = [0] if rdd.getNumPartitions() > 1: nums = rdd.mapPartitions(lambda it: [sum(1 for _ in it)]).collect() count = sum(nums) for i in range(len(nums) - 1): starts.append(starts[-1] + nums[i]) else: count = rdd.count() def func(k, it): for i, v in enumerate(it, starts[k]): yield v, i return count, rdd.mapPartitionsWithIndex(func)
def is_prime ( n ) : if n % 2 == 0 and n > 2 : return False return all ( n % i for i in range ( 3 , int ( math . sqrt ( n ) ) + 1 , 2 ) )
0
python check if prime function
Check if n is a prime number
cosqa-train-18977
def is_prime(n): """ Check if n is a prime number """ if n % 2 == 0 and n > 2: return False return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
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
python reading json files into dictionary
Load JSON file
cosqa-train-18978
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 isfinite ( data : mx . nd . NDArray ) -> mx . nd . NDArray : is_data_not_nan = data == data is_data_not_infinite = data . abs ( ) != np . inf return mx . nd . logical_and ( is_data_not_infinite , is_data_not_nan )
0
how to check whether the set has nan python
Performs an element - wise check to determine if the NDArray contains an infinite element or not . TODO : remove this funciton after upgrade to MXNet 1 . 4 . * in favor of mx . ndarray . contrib . isfinite ()
cosqa-train-18979
def isfinite(data: mx.nd.NDArray) -> mx.nd.NDArray: """Performs an element-wise check to determine if the NDArray contains an infinite element or not. TODO: remove this funciton after upgrade to MXNet 1.4.* in favor of mx.ndarray.contrib.isfinite() """ is_data_not_nan = data == data is_data_not_infinite = data.abs() != np.inf return mx.nd.logical_and(is_data_not_infinite, is_data_not_nan)
def str_to_time ( time_str : str ) -> datetime . datetime : pieces : Any = [ int ( piece ) for piece in time_str . split ( '-' ) ] return datetime . datetime ( * pieces )
0
get date time object python from string
Convert human readable string to datetime . datetime .
cosqa-train-18980
def str_to_time(time_str: str) -> datetime.datetime: """ Convert human readable string to datetime.datetime. """ pieces: Any = [int(piece) for piece in time_str.split('-')] return datetime.datetime(*pieces)
def stretch ( iterable , n = 2 ) : times = range ( n ) for item in iterable : for i in times : yield item
1
python repeat sequence certain amount of times
r Repeat each item in iterable n times .
cosqa-train-18981
def stretch(iterable, n=2): r"""Repeat each item in `iterable` `n` times. Example: >>> list(stretch(range(3), 2)) [0, 0, 1, 1, 2, 2] """ times = range(n) for item in iterable: for i in times: yield item
def position ( self ) -> Position : return Position ( self . _index , self . _lineno , self . _col_offset )
1
reading cursor position in python
The current position of the cursor .
cosqa-train-18982
def position(self) -> Position: """The current position of the cursor.""" return Position(self._index, self._lineno, self._col_offset)
def _str_to_list ( value , separator ) : value_list = [ item . strip ( ) for item in value . split ( separator ) ] value_list_sanitized = builtins . list ( filter ( None , value_list ) ) if len ( value_list_sanitized ) > 0 : return value_list_sanitized else : raise ValueError ( 'Invalid list variable.' )
0
python making a list out of a string
Convert a string to a list with sanitization .
cosqa-train-18983
def _str_to_list(value, separator): """Convert a string to a list with sanitization.""" value_list = [item.strip() for item in value.split(separator)] value_list_sanitized = builtins.list(filter(None, value_list)) if len(value_list_sanitized) > 0: return value_list_sanitized else: raise ValueError('Invalid list variable.')
def get_default_bucket_key ( buckets : List [ Tuple [ int , int ] ] ) -> Tuple [ int , int ] : return max ( buckets )
1
python get key with greatest value
Returns the default bucket from a list of buckets i . e . the largest bucket .
cosqa-train-18984
def get_default_bucket_key(buckets: List[Tuple[int, int]]) -> Tuple[int, int]: """ Returns the default bucket from a list of buckets, i.e. the largest bucket. :param buckets: List of buckets. :return: The largest bucket in the list. """ return max(buckets)
def remove_blank_lines ( string ) : return "\n" . join ( line for line in string . split ( "\n" ) if len ( line . strip ( ) ) )
1
make string empty in python
Removes all blank lines in @string
cosqa-train-18985
def remove_blank_lines(string): """ Removes all blank lines in @string -> #str without blank lines """ return "\n".join(line for line in string.split("\n") if len(line.strip()))
def console_get_background_flag ( con : tcod . console . Console ) -> int : return int ( lib . TCOD_console_get_background_flag ( _console ( con ) ) )
1
python tk get background color
Return this consoles current blend mode .
cosqa-train-18986
def console_get_background_flag(con: tcod.console.Console) -> int: """Return this consoles current blend mode. Args: con (Console): Any Console instance. .. deprecated:: 8.5 Check :any:`Console.default_bg_blend` instead. """ return int(lib.TCOD_console_get_background_flag(_console(con)))
def butlast ( iterable ) : iterable = iter ( iterable ) try : first = next ( iterable ) except StopIteration : return for second in iterable : yield first first = second
1
how to iterate from the last element in a list in python
Yield all items from iterable except the last one .
cosqa-train-18987
def butlast(iterable): """Yield all items from ``iterable`` except the last one. >>> list(butlast(['spam', 'eggs', 'ham'])) ['spam', 'eggs'] >>> list(butlast(['spam'])) [] >>> list(butlast([])) [] """ iterable = iter(iterable) try: first = next(iterable) except StopIteration: return for second in iterable: yield first first = second
def iprotate ( l , steps = 1 ) : if len ( l ) : steps %= len ( l ) if steps : firstPart = l [ : steps ] del l [ : steps ] l . extend ( firstPart ) return l
1
rotating a list in python
r Like rotate but modifies l in - place .
cosqa-train-18988
def iprotate(l, steps=1): r"""Like rotate, but modifies `l` in-place. >>> l = [1,2,3] >>> iprotate(l) is l True >>> l [2, 3, 1] >>> iprotate(iprotate(l, 2), -3) [1, 2, 3] """ if len(l): steps %= len(l) if steps: firstPart = l[:steps] del l[:steps] l.extend(firstPart) return l
def get_valid_filename ( s ) : s = str ( s ) . strip ( ) . replace ( ' ' , '_' ) return re . sub ( r'(?u)[^-\w.]' , '' , s )
0
python sanitize file name
Shamelessly taken from Django . https : // github . com / django / django / blob / master / django / utils / text . py
cosqa-train-18989
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 load_yaml ( file ) : if hasattr ( yaml , "full_load" ) : return yaml . full_load ( file ) else : return yaml . load ( file )
1
handle yaml files in python
If pyyaml > 5 . 1 use full_load to avoid warning
cosqa-train-18990
def load_yaml(file): """If pyyaml > 5.1 use full_load to avoid warning""" if hasattr(yaml, "full_load"): return yaml.full_load(file) else: return yaml.load(file)
def warn_if_nans_exist ( X ) : null_count = count_rows_with_nans ( X ) total = len ( X ) percent = 100 * null_count / total if null_count > 0 : warning_message = 'Warning! Found {} rows of {} ({:0.2f}%) with nan values. Only ' 'complete rows will be plotted.' . format ( null_count , total , percent ) warnings . warn ( warning_message , DataWarning )
0
a function that determines the percentage of missing entries for each column in the dataset python
Warn if nans exist in a numpy array .
cosqa-train-18991
def warn_if_nans_exist(X): """Warn if nans exist in a numpy array.""" null_count = count_rows_with_nans(X) total = len(X) percent = 100 * null_count / total if null_count > 0: warning_message = \ 'Warning! Found {} rows of {} ({:0.2f}%) with nan values. Only ' \ 'complete rows will be plotted.'.format(null_count, total, percent) warnings.warn(warning_message, DataWarning)
def dictlist_wipe_key ( dict_list : Iterable [ Dict ] , key : str ) -> None : for d in dict_list : d . pop ( key , None )
1
python drop a key from dictionary
Process an iterable of dictionaries . For each dictionary d delete d [ key ] if it exists .
cosqa-train-18992
def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None: """ Process an iterable of dictionaries. For each dictionary ``d``, delete ``d[key]`` if it exists. """ for d in dict_list: d.pop(key, None)
def memory_full ( ) : current_process = psutil . Process ( os . getpid ( ) ) return ( current_process . memory_percent ( ) > config . MAXIMUM_CACHE_MEMORY_PERCENTAGE )
1
how to limit python memory
Check if the memory is too full for further caching .
cosqa-train-18993
def memory_full(): """Check if the memory is too full for further caching.""" current_process = psutil.Process(os.getpid()) return (current_process.memory_percent() > config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)
def list_to_str ( list , separator = ',' ) : list = [ str ( x ) for x in list ] return separator . join ( list )
1
changing from list to string in python
>>> list = [ 0 0 7 ] >>> list_to_str ( list ) 0 0 7
cosqa-train-18994
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 is_prime ( n ) : if n % 2 == 0 and n > 2 : return False return all ( n % i for i in range ( 3 , int ( math . sqrt ( n ) ) + 1 , 2 ) )
1
definition of prime in python
Check if n is a prime number
cosqa-train-18995
def is_prime(n): """ Check if n is a prime number """ if n % 2 == 0 and n > 2: return False return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
def from_file ( file_path ) -> dict : with io . open ( file_path , 'r' , encoding = 'utf-8' ) as json_stream : return Json . parse ( json_stream , True )
0
python read a json file into dictionary
Load JSON file
cosqa-train-18996
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 uppercase_chars ( string : any ) -> str : return '' . join ( [ c if c . isupper ( ) else '' for c in str ( string ) ] )
1
keep only uppercase words in string python
Return all ( and only ) the uppercase chars in the given string .
cosqa-train-18997
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 is_unicode ( string ) : str_type = str ( type ( string ) ) if str_type . find ( 'str' ) > 0 or str_type . find ( 'unicode' ) > 0 : return True return False
1
python check is an string
Validates that the object itself is some kinda string
cosqa-train-18998
def is_unicode(string): """Validates that the object itself is some kinda string""" str_type = str(type(string)) if str_type.find('str') > 0 or str_type.find('unicode') > 0: return True return False
def iter_fields ( self , schema : Schema ) -> Iterable [ Tuple [ str , Field ] ] : for name in sorted ( schema . fields . keys ( ) ) : field = schema . fields [ name ] yield field . dump_to or name , field
1
marshmallow python calling schema self for a nested field
Iterate through marshmallow schema fields .
cosqa-train-18999
def iter_fields(self, schema: Schema) -> Iterable[Tuple[str, Field]]: """ Iterate through marshmallow schema fields. Generates: name, field pairs """ for name in sorted(schema.fields.keys()): field = schema.fields[name] yield field.dump_to or name, field