content stringlengths 42 6.51k |
|---|
def set_difference(set_a, set_b):
"""
compare two sets and return the items
which are in set_b but not in set_a
"""
diff = set_b - set_a
return diff |
def _remove_function_tags(label):
"""
Parameters
----------
label: str
Returns
-------
str
"""
if "-" in label and not label in ["-NONE-", "-LRB-", "-RRB-", "-LCB-", "-RCB-"]:
lst = label.split("-")
label = lst[0]
if "=" in label:
lst = label.split("=")
... |
def replace_variables_from_array(arr, s):
"""Takes a string and replaces variables in the string with ones from the array
#Example: (['R10', '5', 'R1', '7'], 'example string R1 and R10') -> 'example string 7 and 5'
:param arr: Array of variables
:param s: String to replace variables in
:return: Str... |
def collect_frequency(simulations):
"""
Calculates the frequency at which sub processes should collect intermediary results for plotting
This is done to ensure that the total number of data points loaded in the charts don't break the
matplotlib chart generation. Based on our tests this number seems to b... |
def _get_branching(container, index):
""" Returns the nearest valid element from an interable container.
This helper function returns an element from an iterable container.
If the given `index` is not valid within the `container`,
the function returns the closest element instead.
Parameter
---... |
def _process_sort_info(sort_info_lst):
""" Split out the zpe and sp sort info
"""
freq_info = None
sp_info = None
sort_prop = {}
if sort_info_lst is not None:
freq_info = sort_info_lst[0]
sp_info = sort_info_lst[1]
if sort_info_lst[2] is not None:
sort_prop['e... |
def unclean_map_javac_to_antlr(javac_token_literal, antlr_literal_rule):
"""
merge ('TOKEN_ID', 'literal value'), ('literal value', 'RULE_NAME') arrays
this is NOT one to one
"""
copy_javac_tl = list(javac_token_literal)
copy_antlr_lt = list(antlr_literal_rule)
copy_javac_tl.reverse()
c... |
def format(string: str, **kwargs) -> str:
"""A string formatter
example:
> n = '$[val]'
> val = "Hello, World!"
> print(format(n, val=val))
Hello, World!
"""
for key,val in kwargs.copy().items():
string.replace(f"$[{key}]", val)
return strin... |
def dollars_to_changes(dollars, dollar_vals):
"""Given a dollars amount (e.g. $8.74), and a list of dollar_values
in descending values (e.g. [5, 1, 0.50, 0.25, 0.10, 0.05, 0.01]),
return a list of tuples of changes.
E.g. [(5, 1), (1, 3), (0.5, 1), (0.1, 2), (0.01, 4)]
"""
cents = int(dolla... |
def _as_parent_key(parent, key):
"""Construct parent key."""
if parent:
return f"{parent}.{key}"
return key |
def sort_labels(labels):
"""Guess what this Sorts the labels
:param labels:
:type labels: list
:return :
:rtype : list
"""
return sorted(labels, key=lambda name: (name[1:], name[0])) |
def start(data):
"""
Get the start coordinate as an int of the data.
"""
value = data["genome_coordinate_start"]
if value:
return int(value)
return None |
def solution1(string):
"""
:type string: str
:rtype: int
"""
stack = []
score = 0
left = True # `left` indicates the if former symbol is '('
for p in string:
if p == '(':
stack.append(p)
left = True
else:
stack.pop()
if l... |
def while_condition(string_unsorted_list):
"""."""
num_lengths = []
for num in string_unsorted_list:
num_lengths.append(len(num))
return max(num_lengths) |
def get_bool(v):
"""Get a bool from value."""
if str(v) == '1' or v == 'true' or v is True:
return True
elif str(v) == '0' or v == 'false' or v is None or v is False:
return False
else:
raise ValueError(f'value {v} was not recognized as a valid boolean') |
def parse_filename(fname):
"""Parse a notebook filename.
This function takes a notebook filename and returns the notebook
format (json/py) and the notebook name. This logic can be
summarized as follows:
* notebook.ipynb -> (notebook.ipynb, notebook, json)
* notebook.json -> (notebook.json, no... |
def decomposeQuadraticSegment(points):
"""Split the quadratic curve segment described by 'points' into a list
of "atomic" quadratic segments. The 'points' argument must be a sequence
with length 2 or greater, containing (x, y) coordinates. The last point
is the destination on-curve point, the rest of the points are... |
def _filter_empty_field(data_d):
"""
Remove empty lists from dictionary values
Before: {'target': {'CHECKSUM': {'checksum-fill': []}}}
After: {'target': {'CHECKSUM': {'checksum-fill': ''}}}
Before: {'tcp': {'dport': ['22']}}}
After: {'tcp': {'dport': '22'}}}
"""
for k, v in data_d.item... |
def get_prefix_less_name(element):
""" Returns a prefix-less name
:param elements: element top use on the search
:type elements: str
:return: The prefix-less name
:rtype: str
"""
return element.split("|")[-1].split(":")[-1] |
def parse_stock_code(code: str):
"""Parses a stock code. NOTE: Only works for the Shinhan HTS"""
if code.startswith("A"):
return code[1:]
elif code == "":
return None
else:
return code |
def escape_string(value: str) -> str:
""" Escape control characters"""
if value:
return value.replace("\n", "\\n").replace("\r", "").replace('"', "'")
return "" |
def order_data(data, byte_order):
"""
Reordena los datos segun el byte_order de la variable/item
"""
A_inx = byte_order.index("A") if "A" in byte_order else 0
B_inx = byte_order.index("B") if "B" in byte_order else 0
C_inx = byte_order.index("C") if "C" in byte_order else 0
D_inx = byte_orde... |
def xor(a, b):
""" Renvoie a xor b. """
x = [False]*len(a)
for i in range(len(a)):
x[i] = a[i] ^ b[i]
return x |
def add(u, v):
"""
Returns the vector addition of vectors u + v
"""
if len(u) != len(v):
raise ValueError("Vectors lengths differ {} != {}".format(len(u),
len(v)))
return tuple(e + g for e, g in zip(u, v)) |
def search_person(lista, nombre):
""" Buscar persona en lista de personas.
Buscamos un nombre en una lista de instancias
de la clase Person.
En caso de que se encuentre regresamos su
indica, en otro caso regresamos -1
Hay que tener cuidado con este valor porque
-1 es un valo... |
def remove(text, targets):
"""."""
for key, val in targets.items():
if key in text:
text = text.replace(key, '', val)
return text |
def convert_time_to_hour_minute(hour, minute, convention):
"""
Convert time to hour, minute
"""
if hour is None:
hour = 0
if minute is None:
minute = 0
if convention is None:
convention = 'am'
hour = int(hour)
minute = int(minute)
if convention.lower() == 'p... |
def dump_rank_records(rank_records, out_fp, with_rank_idx):
"""
each line is
ranking sid score
sid: config.SEP.join((doc_idx, para_idx, sent_idx))
:param sid_score_list:
:param out_fp:
:return:
"""
lines = rank_records
if with_rank_idx:
lines = ['\t'.j... |
def is_asking_nextEvent(text):
"""
Checks if user is asking for next event.
Parameters: text (string): user's speech
Returns: (bool)
"""
state = False
keyword = [
"event",
"events",
"timetable",
"class"
]
for word in keyword:
if ((text.lower(... |
def format_text(text):
""" Foramt text """
string = ""
for i in text:
string += i
return string |
def getTokenType(hueChange: int, lightChange: int) -> str:
"""
Find the toColorToken type based on hue change and lightness change
:param hueChange: number of hue changes between two pixels
:param lightChange: number of lightness changes between two pixels
:return: A string with the toColorToken typ... |
def _service_account_name(service_acct_email):
"""Gets an IAM member string for a service account email."""
return 'serviceAccount:{}'.format(service_acct_email) |
def remove_empty_elements(value):
"""
Recursively remove all None values from dictionaries and lists, and returns
the result as a new dictionary or list.
"""
if isinstance(value, list):
return [remove_empty_elements(x) for x in value if x is not None]
elif isinstance(value, dict):
... |
def is_number(s):
""" Returns True is string is a number. """
try:
float(s)
return True
except ValueError:
return False |
def t_and_beta_to_varcope(t, beta):
"""Convert t-statistic to sampling variance using parameter estimate.
.. versionadded:: 0.0.4
Parameters
----------
t : array_like
T-statistics of the parameter
beta : array_like
Parameter estimates
Returns
-------
varcope : arra... |
def scale_frame_size(frame_size, scale):
"""Scales the frame size by the given factor.
Args:
frame_size: a (width, height) tuple
scale: the desired scale factor
Returns:
the scaled (width, height)
"""
return tuple(int(round(scale * d)) for d in frame_size) |
def x_www_form_urlencoded(post_data):
""" convert origin dict to x-www-form-urlencoded
Args:
post_data (dict):
{"a": 1, "b":2}
Returns:
str:
a=1&b=2
"""
if isinstance(post_data, dict):
return "&".join([
u"{}={}".format(key, value)
... |
def sparse_clip_norm(parameters, max_norm, norm_type=2):
"""Clips gradient norm of an iterable of parameters.
The norm is computed over all gradients together, as if they were
concatenated into a single vector. Gradients are modified in-place.
Supports sparse gradients.
Parameters
----------
... |
def ipv4_arg_to_bin(w, x, y, z):
"""Generate unsigned int from components of IP address
returns: w << 24 | x << 16 | y << 8 | z"""
return (w << 24) | (x << 16) | (y << 8) | z |
def str_to_int(string):
"""Solution to exercise R-4.7.
Describe a recursive function for converting a string of digits into the
integer it represents. For example, "13531" represents the integer 13,531.
"""
n = len(string)
zero_unicode = ord('0')
def recurse(idx):
if idx == n:
... |
def _HexToSignedInt(hex_str):
"""Converts a hex string to a signed integer string.
Args:
hex_str: A string representing a hex number.
Returns:
A string representing the converted signed integer.
"""
int_val = int(hex_str, 16)
if int_val & (1 << 31):
int_val -= 1 << 32
return str(int_val) |
def sum_square_difference(n: int) -> int:
"""
Returns the "sum square difference" of the first n natural numbers.
"""
square_of_sum = (n*(n+1) // 2)**2
sum_of_squares = n*(n+1)*(2*n+1) // 6
return square_of_sum - sum_of_squares |
def islamic_date(year, month, day):
"""Return an Islamic date data structure."""
return [year, month, day] |
def audio_len(audio):
"""
>>> audio_len(([1, 2, 3], [4, 5, 6]))
3
"""
(left, right) = audio
assert len(left) == len(right)
return len(left) |
def FIT(individual):
"""Sphere test objective function.
F(x) = sum_{i=1}^d x_i^2
d=1,2,3,...
Range: [-100,100]
Minima: 0
"""
y = sum(x**2 for x in individual)
return y |
def check_roles(role_required, role_list):
"""Verify string is within the list.
:param string role_required: The string to find
:param list role_list: The list of user roles
:return boolean: True or False based on whether string was found
"""
for index, role in enumerate(role_list):
if... |
def process_group(grp):
"""
Given a list of tokens of tokens
where the first row is a number
and the second (also last) row contains
an `x` or a number separated by ','
, compute the product of additive inverse of
some minimum modular residue with its corresponding
value from the second ... |
def logEq(a, b):
"""Returns 1 if the logical value of a equals the logical value of b, 0 otherwise"""
return (not a) == (not b) |
def get_attempt_data(all_gens):
"""
Extracts the attempt data of succesful generations
all_gens - dict of key nodeID
value list of (nodeID, createTime, attempts, (createID, sourceID, otherID, mhpSeq))
:return: dict of dicts
A dict with keys being nodeIDs and values be... |
def context_combination(
windows,
use_docker,
use_celery,
use_mailhog,
use_sentry,
use_whitenoise,
cloud_provider,
):
"""Fixture that parametrize the function where it's used."""
return {
"windows": windows,
"use_docker": use_docker,
"use_celery": use_celery,
... |
def selection_sort(arr: list) -> list:
"""Sort a list using selection sort
Args:
arr (list): the list to be sorted
Returns:
list: the sorted list
"""
size = len(arr)
# Loop over entire array except the last element
for j in range(size - 1):
# Set the current minimu... |
def move_id_ahead(element_id, reference_id, idstr_list):
"""Moves element_id ahead of reference_id in the list"""
if element_id == reference_id:
return idstr_list
idstr_list.remove(str(element_id))
reference_index = idstr_list.index(str(reference_id))
idstr_list.insert(reference_index, str(e... |
def _LJ_ab_to_rminepsilon(coeffs):
"""
Convert AB representation to Rmin/epsilon representation of the LJ potential
"""
if (coeffs['A'] == 0.0 and coeffs['B'] == 0.0):
return {"sigma": 0.0, "epsilon": 0.0}
try:
Rmin = (2.0 * coeffs['A'] / coeffs['B'])**(1.0 / 6.0)
Eps = coe... |
def tail(list, n):
""" Return the last n elements of a list """
return list[:n] |
def re_escape(string: str) -> str:
"""
Escape literal backslashes for use with re.
:param string:
:type string:
:return:
:rtype:
"""
return string.replace('\\', "\\\\") |
def tip(bill):
"""Adds 15% tip to a restaurant bill."""
bill *= 1.15
print ("With tip: %f" % bill)
return bill |
def _combined_lists(alist, total=None):
"""
Given a list of lists, make that set of lists one list
"""
if total is None:
total = []
if not alist:
return total
return _combined_lists(alist[1:], total + alist[0]) |
def _map_abbreviations(text: str, abbrevs: dict) -> str:
"""Maps the abbreviations using the abbrevs side input."""
output = []
space = " "
for word in text.split(space):
if word in abbrevs:
output.append(abbrevs[word])
else:
output.append(word)
return space.join(output) |
def _invert_signs(signs):
""" Shall we invert signs?
Invert if first (most probable) term is negative.
"""
return signs[0] < 0 |
def setPercentage(pt):
"""
@param pt: The new percentage threshold
@type pt: Float between 1 and 100
@return: 1 value is not correct
"""
if 1 <= pt <= 100:
global PERCENTAGE
PERCENTAGE = pt
else:
return 1 |
def permissions_string(permissions, known_permissions):
"""Return a comma separated string of permission changes.
:param permissions: A list of strings, or ``None``. These strings can
exclusively contain ``+`` or ``-`` prefixes, or contain no prefixes at
all. When prefixed, the resulting string w... |
def extract_helm_from_json(input_json):
"""Extracts the HELM strings out of a JSON array.
:param input_json: JSON array of Peptide objects
:return: output_helm: string (extracted HELM strings separated by a newline)
"""
output_helm = ""
for peptide in input_json:
if len(output_helm) > 0... |
def uniform(n):
""" Initializer for a uniform distribution over n elements
n :: int
"""
return [1 / n for _ in range(n)] |
def remove_non_printable_chars(string):
"""Remove non-ASCII chars like chinese chars"""
printable = set(
"""0123456789abcdefghijklmnopqrstuvwxyz"""
"""ABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ """
)
return "".join(filter(lambda x: x in printable, string)) |
def shorten(text, width, suffix='...'):
"""Truncate the given text to fit in the given width."""
if len(text) <= width:
return text
if width > len(suffix):
return text[:width-len(suffix)] + suffix
if width >= 0:
return suffix[len(suffix)-width:]
raise ValueError('width must b... |
def device_settings(string):
"""Convert string with SoapySDR device settings to dict"""
if not string:
return {}
settings = {}
for setting in string.split(','):
setting_name, value = setting.split('=')
settings[setting_name.strip()] = value.strip()
return settings |
def zeros_matrix(rows, cols):
"""
Creates a matrix filled with zeros.
:param rows: the number of rows the matrix should have
:param cols: the number of columns the matrix should have
:returns: list of lists that form the matrix.
"""
M = []
while len(M) < rows:
M.appe... |
def evaluate(x, poly):
"""
Evaluate the polynomial at the value x.
poly is a list of coefficients from lowest to highest.
:param x: Argument at which to evaluate
:param poly: The polynomial coefficients, lowest order to highest
:return: The result of evaluating the polynomial at x
... |
def get_imaging_maskbits(bitnamelist=None):
"""Return MASKBITS names and bits from the Legacy Surveys.
Parameters
----------
bitnamelist : :class:`list`, optional, defaults to ``None``
If not ``None``, return the bit values corresponding to the
passed names. Otherwise, return the full M... |
def _parse_volumes_kwarg(cli_style_volumes):
"""
The Python API for mounting volumes is tedious.
https://github.com/docker/docker-py/blob/master/docs/volumes.md
This makes it work like the CLI
"""
binds = {}
volumes = []
for volume in cli_style_volumes:
split = volume.split(':')
... |
def finder3(l1, l2):
"""
Find the missing element in a non-python specific approach in constant
space complexity.
"""
result = 0
for num in l1 + l2:
result ^= num
return result |
def subs(string: str, *args: tuple, **kwargs: dict) -> bytes:
"""Function to take ``string``, format it using ``args`` and ``kwargs`` and
encode it into bytes.
Args:
string (str): string to be transformed.
Returns:
bytes: the resulting bytes.
"""
return string.format(*args, **k... |
def sieve_of_eratosthenes(n):
"""sieve_of_eratosthenes(n): return the list of the primes < n."""
if n <= 2:
return []
sieve = list(range(3, n, 2))
top = len(sieve)
for si in sieve:
if si:
bottom = (si*si - 3) // 2
if bottom >= top:
br... |
def generate_legend(legendurl):
"""Generate legend
"""
overlaycoords = '''
<ScreenOverlay>
<name>Legend image</name>
<Icon>
<href>%s</href>
</Icon>
<overlayXY x="0.02" y="0.02" xunits="fraction" yunits="fraction" />
<screenXY x="0.02" y="0.02" xunits="... |
def aterm(f,p,pv0,e,B,R,eta):
"""
For the cubic equation for nu in the four-variable model with CRISPR,
this is the coefficient of nu^3
"""
return B*e**2*f*p*pv0**2*(-1 + f + R) |
def merger(l):
"""
This function takes a list of strings as a parameter and return list of grouped, consecutive strings
:param l: List of strings
:return:
"""
if not l:
print("Error in merge with empty list")
elif len(l) == 1:
return l
else:
# Divide the list from... |
def priority(x, y, goal):
"""Priority for a State."""
return abs(goal[0] - x) + abs(goal[1] - y) |
def remove_overlapping_ems(mentions):
"""
Spotlight can generate overlapping EMs.
Among the intersecting EMs, remove the smaller ones.
"""
to_remove = set()
new_mentions = []
length = len(mentions)
for i in range(length):
start_r = mentions[i]['start']
end_r = mentions[i]... |
def non_zero_push_left(line):
"""
This function pushes non-zero numbers to the left and
returns a new list after filling the zeros in place of the pushed numbers
It takes O(n) time --> linear run-time complexity
:param line:
:return line_copy:
"""
line_copy = []
zero_counter = 0
for num i... |
def parse_minus(data):
"""Parse minus sign from raw multimeter data
:param data: Raw multimeter data, aligned to 15-byte boundary
:type data: bytes
:return: Whether minus is on
:rtype: bool
"""
return bool(data[3] & 1) |
def str_to_int(value):
"""Converts an input string
into int value, or returns input
if input is already int
Method curated by Anuj Som
Args:
value (int, str): Accepts an int or string to convert to int
Returns:
tuple (int, bool): returns (integer value, True) if conversion suc... |
def define_tuner_hparam_space(hparam_space_type):
"""Define tunable hparams for grid search."""
if hparam_space_type not in ('pg', 'pg-topk', 'topk', 'is'):
raise ValueError('Hparam space is not valid: "%s"' % hparam_space_type)
# Discrete hparam space is stored as a dict from hparam name to discre... |
def notifier_title_cleaner(otitle):
"""
Simple function to replace problematic Markdown characters like `[` or `]` that can mess up links.
These characters can interfere with the display of Markdown links in notifications.
:param otitle: The title of a Reddit post.
:return otitle: The cleaned-up ve... |
def UnCapitalize(name):
"""Uncapitalize a name"""
if name:
return name[0].lower() + name[1:]
else:
return name |
def clip_location(position):
"""Clip a postion for a BioPython FeatureLocation to the reference.
WARNING: Use of reference length not implemented yet.
"""
return max(0, position) |
def slicetime(mat):
"""return two matrices, one with only time and the other with the rest of the matrice"""
return [row[0:1] for row in mat], [row[1:] for row in mat] |
def speed_converter(miles_per_min):
"""
>>> speed_converter(0)
0.0
>>> speed_converter(0.5)
1158.48
>>> speed_converter(0.75)
1737.72
>>> speed_converter(2)
4633.92
"""
kilos_per_day =miles_per_min*1.609*24*60
return kilos_per_day |
def duration360days(Ndays):
"""
Convers a number o days into duration tuple (years, months, days)
in a 360/30 day counting convention.
:param Ndays: Number of days
:return: Tuple (years, monhts, days)
:type Ndays: int
:rtype: tuple(int, int, int)
Example:
>>> fr... |
def validate_output(err, count, snr, shr, rnd, crd):
"""
Clean and validate output data
- Remove measurements with unphysical values, such as negative countrate
- Remove low information entries, such as magnitude errors >0.5 & SNR <1
- Remove missing value indicators such as +/- 9.99
"""
ret... |
def get_codec_name(args, codec_type='video'):
"""
Search list of arguments for the codec name.
:param args: list of ffmpeg arguments
:param codec_type: string, type of codec to check for.
:returns: string, name of codec.
"""
try:
query = '-codec:v' if codec_type == 'video' else '-cod... |
def colorscale_to_colors(colorscale):
"""
Extracts the colors from colorscale as a list
"""
color_list = []
for item in colorscale:
color_list.append(item[1])
return color_list |
def merge_coverage(old, new):
# type: (str, str) -> str
"""Merge two coverage strings.
Each of the arguments is compact coverage data as described for
get_coverage_by_job_ids(), and so is the return value.
The merged string contains the 'stronger' or the two corresponding
characters, where 'C'... |
def tabContentState(state):
"""Returns css selector based on tab content state"""
return 'active' if state else 'fade' |
def to_grid(tiles):
""" Organizes a list of tiles into a matrix that can be iterated over. """
tiles = sorted(tiles, key=lambda elem: elem.x)
pivot = 1
for idx, element in enumerate(tiles):
if idx == 0:
continue
prior_element = tiles[idx-1]
if element.x != prior_eleme... |
def align_buf(buf: bytes, sample_width: int):
"""In case of buffer size not aligned to sample_width pad it with 0s"""
remainder = len(buf) % sample_width
if remainder != 0:
buf += b'\0' * (sample_width - remainder)
return buf |
def get_chart_data(tick, nodes, prev_nodes):
"""
Generates chart data for current tick using enumerated data for all
reachable nodes.
"""
data = {
't': tick,
'nodes': len(nodes),
'ipv4': 0,
'ipv6': 0,
'user_agents': {},
'countries': {},
'coordi... |
def is_list(value):
"""
Returns True if the given value is a list-like instance
>>> is_list([1, 2, 3])
True
>>> is_list(u'2')
False
"""
return isinstance(value, (list, tuple, set)) |
def column(tabular, n):
"""get nth column from tabular data
"""
col = []
for row in tabular:
if len(row) < n+1:
col.append("")
else:
col.append(row[n])
return col |
def dict_remove(x, exclude=[]):
"""Remove items from a dict."""
return dict((k, v) for k, v in x.items() if k not in exclude) |
def get_url(id: str):
""" Converts video id into url for the video. """
url = "https://youtu.be/" + id
return url |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.