content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def average(data): """ Calculate the average of values of the data. Args: data (list): values. Returns the average of values of the data. """ return 1.0*sum(data)/len(data)
b65754c225d311a46877dba3f59db1e6cc3ae1e1
631,553
def od2list(od): """Convert an ordered dictionary to a list.""" return list(od.values())
711af62676ec35b4bb3be447b507901fbc5317b9
631,554
def I(x): """Returns its argument as it is. This allows to call Python code within the formula interface. Examples ---------- >>> x + I(x**2) >>> x + {x**2} >>> {(x + y) / z} """ return x
02d2172c3ffdfd020a137b3259f721de3e214221
631,555
def get_group(name, match_obj): """return a blank string if the match group is None""" try: obj = match_obj.group(name) except: return '' else: if obj is not None: return obj else: return ''
8ea0e942e6c9fbf7eadbfeb5bbac20b01d2a5750
631,556
def setGauss(points): """ Create a system of equations for gaussian elimination from a set of points. """ n = len(points) - 1 A = [[0 for i in range(n+2)] for j in range(n+1)] for i in range(n+1): x = points[i]["x"] for j in range(n+1): A[i][j] = x**j A[i][n+...
48f80a4b69a29b71330685cf18195c739861bca8
631,557
def sort_012(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: input_list(list): List to be sorted """ if not input_list: return [] if len(input_list) == 0 or len(input_list) == 1: return input_list lo ...
6e8eec5aa32448d80dcce469a39a4265cde9b16b
631,560
from pathlib import Path def _mklib(topdir: str, pkgname: str, libname: str) -> Path: """Make a for-testing library. Args: topdir: the toplevel directory in which the package will be created. This directory must already exist. pkgname: the name of the package to create in the top...
c800e94baef515e304616225f0e6df4829a712be
631,561
def deprecated_or_revoked(obj): """ Return true if object has a truthy "revoked" or "deprecated" attribute, otherwise False """ return getattr(obj, "revoked", None) or getattr(obj, "deprecated", None)
5be93df40a7bd2364b0668fcc5273fa814729b28
631,562
def prepare_search_string(string: str) -> list: """ Transform a search string into a list of strings if "|" was used inside the string Agrees with escaped pipes. :param string: String to prepare :return: List of strings to search for """ value = string.replace('\\|', '¤$¤') value = [v.repl...
93373680115d8a88721a48dd90a34d3fd7784b42
631,564
def rank(tensor): """Get tensor rank as python list""" return len(tensor.shape.as_list())
9d62e91b9fd4a540ce2cc2e5d8ecaf1dfdcc21d2
631,571
def json_set(item, path, value): """ Set the value corresponding to the path in a dict. Arguments: item (dict): The object where we want to put a field. path (str): The path separated with dots to the field. value: The value to set on the field. Return: (dict): The update...
185e8f060c695d0b0b0391917b339b7809d17521
631,572
import six def binary(v, encoding='utf-8', errors='strict'): """cast value to binary type, Args: v (typing.Any): value encoding (str, optional): encoding when value is not binary. Defaults to 'utf-8'. errors (str, optional): errors setting when value is not binary. Defaults to 'strict...
523015253a2fea2c690ee2d57fd932ccccf05e63
631,573
import re def process_question(question): """Process question. Keep punctuations and use lower cases. Args: question: a string of a sentence Returns: question_words: a list of words in this sentence """ question_words = re.findall(r"[\w']+|[.,!?;]", question) return [w.encode('utf-8').lower()...
bf9086ce0e4c31fb90908f7e6e434c5dbd8bedb1
631,574
def str_or_none(value): """Returns string casted value if given value is not None""" return str(value) if value is not None else value
f92c0399c62ce2355a09c5d346e4053d669c6cae
631,575
def semi_deviation(r): """ Returns the semi deviation, aka negative semi deviation of r r must be a Series or a DataFrame """ is_negative = r < 0 return r[is_negative].std(ddof=0)
6302924e80948948db0a93b8d1b4736bdac88227
631,576
from typing import List from typing import Tuple def row_col_cell_ids(tiling: List[List[int]]) -> List[Tuple[int, int, int]]: """ Infers absolute rows and columns for every cell from the tiling of a table. :param tiling: A list of list of tiling of a table as returned from the :meth:`_tile_table` :re...
914c898dbe74c3d15ffb906ecc194be487a1c125
631,577
def step_factor(t): """ Euler integration suppression factor.""" return (1+t)
106d41bb761d7dcaf7b313e9647ce3ec20e66ee3
631,578
def GetHealthAlertRecipients(builder_run): """Returns a list of email addresses of the health alert recipients.""" recipients = [] for entry in builder_run.config.health_alert_recipients: if '@' in entry: # If the entry is an email address, add it to the list. recipients.append(entry) return re...
4e3bfe74a91ba9fce126d7df021b530c30cb7b43
631,581
def set_fixstim_color(stim, color): """Set the fill and line color of a stim.""" stim.setFillColor(color) stim.setLineColor(color) return stim
9973643ef3736ed29423cff20de56695d65b6e34
631,583
def buscar_posicion_minimo(lista, i): """Devuelve la posición del elemento mínimo en lista[i:]""" posicion_minimo = i while i < len(lista): if lista[i] < lista[posicion_minimo]: posicion_minimo = i i += 1 return posicion_minimo
2a2feb608fb8b0e52ea6f38da690f432eed7d26f
631,585
def is_init_st(id): """Used in p_one_line() --- Checks if id begins with i or I. """ return id[0] in {'i','I'}
c4ac5d5de18099e437e3a1e1f03a511fdb3e6465
631,586
import torch import math def closest_angle_error(angle_a: torch.Tensor, angle_b: torch.Tensor) -> torch.Tensor: """ Finds the closest angle between angle_b - angle_a in radians. :param angle_a: a Tensor of angles in radians :param angle_b: a Tensor of angles in radians :return: The relative angle err...
89073a2d4e69cccecf733f26f301ee43929f7c14
631,587
def to_numbers(string_array): """ Convert an array of strings to floating point numbers """ return [float(string) for string in string_array]
c757207939a812a51abd1f09552cf8c752168bec
631,590
def get_tenant_verify(tenant): """Return whether to turn on SSL verification.""" # sandboxes and the develop instance have a self-signed certs if 'SANDBOX' in tenant.upper(): return False if tenant.upper() == 'DEV-DEVELOP': return False return True
bfed1bea0fba22f40d1c5e92a7ad5a06ef52f9a4
631,592
def span_overlap(span_indices1, span_indices2): """Boolean check if two spans overlap. This does an exclusive overlap check (i.e. (0-2) and (2-3) does not overlap). """ return span_indices1[0] < span_indices2[1] and span_indices2[0] < span_indices1[1]
7641ad1875555e5a4419bd2b9b87c4eeec959b27
631,593
import operator def sort_vocab_by_frequency(vocab_freq_map): """ sorts vocab_freq_map by count args: vocab_freq_map: dict<str term, int count>, vocabulary terms with counts. returns list<tuple<str term, int count>>, sorted by count, descending """ return sorted(vocab_freq_map...
9a7c692054f9b6a90b65149aa70c997aefd3d5d0
631,594
def zipdict(ks, vs): """Returns a dict with the keys mapped to the corresponding vals.""" return dict(zip(ks, vs))
cb00e2ed7810c3cbebe1ef749fc6019b564db84e
631,595
import multiprocessing def _check_n_jobs(n_jobs): """Check n_jobs in particular for negative values Parameters ---------- n_jobs : int The number of jobs. Returns ------- n_jobs : int The checked number of jobs. Always positive. """ if not isinstance(n_jobs, int):...
09473f851f957495044439364fa62e339afc78d3
631,596
def copy(src, dest): """ Copy a file using -f so it doesn't fail if the destination exists. :type src: string :param src: Source file. :type dest: string :param dest: File destination. """ return ["cp -f %s %s" % (src, dest)]
f5293e61be8d2a7dd127a2e6adfc3846885054be
631,602
def xstr(s): """Handle NoneType in strings""" if s is None: return "Unknown" return str(s)
5e28ac7d615aa660ad01c078501dbdcc16b9dee4
631,603
from math import floor def uniform_int_from_avg(a, m, seed): """ Pick a random integer with uniform probability. Returns a random integer uniformly taken from a distribution with minimum value 'a' and average value 'm', X~U(a,b), E[X]=m, X in N where b = 2*m - a. Notes ----- p = (b-floor...
3d7f6053b06a9868bedc47a488571816ea3278c5
631,618
def ascii_join(data): """Convert sequence of numbers to ASCII characters""" return ''.join([chr(n) for n in data])
36dcc04ea469a093ff9af89fc989388681815ba9
631,621
def get_var(n, c, attr, pop=False): """ Retrieves variable references for a given static or time-depending attribute of a given component. The function looks into n.variables to detect whether the variable is a time-dependent or static. Parameters ---------- n : pypsa.Network c : str ...
84edcdfba6784d5cd3a265f4b2b75467db2a276a
631,622
def is_decorated_with_attrs( node, decorator_names=('attr.s', 'attr.attrs', 'attr.attributes')): """Return True if a decorated node has an attr decorator applied.""" if not node.decorators: return False for decorator_attribute in node.decorators.nodes: if decorator_attribute.as_s...
ad98d3ae27b898bba95d1c3febe11204099e9f65
631,623
def a_is_not_b(a, b): """ This is `not (a is b)` """ return a is not b
1b85180acdab4b56ffbb29108380007cdf1373ef
631,626
from typing import Mapping def _remove_empty_dicts(dct: dict, recurse=True) -> dict: """Remove all (nested) keys with empty dict values from `dct`""" for k, v in list(dct.items()): if isinstance(v, Mapping) and recurse: _remove_empty_dicts(dct[k]) if v == {}: del dct[k]...
b73cb8d1c4ce76caef52ec0531e220c2a533d611
631,628
def input_checker(s): """ This function takes a string input and returns false if it contains one or more non terminal spaces. If not, the function returns an integer. Args: s (string): string which needs to be checked Returns: boolean: False if the string contains one or more non ...
0b121f0e2aa079462086773621b154529529381c
631,629
def reverse_complement(dna): """Takes a RNA or DNA sequence string and returns the reverse complement""" complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'U':'A', 'N':'N'} return ''.join([complement[base] for base in dna[::-1]])
f66bd47de037e49d6007c3f41987ce442133bfb8
631,633
from typing import List def join_list_into_message(lst: List[str], joiner="-") -> str: """ Helper function that converts a list into a *bulleted list* :param lst: the list of strings that we want to convert into bullets :param joiner: the character that will be used to denote a bullet :returns: ...
575e7a48ee4816c4de3988287438338bacffe420
631,638
from typing import Any from typing import Optional from typing import Union def convert_literal(literal: Any) -> Optional[Union[bool, str]]: """Convert JSON literals to Python ones.""" # Map for the literals map_ = { "true": True, "false": False, "null": None } # Check if l...
20eb7c950c94d6c7cf161fec4e7ddb8e288a9c86
631,639
def _get_hdr_values(extns, key): """ Helper function to get the all header values from a list of extensions. The return value is a dict keyed on the EXPID value. Parameters ---------- extns : iterable of :any:`astrodata.Astrodata` AstroData extensions to be examined key : str ...
c0715b626079375738d05443028c92caa4888d08
631,643
def _GetGradSource(op_or_tensor): """Identify which call to tf.gradients created this gradient op or tensor. TensorArray gradient calls use an accumulator TensorArray object. If multiple gradients are calculated and run in the same session, the multiple gradient nodes may accidentally flow through the same ac...
e59be86338d920f650db12eaf028882bd1197d79
631,645
from typing import List import random def generate_new_symbol(symbol: List[str]) -> str: """ Select a new currency symbol. Parameters: symbol: The list of currency symbols available. Returns: str: The symbol selected randomly """ index = random.randint(0, len(symbol) - 1) ...
33ad99bba5de0ad44c53c75882f4482276c218ff
631,647
def title(text, level=0): """Given a title, format it as a title/subtitle/etc.""" return '\n' + text + '\n' + '=-~_#%^' [level] * len(text) + '\n\n'
739d11a9a085feb0bdf6748b9854d436dc1b0295
631,648
def boundary_conditions(layer_outer_radii, boundary_temp): """ This function defines the temperature on the outer radius of the particle Inputs -------- -layer_outer_radii: calls on layer_outer_radii for the last point -boundary_temp: User input of the temperature at the outer radius [K] Outp...
e4849de68b66a17f32ecb3355d666b98b9334fdd
631,655
def has_nan(x): """Checks if a Tensor/Array has NaNs.""" return bool((x != x).sum() > 0)
bfd211b4044b65334619952c4b53fa40c1a78ea7
631,658
import binascii def _read_signify_ed25519_signature(signature_file): """ Read a Ed25519 signature file created with OpenBSD signify. http://man.openbsd.org/OpenBSD-current/man1/signify.1 """ with open(signature_file) as f: # signature file format: 2nd line is base64 of 'Ed' || 8 random oc...
4b748cb800599f644b2d0d5e30da70cfd1e07107
631,664
def is_positive(x: float) -> bool: """ Return if x is positive :param x: float :return: bool """ return x > 0
4378417fe26624b3f208ab961b44c8577d3b1572
631,666
import array def isarray(x): """Same as ``isinstance(x, array)``. """ return isinstance(x, array)
8aa78a0d1568d6e87fd9dd71f6d61ca86aff5fe1
631,669
def unit_conversion(current_values, unit_type, current_unit, new_unit): """ Converts given values between the specified units :param current_values: the current values that you want converted between units. It can be any type, so long as arithmetic operations with scalars behave appropriately. A numpy a...
fae5a955619d134116333d8f4e2bb69e366ffbbe
631,670
import csv def create_list_dict(map_data_file): """read file and create list of dictionaries Args: map_data_file (string): filename of .csv file with cities Returns: [list]: list of dictionaries (each dictionary is one city) """ with open(map_data_file, encoding="utf8") as f: ...
b5d68cf1f08671d42e175f6867caeacd4451c714
631,671
def trunc_time(time, freq): """ Truncates values in provided time array to provided frequency. E.g. 2018-01-15T12:00 with freq = 'M' becomes 2018-01-01. """ return time.astype('<M8[' + freq + ']')
826ade5852da8e757bb0392654ac1c295364020b
631,673
def _check_sequence(graph_seq, known_seq): """ Check that the sequence matches up to a certain point for the known sequence. If it does return the index to where it matches. If it doesn't return 0. :param graph_seq: Actual sequence in the graph :param known_seq: One of the known sequences :retur...
c936b0dbb4aa3cfcb603647768fe2b1eef2a1174
631,675
from typing import List def _median_even(xs: List[float]) -> float: """If len(xs) is even, it's the average of the middle two elements""" sorted_xs = sorted(xs) hi_midpoint = len(xs) // 2 # e.g. length 4 => hi_midpoint 2 return (sorted_xs[hi_midpoint - 1] + sorted_xs[hi_midpoint]) / 2
02dd8835aa85f8cb490c2c779e3437ed099def0d
631,678
def expct_val(Op, psi): """ compute expecation value of operator 'Op' with state 'psi' Args: Op - operator corresponding to observable to be measured psi - state-vector (on sub-Hilbertspace) Returns: <psi| Op |psi> """ return (psi.conj().T).dot(Op.dot(psi))
55777f3fd8fd6ae16362468837d68421a43a3c5d
631,683
from typing import List def find_closest_value_in_list(list_request: List, value_request: int) -> int: """ Find the closest value within one list to the value of interest. """ return min(list_request, key=lambda list_value: abs(list_value - value_request))
e69f65bb65ebf0bf4f0eeb9b7058fc3ee7c262ba
631,684
def create_colocation_group_to_ops_map(op_graph): """Generate a dict that maps a colocation group to its op id list.""" retval = {} for op_id, op_data in op_graph.nodes().items(): # assume there is only one group group = op_data['colocation_group'] if group in retval: re...
be8b8567d2ff6988c9f8bbdcd9b3753547b2eccc
631,686
import decimal def scinotation(x,n=2): """ Displays a number in scientific notation. :param x: number :param n: number of significant digits to display """ fmt='%.'+str(n)+'E' s= fmt % decimal.Decimal(str(x)) return s
29cdaa4e4747a981f38cfb8815628d887fdb5047
631,687
import json def load(filename): """Load the configuration file""" config = None # Try to load config try: fin = open(filename, 'r') config = json.load(fin) except Exception as e: print("Failed to load config file: {}".format(filename)) print("Please ensure the...
ffe73834dce8a8f07e1af5f97b24e1f85a99c455
631,688
import requests def callWakatimeAPI(params, route): """handles the API requests :params: object :route: string :returns: json """ headers = {'Accept':'application/x-www-form-urlencoded'} r = requests.get(route, headers=headers, params=params) return r.json()
967509e4ad2246ff7e5a0dcad3e8594020b4baf2
631,690
def apply_to(x, f): """Takes a value and applies a function to it. This function is also known as the thrush combinator""" return f(x)
0a51fca4e46c623241974b6c4e2f97ecc2e0d66c
631,692
def dump_populations(populations): """ Dump a dictionary of populations in a archive Args: populations(dict): the dictionary of the populations Returns: set: the set of filenames (extension '.npy') which have been produced """ files = [] for label, pop in pop...
6e706037742cbfea40d13480a4a651aefe8d4e48
631,695
import torch def get_percentile_min_max(input, lower_percentile, upper_percentile, output_tensor=False): """ Calculate the percentile max and min values in a given tensor Parameters: ---------- input: tensor the tensor to calculate percentile max and min lower_percentile: float ...
a38981dc7afb476bb0d49273d87bc0930cf0bcf1
631,699
def check_incompatible(dict_in, inc_list): """ Check any conflicting keys in the dictionary """ for incomp in inc_list: c = 0 for k in dict_in: if k in incomp: c += 1 if c > 1: return incomp return
42d596a3dbf69c4d8696eb0ec8ea62a096130c7e
631,701
def return_config_without_apis(*, config: dict): # pylint: disable=redefined-outer-name """ A helper test function to help when mocking functions such as filter_config Returns the provided config dict after removing the "apis" keys """ del config["apis"] return config
1ebea05451d846f8a1e305fb5165bdfdc3c71270
631,704
def build_url(serializer, url): """ Return the full url for a file or picture :param serializer: serializer object :param url: the ending url locating the file :return: full url """ request = serializer.context.get('request', None) if request is not None and url[0] == '/': url = ...
3abbca6e41a22d7b592e0d6bfc98e43d3c3663d7
631,719
from datetime import datetime def datetime_fromisoformat(datestr: str): """Convert iso formatted datetime string to datetime object This is only needed for compatibility, as datetime.fromisoformat() was added in Python 3.7 """ return datetime.strptime(datestr, "%Y-%m-%dT%H:%M:%S")
f912313eeeeae68bb1e2c85251fd118e3d0b6869
631,720
import re def sanitize_results_filename(filename: str) -> str: """Sanitizes results file name. Args: filename: original filename Returns: sanitized filename """ return re.sub(r'[^\w\-\=]+', '_', filename)
4641e8cd997df2917d4e269710a7ade2d2d636e5
631,721
import click def get_checkpoint_by_class(db, class_path): """Returns checkpoint entry in `db` indicated by `class_path`. Parameters ---------- class_path : str Fully specified path to class (e.g. `terran.pose.openpose.OpenPose`) of the model to get the checkpoint for. Returns ...
e54fb99a9187394261710ae97402275c144a12e2
631,723
def distinct_powers(a, b): """Generate distinct terms in a**b""" numbers = [] for i in range(a[0], a[1]+1): for j in range(b[0], b[1]+1): numbers.append(i**j) # Set makes it the numbers values unique return set(numbers)
85b53a3d2c0e9b5199302aafb36e556ee79ec26e
631,724
def get_network_bits(mask_binary): """ Returns number of network bits of given mask :param mask_binary: Subnet Mask in binary :return: Number of network bits """ count = 0 for i in mask_binary: if int(i) == 1: count += 1 return count
858e01acc08a6383ca58af48b285e2f56fab60fe
631,725
def request_authorized(request) -> bool: """Return ``true`` if ``request`` was authorized using :py:func:`authorize`.""" return getattr(request, "_oso_authorized", False)
47bcb35c2450c4bb40611b9ede28609b5788ff83
631,727
def encodeWord(word: str, isNormalVersionForLogicallyThinkingHuman: bool) -> str: """Encode single word into its numerical representation in given system (e.g. "koko" -> "3131")""" map1 = {1:['w', 'e', 'r', 'u', 'i', 'o', 'a', 's', 'z', 'x', 'c', 'v', 'n', 'm', 'ę', 'ó', 'ą', 'ś', 'ń', 'ć', 'ż', 'ź'], 2: [...
02da1f692bbfc7d50383d190a905d4a4d1595fef
631,735
def get_durations(bpm): """ Function that generate a dictionary containing the duration in seconds of various rhythmic figures. :param bpm: beat per minutes :return: rhythmic dictionary """ beat_time = 60 / bpm return { '1': beat_time * 4, '2': beat_time * 2, '4'...
6844858f039064c29a76870a8b1af50b9e22e012
631,736
def _before_each(separator, iterable): """Inserts `separator` before each item in `iterable`. Args: separator: The value to insert before each item in `iterable`. iterable: The list into which to intersperse the separator. Returns: A new list with `separator` before each item in `iterabl...
9b3abe45d1c2f7c38e6999f25758a3b610dc374b
631,740
def response_plain_text(output, endsession): """ create a simple json plain text response """ return { 'outputSpeech': { 'type': 'PlainText', 'text': output }, 'shouldEndSession': endsession }
9de8be28e8cd65e3e2185352f1aed6aafb16c1e3
631,741
def part_a(puzzle_input): """ Calculate the answer for part_a. We need to build a list since we do not know where 2017 will end up. Args: puzzle_input (list): Formatted as the provided input from the website. Returns: string: The answer for part_a. """ steps = int(''.join(...
1575a5bac24f79131278d18ae71c29b266c1c2e6
631,743
def hr_size(num, suffix="B") -> str: """ Human-readable data size From https://stackoverflow.com/a/1094933 :param num: number of bytes :param suffix: Optional size specifier :return: Formatted string """ for unit in " KMGTPEZ": if abs(num) < 1024.0: return "%3.1f%s%s"...
832ab92f3360617653856db98e36d38a30031df4
631,749
import json def metadata_dict_to_json(clean_metadata_dict): """ Returns structured JSON from input dictionary --------------------------------------------- input: dictionary of file metadata output: clean metadata json """ clean_metadata_json = json.dumps(clean_metadata_dict) return c...
87f0628c15ee10a64bc8ed2201dece73ed1cd828
631,751
def template_url( url_template: str, state_machine_name: str, label: str, ) -> str: """ Templates a URL for an external service. Adds the label and state machine to a url that contains placeholders in the format `<label>` or '<state_machine>'. """ return url_template.replace( ...
5358249abdf3e9480a9618fba2721c077123cb34
631,753
import re def camel_case_to_underscore(name): """ This function camel_case_to_underscores a Camel Case word to a underscore word """ temp = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', temp).lower()
9bb977cc9aa99807ac3b31b3001705298d50aab4
631,756
def _is_not_lparen_and_rparen(lparens, rtok): """Tests if an RPAREN token is matched with something other than a plain old LPAREN type. """ # note that any([]) is False, so this covers len(lparens) == 0 return rtok.type == "RPAREN" and any(x != "LPAREN" for x in lparens)
60537fcf449bdfdf921eb6978cdbb63d873485b2
631,757
def cw(u, v): """ Returns True if v is to the right of u, that is, the shortest rotation from u to v is cw, turn right False otherwise """ return ((u[0] * v[1] - u[1] * v[0]) < 0)
65e6227706687de134b9abd515bd39c82d8853da
631,762
def total_seconds(td): """ Return the total number of seconds contained in the duration as a float """ return (float(td.microseconds) + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
1b1acde5ef2c7da1c36d6066db0f20e53f9e1d3b
631,763
def sum_digits(n): """Sum all the digits of n. >>> sum_digits(10) # 1 + 0 = 1 1 >>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12 12 >>> sum_digits(1234567890) 45 """ sum = 0 while n > 0: sum += n%10 # mod will give the last digit n = n//10 #removes last digit return...
a598536e68b0bd23ca1fa5c6cd40916700022b51
631,764
def getChunkPartition(chunk_id): """ return partition (if any) for the given chunk id. Parition is encoded in digits after the initial 'c' character. E.g. for: c56-12345678-1234-1234-1234-1234567890ab_6_4, the partition would be 56. For c-12345678-1234-1234-1234-1234567890ab_6_4, the partition ...
461ebdd552ad6881a6f4566b0d40399656720fcd
631,765
import pickle def pickle_stream(sklearn_model): """Returns a byte stream containing a pickled Scikit-Learn model """ return pickle.dumps(sklearn_model)
fbbb5ad74f830179e1a380d0d1d03886ef9ebba5
631,767
import json import requests def add_role_to_cloudcheckr(env, admin_api_key, account_name, role_arn): """ Uses the cross-account role created by the cloud formation stack to add it to CloudCheckr. Uses the edit_credential Admin API call. """ if role_arn is None: print("Role Arn from Cloudformation stack was no...
03ee4511e8894ccbe4418e216379a0194b35bbf5
631,771
def get_duplicates(iterable): """Return a set of the elements which appear multiple times in iterable.""" seen, duplicates = set(), set() for elem in iterable: if elem in seen: duplicates.add(elem) else: seen.add(elem) return duplicates
7e14f37a3819c6d7fe28c577173ba91aae2b687f
631,773
from pathlib import Path import re def namelist_exists(fn: Path, nml: str) -> bool: """ Determines if a namelist exists in a file. Does not check for proper format / syntax. """ pat = re.compile(r"^\s*&(" + nml + ")$") with fn.open("rt") as f: for line in f: if pat.match(...
f1746fe8426c3c7af821723e8e76227f5ef0595b
631,776
def Get_LonghurstProvinceName4Num(input): """ Get full Longhurst Province for given number """ LonghurstProvinceDict = { 'ALSK': 'AlaskaDownwellingCoastalProvince', 'ANTA': 'AntarcticProvince', 'APLR': 'AustralPolarProvince', 'ARAB': 'NWArabianUpwellingProvince', ...
41d62524c22e8534c51e9c20521abaaa38e2bfd6
631,778
def byteswap(*arrays): """ Swapping of bytes for provided arrays. Notes ----- arr.newbyteorder('S') swaps dtype interpretation, but not bytes in memory arr.byteswap() swaps bytes in memory, but not dtype interpretation arr.byteswap(True).newbyteorder('S') completely swaps both Referenc...
1fa1c0662fe525c1575365c7bcde5cf9f9ab96b3
631,779
def deduplicate(stix_obj_list): """Deduplicate a list of STIX objects to a unique set. Reduces a set of STIX objects to unique set by looking at 'id' and 'modified' fields - as a unique object version is determined by the combination of those fields Note: Be aware, as can be seen in the implementa...
5dde3ee3641610b6838b3553550b9dc7c317fef2
631,780
def _io_similar(lhs, rhs): """ Returns True if @lhs and @rhs have the same signature, false otherwise. Note that this does not check the identity of the underlying ports, just their names and types. That is, the following holds args = dict(...) x = IO(**args) y = IO(**args) ...
1955090f82b2a968592d46c442ff976a6824a91f
631,785
def num_bytes(byte_tmpl): """Given a list of raw bytes and template strings, calculate the total number of bytes that the final output will have. Assumes all template strings are replaced by 8 bytes. >>> num_bytes([0x127, "prog_bytes"]) 9 """ total = 0 for b in byte_tmpl: if i...
390e74b214bb29925d5273c1685c03d9cbca9714
631,788
import csv import logging def get_function_signature(hex_signature): """ Requests the function signature from the CSV file based on the hex_signature to get the text_signature Args: hex_signature: the 4-byte signature of the function as hex value (a string starting with 0x) Returns: sign...
6b1c59443e4a1d592c4ef0343ba7f2b9254fd23b
631,794
import json def cancel_reply(id_, solver_name): """A reply saying a problem was canceled.""" return json.dumps({ "status": "CANCELLED", "solved_on": "2013-01-18T10:26:00.020954", "solver": solver_name, "submitted_on": "2013-01-18T10:25:59.941674", "type": "ising", ...
a868804e70deced45f51204b3d98db543b7dc99c
631,795
def globalOutgassing(Fmod_out, Q, m): """ This function will calculate the outgassing flux (equation S9). Inputs: Fmod_out - the modern Earth's outgassing rate [mol C yr-1] Q - pore space heat flow relative to modern Earth [dimensionless] m - scaling parameter [dimensi...
c529a14cb60ec94af4f424843c44a023ac32c404
631,800
def _create_arguments_dictionary(parameter_extractors, environment, context): """Creates a dictionary of arguments (to pass to an action function) using the parameters and the parameter_extractor_mapping as a guide and extracts the values from environment and context. Arguments: parameter_extractors ...
875d2c9c50f3d0603ee33c5307beccaa5342249a
631,801
def _get_overlap(word1, word2): """ Returns the length of the overlap between word1 and word2. The number of letters from the end of word1 that match the beginning of word2. """ max_overlap = min(len(word1), len(word2)) max_found = 0 for size in range(1, max_overlap+1): suffix = wor...
ba8ae3e2b1cf8207209f86c5001e900bbb2ee5d0
631,802