content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def double_middle_drop(progress): """ Returns a linear value with two drops near the middle to a constant value for the Scheduler :param progress: (float) Current progress status (in [0, 1]) :return: (float) if 0.75 <= 1 - p: 1 - p, if 0.25 <= 1 - p < 0.75: 0.75, if 1 - p < 0.25: 0.125 """ eps1 = 0.75 eps2 = 0.25 if 1 - progress < eps1: if 1 - progress < eps2: return eps2 * 0.5 return eps1 * 0.1 return 1 - progress
bfdf14ac75e63b88160f6c511d26c76031f9c663
41,453
def split_info_from_job_url(BASE_URL, job_rel_url): """ Split the job_rel_url to get the separated info and create a full URL by combining the BASE_URL and the job_rel_url :params: job_rel_url str: contain the Relative Job URL :returns: job_id str: the unique id contained in the job_rel_url job_name str: the name of the job job_full_url str: full URL of the job ads """ splitted_url = [i for i in job_rel_url.split("/") if i] # The first element of the list is 'job' as the structure # of the string is like this: # /job/BJR877/assistant-professor-associate-professor-full-professor-in-computational-environmental-sciences-and-engineering/ if len(splitted_url) != 3: raise job_id = splitted_url[1] job_name = splitted_url[2] job_full_url = BASE_URL + job_rel_url return job_id, job_name, job_full_url
276db11041c18a1675ca10b9581a898787b11321
41,457
def get_long_id(list_session_id): """Extract longitudinal ID from a set of session IDs. This will create a unique identifier for a participant and its corresponding sessions. Sessions labels are sorted alphabetically before being merged in order to generate the longitudinal ID. Args: list_session_id (list[str]): List of session IDs (e.g. ["ses-M00"] or ["ses-M00", "ses-M18", "ses-M36"]) Returns: Longitudinal ID (str) Example: >>> from clinica.utils.longitudinal import get_long_id >>> get_long_id(['ses-M00']) 'long-M00' >>> get_long_id(['ses-M00', 'ses-M18', 'ses-M36']) 'long-M00M18M36' >>> get_long_id(['ses-M18', 'ses-M36', 'ses-M00']) # Session IDs do not need to be sorted 'long-M00M18M36' """ sorted_list = sorted(list_session_id) list_session_label = [session_id[4:] for session_id in sorted_list] long_id = "long-" + "".join(list_session_label) return long_id
f5b0ffa6fe75c9059453d0a2d32456dd88da2a16
41,460
def get_attrname(name): """Return the mangled name of the attribute's underlying storage.""" return '_obj_' + name
02d7983a02f7a112479d6289ab1a4ddcb8a104a7
41,468
def extract_valid_libs(filepath): """Evaluate syslibs_configure.bzl, return the VALID_LIBS set from that file.""" # Stub only def repository_rule(**kwargs): # pylint: disable=unused-variable del kwargs # Populates VALID_LIBS with open(filepath, 'r') as f: f_globals = {'repository_rule': repository_rule} f_locals = {} exec(f.read(), f_globals, f_locals) # pylint: disable=exec-used return set(f_locals['VALID_LIBS'])
e8e9b60dcd86e6216b7d3d321a079da09efa19e8
41,475
import itertools def normalise_environment(key_values): """Converts denormalised dict of (string -> string) pairs, where the first string is treated as a path into a nested list/dictionary structure { "FOO__1__BAR": "setting-1", "FOO__1__BAZ": "setting-2", "FOO__2__FOO": "setting-3", "FOO__2__BAR": "setting-4", "FIZZ": "setting-5", } to the nested structure that this represents { "FOO": [{ "BAR": "setting-1", "BAZ": "setting-2", }, { "BAR": "setting-3", "BAZ": "setting-4", }], "FIZZ": "setting-5", } If all the keys for that level parse as integers, then it's treated as a list with the actual keys only used for sorting This function is recursive, but it would be extremely difficult to hit a stack limit, and this function would typically by called once at the start of a program, so efficiency isn't too much of a concern. """ # Separator is chosen to # - show the structure of variables fairly easily; # - avoid problems, since underscores are usual in environment variables separator = "__" def get_first_component(key): return key.split(separator)[0] def get_later_components(key): return separator.join(key.split(separator)[1:]) without_more_components = { key: value for key, value in key_values.items() if not get_later_components(key) } with_more_components = { key: value for key, value in key_values.items() if get_later_components(key) } def grouped_by_first_component(items): def by_first_component(item): return get_first_component(item[0]) # groupby requires the items to be sorted by the grouping key return itertools.groupby(sorted(items, key=by_first_component), by_first_component) def items_with_first_component(items, first_component): return { get_later_components(key): value for key, value in items if get_first_component(key) == first_component } nested_structured_dict = { **without_more_components, **{ first_component: normalise_environment( items_with_first_component(items, first_component) ) for first_component, items in grouped_by_first_component(with_more_components.items()) }, } def all_keys_are_ints(): def is_int(string_to_test): try: int(string_to_test) return True except ValueError: return False # pylint: disable=use-a-generator return all([is_int(key) for key, value in nested_structured_dict.items()]) def list_sorted_by_int_key(): return [ value for key, value in sorted( nested_structured_dict.items(), key=lambda key_value: int(key_value[0]) ) ] return list_sorted_by_int_key() if all_keys_are_ints() else nested_structured_dict
b8670458415404d673e530b0a6e15c9a050ea4ca
41,476
def create_commit(mutations): """A fake Datastore commit method that writes the mutations to a list. Args: mutations: A list to write mutations to. Returns: A fake Datastore commit method """ def commit(req): for mutation in req.mutations: mutations.append(mutation) return commit
dc7cfa4c3f79076c2b67e3261058ab5d55e1f189
41,478
def is_paired(input_string:str): """ Determine that any and all pairs are matched and nested correctly. :param input_string str - The input to check :return bool - If they are matched and nested or not. """ stack = [] for char in input_string: if char in ['[', '{', '(']: stack.append(char) elif char in [']', '}', ')']: # Closing bracket with no open brackets. if len(stack) == 0: return False element = stack.pop() if element == '[' and char == ']': continue elif element == '{' and char == '}': continue elif element == '(' and char == ')': continue return False return len(stack) == 0
040d79e471831d4444ffded490f39ed90247e39e
41,480
import random def random_value_lookup(lookup): """Returns a object for a random key in the lookup.""" __, value = random.choice(list(lookup.items())) return value
b1d7b3859cd9232df2a41505ee4f2bdfaa2607a4
41,484
def symbols(vma): """ Obtain the atomic symbols for all atoms defined in the V-Matrix. :param vma: V-Matrix :type vma: automol V-Matrix data structure :rtype: tuple(str) """ return tuple(zip(*vma))[0] if vma else ()
3f2a547e7ec0eb17e681ec2fe5de93057fdaa22a
41,491
import pickle def decode_dict(dictionary): """Decodes binary dictionary to native dictionary Args: dictionary (binary): storage to decode Returns: dict: decoded dictionary """ decoded_dict = pickle.loads(dictionary) return decoded_dict
158d7db725f1856c276f867bfea3482c3fbe283b
41,494
def form_fastqc_cmd_list(fastqc_fp, fastq_fp, outdir): """Generate argument list to be given as input to the fastqc function call. Args: fastqc_fp(str): the string representing path to fastqc program fastq_fp(str): the string representing path to the fastq file to be evaluated outdir(str): the string representing the path to the output directory Return value: call_args(list): the list of call_args representing the options for the fastqc subprocess call Raises: ValueError is raised when either the fastqc path or the fastqc input files are empty """ # throw exceptions to prevent user from accidentally using interactive fastqc if fastqc_fp is '': raise ValueError('fastqc_fp name is empty') if fastq_fp is '': raise ValueError('fastq_fp file name is empty') # required arguments call_args_list = [fastqc_fp, fastq_fp] # direct output if outdir is not None: call_args_list.extend(["--outdir", outdir]) return call_args_list
ce0ed8eb7d35bdd2565f910bb982da710daa23c5
41,495
from datetime import datetime def get_timestamp_utc() -> str: """Return current time as a formatted string.""" return datetime.utcnow().strftime("%Y-%m-%d-%H%M%S")
05a1cfeeda438a8f5f9857698cb2e97e4bb62e96
41,496
def rtd10(raw_value): """Convert platinum RTD output to degrees C. The conversion is simply ``0.1 * raw_value``. """ return (float(raw_value) / 10.0, "degC")
5b44908c722ff8298cf2f4985f25e00e18f05d21
41,500
def reverse_list(l): """ return a list with the reverse order of l """ return l[::-1]
21bf60edf75a6016b01186efccdae9a8dd076343
41,503
import requests def query_graphql(query, variables, token): """Query GitHub's GraphQL API with the given query and variables. The response JSON always has a "data" key; its value is returned as a dictionary.""" header = {"Authorization": f"token {token}"} r = requests.post("https://api.github.com/graphql", json={"query": query, "variables": variables}, headers=header) r.raise_for_status() return r.json()["data"]
72da627b5600973303ae4001bf3b07f738212f04
41,506
def get_passive_el(passive_coord, centroids): """ Gets index of passive elements . Args: passive_coord (:obj:`tuple`): Region that the shape will not be changed. centroids (:obj:`numpy.array`): Coordinate (x,y) of the centroid of each element. Returns: Index of passive elements. """ mask = (centroids[:, 0] >= passive_coord[0][0]) & (centroids[:, 0] <= passive_coord[0][1]) & (centroids[:, 1] >= passive_coord[1][0]) & (centroids[:, 1] <= passive_coord[1][1]) return (mask > 0).nonzero()[0]
9983ee9d730ced9f8ce56790c07af22c9dfcdb0d
41,507
def get_exposure_id(exposure): """Returns exposure id. """ expinf = exposure.getInfo() visinf = expinf.getVisitInfo() expid = visinf.getExposureId() return expid
a269a08cd62b629d65db803d92d6e6356b76feab
41,508
import re def escapeRegex(text): """ Escape string to use it in a regular expression: prefix special characters « ^.+*?{}[]|()\$ » by an antislash. """ return re.sub(r"([][^.+*?{}|()\\$])", r"\\\1", text)
97f13b05996daf2a7d01ade0e428244bed156af4
41,509
def none(active): """No tapering window. Parameters ---------- active : array_like, dtype=bool A boolean array containing ``True`` for active loudspeakers. Returns ------- type(active) The input, unchanged. Examples -------- .. plot:: :context: close-figs plt.plot(sfs.tapering.none(active1)) plt.axis([-3, 103, -0.1, 1.1]) .. plot:: :context: close-figs plt.plot(sfs.tapering.none(active2)) plt.axis([-3, 103, -0.1, 1.1]) """ return active
e323f7e153049a4f663688d7bee4b73bd8dd1ca9
41,513
import re def get_sandwich(seq, aa="FYW"): """ Add sandwich counts based on aromatics. Parameters: seq: str, peptide sequence aa: str, amino acids to check fo rsandwiches. Def:FYW """ # count sandwich patterns between all aromatic aminocds and do not # distinguish between WxY and WxW. pattern = re.compile(r"(?=([" + aa + "][^" + aa + "][" + aa + "]))") return len(re.findall(pattern, seq))
d8df68a1873d3912aa64fc91563aae9827da324c
41,514
def is_param_free(expr) -> bool: """Returns true if expression is not parametrized.""" return not expr.parameters()
e9dadcaae0c9c0cdcffe1afe5202925d98c6b4fb
41,519
def null_count(df): """ Returns the number of null values in the input DataFrame """ return df.isna().sum().sum()
d92582292a01412df3433cfaa69ec68a92057301
41,522
def get_armstrong_value(num): """Return Armstrong value of a number, this is the sum of n**k for each digit, where k is the length of the numeral. I.e 54 -> 5**2 + 4**2 -> 41. Related to narcisstic numbers and pluperfect digital invariants. """ num = str(num) length = len(num) armstrong_value = 0 for char in num: armstrong_value += int(char)**length return armstrong_value
fd0692566ab0beffb785c1ac4fbd4aa27893cfbf
41,523
import re def convert_bert_word(word): """ Convert bert token to regular word. """ return re.sub("##|\[SEP\]|\[CLS\]", "", word)
f7f7d95fd7fd90b55a104ce13e10b08f6ae0c9f0
41,526
def cleanly_separate_key_values(line): """Find the delimiter that separates key from value. Splitting with .split() often yields inaccurate results as some values have the same delimiter value ':', splitting the string too inaccurately. """ index = line.find(':') key = line[:index] value = line[index + 1:] return key, value
d790f6bca2b52ee87bce01467a561901ba08655d
41,527
def batch(tensor, batch_size = 50): """ It is used to create batch samples, each batch has batch_size samples""" tensor_list = [] length = tensor.shape[0] i = 0 while True: if (i+1) * batch_size >= length: tensor_list.append(tensor[i * batch_size: length]) return tensor_list tensor_list.append(tensor[i * batch_size: (i+1) * batch_size]) i += 1
2b4b10520fd72b90ebe1239b7f52e61ba442484d
41,528
def mse(predictions, targets): """Compute mean squared error""" return ((predictions - targets) ** 2).mean()
516c8767731577db36dc4b503c179c034fca1166
41,531
def _command(register_offset, port_number, register_type): """Return the command register value corresponding to the register type for a given port number and register offset.""" return (register_offset * register_type) + port_number
d09815a2451e86448e0da280c8b037b59cfbd87b
41,532
import math def myceil(x, base=10): """ Returns the upper-bound integer of 'x' in base 'base'. Parameters ---------- x: float number to be approximated to closest number to 'base' base: float base used to calculate the closest 'largest' number Returns ------- n_high: float Closest float number to 'x', i.e. upper-bound float. Example ------- >>>> myceil(12,10) 20 >>>> >>>> myceil(12.05, 0.1) 12.10000 """ n_high = float(base*math.ceil(float(x)/base)) return n_high
6e52b99755cdd25b882f707c54c3ff27f8ff279e
41,537
def get_branch_name(ref): """ Take a full git ref name and return a more simple branch name. e.g. `refs/heads/demo/dude` -> `demo/dude` :param ref: the git head ref sent by GitHub :return: str the simple branch name """ refs_prefix = 'refs/heads/' if ref.startswith(refs_prefix): # ref is in the form "refs/heads/master" ref = ref[len(refs_prefix):] return ref
bb7e791c6dac430fef9a38f8933879782b943fd1
41,542
def stdin(sys_stdin): """ Imports standard input. """ return [int(x.strip()) for x in sys_stdin]
54964452384ae54961472328e603066f69391957
41,546
from typing import Tuple def parse_interval(interval: str) -> Tuple[str, str, str]: """ Split the interval in three elements. They are, start time of the working day, end time of the working day, and the abbreviation of the day. :param interval: A str that depicts the day, start time and end time in one string. Ex.: 'SA14:00-18:00' :return: A tuple with three strings. Ex.: ('SA', '14:00', '18:00') """ interval_parsed = interval.split('-') day = interval_parsed[0][:2] # SU initial_hour = interval_parsed[0][2:] # '19:00' end_hour = interval_parsed[1] # '21:00' return day, initial_hour, end_hour
f2bac53a1b56e1f6371187743170646c08109a27
41,547
def surrogate_loss(policy, all_obs, all_actions, all_adv, old_dist): """ Compute the loss of policy evaluated at current parameter given the observation, action, and advantage value Parameters ---------- policy (nn.Module): all_obs (Variable): all_actions (Variable): all_adv (Variable): old_dist (dict): The dict of means and log_stds Variables of collected samples Returns ------- surr_loss (Variable): The surrogate loss function wrapped in Variable """ new_dist = policy.get_policy_distribution(all_obs) old_dist = policy.distribution(old_dist) ratio = new_dist.likelihood_ratio(old_dist, all_actions) surr_loss = -(ratio * all_adv).mean() return surr_loss
26e0f53e91a9537a4b9d0bfc3a3122dbe4917fc2
41,550
def _get_zero_one_knapsack_matrix(total_weight: int, n: int) -> list: """Returns a matrix for a dynamic programming solution to the 0/1 knapsack problem. The first row of this matrix contains the numbers corresponding to the weights of the (sub)problems. The first column contains an enumeration of the items, starting from the fact that we could not include any item, and this is represented with a 0. m[0][0] is 0 just because of the alignment, it does make any logical sense for this purpose, it could be None, or any other value.""" m = [[0 for _ in range(total_weight + 2)] for _ in range(n + 2)] for x in range(1, total_weight + 2): m[0][x] = x - 1 for j in range(1, n + 2): m[j][0] = j - 1 m[j][1] = 0 return m
bc96eb43f487b6ad20b143c177474ba04afc2319
41,551
def read_atom_file(file): """Read file with atoms label Args: file (str): Name of file with atoms labels Returns: list: atoms labeled as <Residue Name> <Atom Name> """ atoms = [line.rstrip('\n').split() for line in open(file, "r")] atoms = [[a[0] + " " + aa for aa in a[1::]] for a in atoms] return atoms
3d85dff55f7165d1c9b747eb75d395ec03f5b3ce
41,554
def combine_bolds(graph_text): """ Make ID marker bold and remove redundant bold markup between bold elements. """ if graph_text.startswith("("): graph_text = ( graph_text.replace(" ", " ") .replace("(", "**(", 1) .replace(")", ")**", 1) .replace("** **", " ", 1) ) return graph_text
b87afc51de6bb1e83c0f8528773e50f5d797fe2d
41,555
def format_id(kepler_id): """Formats the id to be a zero padded integer with a length of 9 characters. No ID is greater than 9 digits and this function will throw a ValueError if such an integer is given. :kepler_id: The Kepler ID as an integer. :returns: A 0 padded formatted string of length 9. """ return f'{kepler_id:09d}'
427726b825f6ee1c4a20c07d098a3a063c18a0c1
41,556
def rev_comp(s): """A simple reverse complement implementation working on strings Args: s (string): a DNA sequence (IUPAC, can be ambiguous) Returns: list: reverse complement of the input sequence """ bases = { "a": "t", "c": "g", "g": "c", "t": "a", "y": "r", "r": "y", "w": "w", "s": "s", "k": "m", "m": "k", "n": "n", "b": "v", "v": "b", "d": "h", "h": "d", "A": "T", "C": "G", "G": "C", "T": "A", "Y": "R", "R": "Y", "W": "W", "S": "S", "K": "M", "M": "K", "N": "N", "B": "V", "V": "B", "D": "H", "H": "D"} sequence = list(s) complement = "".join([bases[b] for b in sequence]) reverse_complement = complement[::-1] return reverse_complement
3fd61300016da5e8546f0c00303a8477af79902f
41,559
def sumIO(io_list, pos, end_time): """ Given io_list = [(timestamp, byte_count), ...], sorted by timestamp pos is an index in io_list end_time is either a timestamp or None Find end_index, where io_list[end_index] is the index of the first entry in io_list such that timestamp > end_time. Sum the byte_count values in io_list from [pos..end_index). Return (sum_byte_count, end_index). """ sum_byte_count = 0 # print(f'sum to {end_time}') while pos < len(io_list) and io_list[pos][0] <= end_time: # print(f' {pos}') sum_byte_count += io_list[pos][1] pos += 1 return (sum_byte_count, pos)
a6b36148e05ac57f599bc6c68ffac242020dc65f
41,561
def is_child_class(target, base): """ Check if the target type is a subclass of the base type and not base type itself """ return issubclass(target, base) and target is not base
731c551149f94401a358b510aa124ee0cba6d0bd
41,567
def get_pyramid_single(xyz): """Determine to which out of six pyramids in the cube a (x, y, z) coordinate belongs. Parameters ---------- xyz : numpy.ndarray 1D array (x, y, z) of 64-bit floats. Returns ------- pyramid : int Which pyramid `xyz` belongs to as a 64-bit integer. Notes ----- This function is optimized with Numba, so care must be taken with array shapes and data types. """ x, y, z = xyz x_abs, y_abs, z_abs = abs(x), abs(y), abs(z) if (x_abs <= z) and (y_abs <= z): # Top return 1 elif (x_abs <= -z) and (y_abs <= -z): # Bottom return 2 elif (z_abs <= x) and (y_abs <= x): # Front return 3 elif (z_abs <= -x) and (y_abs <= -x): # Back return 4 elif (x_abs <= y) and (z_abs <= y): # Right return 5 else: # (x_abs <= -y) and (z_abs <= -y) # Left return 6
8fe2fbc727f13adf242094c3b0db3805af31a1e9
41,569
import copy def get_midpoint_radius(pos): """Return the midpoint and radius of the hex maze as a tuple (x,y), radius. Params ====== pos: PositionArray nelpy PositionArray containing the trajectory data. Returns ======= midpoint: (x0, y0) radius: float """ # make a local copy of the trajectory data local_pos = copy.copy(pos) # merge the underlyng support to make computations easier local_pos._support = pos.support.merge(gap=10) # apply smoothing to tame some outliers: local_pos = local_pos.smooth(sigma=0.02) midpoint = local_pos.min() + (local_pos.max() - local_pos.min())/2 radius = ((local_pos.max() - local_pos.min())/2).mean() return midpoint, radius
76290309f12e00b6a487f71b2393fabd8f3944ac
41,570
from pathlib import Path from typing import Tuple from typing import List def listdir_grouped(root: Path, ignore_folders=[], include_hidden=False) -> Tuple[List, List]: """Dizindeki dosya ve dizinleri sıralı olarak listeler Arguments: root {Path} -- Listenelecek dizin Keyword Arguments: ignore_folders {list} -- Atlanılacak yollar (default: {[]}) include_hidden {bool} -- Gizli dosyaları dahil etme (default: {False}) Returns: tuple -- dizin, dosya listesi Examples: >>> dirs, files = listdir_grouped(".") """ if isinstance(root, str): root = Path(root) paths = [x for x in root.iterdir()] dirs, files = [], [] for path in paths: condition = not include_hidden and path.name.startswith('.') condition = condition and path.name not in ignore_folders condition = not condition if condition: dirs.append(path) if path.is_dir() else files.append(path) dirs.sort() files.sort() return dirs, files
13d2ea09cafd3b4062714cbf151c0a4b290616e1
41,574
from typing import Optional from typing import List def _with_config_file_cmd(config_file: Optional[str], cmd: List[str]): """ Prefixes `cmd` with ["--config-file", config_file] if config_file is not None """ return (["--config-file", config_file] if config_file else []) + cmd
a7a93f2b089e4265a22fb7fd0ccced1e78e1c55c
41,575
def _clip_points(gdf, poly): """Clip point geometry to the polygon extent. Clip an input point GeoDataFrame to the polygon extent of the poly parameter. Points that intersect the poly geometry are extracted with associated attributes and returned. Parameters ---------- gdf : GeoDataFrame, GeoSeries Composed of point geometry that will be clipped to the poly. poly : (Multi)Polygon Reference geometry used to spatially clip the data. Returns ------- GeoDataFrame The returned GeoDataFrame is a subset of gdf that intersects with poly. """ return gdf.iloc[gdf.sindex.query(poly, predicate="intersects")]
c7f21807d28f37044a4f36f4ededce26defbb837
41,578
import re def get_relval_id(file): """Returns unique relval ID (dataset name) for a given file.""" dataset_name = re.findall('R\d{9}__([\w\d]*)__CMSSW_', file) return dataset_name[0]
5b3369920ae86d7c4e9ce73e1104f6b05779c6d4
41,584
def splitdrive(path): """Split a pathname into drive and path specifiers. Returns a 2-tuple "(drive,path)"; either part may be empty. """ # Algorithm based on CPython's ntpath.splitdrive and ntpath.isabs. if path[1:2] == ':' and path[0].lower() in 'abcdefghijklmnopqrstuvwxyz' \ and (path[2:] == '' or path[2] in '/\\'): return path[:2], path[2:] return '', path
ed50877516130669cfe0c31cd8a6d5085a83e7c6
41,586
import re def safe_filename(url): """ Sanitize input to be safely used as the basename of a local file. """ ret = re.sub(r'[^A-Za-z0-9]+', '.', url) ret = re.sub(r'^\.*', '', ret) ret = re.sub(r'\.\.*', '.', ret) # print('safe filename: %s -> %s' % (url, ret)) return ret
4f43984c35678e9b42e2a9294b5ee5dc8c766ac6
41,588
async def combine_channel_ids(ctx): """Combines all channel IDs. Called by `channel_setter` and `channel_deleter`. Args: ctx (discord.ext.commands.Context): context of the message Returns: list of int: of Discord channel IDs """ channels = [] if not ctx.message.channel_mentions: channels.append(ctx.channel.id) else: for channel_mention in ctx.message.channel_mentions: channels.append(str(channel_mention.id)) return channels
1351faa7e49ce026d4da04c2c8886b62a5f294c3
41,589
def get_role_arn(iam, role_name): """Gets the ARN of role""" response = iam.get_role(RoleName=role_name) return response['Role']['Arn']
ab6ed4fa7fd760cd6f5636e77e0d1a55372909a8
41,590
import logging def get_logger(name: str, level: int = logging.INFO) -> logging.Logger: """ Creates a logger with the given attributes and a standard formatter format. :param name: Name of the logger. :param level: Logging level used by the logger. :return: The newly or previously created Logger object. """ logger = logging.getLogger(name) logger.setLevel(level) # Simple check that prevents a logger from having more than one formatter when using the method. if len(logger.handlers) == 0: ch = logging.StreamHandler() ch.setLevel(level) formatter = logging.Formatter("%(asctime)s - %(levelname).3s - %(name)s > %(message)s") formatter.datefmt = "%Y/%m/%d %I:%M:%S" ch.setFormatter(formatter) logger.addHandler(ch) return logger
7348e1775d236e34e25d9810d71db59a7faff88e
41,594
def gera_estados(quantidade_estados: int) -> list: """ Recebe uma quantidade e retorna uma lista com nomes de estados """ estados: list = [] for i in range(quantidade_estados): estados.append('q'+str(i)) return estados
555ff4821626121b4e32d85acfa1f2ef2a7b08bb
41,596
def valid_cards_syntax(cards_str): """ Confirm that only numeric values separated by periods was given as input """ cards = cards_str.split('.') for c in cards: if not c.isnumeric(): return 'Cards must contain only digits 0-9 separated by periods' return None
8e3811505075269d2b1a37751c14017e107ce69b
41,597
def db_to_amplitude(amplitude_db: float, reference: float = 1e-6) -> float: """ Convert amplitude from decibel (dB) to volts. Args: amplitude_db: Amplitude in dB reference: Reference amplitude. Defaults to 1 µV for dB(AE) Returns: Amplitude in volts """ return reference * 10 ** (amplitude_db / 20)
d1a2a4a1c82ad2d3083b86687670af37dafa8269
41,599
def simple_expand_spark(x): """ Expand a semicolon separated strint to a list (ignoring empties)""" if not x: return [] return list(filter(None, x.split(";")))
1d4a9f8007f879c29770ea0ea8350a909b866788
41,602
def get_output_parameters_of_execute(taskFile): """Get the set of output parameters of an execute method within a program""" # get the invocation of the execute method to extract the output parameters invokeExecuteNode = taskFile.find('assign', recursive=True, value=lambda value: value.type == 'atomtrailers' and len(value.value) == 2 and value.value[0].value == 'execute') # generation has to be aborted if retrieval of output parameters fails if not invokeExecuteNode: return None # only one output parameter if invokeExecuteNode.target.type == 'name': return [invokeExecuteNode.target.value] else: # set of output parameters return [parameter.value for parameter in invokeExecuteNode.target.value]
56ba0c1f1941a72174befc69646b4bdb6bc9e009
41,606
def split_addr(ip_port: tuple[str, int]) -> tuple[int, ...]: """Split ip address and port for sorting later. Example -------- >>> split_addr(('172.217.163.78', 80)) >>> (172, 217, 163, 78, 80) """ split = [int(i) for i in ip_port[0].split(".")] split.append(ip_port[1]) return tuple(split)
d768e493d9bdfe07923927c7d157683515c52d7d
41,610
def is_set(bb, bit): """ Is bit a position `bit` set? """ return (bb & 1 << bit) != 0
4990ccb7eb796da8141bf2b3aec7741addfe2a0c
41,611
def redirect(status, location, start_response): """ Return a redirect code. This function does not set any cookie. Args: status (str): code and verbal representation (e.g. `302 Found`) location (str): the location the client should be redirected to (a URL) start_response: the start_response() callable Returns: list: an empty list """ response_headers = [("location", location)] start_response(status, response_headers) return []
7fb5569d5872be69285a29c404b04df7ff7eef74
41,612
def count_att(data, column, value): """ :param data: Pandas DataFrame :param column: specific column in the dataset :param value: which value in the column should be counted :return: probability of (value) to show in (column), included Laplacian correction """ dataset_len = len(data) try: # if (value) not been found then return laplacian calculation to preserve the probability p = data[column].value_counts()[value] / dataset_len if p == 0: p = 1 / (dataset_len + len(data[column].value_counts())) return p except KeyError: return 1 / (dataset_len + len(data[column].value_counts()))
4dd11d02257ab2a5ac7fcc0f366de0286cdc84f7
41,615
def null_getter(d, fld, default="-"): """ Return value if not falsy else default value """ return d.get(fld, default) or default
7970045e766c60e96bca005f86d214e21762f55c
41,625
def get_list_string(data: list, delim: str = '\t', fmt: str = '{}') -> str: """Converts a 1D data array into a [a0, a1, a2,..., an] formatted string.""" result = "[" first = True for i in data: if not first: result += delim + " " else: first = False result += fmt.format(i) result += "]" return result
25e9bb0e0220776ff79e121bab3bddf99168602d
41,631
def mbar2kPa(mbar: float) -> float: """Utility function to convert from millibars to kPa.""" return mbar/10
9dcb74581fb099da0d136aad57de1c8ac3cf7c1d
41,632
import re def prep_for_search(string): """ Expects a string. Encodes strings in a search-friendy format, lowering and replacing spaces with "+" """ string = re.sub('[^A-Za-z0-9 ]+', '', string).lower() string = string.replace(" ", "+") return string
61a6762598fe3538b2d2e2328bc77de53fba4d74
41,638
def get_default_query_ids(source_id, model): """ Returns set of Strings, representing source_id's default queries Keyword Parameters: source_id -- String, representing API ID of the selection source model -- Dict, representing current DWSupport configuration >>> from copy import deepcopy >>> no_query_model = { 'queries': [] ... ,'associations': [] ... ,'tables': [{'name': 'foo_fact', 'type': 'fact'}] ... ,'variables': [ { 'table': 'foo_fact' ... ,'column': 'foo_ml'}] ... ,'variable_custom_identifiers': []} >>> source = 'my_example.foo_fact' >>> # Check unspecified 'defaults' on a source without 'queries' >>> empty_defaults = [] >>> get_default_query_ids(source, no_query_model) set() >>> # Check a source with a 'query' >>> test_model = { 'queries': [{ 'table': 'foo_fact', 'name': 'core' ... ,'variables': {'foo_fact': ['foo_ml']} ... }] ... ,'associations': [] ... ,'tables': [{'name': 'foo_fact', 'type': 'fact'}] ... ,'variables': [ { 'table': 'foo_fact' ... ,'column': 'foo_ml'} ... ,{ 'table': 'foo_fact' ... ,'column': 'foo_operation_code'}] ... ,'variable_custom_identifiers': []} >>> get_default_query_ids(source, test_model) {'core'} >>> # Check a source with multiple 'queries' >>> multiple_query_model = deepcopy(test_model) >>> multiple_query_model['queries'].append({ ... 'table': 'foo_fact' ... ,'name': 'everything' ... ,'variables': { ... 'foo_fact': [ ... 'foo_ml' ... ,'foo_operation_code']} ... }) >>> defaults_output = get_default_query_ids(source, multiple_query_model) >>> defaults_output == {'core', 'everything'} True """ defaults = set() source_project, source_table_name = source_id.split('.') for query in model['queries']: if query['table'] == source_table_name: #add it set_of_one_identifier_name_to_add = {query['name']} defaults.update(set_of_one_identifier_name_to_add) return defaults
766b69d32433d586dc086eec7ee1c27c312b7724
41,644
import aiohttp from typing import List from typing import Tuple async def get_html_blog( session: aiohttp.ClientSession, url: str, contests: List[int], ) -> Tuple[str, str, List[int]]: """Get html from a blog url. Args: session (aiohttp.ClientSession) : session url (str) : blog url contests (List[int]) : list of contests Returns: Tuple[str, str, List[int]] : url, html, contests list """ async with session.get(url) as resp: return url, await resp.text(), contests
1e0a0a573f1733370a1a59f37ca39a5cd0a5bb9c
41,650
def query_string_to_kwargs(query_string: str) -> dict: """ Converts URL query string to keyword arguments. Args: query_string (str): URL query string Returns: dict: Generated keyword arguments """ key_value_pairs = query_string[1:].split("&") output = {} for key_value_pair in key_value_pairs: if "=" in key_value_pair: key, value = key_value_pair.split("=") if value == "None": value = None else: value = value.replace("+", " ") output[key] = value return output
9382d1c12cc2a534d9edbf183a3fcd3ea7b38968
41,651
import collections def group_transcripts_by_name2(tx_iter): """Takes a iterable of GenePredTranscript objects and groups them by name2""" r = collections.defaultdict(list) for tx in tx_iter: r[tx.name2].append(tx) return r
a2fce0dfa8ba5e0b7321e977d1dbc8455ab6dfd1
41,653
def get_var_mode(prefix): """Returns False if { in prefix. ``prefix`` -- Prefix for the completion Variable completion can be done in two ways and completion depends on which way variable is written. Possible variable complations are: $ and ${}. In last cursor is between curly braces. """ return False if '{' in prefix else True
ab080ae0ea2bce0ce2b267a2e7be839a6a982fb2
41,655
def lol2str(doc): """Transforms a document in the list-of-lists format into a block of text (str type).""" return " ".join([word for sent in doc for word in sent])
61f58f715f1a923c368fb0643a1cf4d7eddefb73
41,657
import textwrap def _pretty_longstring(defstr, prefix='', wrap_at=65): """ Helper function for pretty-printing a long string. :param defstr: The string to be printed. :type defstr: str :return: A nicely formated string representation of the long string. :rtype: str """ outstr = "" for line in textwrap.fill(defstr, wrap_at).split('\n'): outstr += prefix + line + '\n' return outstr
19008289620b86b8760a36829cbaa97d117a8139
41,659
def kronecker(x, y): """ Returns 1 if x==y, and 0 otherwise. Note that this should really only be used for integer expressions. """ if x == y: return 1 return 0
d28e9c101f61e04445b4d87d91cc7919e1921714
41,661
def space_join(conllu,sentence_wise=False): """Takes conllu input and returns: All tokens separated by space (if sentence_wise is False), OR A list of sentences, each a space separated string of tokens """ lines = conllu.replace("\r","").strip().split("\n") lines.append("") # Ensure last blank just_text = [] sentences = [] length = 0 for line in lines: if "\t" in line: fields = line.split("\t") if "." in fields[0]: # ellipsis tokens continue if "-" in fields[0]: # need to get super token and ignore next n tokens just_text.append(fields[1]) start, end = fields[0].split("-") start = int(start) end = int(end) length = end-start+1 else: if length > 0: length -= 1 continue just_text.append(fields[1]) elif len(line.strip())==0 and sentence_wise: # New sentence sent_text = " ".join(just_text) sentences.append(sent_text) just_text = [] if sentence_wise: return sentences else: text = " ".join(just_text) return text
e3e752906b57090f56c2678031f295c5a8e66f29
41,669
def cumsum(arr): """ Cumulative sum. Start at zero. Exclude arr[-1]. """ return [sum(arr[:i]) for i in range(len(arr))]
b629695089e731855b47c8fb3e39be222aeba1db
41,670
def first(it): """Get the first element of an iterable.""" return next(iter(it))
535f9028d96e0e78bc310b4a8e75e558c9217172
41,671
from typing import Dict import hashlib import base64 def headers_sdc_artifact_upload(base_header: Dict[str, str], data: str): """ Create the right headers for sdc artifact upload. Args: base_header (Dict[str, str]): the base header to use data (str): payload data used to create an md5 content header Returns: Dict[str, str]: the needed headers """ headers = base_header.copy() headers["Accept"] = "application/json, text/plain, */*" headers["Accept-Encoding"] = "gzip, deflate, br" headers["Content-Type"] = "application/json; charset=UTF-8" md5_content = hashlib.md5(data.encode('UTF-8')).hexdigest() content = base64.b64encode(md5_content.encode('ascii')).decode('UTF-8') headers["Content-MD5"] = content return headers
6895fff6d1a26cfb8009a3fedd2dcc9357efbe40
41,674
def content_disposition_value(file_name): """Return the value of a Content-Disposition HTTP header.""" return 'attachment;filename="{}"'.format(file_name.replace('"', '_'))
9d7f50b95ab409013af39a08d02d6e7395abe545
41,676
def decode_dataset_id(dataset_id): """Decode a dataset ID encoded using `encode_dataset_id()`. """ dataset_id = list(dataset_id) i = 0 while i < len(dataset_id): if dataset_id[i] == '_': if dataset_id[i + 1] == '_': del dataset_id[i + 1] else: char_hex = dataset_id[i + 1:i + 3] dataset_id[i + 1:i + 3] = [] char_hex = ''.join(char_hex) dataset_id[i] = chr(int(char_hex, 16)) i += 1 return ''.join(dataset_id)
08b31b17f8bda58379e7541eaedb1d1a128e9777
41,679
def _add_tag(tags, label: str) -> bool: """Adds the tag to the repeated field of tags. Args: tags: Repeated field of Tags. label: Label of the tag to add. Returns: True if the tag is added. """ for tag in tags: if tag.label == label: # Episode already has the tag. return False tags.add().label = label return True
932399e97ae823ef0922929dc5123a587c06b211
41,680
def get_admin_net(neutron_client): """Return admin netowrk. :param neutron_client: Authenticated neutronclient :type neutron_client: neutronclient.Client object :returns: Admin network object :rtype: dict """ for net in neutron_client.list_networks()['networks']: if net['name'].endswith('_admin_net'): return net
bbb96a3da0967e74d9229537ca8afbcbfbd786e8
41,681
def binary_search(target,bounds,fn,eps=1e-2): """ Perform binary search to find the input corresponding to the target output of a given monotonic function fn up to the eps precision. Requires initial bounds (lower,upper) on the values of x.""" lb,ub = bounds i = 0 while ub-lb>eps: guess = (ub+lb)/2 y = fn(guess) if y<target: lb = guess elif y>=target: ub = guess i+=1 if i>500: assert False return (ub+lb)/2
be5416bd6cdd53ff5fd8f58c489d7cf036dcd6a6
41,687
from typing import List def format_learning_rates(learning_rates: List[float]) -> str: """ Converts a list of learning rates to a human readable string. Multiple entries are separated by semicolon. :param learning_rates: An iterable of learning rate values. :return: An empty string if the argument is None or empty, otherwise the string representation of the rates, formatted as {:0.2e} """ if learning_rates is None or len(learning_rates) == 0: return "" return "; ".join("{:0.2e}".format(lr) for lr in learning_rates)
06c7395ba609be49ae57db618fe0e739b247de66
41,691
def add_buffer_to_intervals(ranges, n_channels, pad_channels=5): """Extend interval range on both sides by a number of channels. Parameters ---------- ranges : list List of intervals [(low, upp), ...]. n_channels : int Number of spectral channels. pad_channels : int Number of channels by which an interval (low, upp) gets extended on both sides, resulting in (low - pad_channels, upp + pad_channels). Returns ------- ranges_new : list New list of intervals [(low - pad_channels, upp + pad_channels), ...]. """ ranges_new, intervals = ([] for i in range(2)) for i, (low, upp) in enumerate(ranges): low, upp = low - pad_channels, upp + pad_channels if low < 0: low = 0 if upp > n_channels: upp = n_channels intervals.append((low, upp)) # merge intervals if they are overlapping sorted_by_lower_bound = sorted(intervals, key=lambda tup: tup[0]) for higher in sorted_by_lower_bound: if not ranges_new: ranges_new.append(higher) else: lower = ranges_new[-1] # test for intersection between lower and higher: # we know via sorting that lower[0] <= higher[0] if higher[0] <= lower[1]: upper_bound = max(lower[1], higher[1]) ranges_new[-1] = (lower[0], upper_bound) # replace by merged interval else: ranges_new.append(higher) return ranges_new
44548e70f0cbdc8d1f3df59ba7402ebc6aae0f41
41,692
def has_required_vowels(text, no_of_vowels=3): """Check if there are the required number of vowels""" # Set up vowels and vowel count vowels = 'aeiou' vowel_count = 0 # count vowels in text until it reaches no_of_vowels, # at which point, return True, or return False otherwise for character in text: if character in vowels: vowel_count += 1 if vowel_count == no_of_vowels: return True return False
395958ac12f6015bec2d6122670d485d41b2d1b8
41,695
def image_prepare(image): """Clip negative values to 0 to reduce noise and use 0 to 255 integers.""" image[image < 0] = 0 image *= 255 / image.sum() return image.astype(int)
c244a9a9e613215796b1a72b4576e0e39885d65e
41,701
def parse_value(value): """ Tries to convert `value` to a float/int/str, otherwise returns as is. """ for convert in (int, float, str): try: value = convert(value) except ValueError: continue else: break return value
7bab352a5bbcfe0eb9de19f7252d9d759950b01e
41,702
def flatten(xs): """Flatten a 2D list""" return [x for y in xs for x in y]
5b3fc103f699cbb0ef56f0457f482f35d0c3e4af
41,707
def caption_fmt(caption): """ Format a caption """ if caption: return "\n== {} ==\n".format(caption) return ""
e6e94efa5f16f9b0590e912e68ee1e3acfb4d54a
41,712
def rgbi2rgbf(rgbf): """Converts a RGB/integer color into a RGB/float. """ return (int(rgbf[0]*255.0), int(rgbf[1]*255.0), int(rgbf[2]*255.0))
eca27cee4f43653f42b96c84c72a5332927e1dc0
41,713
def node_count(shape): """Total number of nodes. The total number of nodes in a structured grid with dimensions given by the tuple, *shape*. Where *shape* is the number of node rows and node columns. >>> from landlab.utils.structured_grid import node_count >>> node_count((3, 4)) 12 """ assert len(shape) == 2 return shape[0] * shape[1]
f3f460967346afbb25098db6ebb7ea8db45e2870
41,715
def Madd(M1, M2): """Matrix addition (elementwise)""" return [[a+b for a, b in zip(c, d)] for c, d in zip(M1, M2)]
0e01c5be64f7c7b7c0487080ef08c560bacd6fc1
41,717
def bubble_sort(li): """ [list of int] => [list of int] Bubble sort: starts at the beginning of the data set. It compares the first two elements, and if the first is greater than the second, it swaps them. It continues doing this for each pair of adjacent elements to the end of the data set. It then starts again with the first two elements, repeating until no swaps have occurred on the last pass. """ # boolean to keep track of whether the algorithm is sorted unsorted = True while unsorted: # assume it's sorted unsorted = False for i in range(len(li) - 1): if li[i] > li[i + 1]: # it is unsorted unsorted = True # swap elements li[i], li[i + 1] = li[i + 1], li[i] return li
d2730adae8e2ddec4943d5e9a39e2a5e34eaaaaa
41,721
def get_bgp_attrs(g, node): """Return a dict of all BGP related attrs given to a node""" if 'bgp' not in g.node[node]: g.node[node]['bgp'] = {'asnum': None, 'neighbors': {}, 'announces': {}} return g.node[node]['bgp']
9345cb12b263a2aec48f000e84b5b115a158c62f
41,722
def GenerateAndroidResourceStringsXml(names_to_utf8_text, namespaces=None): """Generate an XML text corresponding to an Android resource strings map. Args: names_to_text: A dictionary mapping resource names to localized text (encoded as UTF-8). namespaces: A map of namespace prefix to URL. Returns: New non-Unicode string containing an XML data structure describing the input as an Android resource .xml file. """ result = '<?xml version="1.0" encoding="utf-8"?>\n' result += '<resources' if namespaces: for prefix, url in sorted(namespaces.iteritems()): result += ' xmlns:%s="%s"' % (prefix, url) result += '>\n' if not names_to_utf8_text: result += '<!-- this file intentionally empty -->\n' else: for name, utf8_text in sorted(names_to_utf8_text.iteritems()): result += '<string name="%s">"%s"</string>\n' % (name, utf8_text) result += '</resources>\n' return result
3561769bff337d71a3ee02acd39f30746e89baf9
41,728
def similar_lists(list1, list2, eps=1e-3): """Checks elementwise whether difference between two elements is at most some number""" return all(map(lambda pair: abs(pair[0]-pair[1])<eps, zip(list1, list2)))
09f8d5eea57eb19e3c64ce6f76603ab13a7e37ac
41,730
def normalized_difference(x, y): """ Normalized difference helper function for computing an index such as NDVI. Example ------- >>> import descarteslabs.workflows as wf >>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR", ... start_datetime="2017-01-01", ... end_datetime="2017-05-30") >>> nir, red = col.unpack_bands("nir red") >>> # geoctx is an arbitrary geocontext for 'col' >>> wf.normalized_difference(nir, red).compute(geoctx) # doctest: +SKIP ImageCollectionResult of length 2: * ndarray: MaskedArray<shape=(2, 1, 512, 512), dtype=float64> * properties: 2 items * bandinfo: 'nir_sub_red_div_nir_add_red' * geocontext: 'geometry', 'key', 'resolution', 'tilesize', ... """ return (x - y) / (x + y)
bfb74cbdae173d31811533f42f88e5165489f5ae
41,733
def _jd2mjd( jd ): """ The `_jd2mjd` function converts the Julian date (serial day number)into a Modified Julian date (serial day number). Returns a float. """ return jd - 2400000.5
01f4db238d092ab235374c5ab64517754ef075de
41,736
def tokenTextToDict(text): """ Prepares input text for use in latent semantic analysis by shifting it from a list to a dictionary data structure Parameters ---------- text : list of strings A list of strings where each string is a word and the list is a document Returns ------- wordD : dictionary A dictionary structure where the key is a word, and the item is the word count """ wordD = {} for word in text: if word in wordD: wordD[word] += 1 else: wordD[word] = 1 return wordD
c712eaa06d540486792d59d45f0b489ddb12df56
41,738
def search(array, value, dir="-"): """ Searches a sorted (ascending) array for a value, or if value is not found, will attempt to find closest value. Specifying dir="-" finds index of greatest value in array less than or equal to the given value. Specifying dir="+" means find index of least value in array greater than or equal to the given value. Specifying dir="*" means find index of value closest to the given value. """ if value < array[0]: if dir == "+": return 0 else: raise IndexError(f"No value found before {value}.") if value > array[-1]: if dir == "-": return len(array) - 1 else: raise IndexError(f"No value found after {value}.") J = 0 K = len(array) - 1 while True: if value == array[J]: return J elif value == array[K]: return K elif K == J + 1: if dir == "-": return J elif dir == "+": return K elif dir == "*": return min((J, K), key=lambda n: abs(n - value)) N = (J + K)//2 if value < array[N]: K = N elif value > array[N]: J = N elif value == array[N]: return N
9284ed8f826f3a472d9149531b29f12a8875870c
41,739