content stringlengths 42 6.51k |
|---|
def compare_languge(language, lang_list):
"""
Check if language is found
"""
found = False
for l in lang_list:
if language == l.lower():
found = True
break
return found |
def find_missing(input_list):
""" Find the missing number in shuffled list
"""
# Mathematical formula for finding the sum of consequtive natural numbers
# (N*(N+1))/2
total = (len(input_list) * (len(input_list) +1)) / 2
summed = 0
for element in input_list:
summ... |
def expanded_bb( final_points):
"""computation of coordinates and distance"""
left, right = final_points
left_x, left_y = left
right_x, right_y = right
base_center_x = (left_x+right_x)/2
base_center_y = (left_y+right_y)/2
dist_base = abs(complex(left_x, left_y)-complex(right_x, right_y ) )
... |
def dategetter(date_property, collection):
"""
Attempts to obtains a date value from a collection.
:param date_property: property representing the date
:param collection: dictionary to check within
:returns: `str` (ISO8601) representing the date. ('..' if null or "now",
allowing for an ope... |
def get_col(lut, idx, range):
"""
Get RGB color for an index within a range, using a lookup table
"""
lower, upper = range[0], range[1]
if lower == upper:
pos = 0
else:
pos = (idx - range[0]) / (range[1] - range[0])
return lut[int(pos*(len(lut)-1))] |
def conv_s2hms(seconds, short=False):
"""
Converts seconds to hours, minutes and seconds.
:param seconds: The time in seconds to use
:type seconds: int
:return: str
"""
seconds = int(seconds)
hours = seconds / 3600
seconds -= 3600 * hours
minutes = seconds / 60
seconds -= 6... |
def is_proper_component_name(component):
"""Check if the component name is properly formatted."""
return "@" not in component and "/" not in component |
def line_intersection(line1, line2):
"""!
Returns the instersection coordinate between two lines
@param line1 `tuple` line 1 to calculate intersection coordinate
@param line2 `tuple` line 2 to calculate intersection coordinate
@return `tuple` intersection cord between line 1 and line 2
"""
... |
def areSeqCluParameters(parameters: list) -> bool:
"""
This method verifies whether or not a list of parameters has the format of parameters that are used to
configure the 'SeqClu-PV' algorithm.
:param parameters: A list of parameters for which needs to be verified whether or not it has the... |
def make_cookie_values(cj, class_name):
"""
Makes a string of cookie keys and values.
Can be used to set a Cookie header.
"""
path = "/" + class_name
cookies = [c.name + '=' + c.value
for c in cj
if c.domain == "class.coursera.org"
and c.path == path... |
def extract_friends(json_handle: dict):
"""
Extracting list of friends.
:param json_handle: data handle
:return: List with friends IDs
"""
list = []
for item in json_handle.keys():
list.append(int(item))
return sorted(list) |
def make_add_rich_menu(name, size, areas):
"""
add rich menu content:
reference
- `Common Message Property <https://developers.worksmobile.com/jp/document/1005040?lang=en>`_
You can create a rich menu for the message bot by following these steps:
1. Image uploads: using the "Upload Con... |
def get_thumbnail_size(image_size, thumbnail_height):
"""
Computes the size of a thumbnail
:param image_size: original image size
:param thumbnail_height: thumbnail height
:return: thumbnail size tuple
"""
width = round((float(thumbnail_height) / image_size[1]) * image_size[0])
return wi... |
def get_edit_distance(s1, s2):
"""Calculate the Levenshtein distance between two normalised strings
Adopted from example in https://stackoverflow.com/questions/2460177/edit-distance-in-python
See https://en.wikipedia.org/wiki/Edit_distance
@param s1: the first string to compare
@param s2: the second... |
def memoize(cached_function):
""" Memoization decorator for functions taking one or more arguments. """
# http://code.activestate.com/recipes/578231-probably-the-fastest-memoization-decorator-in-the-/
class MemoDict(dict):
def __init__(self, cached_function):
super().__init__()
... |
def order_mirrored_vertex_points(vertices, plane):
"""
Order mirrored vertex points to keep consistent global system
Args:
:vertices: (tuple) vertices like (a, b, c, d)
:plane: (str) plane ('xy', 'xz' or 'yz')
Returns:
:ordered_vertices: (tuple) ordered vertices
"""
a,... |
def init_parameters(parameter):
"""Auxiliary function to set the parameter dictionary
Parameters
----------
parameter: dict
See the above function inverseSTFT for further information
Returns
-------
parameter: dict
"""
parameter['costFunc'] = 'KLDiv' if 'costFunc' not in pa... |
def _get_requirements_to_disable(old_requirements, new_requirements):
"""
Get the ids of 'CreditRequirement' entries to be disabled that are
deleted from the courseware.
Args:
old_requirements(QuerySet): QuerySet of CreditRequirement
new_requirements(list): List of requirements being ad... |
def is_folder(obj):
"""
Checks if object is a vim.Folder.
:param obj: The object to check
:return: If the object is a folder
:rtype: bool
"""
return hasattr(obj, "childEntity") |
def mock_tqdm(*args, **kwargs):
"""
Parameters
----------
Returns
-------
"""
if args:
return args[0]
return kwargs.get('iterable', None) |
def pair_issue(issue_list1, issue_list2):
""" Associates pairs of issues originating from original and canonical repositories.
:param issue_list1: list of IssueDir
:type issue_list1: array
:param issue_list2: list of IssueDir
:type issue_list2: array
:return: list containing tuples of issue pai... |
def from_string(unicode_string):
"""
Converts the given String to a byte array.
:param unicode_string: The String to be converted to a byte array.
:return: A byte array representing the String.
"""
result = None
if unicode_string is not None:
result = bytearray(unicode_string.encode... |
def to_lower(x):
"""Lower case."""
return x.lower() |
def left_shift(data):
"""
>>> left_shift("0123456789")
'1234567890'
"""
return data[1:] + data[0] |
def markup(text, annotations, positive_class=True):
"""Given a text and a list of AnnotatedSpan objects,
inserts HTML <span> tags around the annotated areas."""
last_char = 0
doc_markedup = []
for start, end, word, weight, level in annotations:
doc_markedup.append(text[last_char:start])
... |
def check(header, key, value):
"""
If *var* is not `None` first check that *var* and *value*
match. Return the parsed *value*.
"""
if value is None:
return header[key]
assert header[key] == value
return value |
def es_letra_atril(event):
"""Verifica que el evento reciente sea un click sobre el atril del usuario."""
return isinstance(event, int) |
def complete_sequence(seq):
"""
Seq is normalized by capitalizing all of the characters
:param seq: sequence to test
:return: True if sequence only contains A, C, T, or G, False if contains N or any other character
"""
allowed = set('ACTG')
return set(seq.upper()).issubset(allowed) |
def format_percent(num: float, force_sign: bool = False) -> str:
"""Formats a decimal ratio as a percentage."""
prefix = '+' if force_sign and num > 0 else ''
return '{}{:,.1f}%'.format(prefix, num * 100) |
def noop_warmup(agent, env, history, args):
"""Warm up with noop."""
return agent, env, history, args |
def CreateSizesExternalDiagnostic(sizes_guid):
"""Creates a histogram external sizes diagnostic."""
benchmark_diagnostic = {
'type': 'GenericSet',
'guid': str(sizes_guid),
'values': ['sizes'],
}
return benchmark_diagnostic |
def prefixe(arbre):
"""Fonction qui retourne le parcours prefixe de l'arbre
sous la forme d'une liste
"""
liste = []
if arbre != None:
liste.append(arbre.get_val())
liste += prefixe(arbre.get_ag())
liste += prefixe(arbre.get_ad())
return liste |
def _isredirect(values):
"""Check if rewrite values is redirect.
"""
return [v.split().pop() in ('redirect', 'permanent') for v in values] |
def get_obj_path_name(object):
"""
Get the full correct name of the provided object.
:param object: UObject
:return: String of the Path Name
"""
if object:
return object.PathName(object)
else:
return "None" |
def find_history_replacements_active_at(objects, time):
"""Return dictionary mapping object pk to object or its history
object at the time, if any.
Same caveats as for find_history_active_at applies."""
if not objects:
return {}
# automatically figure out how to query history model
hi... |
def hus_to_h2o(hus):
"""Calculate H2O in vmr instead of specific humidity."""
mda = 28.966 # molecular mass of dry air
mwv = 18.016 # molecular mass of water vapour
h2o = mda / mwv * hus / (1.0 - hus)
return h2o |
def _unicode_char(char): # pragma: no cover
"""Return true if character is Unicode (non-ASCII) character."""
try:
char.encode("ascii")
except UnicodeEncodeError:
return True
return False |
def c_any(iterable):
"""
Implements python 2.5's any()
"""
for element in iterable:
if element:
return True
return False |
def reposition_bounding_box(bbox, tile_location):
"""Relocates bbox to the relative location to the original image.
Args:
bbox (int, int, int, int): bounding box relative to tile_location as xmin,
ymin, xmax, ymax.
tile_location (int, int, int, int): tile_location in the original image as
xmin,... |
def get_wind_direction(degrees):
"""
:param degrees: integer for degrees of wind
:return: string of the wind direction in shorthand form
"""
try:
degrees = int(degrees)
except ValueError:
return ''
if degrees < 23 or degrees >= 338:
return 'N'
elif degrees < 68:
... |
def add_parameter_group_to_list_of_dicts( Dlist, names, values ):
"""
Copies and returns the given list of dictionaries but with
names[0]=values[0] and names[1]=values[1] etc added to each.
"""
assert len(names) == len(values)
N = len(names)
new_Dlist = []
for D in Dlist:
newD ... |
def addKey(s1, s2):
"""Add two keys in GF(2^4)"""
return [i ^ j for i, j in zip(s1, s2)] |
def scalar_eq(a, b, precision=0):
"""Check if two scalars are equal.
Keyword arguments:
a -- first scalar
b -- second scalar
precision -- precision to check equality
Returns:
True if scalars are equal
"""
return abs(a - b) <= precision |
def get_trf_command(command, transformation=""):
"""
Return the last command in the full payload command string.
Note: this function returns the last command in job.command which is only set for containers.
:param command: full payload command (string).
:param transformation: optional name of trans... |
def split_by_unescaped_sep(text, sep=':'):
"""Split string at sep but only if not escaped."""
def remerge(s):
# s is a list of strings.
for i in range(len(s) - 1):
n_esc = len(s[i]) - len(s[i].rstrip('\\'))
if n_esc % 2 == 0:
continue
else:
... |
def format_itemize(informations, comment_symbol, tag):
"""
Write a latex itemize for all data in informations and return
it as a list, need comment_symbol
informations : set of tuple containing (name, desc) of a func
comment_symbol : string defining a comment line
tag ... |
def strip_optional_prefix(string, prefix, log=None):
"""
>>> strip_optional_prefix('abcdef', 'abc')
'def'
>>> strip_optional_prefix('abcdef', '123')
'abcdef'
>>> strip_optional_prefix('abcdef', '123', PrintingLogger())
String starts with 'abc', not '123'
'abcdef'
"""
if string.st... |
def help_template ( template = None ):
""" Gets or sets the current HelpTemplate in use.
"""
global _help_template
if template is not None:
_help_template = template
return _help_template |
def CCDSELExtracter(CCDSEL):
"""Extract the individual CCDSEL (64, 32, 16, 8, 4, 2, 1) arguments from a number CCDSEL argument assuming the CCDSEL argument is valid.
Argument:
CCDSEL (int): Value between 0 and 127 which represent the selection of a number of CCDs.
Returns:
(list of int): L... |
def dict_list_get_values_for_key(dict_list, key):
"""Get values for keys."""
return [d[key] for d in dict_list] |
def _split_left_right(name):
"""Split record name at the first whitespace and return both parts.
RHS is set to an empty string if not present.
"""
parts = name.split(None, 1)
lhs, rhs = [parts[0], parts[1] if len(parts) > 1 else '']
return lhs, rhs |
def paginated_list(full_list, max_results, next_token):
"""
Returns a tuple containing a slice of the full list
starting at next_token and ending with at most the
max_results number of elements, and the new
next_token which can be passed back in for the next
segment of the full list.
"""
... |
def convert (degrees):
"""
convert degree F to Degree celsius (32F - 32) * 5/9
Args: (float | int value)Degrees Farenheit
returns:(numeric value) celsius
"""
celsius = (degrees - 32 )* 5/9
return celsius |
def is_none_or_empty(param, return_value):
"""
Args:
param :
return_value :
Returns:
"""
return return_value if param is None or param == '' else param |
def find_pax(pnr, paxnum):
"""
Pax number is paxnum - 1 because paxes stored in list.
"""
paxes = pnr["name"]
if len(paxes) < int(paxnum):
return None
return paxes[int(paxnum) - 1] |
def acquire_symbols_from(name, name2sym, never_str=False):
"""
Acquire the symbol(s) from the iterable
:param name: Name of symbol. All namespace is removed.
:type name: ```Union[Any, str]```
:param name2sym: Dict from symbol name to symbol
:type name2sym: ```Dict[Str, Any]```
:param neve... |
def classify_bnd(disrupt_dict):
"""
Classify genic effect of a breakend.
An interchromosomal breakpoint falling within a gene is LOF.
"""
elements = disrupt_dict.keys()
if 'CDS' in elements:
return 'LOF'
if 'transcript' in elements:
return 'LOF'
if 'gene' in elements:
... |
def values_to_string(input_values):
"""Method that takes a list of values and converts them to a '|'-delimted string"""
token_list = []
for value in input_values:
token_list.append(str(value))
return '|'.join(token_list) |
def triangle_area(base, height):
"""Returns the area of a triangle"""
return (base*height)/2 |
def get_data_shape(data, strict_no_data_load=False):
"""
Helper function used to determine the shape of the given array.
In order to determine the shape of nested tuples, lists, and sets, this function
recursively inspects elements along the dimensions, assuming that the data has a regular,
rectang... |
def _addrinfo_to_ip_strings(addrinfo):
"""
Helper function that consumes the data output by socket.getaddrinfo and
extracts the IP address from the sockaddr portion of the result.
Since this is meant to be used in conjunction with _addrinfo_or_none,
this will pass None and EndPoint instances throug... |
def key_mode_to_int(mode):
"""Return the mode of a key as an integer (1 for major and -1 for
minor).
Parameters
----------
mode : {'major', 'minor', None, 1, -1}
Mode of the key
Returns
-------
int
Integer representation of the mode.
"""
if mode in ("minor", -1... |
def seconds_to_hms(seconds):
"""Convert seconds in hour, minutes and seconds
# Example
```python
h, m, s = seconds_to_hms(5401)
print('Hour: {} Minutes: {} Seconds: {}'.format(h, m, s))
```
"""
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
return h,m,s |
def ppm_to_unity(ppm):
"""Converts a ppm value to its unity value equivalent
:param ppm: ppm scale value
:type ppm: float
:return: the unity scale value of the input ppm value
:rtype: float
"""
return 1 + ppm * 1E-6 |
def mangle_sheet_name(s: str) -> str:
"""Return a string suitable for a sheet name in Excel/Libre Office.
:param s: sheet name
:return: string which should be suitable for sheet names
"""
replacements = {
':': '',
'[': '(',
']': ')',
'*': '',
'?': '',
... |
def countDistinctTrianglesSet(arr):
""" int[][] arr
return int
"""
uniq = set()
for tri in arr:
tri = list(tri)
tri.sort()
# key = ":".join([str(s) for s in tri])
key = tuple(tri)
uniq.add(key)
print(uniq)
count = len(uniq)
return count |
def opml_attr(str_name, str_value):
"""Build OPML attribute pairings"""
# return '%s=%s ' % (str_name, str_value)
return ''.join([str_name, '=', str_value, ' ']) |
def decode_expanded_peers(peers):
""" Return a list of IPs and ports, given an expanded list of peers,
from a tracker response. """
return [(p["ip"], p["port"]) for p in peers] |
def check_via_group(via_group, source_sink):
"""
Check the validity of each via set in the via group.
:param via_group: the via_group in question.
:return: via_group with all valid candidate(s)
"""
# valid for 2-via cell: 1 source, 1 sink
# valid for 3-via cell: 2 sink, 1 source
valid_gr... |
def generate_method_bindings(obj):
"""Function to create the function calls, which contain calls to the godot apis"""
result = "\n##################################Generated method bindings#########################################\n"
result += f"cdef godot_method_bind *bind_{obj['name']}\n"
for method i... |
def parse_interface_params(list):
"""
Parse a variable list of key=value args into a dictionary suitable for kwarg usage
"""
return {} if list is None else dict([s.split('=') for s in list]) |
def parse_enzyme_input(enzyme_input: str):
"""
Parse the list of enzymes given as input.
"""
enzyme_list = enzyme_input.strip(" ").split(",")
return enzyme_list |
def rim2arab(num):
"""Convert Latin numbers to Arabic:
L - 50
X - 10
V - 5
I - 1
:type num: str
:rtype: int
"""
res = 0
lt = False
ltx = False
for c in num:
if c == "L":
if ltx:
res += 30
else:
res += 50
... |
def fix_sequence_length(sequence, length):
"""
Function to check if length of sequence matches specified
length and then return a sequence that's either padded or
truncated to match the given length
Args:
sequence (str): the input sequence
length (int): expec... |
def safe_dir(out_dir, year, month):
"""
Make a directory for this year and month as subdirectories of out_dir
:param out_dir: base directory in which new directories will be created
:param year: year for subdirectory
:param month: month for subdirectory
:return: None
"""
syr = str(year)... |
def get_alpha_beta(min_value, max_value, mean_value):
""" for the duration on a state, draw from a beta distribution with parameter alpha and beta """
x = (mean_value - min_value) / (max_value - min_value)
z = 1 / x - 1
a, b = 2, 2 * z
return a, b |
def generate_transition_bigram_probabilities(transition_unigram_counts, transition_bigram_counts):
"""Takes in the unigram and bigram count matrices.
Creates dictionary containing the transition bigram
probabilities in the following format:
{(tag[i-1], tag[i]) : probability}
where the probability is calculat... |
def getCountTime(time):
"""
if the needed time is below 1/10
of a second
"""
if(time<1):return (1/10)/60 |
def fib(a):
"""
Computes Fibonaci series.
:param a:
:return:
"""
prev = 1
prevprev = 1
while a > 0:
tmp = prev + prevprev
prevprev = prev
prev = tmp
a -= 1
return prev |
def realQuadratic(variableA=1, variableB=1, variableC=1) -> tuple:
"""
Calculates solutions for a quadratic formula
variableA: Ax^2 (int|float|complex)
variableB: Bx (int|float|complex)
variableC: C (int|float|complex)
"""
inverseB = (-variableB)
discriminant = ((variableB**2) - (4 * var... |
def get_first_positions(sequence):
"""
Reports the first occurance of each element in the sequence in a dictionary, with each element as keys, and their first position as values.
Example
---------
>>> sequence = [1,1,2,3,4]
>>> ps.get_first_positions(sequence)
{1: 0, 2: 2, 3: 3, 4: 4}
"""
unique_elements =... |
def media_for_creatable_guest_media(medias):
""" This media should be used when creating a guest_media record."""
for m in medias:
if m.id == 'TEST FOR GUESTMEDIA CREATION':
return m |
def empty(n):
"""
:param n: Size of the matrix to return
:return: n by n matrix (2D array) filled with 0s
"""
return [[0 for i in range(n)] for j in range(n)] |
def parse_state(json_obj, state_key: str):
"""
Retrieves the value of a state by the key of the state out of the JSON.
:param json_obj: the processor's general state.
:param state_key: the key for the specific state.
:raises ValueError: if the passed key cannot be found in the processor state.
... |
def create_axisdic(adic,tlen,dlen):
"""
Make an sparky axis dictionary from a universal axis dictionary
Parameters:
* adic axis dictionary from universal dictionary
* tlen tile length
* dlen data length
"""
dic = dict()
dic["nucleus"] = adic["label"]
dic["spectral_shift... |
def Binary_search( data, target, low, high):
"""Return True If element found at the indicated position of a list sequence.
The search only considers the position from data[low] to data[high] inclusive."""
if low > high:
return False
else:
mid = low + high // 2
if ... |
def item_hist(list_):
""" counts the number of times each item appears in the dictionary """
dict_hist = {}
# Insert each item into the correct group
for item in list_:
if item not in dict_hist:
dict_hist[item] = 0
dict_hist[item] += 1
return dict_hist |
def result_saving(text_name, image_name, folder_name, results):
"""
file processing part
"""
#save estimation values
file = open(folder_name + text_name, 'a')
file.write('name' + ' ' + 'cos' + ' ' + 'dice' + ' ' + 'jaccard' + ' ' + 'pearson' + ' ' + 'tanimoto' + '\n')
file... |
def _get_full_bldg_pdf_url(building_id, base_url):
# type: (int, str) -> str
"""Get report pdf url for full buildings
BES does not include the url to the report.pdf in the score response for
v1 full buildings, but does follow a consistent pattern for url creation
in relation to the production or sa... |
def font_size(min, max, high, current_value):
"""
calculate font size by min and max occurances
min - minimum output value
max - maximum output value
high - maximum input value
n - current occurances
"""
if max < min:
raise ValueError('Max cannot be lesser then Min')
if current_value > high:
raise ValueEr... |
def test_func(context):
"""
OCID thread function for testing purposes.
Parameters
----------
context : dict
The thread context.
Returns
-------
dict
The new context.
"""
if 'fname' not in context:
raise ValueError("fname must be defined in the context")
... |
def flip_1d_index_horizontally(index, rows, columns):
"""Finds the index to the corresponding horizontal-flipped 1d matrix value.
Consider a 1d matrix [1, 2, 3, 4, 5, 6] with 3 rows and 2 columns. The
original and horizontally flipped representations are shown below.
1 2 2 1
3 4 -> 4 3
... |
def inverse_mod(a, p):
"""
Compute the modular inverse of a (mod p)
:param a:
An integer
:param p:
An integer
:return:
An integer
"""
if a < 0 or p <= a:
a = a % p
# From Ferguson and Schneier, roughly:
c, d = a, p
uc, vc, ud, vd = 1, 0, 0, 1... |
def split(s):
"""Return a list of words contained in s, which are sequences of characters
separated by whitespace (spaces, tabs, etc.).
>>> split("It's a lovely day, don't you think?")
["It's", 'a', 'lovely', 'day,', "don't", 'you', 'think?']
"""
return s.split() |
def remove_whitespace(line_content, old_col):
""" Removes white spaces from the given line content.
This function removes white spaces from the line content parameter and
calculates the new line location.
Returns the line content without white spaces and the new column number.
E.g.:
line_conten... |
def chunks(data, block_size):
"""Split data to list of chunks"""
return [data[0+i:block_size+i] for i in range(0, len(data), block_size)] |
def show_video(video, top_video=False):
"""
API-call-free, responsive friendly video embed. Don't forget to use it with the JS that tells Firefox not to use native video, and responsifying CSS.
"""
return {
'video': video,
'top_video': top_video
} |
def nonrigid_tors(spc_mod_dct_i, rotors):
""" dtermine if a nonrigid torsional model is specified and further
information is needed from the filesystem
"""
vib_model = spc_mod_dct_i['vib']['mod']
tors_model = spc_mod_dct_i['vib']['mod']
has_tors = bool(any(rotors))
tors_hr_model = bool(
... |
def check_bounds(master_results, subproblem_results):
"""Compare upper and lower bounds - return in absolute and % terms (% difference relative to lower bound)"""
gap, gap_pct = None, None
return gap, gap_pct |
def longest_common_substring(s1, s2):
"""
returns the longest common substring of two strings
:param s1: a string
:type s1: str
:param s2: a second string
:type s2: str
>>> longest_common_substring('hello world how is foo bar?', 'hello daniel how is foo in the world?')
' how is foo '
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.