content stringlengths 42 6.51k |
|---|
def my_merge(list_1, list_2, key=lambda x: x):
""" Quick function to improve the performance of branch_and_bound
Uses the mergesort algorithm to save the headache of resorting the
entire agenda every time we modify it.
Given two sorted lists and a key, we merge them into one sorted list and
return ... |
def path_to_model(path):
"""Return model name from path."""
epoch = str(path).split("phase")[-1]
model = str(path).split("_dir/")[0].split("/")[-1]
return f"{model}_epoch{epoch}" |
def speed_wave(lst):
"""
Delete even indexes of list
:param lst: list of list
:return: list of odd indexes of the original list
"""
return lst[0::2] |
def replace_tokens(string, os_name, os_code_name, os_arch):
"""Replace RPM-specific tokens in the repository base URL."""
for key, value in {
'$basearch': os_arch,
'$distname': os_name,
'$releasever': os_code_name,
}.items():
string = string.replace(key, value)
return str... |
def frame_ranges_to_string(frames):
"""
Take a list of numbers and make a string representation of the ranges.
>>> frame_ranges_to_string([1, 2, 3, 6, 7, 8, 9, 13, 15])
'[1-3, 6-9, 13, 15]'
:param list frames: Sorted list of frame numbers.
:return: String of broken frame ranges (i.e '[10-14, 16, 20-25]').
"""
... |
def strip_some_punct(s):
"""
Return a string stripped from some leading and trailing punctuations.
"""
if s:
s = s.strip(''','"};''')
s = s.lstrip(')')
s = s.rstrip('&(-_')
return s |
def _get_changelist(perforce_str):
"""Extract change list from p4 str"""
import re
rx = re.compile(r'Change: (\d+)')
match = rx.search(perforce_str)
if match is None:
v = 'UnknownChangelist'
else:
try:
v = int(match.group(1))
except (TypeError, IndexError):
... |
def remove(base, string):
"""Remove a substring from a string"""
return base.replace(string, "") |
def score(dice, category):
"""
The dice game [Yacht](https://en.wikipedia.org/wiki/Yacht_(dice_game)) is from
the same family as Poker Dice, Generala and particularly Yahtzee, of which it
is a precursor. In the game, five dice are rolled and the result can be entered
in any of twelve categories. Th... |
def input_lines_to_dict(lines) -> dict:
"""Accept lines from passport batch file and create a dictionary"""
passport = {}
for line in lines:
entries = line.split(" ")
for entry in entries:
key_value = entry.split(":")
passport[key_value[0].upper()] = key_value[1]
... |
def simple_differences(desired_distances, actual_distances):
"""
Returns as error the subtraction between desired and actual values
"""
errors = desired_distances - actual_distances
return errors |
def delete_inline_comments(x):
"""Delete comments inline
lesly.add(0) # holi --> lesly.add(0)
Args:
x (str): A string with Javascript syntax.
Returns:
[str]: Python string
Examples:
>>> from ee_extra import delete_inline_comments
>>> delete_inline_comments('var x ... |
def info_from_ApiKeyAuth(api_key, required_scopes):
"""
Check and retrieve authentication information from api_key.
Returned value will be passed in 'token_info' parameter of your operation function, if there is one.
'sub' or 'uid' will be set in 'user' parameter of your operation function, if there is ... |
def is_word(s):
""" String `s` counts as a word if it has at least one letter. """
for c in s:
if c.isalpha(): return True
return False |
def _get_dist(mit_edge):
"""Extract distribution information from an edge."""
edge_type = mit_edge["type"]
dist = None
if edge_type == "uncontrollable_probabilistic":
dist_type = mit_edge["properties"]["distribution"]["type"]
if dist_type == "gaussian":
mean = mit_edge["prope... |
def list_to_dict(keyslist,valueslist):
"""
convert lists of keys and values to a dict
"""
if len(keyslist) != len(valueslist):
return {}
mydict = {}
for idx in range(0,len(keyslist)):
mydict[keyslist[idx]] = valueslist[idx]
return mydict |
def generate_traits_list(traits: dict) -> list:
"""Returns a list of trait values
Arguments:
traits: a dict containing the current trait data
Return:
A list of trait data
"""
# compose the summary traits
trait_list = [traits['local_datetime'],
traits['canopy_hei... |
def get_verts(voxel,g):
"""return list (len=8) of point coordinates (x,y,z) that are vertices of the voxel (i,j,k)"""
(i,j,k) = voxel
dx,dy,dz = g['dx'],g['dy'],g['dz']
v1_0,v1_1,v1_2 = g['xlo'] + i*dx, g['ylo'] + j*dy, g['zlo'] + k*dz
vertices = [(v1_0,v1_1,v1_2),
(v1_0+dx,v1... |
def gtAlgoH16(str):
""" Proprietary hash based on the Park-Miller LCG """
seed = 0xaa
mult = 48271
incr = 1
modulus = (1 << 31) - 1 # 0x7FFFFFFF
h = 0
x = seed
for c in bytearray(str):
x = (((x + c) * mult + incr) & 0xFFFFFFFF) % modulus
h = h ^ x
# Derive 16-bit v... |
def calculate_param_b(
operating_frequency: float,
atmosphere_height_of_max: float,
atmosphere_semi_width: float,
atmosphere_max_plasma_frequency_squared: float) -> float:
"""
Calculates the B parameter following Hill 1979
"""
atmosphere_base_height = atmosphere_height_of... |
def anon_alters(subid, node_list):
"""
Takes list of node names as input and returns an anonymized list of node IDs.
Node IDs use the following convention: 'SubID-NodeID'
"""
anon_list = [str(subid) + '-' + str(n).zfill(2) for n in list(range(1, len(node_list) + 1))]
mapper = dict(zip(node_list,... |
def get_perm_indices_path(data_dir, data_fn):
"""Get path of pickled perm_indices file."""
return '{}/{}_perm_indices.pkl'.format(data_dir, data_fn) |
def plural(length):
"""
return "s" if length is not 1 else return empty string
example:
0 items
1 item
2 items
Parameters
----------
length: int
length of item list
Returns
-------
str: "s", ""
"""
return "s" if length != 1 else "" |
def _is_chinese_char(cp):
"""Checks whether CP is the codepoint of a CJK character."""
# This defines a "chinese character" as anything in the CJK Unicode block:
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
#
# Note that the CJK Unicode block is NOT all Japanese and Korea... |
def clone_attribute(iterable, attribute):
"""clone parameters"""
return [(j.name, j.estimator)
for i in iterable
for j in getattr(i, attribute)] |
def expected_data_sets():
"""Hardcode the names of existing datasets.
We could also use `dir` or `vars`, but this is quicker for now...
"""
return ("Santa_Clara", "Waterbury") |
def _get_contact_name(args, required):
"""
Force user to input contact name if one wasn't given in the args.
Used for SEND, READ, and SETPREF commands.
:param args: Command-line args to be checked for the contact name
:param required: If the contact name must be specified, or it's optional
:retu... |
def _flattened(lst):
"""Returned list flattend at first level."""
return sum(lst, []) |
def cria_posicao(c, l):
"""
Construtor posicao.
Recebe duas cadeias de carateres correspondentes a coluna c e ha linha l de uma
posicao e devolve a posicao correspondente. Caso algum dos seus argumentos nao seja
valido, a funcao gera um erro com a mensagem 'cria_posicao: argumentos invalidos'... |
def determ(p1, p2, p3):
""" Helping function for convex_hull() that calculates the determinant of 3 points
pre: p1, p2, p3 are tuples of the form (x, y) where x represents
the x-axis location and y represents the y-axis location of the point
on the cartesian plane
post: re... |
def bb_data_to_coordinates(data):
"""
Get bb data as -> [x1,y1,h,w], compute coordinates as -> [x1, y1, x2, y2]
"""
x1 = data[0]
y1 = data[1]
x2 = data[0] + data[3] - 1
y2 = data[1] + data[2] - 1
return [x1,y1, x2, y2] |
def z2a(z):
"""Converts z to a.
Parameters
----------
z : float
Redshift.
"""
return 1./(1.+z) |
def qs(ll):
"""return len(l) ?s sepeated by ',' to use in queries"""
return ','.join('?' for l in ll) |
def parseFieldMap(field_map_full):
""" take field map from json to list of group dictionaries """
groups = []
for item in field_map_full:
for k,v in item.iteritems():
groups.append(v)
return groups |
def _match_attributes(elm, attribs):
""" Match the element attributes. """
for key, value in attribs.items():
if elm.get(key) != value:
return False
return True |
def sample_function(x, y=10):
"""
This text here is the documentation of this function
and everyone should also write docs for their functions.
"""
print('You are in the function')
a = 3
global b
b = 10
key = 'Some Function'
return(a,b, key) |
def start_points(seq, start):
"""Get starting points"""
return [t[0] for t in enumerate(seq) if t[1] == start] |
def makebb(pnts):
"""
Find the bounding box for a list of points.
Arguments:
pnts: Sequence of 2-tuples or 3-tuples
Returns:
A list [minx, maxx, miny, maxy[, minz, maxz]].
"""
x = [p[0] for p in pnts]
y = [p[1] for p in pnts]
rv = [min(x), max(x), min(y), max(y)]
if... |
def check_zeros(counts):
"""
helper function to check if vector is all zero
:param counts:
:return: bool
"""
if sum(counts) == 0:
return True
else:
return False |
def ms_to_kts(spd):
"""
Parameters
Speed (ms^-1)
Returns
Speed (knots)
"""
spdkts = spd * 1.94384449
return spdkts |
def _is_within_open_bracket(s, index, node):
"""Fix to include left '['."""
if index < 1:
return False
return s[index-1] == '[' |
def generate_statement_result(read_io, write_io, processing_time, next_page_token, is_first_page,
values=[{'IonBinary': 1}]):
"""
Generate a statement result dictionary for testing purposes.
"""
page = {'Values': values, 'NextPageToken': next_page_token}
statement_resu... |
def as_number_type(type_, value):
"""Transform a string to a number according to given type information"""
if type_ == "integer":
return int(value)
elif type_ == "number":
return float(value)
else:
raise NotImplementedError(f"as_number_type does not support type {type_}") |
def join_lines_OLD(lines):
"""Return a list in which lines terminated with the backslash line
continuation character are joined."""
result = []
s = ''
continuation = False
for line in lines:
if line and line[-1] == '\\':
s = s + line[:-1]
continuation = True
... |
def calc(term):
"""
input: term of type str
output: returns the result of the computed term.
purpose: This function is the actual calculator and the heart of the application
"""
# This part is for reading and converting arithmetic terms.
term = term.replace(' ', '')
... |
def repos(ln, old_pos, new_pos):
"""
Return a new list in which each item contains the index of the item
in the old order.
Uses the ranges approach (best for large arrays).
"""
lb = min(new_pos, old_pos)
ub = max(new_pos, old_pos)
adj_range = []
if new_pos < old_pos:
... |
def haccredshiftsforstep(stepnumber ,
zin = 200. ,
zfinal = 0. ,
numsteps = 500) :
"""Changed haccredshiftsforstep to match Adrian's time stepper doc"""
ain = 1.0/(1.0 + zin)
afinal = 1.0/(1.0 + zfinal)
astep = (afinal - ain)/numsteps
aatstep = astep * (stepnumber +1.)+ ain
z = 1.0/aatstep - 1.0 ... |
def fibonacci(n):
"""Compute the value of the Fibonacci number F_n.
Parameters
==========
n : int
The index of the Fibonacci number to compute.
Returns
=======
float
The value of the nth Fibonacci number.
"""
# Check the input
if not isinstance(n, int):
... |
def mysql_quote(x):
"""Quote the string x using MySQL quoting rules. If x is the empty string,
return "NULL". Probably not safe against maliciously formed strings, but
whatever; our input is fixed and from a basically trustable source."""
if not x:
return "NULL"
x = x.replace("\\", "\\\\")
... |
def unbits(s, endian = 'big'):
"""unbits(s, endian = 'big') -> str
Converts an iterable of bits into a string.
Arguments:
s: Iterable of bits
endian (str): The string "little" or "big", which specifies the bits endianness.
Returns:
A string of the decoded bits.
Example:
... |
def s3_key_for_revision_content(wiki, pageid, revid):
"""Computes the key for the S3 object storing gzipped revision content."""
return '{:s}page_{:08d}/rev_{:08d}_data.gz'.format(
wiki['s3_prefix'],
pageid,
revid
) |
def lj(r, epsilon, sigma, R):
"""Return lennard jones force and potential."""
F = 4 * epsilon / (r-R) * (12 * (sigma / (r-R))**12 - 6 * (sigma / (r-R))**6)
V = 4 * epsilon * ((sigma / (r-R))**12 - (sigma / (r-R))**6)
return(V, F) |
def get_dict_from_header_form_line(line):
""" Returns dict with attributes for a given header form line. """
if '**' not in line:
return
result = dict()
strip_line = line.strip().split('** ')[-1]
if 'true-depth calculation' in strip_line.lower() or ':' not in strip_line:
result['in... |
def get_links(links, num):
"""
function to get num number of links out of links list
:param links: contain the list of links
:param num: contain the number of links to be extracts out of list
:return links
"""
il = links[:num]
for i in range(num):
if links:
links.pop(... |
def numstr(x):
""" Convert argument to numeric type.
Attempts to convert argument to an integer. If this fails, attempts to
convert to float. If both fail, return as string.
Args:
x: Argument to convert.
Returns:
The argument as int, float, or string.
"""
try:
ret... |
def get_color_belief(rgb_color, ratio=0.5):
""" Return color proportional to belief (darker is stronger)"""
red, green, blue, alpha = rgb_color
return red, green, blue, (alpha * ratio) |
def untag(tagged_sentence):
"""
Remove the tag for each tagged term.
:param tagged_sentence: a POS tagged sentence
:type tagged_sentence: list
:return: a list of tags
:rtype: list of strings
"""
return [w for w, _ in tagged_sentence] |
def _is_url(string):
"""Checks if the given string is an url path. Returns a boolean."""
return "http" in string |
def data_validation(data):
"""Validate that the given data format is a list of dictionary.
Parameters
----------
data : :obj:`Any`
Data to be validated.
Returns
-------
:obj:`bool`
True: The data is a list of dictionary.\n
False: The data is not a list of dictionary... |
def eV(E):
"""
Returns photon energy in eV if specified in eV or KeV. Assumes that any
value that is less than 100 is in KeV.
Parameters
----------
E : float
The input energy to convert to eV
Returns
-------
E : float
Energy converted to eV from KeV
"""
... |
def getValue(obj, path, defaultValue=None, convertFunction=None):
""""Return the value as referenced by the path in the embedded set of dictionaries as referenced by an object
obj is a node or edge
path is a dictionary path: a.b.c
convertFunction converts the value
This function rec... |
def skipnonsettingsinst(instances):
"""Removes non /settings sections. Useful for only returning settings monolith members.
Example: Members with paths `/redfish/v1/systems/1/bios/` and
`/redfish/v1/systems/1/bios/settings`
will return only the `/redfish/v1/systems/1/bios/settings` member.
:param i... |
def contains(a1,a2,b1,b2):
"""
Check whether one range contains another
"""
return ((a1 >= b1) & (a2 <= b2)) |
def tr(texte):
"""
>>> tr("unittestisbetter")
[20, 13, 8, 19, 19, 4, 18, 19, 8, 18, 1, 4, 19, 19, 4, 17]
"""
texte = "".join(t for t in texte if t != " ")
texte = texte.lower()
l = []
for c in texte:
l += [ord(c) - 97]
return l |
def mark_tail(phrase, keyword, pattern = '%s<span class="tail"> %s</span>'):
"""Finds and highlights a 'tail' in the sentense.
A tail consists of several lowercase words and a keyword.
>>> print mark_tail('The Manual of Pybtex', 'Pybtex')
The Manual<span class="tail"> of Pybtex</span>
Look at the... |
def _is_uint(number):
"""Returns whether a value is an unsigned integer."""
try:
return number == int(number) and number >= 0
except ValueError:
return False |
def EGCD(a, b):
"""
Extended Euclidean algorithm
computes common divisor of integers a and b.
a * x + b * y = gcd(a, b)
returns gcd, x, y or gcd, y, x.
Sorry, I can't remember
"""
if a == 0:
return (b, 0, 1)
else:
b_div_a, b_mod_a = divmod(b, a)
... |
def between(minl:int, maxl:int) -> str:
""" Match the previous pattern at between `minl` and `maxl` times, greedily.
>>> import superexpressive as se
>>> se.between(4,8)
'{4,8}'
>>> import superexpressive as se
>>> se.DIGIT + se.between(6,8)
'\\\\d{6,8}'
"""
return f"{{{mi... |
def sigmoid_deriv(x):
"""
Calculates the sigmoid derivative for the given value.
:param x: Values whose derivatives should be calculated
:return: Derivatives for given values
"""
return x * (1. - x) |
def SedovTaylorSolution(time,energy,density):
"""
Adiabatic solution for a blastwave
See http://www.astronomy.ohio-state.edu/~ryden/ast825/ch5-6.pdf
Parameters
----------
time : float/array
time(s) to calculate at in seconds
energy : float
energy of the blastwave in erg
... |
def path_from_schedule(jobs, start):
""" The evaluation is based on building the travel path.
For example in the network A,B,C with 4 trips as:
1 (A,B), 2 (A,C), 3 (B,A), 4 (C,A)
which have the travel path: [A,B,A,C,B,A,C,A]
The shortest path for these jobs is: [A,C,A,B,A] which uses the order:
... |
def sdp_LM(f, u):
"""Returns the leading monomial of `f`. """
if not f:
return (0,) * (u + 1)
else:
return f[0][0] |
def renormalize(values, old_min, old_max, new_min, new_max):
"""
Transforms values in range [old_min, old_max] to values in range [new_min, new_max]
"""
return (new_max - new_min) * (values - old_min) / (old_max -
old_min) + new_min |
def delete_shot_properties(shot):
"""
Delete no longer necessary properties from shot item.
"""
for key in ['match_shot_resutl_id', 'real_date', 'id']:
if key in shot:
del(shot[key])
return shot |
def populate_metadata(case, config):
""" Provide some top level information for the summary """
return {"Type": "Summary",
"Title": "Performance",
"Headers": ["Proc. Counts", "Mean Time Diff (% of benchmark)"]} |
def CodepointsToUTF16CodeUnits( line_value, codepoint_offset ):
"""Return the 1-based UTF-16 code unit offset equivalent to the 1-based
unicode codepoint offset |codepoint_offset| in the Unicode string
|line_value|"""
# Language server protocol requires offsets to be in utf16 code _units_.
# Each code unit is... |
def calculate_stimulation_freq(flash_time: float) -> float:
"""Calculate Stimulation Frequency.
In an RSVP paradigm, the inquiry itself will produce an
SSVEP response to the stimulation. Here we calculate
what that frequency should be based in the presentation
time.
PARAMETERS
... |
def fastMaxVal(to_consider, available_weight, memo={}):
"""Assumes to_consider a list of items,
available_weight a weight
memo supplied by recursive calls
Returns a tuple of the total value of a
solution to 0/1 knapsack problem and
the items of that solution"""
if... |
def HasProviderInterface(value):
""" Return if the default value has the provider interface """
return hasattr(value, "shouldProvide") and hasattr(value, "getValue") |
def generate_d3_object(word_counts: dict, object_label: str,
word_label: str, count_label: str) -> object:
"""Generates a properly formatted JSON object for d3 use.
:param word_counts: dictionary of words and their count
:param object_label: The label to identify this object.
:pa... |
def Status2Int(protect_status):
"""
returns the int-value related to the input-str
Read / Write := 0
Write protect := 1
"""
rtn_value = 0
if 'yes' in protect_status.lower():
rtn_value = 1
return rtn_value |
def day_count(day, data):
"""count the number of people available on a particular day"""
count = 0
for pid in data:
count = count + data[pid]["avail"][day]
return count |
def number_of_frames_is_int(input):
"""
Validate Number of Frame input.
"""
try:
int(input)
return True
except ValueError:
return False |
def histogram(ratings, sample_weight, min_rating=None, max_rating=None):
"""
Returns the (weighted) counts of each type of rating that a rater made
"""
if min_rating is None:
min_rating = min(ratings)
if max_rating is None:
max_rating = max(ratings)
num_ratings = int(max_rating -... |
def count_iterable(i):
""" want this: len(ifilter(condition, iterable)) """
return sum(1 for e in i) |
def shift(coord_paths, shift_vector):
"""
Take an array of paths and shift them by the coordinate.
"""
new_paths = []
for path in coord_paths:
new_path = []
for point in path:
new_path.append( (point[0] + shift_vector[0], point[1]+ shift_vector[1]))
new_paths.app... |
def convert_to_demisto_severity(severity: str) -> int:
"""Maps xMatters severity to Cortex XSOAR severity
Converts the xMatters alert severity level ('Low', 'Medium',
'High') to Cortex XSOAR incident severity (1 to 4)
for mapping.
:type severity: ``str``
:param severity: severity as returned f... |
def host_is_local(hostname, port):
# https://gist.github.com/bennr01/7043a460155e8e763b3a9061c95faaa0
"""returns True if the hostname points to the localhost, otherwise False."""
return True
# HACK(ethanrublee) getfqdn takes a long time and blocks the control loop.
hostname = socket.getfqdn(hostname... |
def get_numeric_event_attribute_value(event, event_attribute):
"""
Get the value of a numeric event attribute from a given event
Parameters
-------------
event
Event
Returns
-------------
value
Value of the numeric event attribute for the given event
"""
if even... |
def is_Replicated(distribution):
""" Check if distribution is of type Replicated
Parameters
----------
distribution : str, list, tuple
Specified distribution of data among processes.
Default value 'b' : Block
Supported types:
'b' : Block
'r' : Replicated
... |
def find_example1(sequence):
"""
Returns True if the given sequence contains a string,
else returns False.
"""
# Returns True or False
for k in range(len(sequence)):
if type(sequence[k]) == str:
return True
return False |
def split_robot_response(msg):
"""
Split byte string from RobotServer into parts corresponding to:
message id, status, timestamps, tail (rest of the bytes)
"""
elements = msg.split(b':')
msg_id, status, timestamps, pose = elements[:4]
tail = elements[4:]
return msg_id, status, timesta... |
def retrieve_num_instances(service):
"""Returns the total number of instances."""
instance_counts = service["instance-counts"]
return instance_counts["healthy-instances"] + instance_counts["unhealthy-instances"] |
def strike(text: str) -> str:
"""
Return the *text* surrounded by strike HTML tags.
>>> strike("foo")
'<s>foo</s>'
"""
return f"<s>{text}</s>" |
def get_assignment_detail(assignments):
"""
Iterate over assignments detail from response.
:param assignments: assignments detail from response.
:return: list of assignment elements.
"""
return [{
'ID': assignment.get('id', ''),
'FirstName': assignment.get('firstName', ''),
... |
def _group_all(mapping):
"""
Maps every practice contained in the supplied mapping to a single entity,
which we give an ID of None as it doesn't really need an ID
"""
return {practice_code: None for practice_code in mapping.keys()} |
def detect_depth(depths):
"""
Count number of increases between measurements.
Inputs: depths, a list of ints.
Returns: an int.
"""
return sum(x < y for x, y in zip(depths, depths[1:])) |
def hash_djb2(s, seed=5381):
"""
Hash string with djb2 hash function
:type s: ``str``
:param s: The input string to hash
:type seed: ``int``
:param seed: The seed for the hash function (default is 5381)
:return: The hashed value
:rtype: ``int``
"""
hash_name = seed
... |
def get_ratios(vect1, vect2):
"""Assumes: vect1 and vect2 are equal length lists of numbers
Returns: a list containing the meaningful values of
vect1[i]/vect2[i]"""
ratios = []
for index in range(len(vect1)):
try:
ratios.append(vect1[index]/vect2[index])
exce... |
def muli(registers, a, b, c):
"""(multiply immediate) stores into register C the result of multiplying register A and value B."""
registers[c] = registers[a] * b
return registers |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.