content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def is_punct(text): """ returns true if the text consists solely of non alpha-numeric characters """ for letter in text.lower(): if letter in set('abcdefghijklmnopqrstuvwxyz1234567890'): return False return True
c882d11f5004b23aea19c16fb599432fc142d3d6
625,653
def _JsonChecks(input_api, output_api): """Run checks on any modified json files.""" failing_files = [] for affected_file in input_api.AffectedFiles(None): affected_file_path = affected_file.LocalPath() is_json = affected_file_path.endswith('.json') is_metadata = (affected_file_path.startswith('site/'...
af172d8a1ac2812078b1f33c12524f10999a4473
625,655
def get_mean_pore_size(img, nx): """ Finds the mean pore diameter of the domain Parameters: ---------- :param np.ndarray img: binary image array of domain :param int nx: number of pixels in x direction of fluid domain Returns ------- :return: Model domain mean pore ...
0ec3b3d6d103b22d769423c1c8ec9fa1af983e2d
625,660
def parsed_data(provides, data): """ Function that parse data. :param provides: action name :param data: response data :return: parsed response """ boolean_dict = {"True": "Yes", "False": "No"} if provides == "list patches": for item in data: try: item["...
4c689b4fa24ca49ffb785084719b0262576c3f9f
625,661
import math def diff(a, b): """Returns the difference between two values.""" return int(math.fabs(a - b))
b87a817acf274563ceb0c7d7d6df17f1f42b405d
625,668
def normalizeShape(shape): """ Method used to convert shape to tuple Arguments: -shape: int, tuple, list, or anything convertible to tuple Raises: -TypeError: If conversion to tuple failed Returns: A tuple representing the shape """ if isins...
533040ca50e720301aaef602a37b104501aea1c8
625,670
def _PrettyPrintSize(x): """Pretty print sizes in bytes, e.g. 123456 -> 123.45kB. Args: x: (int) size Returns: (str) Pretty printed version, 2 decimal places. """ if x < 1e3: return '%dB' % x elif 1e3 <= x < 1e6: return '%.2fkB' % (x / 1e3) elif 1e6 <= x < 1e9: return '%.2fMB' % (x /...
439adf65e31a8bdb171d91cfc3d19dfba45cf502
625,671
import re def default_get_arg_names_from_class_name(class_name): """Converts normal class names into normal arg names. Normal class names are assumed to be CamelCase with an optional leading underscore. Normal arg names are assumed to be lower_with_underscores. Args: class_name: a class name,...
0641f1763bf8ac1c7f0906e94d817ef1e615bb37
625,673
def _tid_to_slice_ix(tid, train_ids, stop=False): """Convert a train ID to an integer index for slicing the dataset Throws ValueError if the slice won't overlap the trains in the data. The *stop* parameter tells it which end of the slice it is making. """ if tid is None: return None tr...
8a8512783c10b34ef9128a23961b9b756600f79b
625,674
def group_metrics(metric): """Return the group of a metric""" if metric in ['nme', 'mbe', 'sd_diff', 'corr']: return "common" elif metric in ['extreme_5', 'extreme_95']: return 'extremes' elif metric in ['skewness', 'kurtosis', 'overlap']: return 'distribution' else: ...
d34d3b9f31e3186579e82d6083d5330c1d31c4ab
625,682
def _parse_bool_str(attr, key, default='False'): """Parse bool string to boolean.""" return attr.get(key, default).strip().lower() in ['true', '1', 't', 'y', 'yes']
92adfff0d95df5054d6ad01802460b81d7e40eb5
625,684
def arrayCheck(nums): """ Function to find a sequence 1, 2, 3. Given a list of integers, return True if the sequence of numbers 1, 2, 3 appears in the list somewhere. Args: nums (Array): Array of integer """ for i in range(len(nums)-2): if nums[i] == 1 and nums[i+1] == 2 a...
22b871e12e49fbd215ca517ff1071d38f06c26cc
625,685
import pathlib def _extract_serialization_type(first_file: pathlib.Path) -> str: """ Deduce the serialization type :param first_file: serialized file :return: one from ["msgpack", "pickle", "json"]. """ msg_pack = first_file.suffixes == ['.msgpack', '.xz'] msg_pickle = first_file.suffixes ...
924584ea2fa834b79ff458c448dde8cdb5a8e293
625,688
def edges_between_nodes(graph, nodes): """ Return all edges in graph that connect the nodes :param graph: :param nodes: :return: """ edge_selection = [] for edge in graph.edges: if edge[0] in nodes and edge[1] in nodes: edge_selection.append(edge) return edge_s...
ab679b0f89920dc89f4928aa3da7e8b6f9bab2c7
625,689
def pos2iso6709(lat: float, lon: float, alt: float, crs: str = "WGS_84") -> str: """ convert decimal degrees and alt to iso6709 format. :param float lat: latitude :param float lon: longitude :param float alt: altitude :param float crs: coordinate reference system (default = WGS_84) :return:...
e1dbf684402504f93f44f7607d755bb17c6c5546
625,690
def lowercase(word): """ LOWERCASE word outputs a copy of the input word, but with all uppercase letters changed to the corresponding lowercase letter. """ return word.lower()
965713e650c08b0b336a3b17c046ccee605053f0
625,692
import re def get_day_number_from_heading_string(heading_string: str) -> int: """ Extract day number from heading string. >>> get_day_number_from_heading_string( ... "Day 1: October 16, 2019, Wednesday", ... ) 1 Arguments: heading_string (str): Day's log header string from whi...
77662cd0c6a89fcb649b12e6f374981bef8243aa
625,694
import json def parse_sns_message(event: dict) -> dict: """ Parses SNS record and returns its message. :param event: SNS event that triggered the lambda :return: parsed SNS message """ return json.loads(event["Records"][0]["Sns"]["Message"])
3d741bd6aa454e9301fa5c3f5b2fd35ed9300859
625,700
def generate_interpolation_trajectory(x_start, x_final, traj_to_match): """Generate a 1d interpolation profile, where the velocity is constant over the duration of the trajectory. Args: x_start: Start position of the trajectory. x_final: End position of the trajectory. traj_to_match:...
392cb050bb0b0452a9d1bc564bbeb3406d4dbe2b
625,701
def deal(deck): """Draws a card and returns card""" card = deck.draw_card() return card
d8373040d9762542ba6eeb1322d38ff87dfb9e02
625,703
def step_reduce(reducee, reducer, order): """ Return the reduced polynomial of reducee by reducer. That is, if one of reducee's bases is divisible by the leading base of reducer with respect to the order, the returned polynomial is the result of canceling out the term. """ lb, lc = order.le...
a98db8a9627f27670d8236f39339979a79a5ab11
625,704
import re def _extract_parameters(s:str)->dict: """ The functions parses all parameters from a ShipFlow Motions indata file. The function searches for: x = ... and saves all those occurences as a key value pair in a dict. Parameters ---------- s : str Motions indata file c...
e1c50dee22f78af16a5e5567f4ac70d389e6b9b3
625,708
from datetime import datetime def get_readable_date(datetime_str): """ Convert UTC datetime to readable form of date """ date_str = datetime_str.split('T')[0] return datetime.strptime(date_str, "%Y-%m-%d").strftime("%d/%m/%Y")
1d6090e2cf77805ce5dd5f8db6e2624f1273f202
625,709
def crop_center(im): """ Crops the center out of an image. Args: im (numpy.ndarray): Input image to crop. Returns: numpy.ndarray, the cropped image. """ h, w = im.shape[0], im.shape[1] if h < w: return im[0:h, int((w - h) / 2):int((w - h) / 2) + h, :] else: ...
b98639419c0b792366273ddd8c90c5370292a73e
625,711
def update_param_vals(pars, prefix, **kwargs): """Update parameter values with keyword arguments.""" for key, val in kwargs.items(): pname = "%s%s" % (prefix, key) if pname in pars: pars[pname].value = val return pars
bde24b19dc0597690f74f66ccd6e7c195d1e2267
625,717
import glob import json def load_recipes(path): """Load recipes from json files Parameters ---------- path : str Path to json files e.g. ./json/*.json Returns ------- list List of dicts """ jsonfiles = glob.glob(f'{path}/*.json') recipes = [] ...
1d0fafbaddabe91ef28220c1bbd91e8e59a6ac0a
625,720
import binascii def get_partition(num_partitions, queue, project=None): """Get the partition number for a given queue and project. Hashes the queue to a partition number. The hash is stable, meaning given the same queue name and project ID, the same partition number will always be returned. Note also...
2ef0cede503eb7abc361b8b7cebae65805fbec38
625,721
import pathlib import io import yaml def load_nondev_yaml(dev_path: pathlib.Path) -> bool: """ Partially reads a yaml file and stores results in a dictionary. Parameters ---------- dev_path : pathlib.Path Path to the conda file with dependencies (e.g. `environment-dev.yml`). This ...
8b110beec4fd93d9274d3606b0dfa7c12153892a
625,722
def upper(text): """ Creates a copy of ``text`` with all the cased characters converted to uppercase. Note that ``isupper(upper(s))`` might be False if ``s`` contains uncased characters or if the Unicode category of the resulting character(s) is not "Lu" (Letter, uppercase). The uppercas...
b4d2b1b03240e78a3c4113dd66e98e29419f91d5
625,724
def FileName(dir,stat,alg,avg,min,max): """get svg graph file name from dimensions. For stat use 'perf|size(min|avg|max)' used for the y axis. Use 't' for the dimension used as the timeseries label. Use 'x' for dimension used as x axis. Use 'o' for the optimal value for the algorithm. Use 's' for the stand...
3342f403281b31c5d6fbda96c7340cf74b89c00f
625,726
import random def get_next(th): """ Decide if will proceede to next stage or not """ sort = random.randint(0, 100) if (sort < th): return True return False
8410cb08b803f36bd7dac2ed68cdd307582f1256
625,728
def number_of_publications(publications: list[dict]) -> int: """Computes the number of publications. (This function exists rather for consistency.) :param: a list of publications. :return: the number of publications. """ return len(publications)
f8e9927f8d0aa91982abfc5e905fbac2fe6ef6d5
625,731
import torch def calculate_R_pi(R, pi): """ calculates R_pi R_pi(s) = \sum_a pi(s,a) r(s,a) :param R: reward matrix of size |S| x |A| :param pi: matrix of size |S| x |A| indicating the policy :return: """ return torch.einsum('sa,sa->s', R, pi)
5897287b08cd0747d21a907f06d86324912b94fc
625,735
def rename_list_to_dict(rlist): """ Helper for main to parse args for rename operator. The args are assumed to be a pair of strings separated by a ":". These are parsed into a dict that is returned with the old document key to be replaced as the (returned) dict key and the value of the return ...
a22b0931580488b9b3e8457eeb49a8509695e7fd
625,737
import io import gzip import json def load_cloudtrail_log(s3_client, bucket, key): """ Loads a CloudTrail log file, decompresses it, and extracts its records. :param s3_client: Boto3 S3 client :param bucket: Bucket where log file is located :param key: Key to the log file object in the bucket ...
a043e1b9172404f67b70d1cb42f64fc5e6603836
625,738
import requests def bio(name): """ Provides paragraph biography/background description of 1 individual or entity from an entity get request on LittleSis API. Resorts to entity with the highest number of relationships listed for entries that point to multiple entites (like last name only entries). ...
9cf3b61f24eae9cb0f8ce5c2b7ae24331a099ad5
625,739
def get_device_family_chipset(vendor_id, device_id, device_map): """Get the family and chipset strings given the vendor and device ids. Args: vendor_id: a string representing the vendor id (e.g. '0xabcd'). device_id: a string representing the device id (e.g. '0xbcde'). Returns: A s...
f45e8174cd67d7351079c7f11eee54e9e4645276
625,742
def default_split(data: str, separator: str=' ', default: str='', maxsplits: int=0) -> list: """ Function to split a string and return a list of substring. If more splits requested than there are substrings then a default value is used. Args: data (str): String to be split. separato...
9ca07068e9c291ff9cf2ee1bda8f8a61201b47ba
625,756
def read_file(file_str): """ Return file lines for a file """ file_obj = open(file_str, "r") file_lines = file_obj.readlines() return file_lines
eee386bd7478c70680bf5a8e6997a8cd4f73f872
625,759
import itertools def generate_test_list(settings): """All options that need to be tested are multiplied together. This creates a full list of all possible benchmark permutations that need to be run. """ loop_items = settings["loop_items"] dataset = [] for item in loop_items: resul...
1addf07dd99085d4aab0e4a2198dc42634a9c47b
625,760
def solve(passphrases): """Calculate number of valid passphrases. :passphrases: string of passphrases, separated by newlines :return: number of valid passphrases >>> solve('abcde fghij') 1 >>> solve('abcde xyz ecdab') 0 >>> solve('a ab abc abd abf abj') 1 >>> solve('iiii oiii o...
288fc700eea2235e90be2a0c3f1d5e5e4db138f3
625,766
def group_by_xs(datasets): """ Return datasets grouped by polarization cross section. """ cross_sections = {} for data in datasets: cross_sections.setdefault(data.polarization, []).append(data) #print("datasets", [":".join((d.name, d.entry, d.polarization, d.intent)) for d in datasets])...
768d044a23836e0ece52950145621c5f5f15d50a
625,768
def _comment_ipython_line_magic(line, magic): """Adds suffix to line magics: # [magic] %{name} Converts: %timeit x = 1 Into: x = 1 # [magic] %timeit """ return line.replace(magic, '').strip() + f' # [magic] {magic.strip()}'
e9419fdbe54978eb65d3cadf1c98095f74daaa72
625,770
def _compose_sources(compose): """ Get compose sources . :param compose dict: Compose info from ODCS. :return: a list of lists in format [[N1, S1, V1, C1], [N2, S2, V2, C2]...]. :rtype: list """ source_value = compose.get("source", "") sources = [] for source in source_value.split()...
f7729e841b1ad7266531c5e96b980d4e63ff33be
625,775
import importlib def import_func(func): """ Imports a function from the autocnet package. Parameters ---------- func : str import path. For example, to import the place_points_in_overlap function, this func can be called with: 'spatial.overlap.place_points_in_overlap' R...
f7830c3d26e02349c7f4a8f7ae0b790b98b0e7d4
625,777
def calc_delta_capacitance_ratio(capacitance_doublelayer, capacitance_dielectric): """ Ratio of the double layer to dielectric capacitance units: ~ Notes: Squires, 2010 - "Ratio of the double layer to dielectric capacitance" Adjari, 2006 - "Surface capacitance ratio" ...
e4863a5920548e7335aedd07176bb6d67e048590
625,779
import torch def load_waveglow_model(waveglow_path): """ Loads the Waveglow model. Uses GPU if available, otherwise uses CPU. Parameters ---------- waveglow_path : str Path to waveglow model Returns ------- Torch Loaded waveglow model """ waveglow = torch....
2289ef4649c54f746c86bbea2f8a2e0038da4e05
625,780
def _to(f, x, nearest): """ :param f: rounding function, e.g. ceiling, floor, round :param x: number to round :param nearest: number to round to :return: x rounded to `nearest` """ return nearest * f(float(x) / nearest)
119e3569cd16cc4eeea9316b4ad24e27ca91719e
625,781
import json def read_JSON_file(path): """ Given a line-by-line JSON file, this function converts it to a Python dict and returns all such lines as a list. :param path: the path to the JSON file :returns items: a list of dictionaries read from a JSON file """ items = list() with open(...
3de5dff408e8ca9ee0840617214fdef558acd153
625,783
def unesc(s, esc_chars): """ UnEscape special characters """ for c in esc_chars: esc_str = '\\' + c s = s.replace(esc_str, c) return s
030d4102825fef7a3ca5e3e2cdcb764dea77dbc8
625,784
def _read(filename: str) -> str: """ Reads in the content of the file. :param filename: The file to read. :return: The file content. """ with open(filename, "r") as file: return file.read()
f2cbf7dba5df7044dfde49e2dd9dfd6be73aae08
625,786
def all_boolean_reductions(request): """Fixture for boolean reduction names.""" return request.param
f4ac578c5ab5777872c9345182b5f1081bd0f00d
625,787
def _mid(pt1, pt2): """ (Point, Point) -> Point Return the point that lies in between the two input points. """ (x0, y0), (x1, y1) = pt1, pt2 return 0.5 * (x0 + x1), 0.5 * (y0 + y1)
a1095d46c01772ff3de373ccb91c626bf9222814
625,790
import glob def get_num_files(start_year, end_year, perf_dir): """ Get number of files to read given start_year end_year and path to performance files """ count = 0 for year in range(start_year, end_year + 1): count += len(glob.glob(perf_dir + f"/*{year}*")) return count
c5948bf84ce3ce0a5061af8dbe2cfcd0c7f85f79
625,792
def _CountChar(line, opening_char, closing_char): """Count (number of opening_char) - (number of closing_char) in |line|. Used to check for the end of JSON parameters. Ignores characters inside of non-escaped quotes. Args: line: line to count characters in opening_char: "+1" character, { or [ clos...
43ca7a0d91e4fbed2af769840e228c910a659780
625,793
from typing import List import re def find_indexes(haystack: List[str], regex: str) -> List[int]: """ Find indexes in a list where a regular expression matches. Parameters ---------- haystack List of strings. regex Regular expression to match. Returns ------- ...
b80924cb6955abb54968e793d2604b84c581f18c
625,797
def optimize(gan, ddgan): """ Create optimizer Args: gan (GAN): The GAN to optimize ddgan (Module): The ddgan module Returns: Optimizer: The optimizer """ kwargs_opt = { "start_from": 0, "nPOD": 10, "nLatent": 100, "npredictions": 2, ...
b19508e0115a05efdf883cbdfa083d9291f2aede
625,798
def _batch_updates(updates): """Takes a list of updates of form [(token, row)] and sets the token to None for all rows where the next row has the same token. This is used to implement batching. For example: [(1, _), (1, _), (2, _), (3, _), (3, _)] becomes: [(None, _), (1, _), (2,...
b25af9f6748fb0dfc96c9d28989db27d5f23b176
625,800
import torch def get_best_non_unk_predictions(logits: torch.Tensor, unk_id): """ For every sample, returns the prediction with the highest score. If this is the <unk> token, then the prediction with the second highest score will be returned instead :param logits: batch_size x num_predict x num_subtoke...
f5736c0b5f8f792f0fa2be0e49dbcb0bd1c36c09
625,804
def tf(words) -> float: """Boolean term frequency, weighted over the document's word count.""" return 1/len(words)
24a64f4af3e8af1a88075c3e0ce7c97761cb4510
625,807
from typing import List def knapsack_no_value(target: int, objects: List[int], cur: int) -> bool: """ we should assume objects are in heavy to light order :param target: the target weight, or the capacity of the knapsack :param objects: all available weights for items :param cur: current index in...
a619ed6d3f7b6637a5a1f2e1feb918bc7eb0c2b9
625,808
def nested_getattr(obj, attr): """getattr implementation supporting nested attributes.""" attributes = attr.split('.') for i in attributes: if obj is None: break try: obj = getattr(obj, i) except AttributeError: raise return obj
76c7afe5e17f9808856554d5b44b90428aa5831d
625,809
def ndependents(dependencies, dependents): """ Number of total data elements that depend on key For each key we return the number of data that can only be run after this key is run. The root nodes have value 1 while deep child nodes will have larger values. Examples -------- >>> dsk = {'...
5d45d83b26cfe079f5f8181d56333e66ed179f9a
625,813
def unique_values_from_query(query_result): """Simplify Athena query results into a set of values. Useful for listing tables, partitions, databases, enable_metrics Args: query_result (dict): The result of run_athena_query Returns: set: Unique values from the query result """ r...
31dd32fdf548976694d50c8466c11c3a42f7b9cc
625,817
def create_dockerfile(ctx): """ Creates a Dockerfile for this project. """ return ctx.obj['docker'].create_dockerfile( project=ctx.obj['project_name'] )
4530978e708bf727fd9c8e904972cf55da4aef18
625,820
def find_name_from_len(lmin, lens): """ reverse lookup, get name from dict >>> lens = {'chr1': 4, 'chr2': 5, 'chr3': 4} >>> find_name_from_len(5, lens) 'chr2' """ for fname, l in lens.iteritems(): if l == lmin: return fname raise Exception('name not found')
6e4dc740442243fea1ebd3c09645a7972b200db9
625,822
def bits_to_byte(bits): """ Return int represented by bits, padded on right. @param str bits: a string representation of some bits @rtype: int >>> bits_to_byte("00000101") 5 >>> bits_to_byte("101") == 0b10100000 True """ return sum([int(bits[pos]) << (7 - pos) for p...
1453e4fff3fc19b7a024424feb5486af83a0282b
625,823
from typing import Dict import collections def count_char_ngrams(s: str, n: int, pad_char: str = "$") -> Dict[str, int]: """Count all character n-grams in s. Args: s: String to analyze n: The desired length of the n-grams. E.g. `3` to get 3-grams like `"abc"`, `"def"` pad_char: Paddin...
f3d0fb83f874f922ac09ea1b91acac020cfecd42
625,825
def remove_background(df): """ Helper function removing background flows from a given dataframe :param df: the dataframe :return: the no-background dataframe """ df = df[df['label'] != 'Background'] return df
7c5bc8ed5a4e68daf0fe4f402890ae0add9b3b20
625,828
def optimal_tilt(lat): """ Returns an optimal tilt angle for the given ``lat``, assuming that the panel is facing towards the equator, using a simple method from [1]. This method only works for latitudes between 0 and 50. For higher latitudes, a static 40 degree angle is returned. These result...
4c06ad391a4f71d56a952f28fcf28f94f657d9b3
625,829
def for_language(cell, languages=set()): """Check if a given paragraph is in an expected language""" return cell.get("_lang") in languages
c79c61f85cef9b127994fc950cfc4c8e817f937f
625,830
def to_binary(x): """Convert a binary field to 1's and 0's""" if x == None: return 0 else: return 1
6f4c2db1da768c704f9ad8d150ce264dbfe48127
625,833
from typing import Sequence def bernstein3_d1(t: float) -> Sequence[float]: """ First derivative of Bernstein polynom of 3rd degree. """ t2 = t * t a = -3.0 * (1.0 - t) ** 2 b = 3.0 * (1.0 - 4.0 * t + 3.0 * t2) c = 3.0 * t * (2.0 - 3.0 * t) d = 3.0 * t2 return a, b, c, d
ce6c707d5d8c46c1d3f3c2833a042ef1f39834df
625,836
from typing import List import re def parse_tag_list(message: str, tag: str, allowed_chars: str) -> List[str]: """Parses a comma separated list following a tag. Example: The function call parse_tag_list('abc IMPORTS=foo,bar abc', 'IMPORTS', 'a-z') returns ['foo', 'bar']. Args...
c8e846e751b783b09bb93b7984906cdaceb0e207
625,839
def upload_dup_file(rest_obj, module): """Upload DUP file to OME and get a file token.""" upload_uri = "UpdateService/Actions/UpdateService.UploadFile" headers = {"Content-Type": "application/octet-stream", "Accept": "application/octet-stream"} upload_success, token = False, None dup_...
d0c8c8c51fd99e689c1069591078a0f79ead0db8
625,840
def rename_uuid_columns(data): """Renames any columns called or containing `uuid`, to the convention of `id`. Args: data (:obj:`pandas.Dataframe`): dataframe with column names to amend Returns: (:obj:`pandas.Dataframe`): the original dataframe with amended column names """ renames ...
71f2b17990ea3801e5406fb47fcc47dad42df5b8
625,841
def _remove_none(**kwargs): """Drop optional (None) arguments.""" return {k: v for k, v in kwargs.items() if v is not None}
586bdb799632f2ca860a1a908ae6cb2148d56c42
625,843
def get_straights(edge): """ Get vectors representing straight edges """ return [v for v in edge if v[0] == 0 or v[1] == 0]
a5e22561eb1cad7b6f5e7cc5bc72bb6cf68c228a
625,846
def clean_img_attributes(page): """ Remove image alt and data-mathml attributes because they confuse html2text. """ imgs = page.find_all('img') for img in imgs: img['alt'] = '' img['data-mathml'] = '' return page
07db938a3a525ee73c66ff2ed1925a5edb72c24d
625,850
import math def cal_line_length(point1, point2): """Calculate the length of line. Args: point1 (List): [x,y] point2 (List): [x,y] Returns: length (float) """ return math.sqrt( math.pow(point1[0] - point2[0], 2) + math.pow(point1[1] - point2[1], 2))
c1f86763523da7eb7e713319cba6429268021471
625,853
import textwrap def reindent(text, indentation): """Return reindented text that matches indentation.""" if '\t' not in indentation: text = text.expandtabs() text = textwrap.dedent(text) return '\n'.join( [(indentation + line).rstrip() for line in text.splitlines()]).rstrip()...
429ae2b9b5081d2cd6b9c61637ebb912e44cf4bb
625,854
import yaml def load_yaml_config(yaml_path): """Helper function to load a yaml config file""" with open(yaml_path, "r") as stream: try: return yaml.safe_load(stream) except yaml.YAMLError as exc: raise ValueError("Yaml error - check yaml file")
b0d92536613b2ae31a9f23e64070f0baabb2205a
625,856
def extended_euclidean_algorithm(a: int, b: int) -> tuple[int, int]: """ Extended Euclidean Algorithm. Finds 2 numbers a and b such that it satisfies the equation am + bn = gcd(m, n) (a.k.a Bezout's Identity) >>> extended_euclidean_algorithm(1, 24) (1, 0) >>> extended_euclidean_algorithm(...
616c2ef7277f03c0ca8b6213e7870958731e9fb3
625,857
import json def load_from_json(file_path): """ Loading data from a json file. Input: file_path: (the source file) Output: data: the loaded data """ # catching possible pathlib.Path object if isinstance(file_path, str) is False: file_path = str(file_path) # c...
1265b060633b3422df31deb477835eb8bcf3b3fd
625,858
def get_mean_value(predicted_values): """ Method for calculate mean prediction value by all predicted value :param predicted_values: all predicted values :type predicted_values: list :return: mean prediction value :rtype: float """ if len(predicted_values) == 0: return None ...
76471d0f8212cda6676fd06eaad03bc529dc7f75
625,860
def crop_center(img, crop_x, crop_y): """ Crops image from center to new size Args: img: input image width: width of cropped image height: height of cropped image Returns: Cropped image """ height, width = img.shape startx = width // 2 - (crop_y // 2) st...
f1da95e8f8f64a4510b7e124f8574d00bf6d0e6a
625,862
import uuid def generate_id() -> str: """ Create a unique ID. This is passed in each message, and used to match requests to responses. """ return uuid.uuid4().hex
eae268d641f0ee6e310ea85d75316bfa327b31b9
625,865
def xstr(s): """return empty string if input is none/false""" return '' if not s else s
2a9e2075d7d21f0d7af237d97f472eec72e14088
625,870
def get_column(wks, row, col, number): """Get column with starting row and column, and then going down `number` rows.""" return list(map(lambda x: x.value, wks.range(row, col, number+row-1, col)))
3a0f82cd824325de0e5fd4e91ee4a54fcdc4ad78
625,871
def not_empty(x): """Check if a collection is not empty or object is not None""" if hasattr(x, '__len__'): return len(x) > 0 return x is not None
377d188bf0922ee1d5e5a511b2393227f77a61cd
625,875
import time def get_object_paths(s3, bucket, prefix): """List objects in S3 bucket with given prefix. Uses paginator to ensure a complete list of object paths is returned. """ # r1 = s3.list_objects(Bucket=DEND_BUCKET, Prefix=prefix) # r2 = list(map(lambda obj: obj['Key'], r1['Contents'])) # r...
e284cd6ac420cd293675d18cb7c16700fe52e019
625,876
import json def read_json(json_path): """Read json file.""" with open(json_path, "r") as f: meta = json.load(f) return meta
bb4b2398694c268fd7d5b4a009a90ee0db6e99fd
625,879
def keymap(fn, d): """ Apply function to keys of dictionary >>> bills = {"Alice": [20, 15, 30], "Bob": [10, 35]} >>> keymap(str.lower, bills) # doctest: +SKIP {'alice': [20, 15, 30], 'bob': [10, 35]} See Also: valmap """ return dict(zip(map(fn, d.keys()), d.values()))
27b3a9cab7b24bff893e3f668d9fc55853eaad41
625,881
from typing import Callable from typing import Optional from typing import Tuple import multiprocessing def start_process( target: Callable, args: Optional[Tuple] = None ) -> multiprocessing.Process: """Start a process from with the multiprocessing framework. Parameters ---------- target: callabl...
7570672290436527e200e0bb59746ac2203315eb
625,882
import hashlib def sha256(_input: str): """ Creates a sha256 hash from the input Args: _input (str): A string Returns: A sha256 hash string """ m = hashlib.sha256() m.update(_input.encode("UTF-8")) return m.hexdigest()
a09835aca6726bb8d974fe1be443806588b7288e
625,883
import json def build_search_body(event): """Extract owners and filters from event.""" owners = json.loads(event["Owners"]) filters = json.loads(event["Filters"]) return {"Owners": owners, "Filters": filters}
07818f59cd992cb10e5dd28d112873c136bf5dc1
625,885
import traceback def read_txt(*, file_path: str) -> str: """ Read specified file's text. Parameters ---------- file_path : str File path to read. Returns ------- txt : str Target file's text. """ with open(file_path, 'r', encoding='utf-8') as f: try: ...
77271f8f34f5eaf6aef7bfeb8dcd84c985afe3ae
625,887
def _get_interior_years(from_year, to_year, start_year, end_year): """Return the Rule years that overlap with the Match[start_year, end_year]. """ years = [] for year in range(start_year, end_year + 1): if from_year <= year and year <= to_year: years.append(year) return years
6d0c73edef146b113f357e8eb75ef6806597b052
625,889
def get_show(name, cursor): """returns None if TV series name does not exists in database Args: name: name of TV series cursor: cursor object """ sql = "select id from tvshow where name = %s" cursor.execute(sql, (name,)) result = cursor.fetchone() if result == None: return None else: return result[0]
f364cf695ba773c42fd9cb7aaa7d6378f42002ca
625,890
def distribute_indices_base(indices, nprocs, rank, allow_split_comm=True): """ Partition an array of "indices" evenly among a given number of "processors" This function is similar to :func:`distribute_indices`, but allows for more a more generalized notion of what a "processor" is, since the number of ...
17cefd2d45944e6eb9c788f7ec8bcf1d813e91d9
625,893