content stringlengths 42 6.51k |
|---|
def printout(data):
"""Print and then return the given data."""
print(data.decode('utf-8'))
return data |
def map_label_to_id(labels):
"""
Generate an id for each unique label in the list. Returns a dictionary to map between them.
Parameters
----------
labels: list of str
List of labels
Returns
-------
label_to_id: dict
Unique label to integer id mapping
id_to_label: di... |
def notas(*nota, sit=False):
"""
-> Funcao para analisar notas e situacoes de varios alunos.
:param nota: uma ou mais notas dos alunos (aceita varias)
:param sit: valor opcional, indicando se deve ou nao adicionar a situcao
:return: dicionario com varias informacoes sobre a situacao da turma
"""... |
def get_db(name, server):
"""Get or create database"""
try:
if name not in server:
db = server.create(name)
else:
db = server[name]
except Exception:
return None
return db |
def get_xor_logic_c(key: int) -> str:
"""Return the XOR logic"""
if key == 0:
return ""
else:
return f"for (int i = 0; i < count; ++i)\n\t{{\n\t\tshellcode[i] = (unsigned char)shellcode[i] ^ {hex(key)};\n\t}}" |
def get_n_last_elements(py_list, n_elements):
"""Get the last `n` elements of a list.
Args:
py_list (list): A list of elements.
n_elements (int): The number of elements.
Returns:
sub_list (list): A list with the last `n` elements of `py_list`.
Examples:
>>> py_list = [1,2... |
def get_project_from_manifest(manifest, pid):
"""
Returns the project entry from the manifest
:param manifest:
:param pid:
:return:
"""
if 'projects' not in manifest:
return None
for project in manifest['projects']:
if project['identifier'] == pid:
return proj... |
def check_constraint(variables_set: set, value: int):
"""
This function is used to check whether the given constrain is valid of not
:param variables_set: variables of the constraint
:param value: value of the given constraint
:return: True if the constraint can be satisfied otherwise False
"""
... |
def map_outputs(building_name, outputs, mapping):
"""
Maps outputs from EnergyPlus to OPC tags
Inputs:
building_name- The name of the building
outputs- List of values from EnergyPlus
Outputs:
[(OPC_tag, value)]- List of tuples of tags and values
"""
output_tags = mapping[building_name]["Outputs"]
ret = []
... |
def u8(x):
"""Unpacks a 1-byte string into an integer"""
import struct
return struct.unpack('<B', x)[0] |
def get_index_max_value(tab):
"""This function determine the index of max value of list tab
Parameters :
tab: the list
Returns :
return the index of max value of list
"""
max_val = 0
n = 0
index = 0
for i in tab:
n+=1
if i > max_val:
max_val ... |
def bool_val(string):
"""
Returns a boolean value of a string.
Examples:
>>> bool_val('yes')
True
>>> bool_val('True')
True
>>> bool_val('0')
False
Args:
string (str): string to be evaluated
"""
val = string.lower() in ['true', 't', 'y', ... |
def get_verbose_name(instance, field_name):
"""
Returns verbose_name for a field.
inspired by https://stackoverflow.com/questions/14496978/fields-verbose-name-in-templates
call in template like e.g. 'get_verbose_name <classname> "<fieldname>" '
"""
try:
label = instance._meta.get_field(f... |
def as_bytes(num, final_size):
"""Converts an integer to a reversed bitstring (of size final_size).
Arguments
---------
num: int
The number to convert.
final_size: int
The length of the bitstring.
Returns
-------
list:
A list which is the reversed bi... |
def _get_revert_subject(original_subject):
"""Creates and returns a subject for the revert CL.
If the original CL was a revert CL then 'Revert of' is replaced with
'Reland of'.
If the original CL was a reland CL then 'Reland of' is replaced
with 'Revert of'.
All other CLs get 'Revert of' prefixed to the su... |
def prepend_anaconda_url(url):
"""
Take a partial url and prepend 'https://anaconda.org'
"""
return 'https://anaconda.org%s' % url |
def get_center_trackwindow(trackwindow):
"""
Get center of a track window given as a tuple of :
(xmin, ymin, width, height)
"""
return (trackwindow[0]+(trackwindow[2]/2),trackwindow[1]+(trackwindow[3]/2)) |
def fnmatch_decorate( pattern ):
""" wrap the given string with '*' if there are no other glob symbols in it """
if '*' not in pattern:
if '?' not in pattern:
pattern = '*' + pattern + '*'
return pattern |
def first(condition_function, sequence, default=None):
"""\
Return first item in sequence where condition_function(item) == True,
or None if no such item exists.
"""
for item in sequence:
if condition_function(item):
return item
return default |
def nbr_color(value):
"""Generate the color of a number block
depending to its value
"""
return (150 + value * 10, 120, 100 + (10 - value) * 10) |
def get_aa_at_gene_pos(row, ref_aa_seq_dict):
"""
Helper function to apply on every row of a data frame
to find the reference amino acid at given a gene and amino acid position.
Parameters:
==============
- row: dict
Row of dataframe in dict form. Should have fields aa_pos (1-based aa po... |
def initial_checks(N,n,K,k):
"""
initial_checks(int,int,int,int)
Check correctness of inputs for hypergeometric distributions
Parameters
----------
N : int
Size of the population.
n : int
Size of the sample.
K: int
Number of successes in the population.
k : int
Num... |
def gcd(number1: int, number2: int) -> int:
"""Counts a greatest common divisor of two numbers.
:param number1: a first number
:param number2: a second number
:return: greatest common divisor"""
number_pair = (min(abs(number1), abs(number2)), max(abs(number1), abs(number2)))
while number_pair[... |
def median(v):
"""finds the 'middle-most' value of v"""
n = len(v)
sorted_v = sorted(v)
midpoint = n // 2
if n % 2 == 1:
# if odd, return the middle value
return sorted_v[midpoint]
else:
# if even, return the average of the middle values
lo = midpoint - 1
... |
def extract_extra_labels(metadata_dict):
"""Return the 'extra_labels' labels from metadata_dict, as a list."""
labels = metadata_dict.get('extra_labels', None)
if labels:
extra_labels = labels.split(', ')
extra_labels = [label.lower() for label in extra_labels]
else:
extra_labels... |
def _get_vqsr_annotations(filter_type):
"""Retrieve appropriate annotations to use for VQSR based on filter type.
Issues reported with MQ and bwa-mem quality distribution, results in intermittent
failures to use VQSR:
http://gatkforums.broadinstitute.org/discussion/4425/variant-recalibration-failing
... |
def accuracy(results):
"""
Evaluate the accuracy of results, considering victories and defeats.
"""
return results[1] / (results[0] + results[1]) * 100 |
def union(list1, list2):
"""
Returns the union of two lists
:param list1: first list
:param list2: second list
:return: A list containing the union over list1 and list2
"""
ret = list1[:]
for i in list2:
if i not in ret:
ret.append(i)
return ret |
def create_move_dicts(pdn_moves, moves):
"""
creates two dictionaries to convert pdn_moves to moves. the pdn_moves and the moves need to have the same order
:param pdn_moves: a list of pdn-moves
:param moves: a list of moves
:return:
"""
pdn_dict = {}
move_dict = {}
for pdn_... |
def count_set_bits_using_lookup_table(number):
"""Count bit set using lookup table
This approach requires an O(1) time solution to count the set bits.
However, this requires some preprocessing.
So, we divide our 32-bit input into 8-bit chunks, so there are four chunks.
We have 8 bits in each chunk,... |
def make_ArrayOfInstrument(param, factory):
"""Generates ArrayOfInstrument from a list of RICs"""
if isinstance(param, str):
param = [param]
if isinstance(param, list):
return factory.ArrayOfInstrument([{'code': ric} for ric in param])
else:
return param |
def _id(value: str) -> str:
"""Coerce id by removing '-'."""
return value.replace('-', '') |
def test_path (routes, src_node, dst_node):
"""
Overview: Function to test a path from src_node to dst_node.
Arguments:
- routes: nodes routing table.
- src_node: path source.
- dst_node: path destination.
Returns:
- status: path status (e.g. ok, drop, loop).
- path: current path s... |
def other_end(end1):
"""
Changes scaffold end name from 'fiveprime' to 'threeprime' and vice versa.
"""
name_parts = end1.split("prime_")
if name_parts[0] == "three":
end2 = "fiveprime_" + name_parts[1]
elif name_parts[0] == "five":
end2 = "threeprime_" + name_parts[1]
else:
... |
def normalise_number(v):
"""Attempt to convert a value to a number.
Will convert to int type if it has no decimal places.
@param v: the value (string, int, float, etc) to convert.
@returns: an int or float value
@exception ValueError: if the value cannot be converted
@see: L{is_number}
"""
... |
def addToInventory(inventory, addedItems):
""" Add Items to inventory
Args:
inventory (dict): Inventory containing items and their counts
addedItems (list): Items to add to inventory
Returns:
updatedInventory (dict): Inventory containing updated items and their ... |
def split_project_fullname(project_name):
"""Returns the user, namespace and
project name from a project fullname"""
user = None
namespace = None
if "/" in project_name:
project_items = project_name.split("/")
if len(project_items) == 2:
namespace, project_name = projec... |
def temperate_seasons(year=0):
"""Temperate seasons.
Parameters
----------
year : int, optional
(dummy value).
Returns
-------
out : list of int
seasons of the year.
Notes
-----
Appropriate for use as 'year_cycles' function in :class:`Calendar`.
This module... |
def B23p_T(T):
"""function B23p_T = B23p_T(T)
Section 4.1 Boundary between region 2 and 3.
Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam 1997 Section 4 Auxiliary Equation for the Boundary between Regions 2 and 3
Eq 5, Page 5
"""
return 34... |
def quantize_key_values(key):
"""
Used in the Django trace operation method, it ensures that if a dict
with values is used, we removes the values from the span meta
attributes. For example::
>>> quantize_key_values({'key': 'value'})
# returns ['key']
"""
if isinstance(key, dict)... |
def int_or_None(val):
"""converter that casts val to int, or returns None if val is string 'None'"""
if val == 'None':
return None
else:
return int(val) |
def cstr(v):
"""Convert Python 3.x string to C compatible char *."""
return v.encode('utf8') |
def give_sign_perm(perm0, perm1):
"""Check if 2 permutations are of equal parity.
Assume that both permutation lists are of equal length
and have the same elements. No need to check for these
conditions.
"""
assert len(perm0) == len(perm1)
perm1 = list(perm1) ## copy this into a l... |
def _cleanup_env_list(l):
"""
Remove quote characters and strip whitespace.
Intended to cleanup environment variables that are comma-separated lists parsed by `environ`.
>>> _cleanup_quoted_list(['" something'])
['something']
:param l:
:type l:
:return:
:rtype:
"""
return [... |
def find_similar_chars_n(str1, str2):
"""Returns a string containing only the characters found in both strings
Complexity: O(N)
"""
return ''.join(sorted([char1 for char1 in str1 if char1 in str2])) |
def create_attribute_filter(attribute_name: str, values: list) -> dict:
"""
Create a categorical attribute filter to be used in a trace filter sequence.
Args:
attribute_name:
A string denoting the name of the attribute.
values:
A list of values to be filtered.
R... |
def check_scenarios(scenes):
"""
Make sure all scenarios have unique case insensitive names
"""
assert len(scenes) == len(dict((k.lower(), v) for k, v in scenes))
return scenes |
def normalize_br_tags(s):
"""
I like 'em this way.
>>> normalize_br_tags('Hi there')
'Hi there'
>>> normalize_br_tags('Hi <br>there')
'Hi <br />there'
>>> normalize_br_tags('Hi there<br/>')
'Hi there<br />'
"""
return s.replace("<br>", "<br />").replace("<br/>", "<br />") |
def tec_factor(f1, f2):
"""Tec_factor(f1, f2) -> the factor.
TEC factor to calculate TEC, TECU.
Parameters
----------
f1 : float
f2 : float
Returns
-------
factor : float
"""
return (1 / 40.308) * (f1 ** 2 * f2 ** 2) / (f1 ** 2 - f2 ** 2) * 1.0e-16 |
def _prune_dict(dic):
"""Remove entries with empty string value
"""
new = {}
for key, item in dic.items():
if item:
new[key] = item
return new |
def submatrix(mat, rows=None, cols=None):
"""Returns the submatrix of mat"""
if rows is None:
rows = range(len(mat))
if cols is None:
cols = range(len(mat[0]))
mat2 = []
for i in rows:
mat2.append([])
for j in cols:
mat2[-1].append(mat[i][j])
retur... |
def payloadDictionary(payload, lst):
"""creates payload dictionary.
Args:
payload: String
SQL query
lst: List of Strings
keywords for payload dictionary
Returns:
dikt: dictionary
dictionary using elements ... |
def is_relevant_assembly(rel_type, asm_level, refseq_category, refseq_acc):
""" Determine if assembly is suitable for SCP
"""
if (rel_type in 'Major' and asm_level == 'Chromosome') == False:
# Exclude patch assemblies, and genomes that lack assembled chromosomes
return False
if refseq_... |
def build_mzi_list(numModes, numPhotons=None):
"""gives reck MZI addresses in [diagonal, mode], in order of
construction
"""
if numPhotons is None:
ls = []
for j in range(numModes-1):
lsloc = []
for i in range(j, numModes-1):
lsloc.append((j, i))
... |
def generate_artifact_link(owner: str, name: str) -> str:
"""Generate link for downloading artifacts
:param owner: Github repo owner name
:type owner: str
:param name: Github repo name
:type name: str
:returns: Link to api to download artifacts
:rtype: str
"""
return f"https://api.... |
def force_text(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Similar to smart_text, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
"""
# Handle the common case first for... |
def find_anagrams_in(sentence):
"""Find pairs of anagrams the sentence.
Params
------
sentence: str
Sequence of words.
Returns
-------
list
A list of anagrams.
"""
words_unique = list(set(sentence.lower().split(" "))) # removed duplicates
wor... |
def getGamesListUrl(user_name, page, block_size=100):
"""Returns lichess url for downloading list of games"""
URL_TEMPLATE = "https://en.lichess.org/api/user/{}/games?page={}&nb={}"
return URL_TEMPLATE.format(user_name, page, block_size) |
def from_list_points_timestamps(timestamps, gap=1):
""" Convert list of timestamps to list of tuples.
Convert a list of anomalies identified by timestamps,
to a list of tuples marking the start and end interval
of anomalies; make it contextually defined.
Args:
timestamps (list): contains t... |
def set_config_value_unknown(config_dict, find_key, new_value, unknown):
"""for a given dictionary, it will recursively search for the key.
if a key is found it will assign the new value
if the key is not found, it will assign the key-value pair to the
unknown key in the dictionary
"""
def _se... |
def is_consecutive(ls):
"""
Returns true iff ls represents a list of consecutive numbers.
"""
return all((y - x == 1) for x, y in zip(ls, ls[1:])) |
def _format_args(args):
"""Formats a series of arguments as an STSADM argument string"""
argstring = ""
for kw in args.keys():
if type(args[kw]) is bool:
if args[kw] == True:
argstring += "-" + kw
else:
argstring += "-" + kw + " \"" + args[kw] + "\""
argstring += " "
return argstring |
def array_unique(array):
"""
Removes duplicate values from an array
"""
return list(set(array)) |
def italic(string: str) -> str:
"""
Add italic md style.
:param string: The string to process.
:type string:str
:return: Formatted String.
:rtype: str
"""
return f"*{string}*" |
def first_non_repeating_letter(string):
"""Return first non repeating letter or '' if none."""
for i in string:
if string.lower().count(i.lower()) == 1:
return i
else:
return '' |
def isIterable( obj ):
"""
Returns a boolean whether or not 'obj' is iterable, e.g. is a collection,
a collection view, a string, a generator, etc.
"""
try:
iter(obj)
except TypeError:
return False
else:
return True |
def population2(generation, fis):
"""
A imperative Pythonic translation of the functional solution using mutable state,
which probably is more efficient in Python's execution environment.
"""
for _ in range(generation):
spawn = fis.pop(0)
fis.append(spawn)
fis[6] += spawn
... |
def quest_to_title(quest):
""" Returns a quest name (lower case) in the proper title format. """
return quest.title()\
.replace(' Ii', ' II')\
.replace("'S", "'s")\
.replace(' Of ', ' of ')\
.replace(' The ', ' the ')\
.replace(' From ', ' from ')\
.replace(' And ', ' and ')\
.replace(' In ', '... |
def _scrub_cdata_content(text):
""" User should scrub data themselves; but this gives ideas of what goes wrong when adding text to Solr
<,>,& all must be escaped.
"""
return text.replace('<', '(less than)').replace('>', '(greater than)').replace('&', '& ') |
def scale_list(l, scale_value):
"""Scale all the parameters on a list by the same value
The operates on the list in place
Parameters
----------
l : list
scale_value : float
Returns
-------
l : list
"""
for i, v in enumerate(l):
l[i] = v * scale_value
return ... |
def error_label(error):
"""Get the alert box/label coloring based on error found."""
levels = dict()
levels['wrong-import-position'] = 'info'
levels['fatal'] = 'danger'
levels['MC0001'] = 'warning' # McCabe's cyclomatic complexity warning.
if error not in levels:
return 'warning'
re... |
def facing_to_vector2d(facing):
"""
Convert a string facing to a vector2d.
Parameter
---------
facing: facing to convert <up|down|left|right|up-left|up-right|down-left|down-right>(str).
Return
------
vector: vector2d from facing (tuple(int, int)).
Version
-------
Specifica... |
def csv_to_list(x):
"""Converts a comma separated string to a list of strings."""
return x.split(",") |
def fn_basename(fn, ext):
"""return the basename of fn based on ext"""
if '.' in ext:
return(fn[:-len(ext)])
else:
return(fn[:-(len(ext)+1)]) |
def list_animals(animals) -> str:
"""This function formats animals string."""
string = ''
for i in range(len(animals)):
string += str(i + 1) + '. ' + animals[i] + '\n'
return string |
def _resource_differ(resource, revision):
"""Check if resource differ from resource revision is created for."""
return (resource is None or
revision.resource_type != resource.__class__.__name__ or
revision.resource_id != resource.id) |
def upper(value): #Only one argument
"""Converts a string into all uppercase"""
return value.upper() |
def strip_list(list):
"""Strips individual elements of the strings"""
return [item.strip() for item in list] |
def defuzz_centroid(fset):
"""
Defuzzification using centroid (`center of gravity`) method.
Parameters
----------
fset : dictionary, length M
Fuzzy set
Returns
-------
center : float,
center of gravity
"""
# check for input type
if not isinstance(fset,... |
def jwt_response_payload_handler(token, user=None, request=None):
"""
Returns the response data for both the login and refresh views.
Override to return a custom response such as including the
serialized representation of the User.
Example:
def jwt_response_payload_handler(token, user=None, re... |
def fixDateForSafari(s):
""" reformat data string if taken from Safari"""
if s[2] == '/':
return s[6:] + '-' + s[:2] + '-' + s[3:5]
return s |
def filter_by_genre(shows, genre):
"""
This function filters a list of shows by genre.
Parameters:
shows (list): A list of shows
genre (str): A string representing a genre of shows
Returns:
(list): A list of shows that match the given genre
"""
filtered_shows = []
f... |
def prepare_show_ipv6_interface_output(data):
"""
Helper function to prepare show ipv6 interface output
:param data:
:return:
"""
output = dict()
result = list()
for ip_data in data:
if output.get(ip_data["interface"]):
output[ip_data["interface"]].append(ip_data)
... |
def indent_iterable(elems, num=2):
"""Indent an iterable."""
return [" " * num + l for l in elems] |
def _get_host_meta_vars_as_dict(inventory):
"""parse host meta vars from inventory as dict"""
host_meta_vars = {}
if '_meta' in inventory.keys():
if 'hostvars' in inventory['_meta']:
for host in inventory['_meta']['hostvars'].keys():
host_meta_vars[host] = ' '.join(
... |
def delanguageTag(obj):
"""
Function to take a language-tagged list of dicts and return an untagged
string.
:param obj: list of language-tagged dict
:type obj: list
:returns: string
"""
if not isinstance(obj, list):
return(obj)
data = (obj if len(obj) else [{}])[-1]
ret... |
def guess(key, values):
"""
Returns guess values for the parameters of this function class based on the input. Used for fitting using this
class.
"""
return 0, 10, 100e-6, 2e-3 |
def print_summary(docstring: str) -> None:
"""
Prints a function's docstring.
Args:
docstring (str): documentation
"""
print('\n')
print('The `verbose` flag was set to `True`\n')
print('Summary of main function:\n')
print(docstring)
print('\n')
return None |
def divide_numbers(numerator, denominator):
"""For this exercise you can assume numerator and denominator are of type
int/str/float.
Try to convert numerator and denominator to int types, if that raises a
ValueError reraise it. Following do the division and return the result.
However if denominator ... |
def _polygon_area(x, y):
"""
Function to compute the area of a polygon by giving its coordinates in
counter-clockwise order.
"""
area = 0
j = len(x)-1;
for i in range (0, len(x)):
area += (x[j]+x[i]) * (y[i]-y[j]);
j = i
return area/2; |
def display_time(seconds, granularity=1):
""" Turns seconds into weeks, days, hours, minutes and seconds.
Granularity determines how many time units should be returned. EG:
# 2 time unites, week and day
1934815, 2 = '3 weeks, 1 day'
# 4 time units
1934815, 4 = '3 weeks, 1 day, 9 hours, 26 minute... |
def repeats(arr: list) -> int:
""" This function returns the sum of the numbers that occur only once. """
no_repeats = []
for i in sorted(arr):
if arr.count(i) == 1:
no_repeats.append(i)
return (sum(no_repeats)) |
def validate_kmer_size(kmer_size: str) -> int:
"""
Transform and validate input k-mer size
:param kmer_size: Input k-mer size as string
:return: K-mer size as int
"""
value = int(kmer_size)
assert 1 <= value <= 32
return value |
def to_time(seconds):
"""
Convert *n* seconds to a :py:class:`str` with this pattern: "{min}:{sec:02}".
:type seconds: int
:param seconds: Number of seconds to be converted.
:rtype: str
:return: Returns a string formatted as #:##. E.g. "1:05"
"""
minutes = int(seconds / 60)
seconds = seconds ... |
def convert_min_required_version(version):
"""Converts the minimal required SPIR-V version encoded in the grammar to
the symbol in SPIRV-Tools."""
if version is None:
return 'SPV_SPIRV_VERSION_WORD(1, 0)'
if version == 'None':
return '0xffffffffu'
return 'SPV_SPIRV_VERSION_WOR... |
def calc_tstart(num_bins, binsize, t_stop):
"""
Calculates the start point from given parameter.
Calculates the start point :attr:`t_start` from the three parameter
:attr:`t_stop`, :attr:`num_bins` and :attr`binsize`.
Parameters
----------
num_bins: int
Number of bins
binsize: ... |
def init_box_map(name):
"""Initialize a box map suitable for a convertion to JSON."""
return {"name": name, "versions": []} |
def preprocess_yaml_type_array(typeArray):
"""
Flattens an array type into a tuple list that can be used to get the
supported cpp type from each element.
"""
result = []
for i in range(len(typeArray)):
# Ignore lists because we merge them with the previous element
if type(typeA... |
def bv_slice(value, offset, size, rev, bw):
"""
Extremely cute utility to pretend you've serialized a value to stored bytes, sliced it a la python slicing, and then
deserialized those bytes to an integer again.
:param value: The bitvector to slice
:param offset: The byte offset from the first st... |
def retrieve(result_queue, queue_size):
""" Retrieve results from a shared queue.
"""
results = []
while queue_size:
results.append(result_queue.get())
queue_size -= 1
return results |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.