content stringlengths 42 6.51k |
|---|
def PrettySize(size):
"""Returns a size in bytes as a human-readable string."""
units = 'BKMGT'
unit = 0
# By the time we get to 3072, the error caused by
# shifting units is <2%, so we don't care.
while size > 3072 and unit < len(units) - 1:
size /= 1024
unit += 1
return '{:1.1f}{}'.format(size... |
def round_down(number, base=1):
"""
Args:
number (float/int)
base (float/int)
Example:
| for i in range(11):
| print(i, round_down(i,5))
| (0, 0)
| (1, 0)
| (2, 0)
| (3, 0)
| (4, 0)
| (5, 5) # does not round down if remainder is zero
... |
def table_is_empty(db_session, table_name, query_id):
"""Check to see if a portion of the table is empty."""
try:
c = db_session.cursor()
if table_name == "albums": # albums
c.execute("""SELECT 1 FROM %s WHERE artist_id = ? LIMIT 1""" % table_name, [query_id])
elif table_name... |
def get_commit_id(build_info):
"""Fetch the git commit id from the build info json object."""
actions = build_info.get('actions')
build_data = next(
a for a in actions
if a.get('_class') == 'hudson.plugins.git.util.BuildData')
if not build_data:
raise ValueError('Missing BuildData: %s' % build_i... |
def extract_column(col_num, table):
"""
Extract a list representing a column from 2
dimensional list
INPUTS:
col_num - determines which item in the row will be
extracted
table - 2 dimensional list. Each inner list represents
one 1 row in the table
"""
... |
def format_number(number, number_of_digits):
"""
The function format_number() return a string-representation of a number
with a number of digits after the decimal separator.
If the number has more digits, it is rounded.
If the number has less digits, zeros are added.
@param number: the number t... |
def calc_seconds(seconds: int) -> int:
"""
Calculate seconds
:param seconds:
:return:
"""
if seconds < 60:
return seconds
return seconds % 60 |
def _open_file(f, mode):
"""Opens a file if a string is provided, otherwise leaves the file open.
Parameters
----------
f : str or file
The open file or filename.
mode : str
The file mode for builtin function `open` (r, w, ...).
Returns
-------
file
The desired ... |
def extract_number_from_money(string):
"""
Extract number from string following this pattern:
$130,321 -> 130321
Also will round to 2 decimal places
"""
try:
trimmed = string.replace(",", "").replace("$", "").replace(" ", "").strip()
number = float(trimmed)
return round(n... |
def build_complement(dna):
"""
:param dna: string, the dna that was input
:return: string, the complement of the user's dna
"""
dna = dna.upper()
result = ''
for i in range(len(dna)):
ch = dna[i]
if ch == 'A':
result += 'T'
elif ch == 'T':
resu... |
def filter_date_range_for_carbs(
starts, values, absorptions,
start_date,
end_date
):
""" Returns an array of elements filtered by the specified date range.
Arguments:
starts -- start dates (datetime)
values -- carb values (g)
absorptions -- absorption times for entr... |
def determine_site_type(name, website):
""" The name (or website) of a Federal Site in this list provides an
indication of what type of site it might be. This extracts that out. """
name_fragments = [
(' BLM', 'BLM'), (' NF', 'NF'), ('National Forest', 'NF'),
(' NWR', 'NWR'), (' NHS', 'NHS... |
def get_fewest(list_of_counts, num):
"""returns the layer with the fewest of the number
"""
number_seq = [d[num] for d in list_of_counts]
loc = number_seq.index(min(number_seq))
return list_of_counts[loc] |
def get_center_location(N, M):
"""
Function: get_center_location\n
Parameters: N -> Number of rows in the Grid, M -> Number of columns in the Grid\n
Returns: a tuple of center location of the disaster area\n
"""
x = N // 2
y = M // 2
return (x, y) |
def extract_cols_from_data_type(data_type, column_definition,
excluded_input_types):
"""Extracts the names of columns that correspond to a define data_type.
Args:
data_type: DataType of columns to extract.
column_definition: Column definition to use.
excluded_input_ty... |
def str_to_bool(parameter):
"""
Utility for converting a string to its boolean equivalent.
"""
if isinstance(parameter, bool):
return parameter
if parameter.lower() in {'false', 'f', '0', 'no', 'n'}:
return False
elif parameter.lower() in {'true', 't', '1', 'yes', 'y'}:
r... |
def dst_main_directory(library: str) -> str:
"""
Main directory for report files resulting from
the reconciliation process.
"""
return f"./files/{library}" |
def get_searched_index(graph, start, nodes_count):
"""
Returns a dictionary with a key for each node in the graph with an integer
initialized to the total number of nodes, which is more than the maximum
number of levels, since we're counting levels from 0, so it can double as
a bool indicating wheth... |
def tryint(str):
"""
Returns an integer if `str` can be represented as one.
:param str: String to check.
:type str: string
:returns: int(str) if str can be cast to an int, else str.
:rtype: int or str
"""
try:
return int(str)
except:
return str |
def rename_relation(relation, mapping):
"""
Takes a tuplized relational attribute (e.g., ``('before', 'o1', 'o2')``)
and a mapping and renames the components based on the mapping. This
function contains a special edge case for handling dot notation which is
used in the NameStandardizer.
:param ... |
def make_alignment_line(strand, kmer, prob, event):
"""Convert strand, kmer, probability and event to a correctly formatted alignment file line
:param strand: 't' or 'c' representing template or complement strand of read
:param kmer: nucleotide kmer
:param prob: probability of kmer coming from certain e... |
def to_dir_str(str_):
"""Convert a str to a str that can be used as a dir path. Specifically,
* remove spaces
* remove '
* replace [] with ()
"""
str_ = str_.replace(" ", "")
str_ = str_.replace("'", "")
str_ = str_.replace("[", "(")
str_ = str_.replace("]", ")")
ret... |
def fromRGB(rgb: str):
"""
convert rgb string to 3 element list suitable for passing to OpenGL
"""
return [int(rgb[2 * i: 2 * i + 2], 16) / 255 for i in range(3)] |
def xtick_formatter(x, pos):
"""
A formatter used in main_paper function to divide
ticks by specific amount.
From Stackoverflow #27575257
"""
s = '%d' % int(x / 1000)
return s |
def float_sec_to_int_sec_nano(float_sec):
"""
From a floating value in seconds, returns a tuple of integer seconds and
nanoseconds
"""
secs = int(float_sec)
nsecs = int((float_sec - secs) * 1e9)
return (secs, nsecs) |
def mean(data):
""" Return the sample arithmetic mean of data. """
n = len(data)
if n < 1:
raise ValueError('mean requires at least one data point')
return sum(data)/n |
def break_up_whiles(vba_code):
"""
Break up while statements like 'While(a>b)c = c+1'.
"""
# Can we skip this?
vba_code_l = vba_code.lower()
if ("while" not in vba_code_l):
return vba_code
# Look for single line while statements.
pos = 0
changes = {}
vba_code += "\n"
... |
def check_policy_for_encryption(event):
"""
Check for encryption in S3 bucket policy.
Checks the event for a bucket policy PUT. Loops through and checks for either AES256 or
AWS:KMS. Otherwise, trigger a violation.
"""
try:
for statement in event["detail"]["requestParameters"]["bucket... |
def off_stoich(conc):
"""
works out, for the lattice parameters of t-LLZO, defects per formula unit from defects per cubic cm
args:
number (float): defect per cubic cm
returns:
per_cubic_cm: defect per formula unit
"""
per_cubic_angstrom = conc / 1e+24
per_unit_cell = per_cub... |
def urlquerybase(url):
"""
Appends '?' or '&' to an url, so you can easily add extra GET parameters.
"""
if url:
if '?' in url:
url += '&'
else:
url += '?'
return url |
def average(values, lazy=False):
"""Calculate the average of a given number of values.
:param values: The values to be averaged.
:type values: list | tuple
:param lazy: When ``True`` zeroes (0) are removed before averaging.
:type lazy: bool
:rtype: float
Ever get tired of creating a try/... |
def which_set(filename_hash, validation_percentage, testing_percentage):
"""
Code adapted from Google Speech Commands dataset.
Determines which data split the file should belong to, based
upon the filename int hash.
We want to keep files in the same training, validation, or testing
sets even i... |
def list_without_element(array, element):
"""Returns a new list that doesn't contain the element"""
copy = array.copy()
copy.remove(element)
return copy |
def fill_mask(row, col, height, width, orig_img):
"""
Fill the mask cell with the nearest neighbour pixel of image
Params:
col, type(int)
row, type(int)
height, type(int)
width, type(int)
"""
# select a value from neighbour
fill_val_1 = 255
fill_val_2 = 255
fill_... |
def get_pathways_from_statement(mapping_statement, mapping_type):
"""Return the subject, object of the mapping.
:param str mapping_statement: statement
:param str mapping_type: type of relationship
:rtype: tuple[str,str]
"""
_pathways = mapping_statement.split(mapping_type)
return _pathway... |
def call_name(argt):
""" current call name
"""
argv, pos = argt
cmd_str = ' '.join(argv[:pos])
return cmd_str |
def isAlphanum(c):
"""return true if the character is a letter, digit, underscore,
dollar sign, or non-ASCII character.
"""
return ((c >= 'a' and c <= 'z') or (c >= '0' and c <= '9') or
(c >= 'A' and c <= 'Z') or c == '_' or c == '$' or c == '\\' or (c is not None and ord(c) > 126)); |
def sort_by_keys(xs, keys, reverse=True):
"""Sort list of xs by a list of identical length keys
Args:
xs: List of items to rank
keys: Numerical values against which to sort.
reverse: If True, sort by descending order (we want the examples of highestt difference). Otherwise, sort asc... |
def get_prop_type(value, key=None):
"""
Performs typing and value conversion for the graph_tool PropertyMap class.
If a key is provided, it also ensures the key is in a format that can be
used with the PropertyMap. Returns a tuple, (type name, value, key)
"""
"""
if isinstance(key, unicode):... |
def set_value_in_place(target_object, key, new_value):
"""
updates the value at key in the given object in place
:param target_object: the object to change the value of
:param key: the key to change - can be a path like color/r for the key r in the underlying object color
:param new_value: the... |
def nested_format(data, default, tab_level=1):
"""
Print a human readable nested dictionary or nested list.
Parameters
----------
data : `object`
Data to print.
default: `bool`
Indicator indicating if a value is a default.
tab_level : `int`
Number of tabs to ind... |
def get_hour(date):
"""takes in date from javascript/flask, and sets the variable hour to
what the hour is
>>> get_hour("Tue Apr 23 2019 23:19:57 GMT-0400 (Eastern Daylight Time)")
'23'
>>> get_hour("Wed Apr 24 2019 06:59:38 GMT+0300 (Asia Qatar Standard Time)")
'06'
"""
a = date.find(... |
def format_seconds(seconds, hide_seconds=False):
"""
Returns a human-readable string representation of the given amount
of seconds.
"""
if seconds <= 60:
return str(seconds)
output = ""
for period, period_seconds in (
('y', 31557600),
('d', 86400),
('h', 3600)... |
def get_titgroup_type_from_titgroup(group):
"""Given a titratable group unique id e.g. (A:0112:CTERM), return the titgroup type (CTERM)"""
return group.split(':')[-1] |
def join_args(*arglists):
"""Join split argument tokens."""
return ", ".join(arg for args in arglists for arg in args if arg) |
def _find_scope_defining_line(line_index, file_content):
"""Finds the scope defining line for the line on the specified index.
The scope defining line is the last line containing `{` that was not closed afterwards.
If the scope defining line could not be found, returns (`-1`, `None`).
Args:
l... |
def str2hex(src: str):
"""python ->707974686f6e"""
bytes_src = bytes(src, encoding='utf-8')
return bytes_src.hex() |
def corr(x, y):
"""
Correlation of 2 causal signals, x(t<0) = y(t<0) = 0, using discrete
summation.
Rxy(t) = \int_{u=0}^{\infty} x(u) y(t+u) du = Ryx(-t)
where the size of x[], y[], Rxy[] are P, Q, N=P+Q-1 respectively.
The Rxy[i] data is not shifted, so relationship with the continuous
... |
def selectDegrees(degree_root, index_left, index_right, degree_left,
degree_right):
"""
Select the which degree to be next step.
"""
if index_left == -1:
degree_now = degree_right
elif index_right == -1:
degree_now = degree_left
elif (abs(degree_left - degree_r... |
def stringified(value, converter=None, none="None"):
"""
Args:
value: Any object to turn into a string
converter (callable | None): Optional converter to use for non-string objects
none (str | bool | None): Value to use to represent `None` ("" or False represents None as empty string)
... |
def tokenize(buffer):
""" tokenizes a JSON string """
tokens = []
maxIndex = len(buffer)-1
index = 0
while index <= maxIndex:
if buffer[index] in ["{", "}", ":", ",", "[", "]"]:
tokens.append(buffer[index])
index += 1
elif buffer[index] in ".1234567890":
... |
def get_pad_params(desired_size, cur_size):
"""
Get padding parameters for np.pad function
Args:
desired_size: int, Desired padded output size
cur_size: int, Current size. Should always be less than or equal to cur_size
Returns:
pad_params: tuple(int), Number of values padded to ... |
def sizeof_fmt(num, dec = 3, kibibyte = False):
"""Byte size formatting utility function."""
prefixes = None
factor = None
if kibibyte:
factor = 1024.0
prefix = ['bytes','KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB']
else:
factor = 1000.0
prefix = ['bytes','KB','MB','GB','TB','PB','EB','ZB','YB']
for x ... |
def parent_request_dict(ts_epoch):
"""A parent request represented as a dictionary."""
return {
'system': 'parent_system',
'system_version': '1.0.0',
'instance_name': 'default',
'command': 'say',
'id': '58542eb571afd47ead90d25f',
'parent': None,
'parameter... |
def debug_scale_cut_point_diameter(scaled_diameter, scale):
"""
Returns a new scaled diameter for visual debugging of cut-point nodes.
:param scaled_diameter: The current, scaled node diameter
:param scale: The scaling factor
:return: New diameter for cut node
"""
return max(2 * scale, scale... |
def gf_mod(a, r, m=64, n=32):
""" generic galois-field modulo return a [X^n+r], deg(a) < m """
assert m >= n
mod = (r << (m - n)) ^ (1 << m)
mask = (2^n - 1)
rem = a
for i in range(m,n-1,-1):
if rem & (1 << i):
rem ^= mod
mod = mod >> 1
return rem |
def upperBound(sortedCollection, item, key=lambda x: x):
"""
Given a sorted collection, perform binary search to find element x for which
the following holds: item < key(x) and the value key(x) is the smallest.
Returns index of such an element.
"""
lo = 0
hi = len(sortedCollection)
while... |
def IsVersionNewer(cur_version, new_version):
"""Determines if new Chrome version is higher than the installed one.
Args:
cur_version: Current version of Chrome.
new_version: New version that will be installed.
Returns:
True, if new version is higher, otherwise False.
"""
if cur_version == new_v... |
def asList( o ):
"""Convert to a list if not already one"""
if not isinstance( o, list ):
return list(o)
return o |
def add(x, y):
"""Adds x and y. The left arg x is the accumulated value, the right argument y is the value form the sequence
x: -3, y: 0
x: -3, y: 1
x: -2, y: 2
x: 0, y: 3
x: 3, y: 4
Applied 5 times to list numbers, first time takes in the initial value and the first number, adds them and s... |
def names_of_defined_flags():
"""Returns: List of names of the flags declared in this module."""
return ['tmod_bar_x',
'tmod_bar_y',
'tmod_bar_z',
'tmod_bar_t',
'tmod_bar_u',
'tmod_bar_v'] |
def check_not_finished_board(board: list):
"""
Check if skyscraper board is not finished, i.e., '?' present
on the game board.
Return True if finished, False otherwise.
>>> check_not_finished_board(['***21**', '4?????*', '4?????*',\
'*?????5', '*?????*', '*?????*', '*2*1***'])
False
>>> ... |
def filter_dicom(dcmdata):
"""Return True if a DICOM dataset should be filtered out, else False"""
comments = getattr(dcmdata, 'ImageComments', '')
if len(comments):
if 'reference volume' in comments.lower():
print("Filter out image with comment '%s'" % comments)
return True
... |
def _mod_name_key(typ):
"""Return a (__module__, __name__) tuple for a type.
Used as key in Formatter.deferred_printers.
"""
module = getattr(typ, '__module__', None)
name = getattr(typ, '__name__', None)
return (module, name) |
def list2int(x):
"""
Converts a binary list to number
"""
return int("".join(str(i) for i in x), 2) |
def taum_bday(b, w, bc, wc, z):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/taum-and-bday/problem
Taum is planning to celebrate the birthday of his friend, Diksha. There are two types of gifts that Diksha wants
from Taum: one is black and the other is white. To make her happy, Taum has to ... |
def _get_drive_distance(maps_response):
"""
from the gmaps response object, extract the driving distance
"""
try:
return maps_response[0].get('legs')[0].get('distance').get('text')
except Exception as e:
print(e)
return 'unknown distance' |
def top_sentences(query, sentences, idfs, n):
"""
Given a `query` (a set of words), `sentences` (a dictionary mapping
sentences to a list of their words), and `idfs` (a dictionary mapping words
to their IDF values), return a list of the `n` top sentences that match
the query, ranked according to idf... |
def version_to_int(version: str):
"""
>>> version_to_int('3.2.1')
30201
>>> version_to_int('30.2.1')
300201
>>> version_to_int('2.1')
201
>>> version_to_int('2.x.1')
20001
>>> version_to_int('4.10.25')
41025
"""
parts = version.split('.')
result = 0
for i,... |
def viz_white(body, bgcolor="white"): # pylint: disable=unused-argument
"""Create hidden text for graphviz"""
return '<FONT COLOR="{bgcolor}">{body}</FONT>'.format(**locals()) |
def all_neg(literals):
"""
>>> all_neg(['x1', 'x2', 'x3'])
'!x1 !x2 !x3'
>>> all_neg(['x1'])
'!x1'
"""
return "!" + " !".join(literals) |
def _make_divisible(v, divisor=4, min_value=None):
"""
It ensures that all layers have a channel number that is divisible by 4
"""
if min_value is None:
min_value = divisor
new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
# Make sure that round down does not go down by m... |
def label_to_color_codex(label):
"""
Takes in a label for a fitting polynomial
:param label:
:return:
"""
fingerprint = label.split(',')
fingerprint = [x.split(':') for x in fingerprint]
fingerprint = {x[0] :x[1] for x in fingerprint}
for key in ['deg' ,'fraction_size' ,'chunk' ,'coe... |
def _float(v):
"""
>>> _float('5')
5.0
>>> _float('Abacate')
nan
"""
try:
return float(v)
except Exception:
return float("nan") |
def to_days(astring, unit):
""" No weeks in QUDT unit library: days or years """
factors = {
"week": 7.0, "weeks": 7.0,
"Week": 7.0, "Weeks": 7.0,
"day": 1.0, "Day": 1.0,
"days": 1.0, "Days": 1.0,
... |
def _float_list(str_list):
"""
Converts all items in the given list to floats.
Most other conversion functions take strings. But the readers for items.csv
and key_bindings.csv aggregate several columns into a single value before
passing them to the DataStore.
This is probably confusing. I'm sorry.
"""
... |
def practice_problem2a(sequence, delta):
"""
What comes in:
-- A sequence of integers, e.g. ([2, 10, 5, -20, 8])
-- A number delta
What goes out:
-- Returns a new list that is the same as the given list,
but with each number in the list having had the given
delta
... |
def get_common_actors(first_movie_cast, second_movie_cast):
"""
Takes two arrays of movie casts, first_movie_cast and second_movie_cast
Returns an array of actors that are common to both movies
"""
common_actors = []
for first_actor in first_movie_cast:
for second_actor in second_movie_cast:
if fi... |
def get_label_names(l_json):
"""
Get names of all the labels in given json
:param l_json: list of labels jsons
:type l_json: list
:returns: list of labels names
:rtype: list
"""
llist = []
for j in l_json:
llist.append(j['name'])
return llist |
def hash_dict(d):
"""
Sorts the dict's keys, then returns the dict in a standardized string form
"""
keys = sorted(list(d.keys()))
if len(keys)==0: return "{}"
s = "{"
for k in keys[:-1]:
s += "%s: %s, "%(repr(k), repr(d[k]))
k = keys[-1]
s += "%s: %s}"%(repr(k), repr(d[k]))
... |
def _state_return(ret):
"""
Return True if ret is a Salt state return
:param ret: The Salt return
"""
ret_data = ret.get("return")
if not isinstance(ret_data, dict):
return False
return ret_data and "__id__" in next(iter(ret_data.values())) |
def check_string(seq):
"""Checks if seq is a string"""
if not isinstance(seq, str):
assert False, "Input is not a string."
else:
pass
return None |
def thresholdToCssName(threshold):
"""
Turn a floating point threshold into a string that can be used as a CSS
class name.
param threshold: The C{float} threshold.
return: A C{str} CSS class name.
"""
# '.' is illegal in a CSS class name.
return 'threshold-' + str(threshold).replace('.'... |
def individual_summary_format(filename, summary_dict):
"""
@param filename: the pileup file name, the dict refers to
@param summary_dict: the summary dict of the pileup file
@return: a string that represent the summary dict : pileup_filename\nchange:percentage\tchange:percentage\t...
"""
summ... |
def _is_valid_perm(perm):
"""Check string to be valid permission spec."""
for char in perm:
if char not in 'rwcda':
return False
return True |
def get_context_object(context):
"""
Try to return the object instance in the context. On Except, bubble the
exeption to the call.
"""
try:
obj = context['object']
return obj
except Exception:
raise |
def find_parent_split(node, orientation):
"""
Find the first parent split relative to the given node
according to the desired orientation
"""
if (node and node.orientation == orientation
and len(node.children) > 1):
return node
if not node or node.type == "workspace":
r... |
def parens(n):
""" 8.9 Parens: Implement an algorithm to print all valid
(e.g., properly opened and closed) combinations of n pairs of parentheses.
Example:
Input: 3
Output: ( ( () ) ) , ( () () ) , ( () ) () , () ( () ) , () () ()
"""
if n <= 0:
return []
if n == 1:
ret... |
def base64_add_padding(string):
"""
Add padding to a URL safe base64 string.
:param string: Non-padded Url-safe Base64 string.
:return: Padded Url-safe Base64 string.
"""
while len(string) % 4 != 0:
string += "="
return string |
def urljoin(*args):
"""
There's probably a better way of handling this.
"""
return "/".join(map(lambda x: str(x).rstrip('/'), args)) |
def take(n, collection):
"""Returns at most n items from the collection in a list
>>> take(4, range(100000, 1000000, 4))
[100000, 100004, 100008, 100012]
>>> take(10, ['hello', 'world'])
['hello', 'world']
"""
return [item for item, _ in zip(collection, range(n))] |
def oo_haproxy_backend_masters(hosts, port):
""" This takes an array of dicts and returns an array of dicts
to be used as a backend for the haproxy role
"""
servers = []
for idx, host_info in enumerate(hosts):
server = dict(name="master%s" % idx)
server_ip = host_info['openshift'... |
def get_ema_vars(ema, model):
"""Get ema variables."""
if ema:
try:
return {
ema.average(v).name: ema.average(v) for v in model.trainable_variables
}
except: # pylint: disable=bare-except
ema.apply(model.trainable_variables)
return {
ema.average(v).name: ema.aver... |
def to_regexp(seq: str) -> (str):
"""
Convert IUPAC to regular expresions.
Decodes a sequence which is IUPAC and convert
this to a regular expression friendly sequence.
:param seq: the sequence to encode
:return: the regular expression
"""
# convert IUPAC bases
seq = seq... |
def pack(join, alist):
"""Interleave a list with a value
This function interleaves a list of values with the joining
element.
Params:
join -- The value to be interleaved within the list
alist -- The supplied list
Returns:
A new list
pack("a",[1,2,3,4]) ==> ["a",1... |
def create_dictionary(item_list):
"""
Create a dictionary of items from a list of list of items.
"""
assert type(item_list) is list
dictionary = {}
for items in item_list:
for item in items:
if item not in dictionary:
dictionary[item] = 1
else:
... |
def _find_index(host_port, cluster_spec):
"""
Args:
host_port:
cluster_spec:
Returns:
"""
index = 0
for entry in cluster_spec["cluster"]["worker"]:
if entry == host_port:
return index
else:
index = index + 1
return -1 |
def unit_vector(vector):
"""
Calculate a unit vector in the same direction as the input vector.
Args:
vector (list): The input vector.
Returns:
list: The unit vector.
"""
length = sum([v ** 2 for v in vector]) ** 0.5
unit_vector_ = [v / length for v in vector]
return un... |
def to_set(arg1):
"""Converts the given argument to a set.
Examples:
>>> to_set(1)
{1}
>>> to_set([1, 2, 3])
{1, 2, 3}
.. warning:: This function does not work with :obj:`range` objects, and maybe some others.
"""
try:
set1 = {arg1}
except TypeError:
... |
def get_github_page(pypi_pkg):
"""Retrieve github page URL if available"""
github_page = ""
# Check potential fields for a github link
potential_github_fields = [pypi_pkg["pypi_data"]["info"]["home_page"]]
# Add project url fields
for _, url in pypi_pkg["pypi_data"]["info"]["project_urls"].item... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.