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 numpy_to_yaml ( representer : Representer , data : np . ndarray ) -> Sequence [ Any ] : return representer . represent_sequence ( "!numpy_array" , data . tolist ( ) )
1
python numpy ndarray yaml
Write a numpy array to YAML .
cosqa-train-18800
def numpy_to_yaml(representer: Representer, data: np.ndarray) -> Sequence[Any]: """ Write a numpy array to YAML. It registers the array under the tag ``!numpy_array``. Use with: .. code-block:: python >>> yaml = ruamel.yaml.YAML() >>> yaml.representer.add_representer(np.ndarray, yaml.numpy_to_yaml) Note: We cannot use ``yaml.register_class`` because it won't register the proper type. (It would register the type of the class, rather than of `numpy.ndarray`). Instead, we use the above approach to register this method explicitly with the representer. """ return representer.represent_sequence( "!numpy_array", data.tolist() )
def read_set_from_file ( filename : str ) -> Set [ str ] : collection = set ( ) with open ( filename , 'r' ) as file_ : for line in file_ : collection . add ( line . rstrip ( ) ) return collection
1
create set from file in python
Extract a de - duped collection ( set ) of text from a file . Expected file format is one item per line .
cosqa-train-18801
def read_set_from_file(filename: str) -> Set[str]: """ Extract a de-duped collection (set) of text from a file. Expected file format is one item per line. """ collection = set() with open(filename, 'r') as file_: for line in file_: collection.add(line.rstrip()) return collection
def looks_like_url ( url ) : if not isinstance ( url , basestring ) : return False if not isinstance ( url , basestring ) or len ( url ) >= 1024 or not cre_url . match ( url ) : return False return True
0
how to check if a string is a link python
Simplified check to see if the text appears to be a URL .
cosqa-train-18802
def looks_like_url(url): """ Simplified check to see if the text appears to be a URL. Similar to `urlparse` but much more basic. Returns: True if the url str appears to be valid. False otherwise. >>> url = looks_like_url("totalgood.org") >>> bool(url) True """ if not isinstance(url, basestring): return False if not isinstance(url, basestring) or len(url) >= 1024 or not cre_url.match(url): return False return True
def clean_all_buckets ( self ) : bucket_keys = self . redis_object . keys ( pattern = 'nearpy_*' ) if len ( bucket_keys ) > 0 : self . redis_object . delete ( * bucket_keys )
0
redis cluster delete all keys python
Removes all buckets from all hashes and their content .
cosqa-train-18803
def clean_all_buckets(self): """ Removes all buckets from all hashes and their content. """ bucket_keys = self.redis_object.keys(pattern='nearpy_*') if len(bucket_keys) > 0: self.redis_object.delete(*bucket_keys)
def normalize ( numbers ) : total = float ( sum ( numbers ) ) return [ n / total for n in numbers ]
0
sum to 1 normalize 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-18804
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 get_now_sql_datetime ( ) : ## > IMPORTS ## from datetime import datetime , date , time now = datetime . now ( ) now = now . strftime ( "%Y-%m-%dT%H:%M:%S" ) return now
0
python3 orm mysql datetime now
* A datetime stamp in MySQL format : YYYY - MM - DDTHH : MM : SS *
cosqa-train-18805
def get_now_sql_datetime(): """ *A datetime stamp in MySQL format: ``YYYY-MM-DDTHH:MM:SS``* **Return:** - ``now`` -- current time and date in MySQL format **Usage:** .. code-block:: python from fundamentals import times now = times.get_now_sql_datetime() print now # OUT: 2016-03-18T11:08:23 """ ## > IMPORTS ## from datetime import datetime, date, time now = datetime.now() now = now.strftime("%Y-%m-%dT%H:%M:%S") return now
def is_end_of_month ( self ) -> bool : end_of_month = Datum ( ) # get_end_of_month(value) end_of_month . end_of_month ( ) return self . value == end_of_month . value
1
python check if date is end of month
Checks if the date is at the end of the month
cosqa-train-18806
def is_end_of_month(self) -> bool: """ Checks if the date is at the end of the month """ end_of_month = Datum() # get_end_of_month(value) end_of_month.end_of_month() return self.value == end_of_month.value
def uuid2buid ( value ) : if six . PY3 : # pragma: no cover return urlsafe_b64encode ( value . bytes ) . decode ( 'utf-8' ) . rstrip ( '=' ) else : return six . text_type ( urlsafe_b64encode ( value . bytes ) . rstrip ( '=' ) )
1
string to uuid python
Convert a UUID object to a 22 - char BUID string
cosqa-train-18807
def uuid2buid(value): """ Convert a UUID object to a 22-char BUID string >>> u = uuid.UUID('33203dd2-f2ef-422f-aeb0-058d6f5f7089') >>> uuid2buid(u) 'MyA90vLvQi-usAWNb19wiQ' """ if six.PY3: # pragma: no cover return urlsafe_b64encode(value.bytes).decode('utf-8').rstrip('=') else: return six.text_type(urlsafe_b64encode(value.bytes).rstrip('='))
def 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
how to check is a column is null 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-18808
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 suppress_stdout ( ) : save_stdout = sys . stdout sys . stdout = DevNull ( ) yield sys . stdout = save_stdout
1
supress python output shell
Context manager that suppresses stdout .
cosqa-train-18809
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 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 creating dictionary from list of lists
Converts a list into a space - separated string and puts it in a dictionary
cosqa-train-18810
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 gen_lower ( x : Iterable [ str ] ) -> Generator [ str , None , None ] : for string in x : yield string . lower ( )
1
python lower each element of list
Args : x : iterable of strings
cosqa-train-18811
def gen_lower(x: Iterable[str]) -> Generator[str, None, None]: """ Args: x: iterable of strings Yields: each string in lower case """ for string in x: yield string.lower()
def inverted_dict ( d ) : return dict ( ( force_hashable ( v ) , k ) for ( k , v ) in viewitems ( dict ( d ) ) )
1
python invert a dict
Return a dict with swapped keys and values
cosqa-train-18812
def inverted_dict(d): """Return a dict with swapped keys and values >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0} True """ return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))
def remove_links ( text ) : tco_link_regex = re . compile ( "https?://t.co/[A-z0-9].*" ) generic_link_regex = re . compile ( "(https?://)?(\w*[.]\w+)+([/?=&]+\w+)*" ) remove_tco = re . sub ( tco_link_regex , " " , text ) remove_generic = re . sub ( generic_link_regex , " " , remove_tco ) return remove_generic
1
remove hyper links from sentence in python
Helper function to remove the links from the input text
cosqa-train-18813
def remove_links(text): """ Helper function to remove the links from the input text Args: text (str): A string Returns: str: the same text, but with any substring that matches the regex for a link removed and replaced with a space Example: >>> from tweet_parser.getter_methods.tweet_text import remove_links >>> text = "lorem ipsum dolor https://twitter.com/RobotPrincessFi" >>> remove_links(text) 'lorem ipsum dolor ' """ tco_link_regex = re.compile("https?://t.co/[A-z0-9].*") generic_link_regex = re.compile("(https?://)?(\w*[.]\w+)+([/?=&]+\w+)*") remove_tco = re.sub(tco_link_regex, " ", text) remove_generic = re.sub(generic_link_regex, " ", remove_tco) return remove_generic
def decode_value ( stream ) : length = decode_length ( stream ) ( value , ) = unpack_value ( ">{:d}s" . format ( length ) , stream ) return value
1
python parsing bits of stream
Decode the contents of a value from a serialized stream .
cosqa-train-18814
def decode_value(stream): """Decode the contents of a value from a serialized stream. :param stream: Source data stream :type stream: io.BytesIO :returns: Decoded value :rtype: bytes """ length = decode_length(stream) (value,) = unpack_value(">{:d}s".format(length), stream) return value
def most_significant_bit ( lst : np . ndarray ) -> int : return np . argwhere ( np . asarray ( lst ) == 1 ) [ 0 ] [ 0 ]
1
identify the most common number in an array python
A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s i . e . the first position where a 1 appears reading left to right .
cosqa-train-18815
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 fcast ( value : float ) -> TensorLike : newvalue = tf . cast ( value , FTYPE ) if DEVICE == 'gpu' : newvalue = newvalue . gpu ( ) # Why is this needed? # pragma: no cover return newvalue
0
python get value from tensor as float
Cast to float tensor
cosqa-train-18816
def fcast(value: float) -> TensorLike: """Cast to float tensor""" newvalue = tf.cast(value, FTYPE) if DEVICE == 'gpu': newvalue = newvalue.gpu() # Why is this needed? # pragma: no cover return newvalue
def dotproduct ( X , Y ) : return sum ( [ x * y for x , y in zip ( X , Y ) ] )
1
how to product of a list in python
Return the sum of the element - wise product of vectors x and y . >>> dotproduct ( [ 1 2 3 ] [ 1000 100 10 ] ) 1230
cosqa-train-18817
def dotproduct(X, Y): """Return the sum of the element-wise product of vectors x and y. >>> dotproduct([1, 2, 3], [1000, 100, 10]) 1230 """ return sum([x * y for x, y in zip(X, Y)])
def snake_to_camel ( s : str ) -> str : fragments = s . split ( '_' ) return fragments [ 0 ] + '' . join ( x . title ( ) for x in fragments [ 1 : ] )
1
how to capitalize a letter in a string python
Convert string from snake case to camel case .
cosqa-train-18818
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 check_valid ( number , input_base = 10 ) : for n in number : if n in ( "." , "[" , "]" ) : continue elif n >= input_base : if n == 1 and input_base == 1 : continue else : return False return True
1
how to tell if a value is valid based of its base python
Checks if there is an invalid digit in the input number . Args : number : An number in the following form : ( int int int ... . int int int ) ( iterable container ) containing positive integers of the input base input_base ( int ) : The base of the input number . Returns : bool True if all digits valid else False . Examples : >>> check_valid (( 1 9 6 . 5 1 6 ) 12 ) True >>> check_valid (( 8 1 15 9 ) 15 ) False
cosqa-train-18819
def check_valid(number, input_base=10): """ Checks if there is an invalid digit in the input number. Args: number: An number in the following form: (int, int, int, ... , '.' , int, int, int) (iterable container) containing positive integers of the input base input_base(int): The base of the input number. Returns: bool, True if all digits valid, else False. Examples: >>> check_valid((1,9,6,'.',5,1,6), 12) True >>> check_valid((8,1,15,9), 15) False """ for n in number: if n in (".", "[", "]"): continue elif n >= input_base: if n == 1 and input_base == 1: continue else: return False return True
def ResetConsoleColor ( ) -> bool : if sys . stdout : sys . stdout . flush ( ) bool ( ctypes . windll . kernel32 . SetConsoleTextAttribute ( _ConsoleOutputHandle , _DefaultConsoleColor ) )
1
python curses set text colour
Reset to the default text color on console window . Return bool True if succeed otherwise False .
cosqa-train-18820
def ResetConsoleColor() -> bool: """ Reset to the default text color on console window. Return bool, True if succeed otherwise False. """ if sys.stdout: sys.stdout.flush() bool(ctypes.windll.kernel32.SetConsoleTextAttribute(_ConsoleOutputHandle, _DefaultConsoleColor))
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 time zone info
Discover the current time zone and it s standard string representation ( for source { d } ) .
cosqa-train-18821
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 upsert_multi ( db , collection , object , match_params = None ) : if isinstance ( object , list ) and len ( object ) > 0 : return str ( db [ collection ] . insert_many ( object ) . inserted_ids ) elif isinstance ( object , dict ) : return str ( db [ collection ] . update_many ( match_params , { "$set" : object } , upsert = False ) . upserted_id )
0
bulk insert into mongodb collection in python
Wrapper for pymongo . insert_many () and update_many () : param db : db connection : param collection : collection to update : param object : the modifications to apply : param match_params : a query that matches the documents to update : return : ids of inserted / updated document
cosqa-train-18822
def upsert_multi(db, collection, object, match_params=None): """ Wrapper for pymongo.insert_many() and update_many() :param db: db connection :param collection: collection to update :param object: the modifications to apply :param match_params: a query that matches the documents to update :return: ids of inserted/updated document """ if isinstance(object, list) and len(object) > 0: return str(db[collection].insert_many(object).inserted_ids) elif isinstance(object, dict): return str(db[collection].update_many(match_params, {"$set": object}, upsert=False).upserted_id)
def get_language ( ) : from parler import appsettings language = dj_get_language ( ) if language is None and appsettings . PARLER_DEFAULT_ACTIVATE : return appsettings . PARLER_DEFAULT_LANGUAGE_CODE else : return language
1
how to get visitor's language in python django
Wrapper around Django s get_language utility . For Django > = 1 . 8 get_language returns None in case no translation is activate . Here we patch this behavior e . g . for back - end functionality requiring access to translated fields
cosqa-train-18823
def get_language(): """ Wrapper around Django's `get_language` utility. For Django >= 1.8, `get_language` returns None in case no translation is activate. Here we patch this behavior e.g. for back-end functionality requiring access to translated fields """ from parler import appsettings language = dj_get_language() if language is None and appsettings.PARLER_DEFAULT_ACTIVATE: return appsettings.PARLER_DEFAULT_LANGUAGE_CODE else: return language
def url_concat ( url , args ) : if not args : return url if url [ - 1 ] not in ( '?' , '&' ) : url += '&' if ( '?' in url ) else '?' return url + urllib . urlencode ( args )
1
python join query string to url
Concatenate url and argument dictionary regardless of whether url has existing query parameters .
cosqa-train-18824
def url_concat(url, args): """Concatenate url and argument dictionary regardless of whether url has existing query parameters. >>> url_concat("http://example.com/foo?a=b", dict(c="d")) 'http://example.com/foo?a=b&c=d' """ if not args: return url if url[-1] not in ('?', '&'): url += '&' if ('?' in url) else '?' return url + urllib.urlencode(args)
def get_system_flags ( ) -> FrozenSet [ Flag ] : return frozenset ( { Seen , Recent , Deleted , Flagged , Answered , Draft } )
1
get all the flags in python
Return the set of implemented system flags .
cosqa-train-18825
def get_system_flags() -> FrozenSet[Flag]: """Return the set of implemented system flags.""" return frozenset({Seen, Recent, Deleted, Flagged, Answered, Draft})
def chars ( string : any ) -> str : return '' . join ( [ c if c . isalpha ( ) else '' for c in str ( string ) ] )
0
how to check if a string is all letters python
Return all ( and only ) the chars in the given string .
cosqa-train-18826
def chars(string: any) -> str: """Return all (and only) the chars in the given string.""" return ''.join([c if c.isalpha() else '' for c in str(string)])
def count ( args ) : counts = defaultdict ( int ) for arg in args : for item in arg : counts [ item ] = counts [ item ] + 1 return counts
1
count the frequency of an integer in a list python
count occurences in a list of lists >>> count ( [[ a b ] [ a ]] ) defaultdict ( int { a : 2 b : 1 } )
cosqa-train-18827
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 chars ( string : any ) -> str : return '' . join ( [ c if c . isalpha ( ) else '' for c in str ( string ) ] )
0
isalpha of a character in a string python3
Return all ( and only ) the chars in the given string .
cosqa-train-18828
def chars(string: any) -> str: """Return all (and only) the chars in the given string.""" return ''.join([c if c.isalpha() else '' for c in str(string)])
def 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
how to get random walk onto python
Generate a random walk and return True if the walker has returned to the origin after taking n steps .
cosqa-train-18829
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 memory_full ( ) : current_process = psutil . Process ( os . getpid ( ) ) return ( current_process . memory_percent ( ) > config . MAXIMUM_CACHE_MEMORY_PERCENTAGE )
0
python get cache usage for a process
Check if the memory is too full for further caching .
cosqa-train-18830
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 dictlist_wipe_key ( dict_list : Iterable [ Dict ] , key : str ) -> None : for d in dict_list : d . pop ( key , None )
0
remove from python dict by key
Process an iterable of dictionaries . For each dictionary d delete d [ key ] if it exists .
cosqa-train-18831
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 flatten_list ( l : List [ list ] ) -> list : return [ v for inner_l in l for v in inner_l ]
1
python3 flatten a list
takes a list of lists l and returns a flat list
cosqa-train-18832
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 process_literal_param ( self , value : Optional [ List [ int ] ] , dialect : Dialect ) -> str : retval = self . _intlist_to_dbstr ( value ) return retval
1
python pyodbc int to string
Convert things on the way from Python to the database .
cosqa-train-18833
def process_literal_param(self, value: Optional[List[int]], dialect: Dialect) -> str: """Convert things on the way from Python to the database.""" retval = self._intlist_to_dbstr(value) return retval
def __rmatmul__ ( self , other ) : return self . T . dot ( np . transpose ( other ) ) . T
0
how does python multiply m,atrices
Matrix multiplication using binary
cosqa-train-18834
def __rmatmul__(self, other): """ Matrix multiplication using binary `@` operator in Python>=3.5. """ return self.T.dot(np.transpose(other)).T
def non_increasing ( values ) : return all ( x >= y for x , y in zip ( values , values [ 1 : ] ) )
0
determine if three consectuitve day are above a number python
True if values are not increasing .
cosqa-train-18835
def non_increasing(values): """True if values are not increasing.""" return all(x >= y for x, y in zip(values, values[1:]))
def _duplicates ( list_ ) : item_indices = { } for i , item in enumerate ( list_ ) : try : item_indices [ item ] . append ( i ) except KeyError : # First time seen item_indices [ item ] = [ i ] return item_indices
1
python list index for duplicated data
Return dict mapping item - > indices .
cosqa-train-18836
def _duplicates(list_): """Return dict mapping item -> indices.""" item_indices = {} for i, item in enumerate(list_): try: item_indices[item].append(i) except KeyError: # First time seen item_indices[item] = [i] return item_indices
def __replace_all ( repls : dict , input : str ) -> str : return re . sub ( '|' . join ( re . escape ( key ) for key in repls . keys ( ) ) , lambda k : repls [ k . group ( 0 ) ] , input )
1
replace every instance of word in python string
Replaces from a string ** input ** all the occurrences of some symbols according to mapping ** repls ** .
cosqa-train-18837
def __replace_all(repls: dict, input: str) -> str: """ Replaces from a string **input** all the occurrences of some symbols according to mapping **repls**. :param dict repls: where #key is the old character and #value is the one to substitute with; :param str input: original string where to apply the replacements; :return: *(str)* the string with the desired characters replaced """ return re.sub('|'.join(re.escape(key) for key in repls.keys()), lambda k: repls[k.group(0)], input)
def rate_limited ( max_per_hour : int , * args : Any ) -> Callable [ ... , Any ] : return util . rate_limited ( max_per_hour , * args )
0
create a limit of a function in python
Rate limit a function .
cosqa-train-18838
def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]: """Rate limit a function.""" return util.rate_limited(max_per_hour, *args)
def codes_get_size ( handle , key ) : # type: (cffi.FFI.CData, str) -> int size = ffi . new ( 'size_t *' ) _codes_get_size ( handle , key . encode ( ENC ) , size ) return size [ 0 ]
1
how to get the length of a key python
Get the number of coded value from a key . If several keys of the same name are present the total sum is returned .
cosqa-train-18839
def codes_get_size(handle, key): # type: (cffi.FFI.CData, str) -> int """ Get the number of coded value from a key. If several keys of the same name are present, the total sum is returned. :param bytes key: the keyword to get the size of :rtype: int """ size = ffi.new('size_t *') _codes_get_size(handle, key.encode(ENC), size) return size[0]
def setup_cache ( app : Flask , cache_config ) -> Optional [ Cache ] : if cache_config and cache_config . get ( 'CACHE_TYPE' ) != 'null' : return Cache ( app , config = cache_config ) return None
0
python flask disable cache
Setup the flask - cache on a flask app
cosqa-train-18840
def setup_cache(app: Flask, cache_config) -> Optional[Cache]: """Setup the flask-cache on a flask app""" if cache_config and cache_config.get('CACHE_TYPE') != 'null': return Cache(app, config=cache_config) return None
def truncate ( value : Decimal , n_digits : int ) -> Decimal : return Decimal ( math . trunc ( value * ( 10 ** n_digits ) ) ) / ( 10 ** n_digits )
1
python how to shorten the decimals in a float
Truncates a value to a number of decimals places
cosqa-train-18841
def truncate(value: Decimal, n_digits: int) -> Decimal: """Truncates a value to a number of decimals places""" return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)
def _isint ( string ) : return type ( string ) is int or ( isinstance ( string , _binary_type ) or isinstance ( string , _text_type ) ) and _isconvertible ( int , string )
1
how to check whether a string is int in python
>>> _isint ( 123 ) True >>> _isint ( 123 . 45 ) False
cosqa-train-18842
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 call_fset ( self , obj , value ) -> None : vars ( obj ) [ self . name ] = self . fset ( obj , value )
1
add a local variable python setattr
Store the given custom value and call the setter function .
cosqa-train-18843
def call_fset(self, obj, value) -> None: """Store the given custom value and call the setter function.""" vars(obj)[self.name] = self.fset(obj, value)
def count ( args ) : counts = defaultdict ( int ) for arg in args : for item in arg : counts [ item ] = counts [ item ] + 1 return counts
1
count occurences in a list python
count occurences in a list of lists >>> count ( [[ a b ] [ a ]] ) defaultdict ( int { a : 2 b : 1 } )
cosqa-train-18844
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 src2ast ( src : str ) -> Expression : try : return ast . parse ( src , mode = 'eval' ) except SyntaxError : raise ValueError ( "Not a valid expression." ) from None
0
how to add ast in python
Return ast . Expression created from source code given in src .
cosqa-train-18845
def src2ast(src: str) -> Expression: """Return ast.Expression created from source code given in `src`.""" try: return ast.parse(src, mode='eval') except SyntaxError: raise ValueError("Not a valid expression.") from None
def put ( self , endpoint : str , * * kwargs ) -> dict : return self . _request ( 'PUT' , endpoint , * * kwargs )
1
python make a put request to restful endpoint
HTTP PUT operation to API endpoint .
cosqa-train-18846
def put(self, endpoint: str, **kwargs) -> dict: """HTTP PUT operation to API endpoint.""" return self._request('PUT', endpoint, **kwargs)
def indexes_equal ( a : Index , b : Index ) -> bool : return str ( a ) == str ( b )
0
if two strungs are equal python
Are two indexes equal? Checks by comparing str () versions of them . ( AM UNSURE IF THIS IS ENOUGH . )
cosqa-train-18847
def indexes_equal(a: Index, b: Index) -> bool: """ Are two indexes equal? Checks by comparing ``str()`` versions of them. (AM UNSURE IF THIS IS ENOUGH.) """ return str(a) == str(b)
def listify ( a ) : if a is None : return [ ] elif not isinstance ( a , ( tuple , list , np . ndarray ) ) : return [ a ] return list ( a )
0
cast list as array in python
Convert a scalar a to a list and all iterables to list as well .
cosqa-train-18848
def listify(a): """ Convert a scalar ``a`` to a list and all iterables to list as well. Examples -------- >>> listify(0) [0] >>> listify([1,2,3]) [1, 2, 3] >>> listify('a') ['a'] >>> listify(np.array([1,2,3])) [1, 2, 3] >>> listify('string') ['string'] """ if a is None: return [] elif not isinstance(a, (tuple, list, np.ndarray)): return [a] return list(a)
def inverted_dict ( d ) : return dict ( ( force_hashable ( v ) , k ) for ( k , v ) in viewitems ( dict ( d ) ) )
0
how do you invert a dictionary python
Return a dict with swapped keys and values
cosqa-train-18849
def inverted_dict(d): """Return a dict with swapped keys and values >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0} True """ return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))
def string ( value ) -> str : return system_json . dumps ( Json ( value ) . safe_object ( ) , ensure_ascii = False )
0
python turn json into string
string dict / object / value to JSON
cosqa-train-18850
def string(value) -> str: """ string dict/object/value to JSON """ return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)
def recClearTag ( element ) : children = element . getchildren ( ) if len ( children ) > 0 : for child in children : recClearTag ( child ) element . tag = clearTag ( element . tag )
0
python elementtree clear children
Applies maspy . xml . clearTag () to the tag attribute of the element and recursively to all child elements .
cosqa-train-18851
def recClearTag(element): """Applies maspy.xml.clearTag() to the tag attribute of the "element" and recursively to all child elements. :param element: an :instance:`xml.etree.Element` """ children = element.getchildren() if len(children) > 0: for child in children: recClearTag(child) element.tag = clearTag(element.tag)
def get_table_names_from_metadata ( metadata : MetaData ) -> List [ str ] : return [ table . name for table in metadata . tables . values ( ) ]
1
list of ms access table names python
Returns all database table names found in an SQLAlchemy : class : MetaData object .
cosqa-train-18852
def get_table_names_from_metadata(metadata: MetaData) -> List[str]: """ Returns all database table names found in an SQLAlchemy :class:`MetaData` object. """ return [table.name for table in metadata.tables.values()]
def clean_column_names ( df : DataFrame ) -> DataFrame : f = df . copy ( ) f . columns = [ col . strip ( ) for col in f . columns ] return f
1
remove extra whitespace from all kind of data frame column values in python
Strip the whitespace from all column names in the given DataFrame and return the result .
cosqa-train-18853
def clean_column_names(df: DataFrame) -> DataFrame: """ Strip the whitespace from all column names in the given DataFrame and return the result. """ f = df.copy() f.columns = [col.strip() for col in f.columns] return f
def signed_distance ( mesh , points ) : # make sure we have a numpy array points = np . asanyarray ( points , dtype = np . float64 ) # find the closest point on the mesh to the queried points closest , distance , triangle_id = closest_point ( mesh , points ) # we only care about nonzero distances nonzero = distance > tol . merge if not nonzero . any ( ) : return distance inside = mesh . ray . contains_points ( points [ nonzero ] ) sign = ( inside . astype ( int ) * 2 ) - 1 # apply sign to previously computed distance distance [ nonzero ] *= sign return distance
1
python shortest distance on triangulated mesh
Find the signed distance from a mesh to a list of points .
cosqa-train-18854
def signed_distance(mesh, points): """ Find the signed distance from a mesh to a list of points. * Points OUTSIDE the mesh will have NEGATIVE distance * Points within tol.merge of the surface will have POSITIVE distance * Points INSIDE the mesh will have POSITIVE distance Parameters ----------- mesh : Trimesh object points : (n,3) float, list of points in space Returns ---------- signed_distance : (n,3) float, signed distance from point to mesh """ # make sure we have a numpy array points = np.asanyarray(points, dtype=np.float64) # find the closest point on the mesh to the queried points closest, distance, triangle_id = closest_point(mesh, points) # we only care about nonzero distances nonzero = distance > tol.merge if not nonzero.any(): return distance inside = mesh.ray.contains_points(points[nonzero]) sign = (inside.astype(int) * 2) - 1 # apply sign to previously computed distance distance[nonzero] *= sign return distance
def butlast ( iterable ) : iterable = iter ( iterable ) try : first = next ( iterable ) except StopIteration : return for second in iterable : yield first first = second
1
python last item inl list
Yield all items from iterable except the last one .
cosqa-train-18855
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 needs_check ( self ) : if self . lastcheck is None : return True return time . time ( ) - self . lastcheck >= self . ipchangedetection_sleep
1
easy way to check is a boolean has changed in python
Check if enough time has elapsed to perform a check () .
cosqa-train-18856
def needs_check(self): """ Check if enough time has elapsed to perform a check(). If this time has elapsed, a state change check through has_state_changed() should be performed and eventually a sync(). :rtype: boolean """ if self.lastcheck is None: return True return time.time() - self.lastcheck >= self.ipchangedetection_sleep
def _kbhit_unix ( ) -> bool : dr , dw , de = select . select ( [ sys . stdin ] , [ ] , [ ] , 0 ) return dr != [ ]
0
python script to check for keyboard input
Under UNIX : is a keystroke available?
cosqa-train-18857
def _kbhit_unix() -> bool: """ Under UNIX: is a keystroke available? """ dr, dw, de = select.select([sys.stdin], [], [], 0) return dr != []
def get_from_gnucash26_date ( date_str : str ) -> date : date_format = "%Y%m%d" result = datetime . strptime ( date_str , date_format ) . date ( ) return result
1
python how to create date from string
Creates a datetime from GnuCash 2 . 6 date string
cosqa-train-18858
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 replace_in_list ( stringlist : Iterable [ str ] , replacedict : Dict [ str , str ] ) -> List [ str ] : newlist = [ ] for fromstring in stringlist : newlist . append ( multiple_replace ( fromstring , replacedict ) ) return newlist
0
python replacing strings in a list using a dictionary
Returns a list produced by applying : func : multiple_replace to every string in stringlist .
cosqa-train-18859
def replace_in_list(stringlist: Iterable[str], replacedict: Dict[str, str]) -> List[str]: """ Returns a list produced by applying :func:`multiple_replace` to every string in ``stringlist``. Args: stringlist: list of source strings replacedict: dictionary mapping "original" to "replacement" strings Returns: list of final strings """ newlist = [] for fromstring in stringlist: newlist.append(multiple_replace(fromstring, replacedict)) return newlist
def get_creation_date ( self , bucket : str , key : str , ) -> datetime . datetime : blob_obj = self . _get_blob_obj ( bucket , key ) return blob_obj . time_created
0
python boto3 s3 get latest object date
Retrieves the creation date for a given key in a given bucket . : param bucket : the bucket the object resides in . : param key : the key of the object for which the creation date is being retrieved . : return : the creation date
cosqa-train-18860
def get_creation_date( self, bucket: str, key: str, ) -> datetime.datetime: """ Retrieves the creation date for a given key in a given bucket. :param bucket: the bucket the object resides in. :param key: the key of the object for which the creation date is being retrieved. :return: the creation date """ blob_obj = self._get_blob_obj(bucket, key) return blob_obj.time_created
def __replace_all ( repls : dict , input : str ) -> str : return re . sub ( '|' . join ( re . escape ( key ) for key in repls . keys ( ) ) , lambda k : repls [ k . group ( 0 ) ] , input )
0
python replace multiple characters from string
Replaces from a string ** input ** all the occurrences of some symbols according to mapping ** repls ** .
cosqa-train-18861
def __replace_all(repls: dict, input: str) -> str: """ Replaces from a string **input** all the occurrences of some symbols according to mapping **repls**. :param dict repls: where #key is the old character and #value is the one to substitute with; :param str input: original string where to apply the replacements; :return: *(str)* the string with the desired characters replaced """ return re.sub('|'.join(re.escape(key) for key in repls.keys()), lambda k: repls[k.group(0)], input)
def csv_to_numpy ( string_like , dtype = None ) : # type: (str) -> np.array stream = StringIO ( string_like ) return np . genfromtxt ( stream , dtype = dtype , delimiter = ',' )
0
python numpy read in a csv file into a numpy array
Convert a CSV object to a numpy array .
cosqa-train-18862
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 memory_full ( ) : current_process = psutil . Process ( os . getpid ( ) ) return ( current_process . memory_percent ( ) > config . MAXIMUM_CACHE_MEMORY_PERCENTAGE )
1
how to check if memory leak in python program
Check if the memory is too full for further caching .
cosqa-train-18863
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 file_exists ( fname ) : try : return fname and os . path . exists ( fname ) and os . path . getsize ( fname ) > 0 except OSError : return False
0
python test if path is full
Check if a file exists and is non - empty .
cosqa-train-18864
def file_exists(fname): """Check if a file exists and is non-empty. """ try: return fname and os.path.exists(fname) and os.path.getsize(fname) > 0 except OSError: return False
def get_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
0
python dateutil last day of month
Returns day number of the last day of the month : param t : datetime : return : int
cosqa-train-18865
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 safe_pow ( base , exp ) : if exp > MAX_EXPONENT : raise RuntimeError ( "Invalid exponent, max exponent is {}" . format ( MAX_EXPONENT ) ) return base ** exp
1
python how to ise math pow(x n)
safe version of pow
cosqa-train-18866
def safe_pow(base, exp): """safe version of pow""" if exp > MAX_EXPONENT: raise RuntimeError("Invalid exponent, max exponent is {}".format(MAX_EXPONENT)) return base ** exp
def is_finite ( value : Any ) -> bool : return isinstance ( value , int ) or ( isinstance ( value , float ) and isfinite ( value ) )
1
check if value is infinity in python
Return true if a value is a finite number .
cosqa-train-18867
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 strtobytes ( input , encoding ) : py_version = sys . version_info [ 0 ] if py_version >= 3 : return _strtobytes_py3 ( input , encoding ) return _strtobytes_py2 ( input , encoding )
0
cython string to char python3
Take a str and transform it into a byte array .
cosqa-train-18868
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 is_empty_shape ( sh : ShExJ . Shape ) -> bool : return sh . closed is None and sh . expression is None and sh . extra is None and sh . semActs is None
0
how to check if shape file is empty or not python
Determine whether sh has any value
cosqa-train-18869
def is_empty_shape(sh: ShExJ.Shape) -> bool: """ Determine whether sh has any value """ return sh.closed is None and sh.expression is None and sh.extra is None and \ sh.semActs is None
def chars ( string : any ) -> str : return '' . join ( [ c if c . isalpha ( ) else '' for c in str ( string ) ] )
0
check each character in a string python alphanumeric
Return all ( and only ) the chars in the given string .
cosqa-train-18870
def chars(string: any) -> str: """Return all (and only) the chars in the given string.""" return ''.join([c if c.isalpha() else '' for c in str(string)])
def get_day_name ( self ) -> str : weekday = self . value . isoweekday ( ) - 1 return calendar . day_name [ weekday ]
0
get name of week day in python
Returns the day name
cosqa-train-18871
def get_day_name(self) -> str: """ Returns the day name """ weekday = self.value.isoweekday() - 1 return calendar.day_name[weekday]
def _my_hash ( arg_list ) : # type: (List[Any]) -> int res = 0 for arg in arg_list : res = res * 31 + hash ( arg ) return res
0
how to meausre distributed of hash function in python
Simple helper hash function
cosqa-train-18872
def _my_hash(arg_list): # type: (List[Any]) -> int """Simple helper hash function""" res = 0 for arg in arg_list: res = res * 31 + hash(arg) return res
def proper_round ( n ) : return int ( n ) + ( n / abs ( n ) ) * int ( abs ( n - int ( n ) ) >= 0.5 ) if n != 0 else 0
1
python round or cast to int
rounds float to closest int : rtype : int : param n : float
cosqa-train-18873
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 year ( date ) : try : fmt = '%m/%d/%Y' return datetime . strptime ( date , fmt ) . timetuple ( ) . tm_year except ValueError : return 0
0
just get an year from a date in python
Returns the year .
cosqa-train-18874
def year(date): """ Returns the year. :param date: The string date with this format %m/%d/%Y :type date: String :returns: int :example: >>> year('05/1/2015') 2015 """ try: fmt = '%m/%d/%Y' return datetime.strptime(date, fmt).timetuple().tm_year except ValueError: return 0
def astensor ( array : TensorLike ) -> BKTensor : tensor = tf . convert_to_tensor ( value = array , dtype = CTYPE ) return tensor
0
from 1d tensor to a 3d tensor python
Covert numpy array to tensorflow tensor
cosqa-train-18875
def astensor(array: TensorLike) -> BKTensor: """Covert numpy array to tensorflow tensor""" tensor = tf.convert_to_tensor(value=array, dtype=CTYPE) return tensor
def MoveWindow ( handle : int , x : int , y : int , width : int , height : int , repaint : int = 1 ) -> bool : return bool ( ctypes . windll . user32 . MoveWindow ( ctypes . c_void_p ( handle ) , x , y , width , height , repaint ) )
1
win32 move window python
MoveWindow from Win32 . handle : int the handle of a native window . x : int . y : int . width : int . height : int . repaint : int use 1 or 0 . Return bool True if succeed otherwise False .
cosqa-train-18876
def MoveWindow(handle: int, x: int, y: int, width: int, height: int, repaint: int = 1) -> bool: """ MoveWindow from Win32. handle: int, the handle of a native window. x: int. y: int. width: int. height: int. repaint: int, use 1 or 0. Return bool, True if succeed otherwise False. """ return bool(ctypes.windll.user32.MoveWindow(ctypes.c_void_p(handle), x, y, width, height, repaint))
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 isprime function print integers for a range
Check if n is a prime number
cosqa-train-18877
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 try_cast_int ( s ) : try : temp = re . findall ( '\d' , str ( s ) ) temp = '' . join ( temp ) return int ( temp ) except : return s
1
python strip to turn string into number
( str ) - > int All the digits in a given string are concatenated and converted into a single number .
cosqa-train-18878
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 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
read line in python skip certain newline
Helper for iterating only nonempty lines without line breaks
cosqa-train-18879
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 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 )
0
initialize an array in python without numpy
Given a value wrap it in a 0 - D numpy . ndarray .
cosqa-train-18880
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 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
0
check whether date is valid python
Retrun True if x is a valid YYYYMMDD date ; otherwise return False .
cosqa-train-18881
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 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
difining np array in python string
Format numpy array as a string .
cosqa-train-18882
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 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
python get last month days
Returns day number of the last day of the month : param t : datetime : return : int
cosqa-train-18883
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 clip_to_seconds ( m : Union [ int , pd . Series ] ) -> Union [ int , pd . Series ] : return m // pd . Timedelta ( 1 , unit = 's' ) . value
0
python series datetime to seconds
Clips UTC datetime in nanoseconds to seconds .
cosqa-train-18884
def clip_to_seconds(m: Union[int, pd.Series]) -> Union[int, pd.Series]: """Clips UTC datetime in nanoseconds to seconds.""" return m // pd.Timedelta(1, unit='s').value
def dict_to_enum_fn ( d : Dict [ str , Any ] , enum_class : Type [ Enum ] ) -> Enum : return enum_class [ d [ 'name' ] ]
0
boost python expose a struct with enum type member
Converts an dict to a Enum .
cosqa-train-18885
def dict_to_enum_fn(d: Dict[str, Any], enum_class: Type[Enum]) -> Enum: """ Converts an ``dict`` to a ``Enum``. """ return enum_class[d['name']]
def setlocale ( name ) : with LOCALE_LOCK : old_locale = locale . setlocale ( locale . LC_ALL ) try : yield locale . setlocale ( locale . LC_ALL , name ) finally : locale . setlocale ( locale . LC_ALL , old_locale )
0
python set locale threadsafe
Context manager with threading lock for set locale on enter and set it back to original state on exit .
cosqa-train-18886
def setlocale(name): """ Context manager with threading lock for set locale on enter, and set it back to original state on exit. :: >>> with setlocale("C"): ... ... """ with LOCALE_LOCK: old_locale = locale.setlocale(locale.LC_ALL) try: yield locale.setlocale(locale.LC_ALL, name) finally: locale.setlocale(locale.LC_ALL, old_locale)
def to_javascript_ ( self , table_name : str = "data" ) -> str : try : renderer = pytablewriter . JavaScriptTableWriter data = self . _build_export ( renderer , table_name ) return data except Exception as e : self . err ( e , "Can not convert data to javascript code" )
0
python to javascript table
Convert the main dataframe to javascript code
cosqa-train-18887
def to_javascript_(self, table_name: str="data") -> str: """Convert the main dataframe to javascript code :param table_name: javascript variable name, defaults to "data" :param table_name: str, optional :return: a javascript constant with the data :rtype: str :example: ``ds.to_javastript_("myconst")`` """ try: renderer = pytablewriter.JavaScriptTableWriter data = self._build_export(renderer, table_name) return data except Exception as e: self.err(e, "Can not convert data to javascript code")
def file_exists ( fname ) : try : return fname and os . path . exists ( fname ) and os . path . getsize ( fname ) > 0 except OSError : return False
0
condition for checking file/folder is empty or not inpython
Check if a file exists and is non - empty .
cosqa-train-18888
def file_exists(fname): """Check if a file exists and is non-empty. """ try: return fname and os.path.exists(fname) and os.path.getsize(fname) > 0 except OSError: return False
def write_text ( filename : str , text : str ) -> None : with open ( filename , 'w' ) as f : # type: TextIO print ( text , file = f )
0
how to write text to a file in python
Writes text to a file .
cosqa-train-18889
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 isfile_notempty ( inputfile : str ) -> bool : try : return isfile ( inputfile ) and getsize ( inputfile ) > 0 except TypeError : raise TypeError ( 'inputfile is not a valid type' )
0
python check to see if file is empty
Check if the input filename with path is a file and is not empty .
cosqa-train-18890
def isfile_notempty(inputfile: str) -> bool: """Check if the input filename with path is a file and is not empty.""" try: return isfile(inputfile) and getsize(inputfile) > 0 except TypeError: raise TypeError('inputfile is not a valid type')
def availability_pdf ( ) -> bool : pdftotext = tools [ 'pdftotext' ] if pdftotext : return True elif pdfminer : log . warning ( "PDF conversion: pdftotext missing; " "using pdfminer (less efficient)" ) return True else : return False
0
tiff to searchable pdf python
Is a PDF - to - text tool available?
cosqa-train-18891
def availability_pdf() -> bool: """ Is a PDF-to-text tool available? """ pdftotext = tools['pdftotext'] if pdftotext: return True elif pdfminer: log.warning("PDF conversion: pdftotext missing; " "using pdfminer (less efficient)") return True else: return False
def _duplicates ( list_ ) : item_indices = { } for i , item in enumerate ( list_ ) : try : item_indices [ item ] . append ( i ) except KeyError : # First time seen item_indices [ item ] = [ i ] return item_indices
0
python create mapping from value to index of a list
Return dict mapping item - > indices .
cosqa-train-18892
def _duplicates(list_): """Return dict mapping item -> indices.""" item_indices = {} for i, item in enumerate(list_): try: item_indices[item].append(i) except KeyError: # First time seen item_indices[item] = [i] return item_indices
def fetchallfirstvalues ( self , sql : str , * args ) -> List [ Any ] : rows = self . fetchall ( sql , * args ) return [ row [ 0 ] for row in rows ]
0
how to get first 5 rows from sql in python
Executes SQL ; returns list of first values of each row .
cosqa-train-18893
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 remove_blank_lines ( string ) : return "\n" . join ( line for line in string . split ( "\n" ) if len ( line . strip ( ) ) )
1
how to not except empty string python
Removes all blank lines in @string
cosqa-train-18894
def remove_blank_lines(string): """ Removes all blank lines in @string -> #str without blank lines """ return "\n".join(line for line in string.split("\n") if len(line.strip()))
def is_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
how to see if a line matches in a file python
Detects whether a line is present within a file .
cosqa-train-18895
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 name_is_valid ( name ) : # The name can only be 80 characters long. if len ( name ) > MAX_NAME_LENGTH : return False return bool ( NAME_VALID_CHARS_REGEX . match ( name ) )
1
how to check if a variable name is valid in python
Return True if the dataset name is valid .
cosqa-train-18896
def name_is_valid(name): """Return True if the dataset name is valid. The name can only be 80 characters long. Valid characters: Alpha numeric characters [0-9a-zA-Z] Valid special characters: - _ . """ # The name can only be 80 characters long. if len(name) > MAX_NAME_LENGTH: return False return bool(NAME_VALID_CHARS_REGEX.match(name))
def get_column_names ( engine : Engine , tablename : str ) -> List [ str ] : return [ info . name for info in gen_columns_info ( engine , tablename ) ]
1
access database python retreive column names
Get all the database column names for the specified table .
cosqa-train-18897
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 safe_pow ( base , exp ) : if exp > MAX_EXPONENT : raise RuntimeError ( "Invalid exponent, max exponent is {}" . format ( MAX_EXPONENT ) ) return base ** exp
0
add exponents by the power of 2 in python
safe version of pow
cosqa-train-18898
def safe_pow(base, exp): """safe version of pow""" if exp > MAX_EXPONENT: raise RuntimeError("Invalid exponent, max exponent is {}".format(MAX_EXPONENT)) return base ** exp
def __rmatmul__ ( self , other ) : return self . T . dot ( np . transpose ( other ) ) . T
1
python how to multiply matrix
Matrix multiplication using binary
cosqa-train-18899
def __rmatmul__(self, other): """ Matrix multiplication using binary `@` operator in Python>=3.5. """ return self.T.dot(np.transpose(other)).T