content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import copy def make_retirement(state_in): """ Simulates a retirement. The individual with the maximum retirement date leaves. """ state_out = copy.deepcopy(state_in) retirement_dates = [ [individual.retirement_date for individual in level] for level in state_out[:-1] ] ...
0051f162ba2875489c49e2b2f2062518aaebb9c9
659,390
def parse_column_info(df, columns): """ Aus den Columns den Typ ermitteln. JSON-Dict zurückliefern. """ crossover = {} oscillator = {} binary = {} for col in columns: d = { "min": df[col].min(), "max": df[col].max() } if df[col].n...
00593d3dc2d650917b2219d6d91abbcf2214555b
659,391
def remove_id(iterable, obj_id): """ Removes any entry from iterable with matching ID :param iterable: list - A collection of objects (ie. Dataset, Model) :param obj_id: int - The ID matching the objects contained in iterable :return: The iterable without an entry for the filter ID """ retu...
834f774fa249eb174fab4ac52238b2d84d14a902
659,392
import re def isValid(text): """ Returns True if Jasper hears the word "Say" """ return bool(re.search(r'\bsay \b', text, re.IGNORECASE))
65ebcb22beec55c3be6200be3d337a0cf15a3653
659,393
from typing import Dict from typing import Any def _set_type_and_bounds(tmp_dict: Dict[str, Any], value: Any) -> Dict[str, Any]: """Returns a dict that can be added to a list of hyperparameters. The dict extends the tmp_dict with information from value. Parameters ---------- tmp_dict: Dict[str, ...
4e280cd8279a2d560e3270b157ae8ebd37d1952d
659,394
import os def find_subdirectories(basepath): """ Return directories (and sub) starting from a base """ directories = [] for root, dirnames, filenames in os.walk(basepath): new_directories = [d for d in dirnames if d not in directories] directories = directories + new_directories ...
4185b08395fd695446d0649de5c7176154fa465e
659,395
def removeAlias(aname: str) -> str: """Return a query to remove a character's alias.""" return (f"DELETE FROM alias " f"WHERE aname='{aname}';" )
24cb87ee158792c3060f105bded02a826adaede0
659,396
def dummy(): # ############################ # dummy() function performs the functionality displaying the message "feature will be added soon" # route "/dummy" will redirect to dummy() function. # Output: redirects to dummy.html # ########################## """response = make_response( ...
f9ad44740d2e0f6853569c72e947478a656b9b11
659,398
import functools def pmg_serialize(method): """ Decorator for methods that add MSON serializations keys to the dictionary. See documentation of MSON for more details """ @functools.wraps(method) def wrapper(*args, **kwargs): self = args[0] d = method(*args, **kwargs) #...
7bb59ce3e2edf97c53f6bb25c1a1850c80ca130d
659,399
def init_field(height=20, width=20): """Creates a field by filling a nested list with zeros.""" field = [] for y in range(height): row = [] for x in range(width): row.append(0) field.append(row) return field
0b61b12bec1ad506da357715139bef37b407b576
659,400
def name(): """ Provides a user-friendly name of the projec.t This can be used to get the name wherever it may be useful. One example case is that this is used to determine the name of the package in the Python package index. This is defined as a function so that the behavior can be easily overridd...
cfd59065df6300b332a05eea8bc00f10323ec8e5
659,401
from pathlib import Path import json def url_data(): """url_data """ filepath = Path(__file__).parent / "fixtures" / "url_data.json" if filepath: with open(filepath) as file: return json.load(file) else: return {}
18a3992159aa050ae6ca37de7d7619f98cde0e8e
659,402
import argparse def cli_args(): """Return input argument/s for a script via CLI.""" parser = argparse.ArgumentParser() parser.add_argument('-o_f', '--output_folder', type=str, default='data/', help='Define the name for the output folder') parser.add_argument('-t_n', '--ticker_n...
29f3760df0c1680bbd296626228a878c6a314a9c
659,403
def _x_zip_matcher(art): """ Is this artifact the x.zip file? """ return art['name'].endswith('.zip')
b018870a12ad3f5ad54aec28f346973c575f9241
659,404
def calc_death_rate(confirmed, deaths): """ Calculates the daily death rate in confirmed cases. :param confirmed: DataFrame of confirmed cases :param deaths: DataFrame of deaths :return: DataFrame of daily death rate """ death_rate = (deaths / confirmed) * 100 death_rate = death_rate.fil...
61f6e445d52b4495c3d07cf115692620c047fc75
659,405
def tuple_keys_from_dict(from_dict, attr_name): """from-dict for attributes that are dicts with tuples as keys""" def tuple_keys_dict_from_dict(name, dct): keys = dct[name + "_tuple_keys"] values = dct[name + "_values"] return {tuple(k): v for k, v in zip(keys, values)} def inner(cl...
4bb77f7e015f96ccefee31851412ca45de879caa
659,406
def index(): """Returns the version number of the application. :return: Application version :rtype: string """ return "Suggested Link Optimizer App v0.0.1"
400d452ff0a93f0105f718ed1ce3ba230c08cb01
659,407
def get_users_location(data: dict) -> list: """ Get users' names and location from dictionary with information about these users. Return a list of users. >>> get_users_location(get_json("@BarackObama")) [['Bill Clinton', 'New York, NY'], ['Kamala Harris', 'California']] >>> get_users_location(...
33d182386fdd01faa0bfe5d0d782d68d86fe3f03
659,408
import tqdm def loading_bar(iterable, width=80, verbosity=0): """ Checks if tqdm exists and makes a loading bar, otherwise just returns initial iterable. Parameters: iterable (iterable): the thing to be iterated over. Keyword arguments: width (int): maximum number of columns to use o...
ba259f1f7d9f0a28ff0d8ef7d7b794af59b5e768
659,409
import click import json def echo_event(data): """Echo a json dump of an object using click""" return click.echo(json.dumps(data, sort_keys=True, indent=2))
939003989c5bf02015ee75a67538be109115a079
659,410
def read_txt(file_path, comment_str="#"): """Txt file reader that ignores comments and empty lines """ out = [] with open(file_path, "r", encoding="utf-8") as f: for line in f: line = line.partition(comment_str)[0] line = line.strip() if len(line) > 0: ...
5a03ed90474c3cec7beb2065e5c380ae97e24439
659,411
def pobox(to_parse=None): """ Returns the mailing address for the PO box :param to_parse: :return: """ output = "You can send stuff to me at the following address: \n" \ "7241 185th Ave NE \n" \ "# 2243 \n" \ "Redmond, WA 98073" return output
0a36f55afcd9d3bbfe3c6356ff7086f5808f79cb
659,412
def build_debt_string(debt): """Build a nice string to represent the debt.""" if not debt: return "-" # convert tuples to nice string format (only first 3, the used ones) debt_nicer = ["{}-{:02d}".format(*d) for d in debt[:3]] exceeding = "" if len(debt) <= 3 else ", ..." result = "{} (...
9aa7d75f62c04eb908a0610cfc11df2c14474b92
659,414
def conform_speaker(speaker, main_character): """ Normalize speaker names using the predefined map. """ CHARACTERS_MAP = { 'a' : 'amicus', 'm' : main_character, 'unk': '?????', 'com': 'computer', 'c' : 'cassius', 'ca' : 'cato', 'al' : 'alexios'...
9a5e4ab5a8be3f77fc25a098494defc924331248
659,415
def add (x, y): """returns the sum of two vectors""" return x [0] + y [0], x [1] + y [1]
dd2d0dca541a01852ae60f5ea21e7be3becaff8b
659,416
def poentry__cmp__( self, other, compare_obsolete=True, compare_msgstr=True, compare_occurrences=True, ): """Custom comparation ``__cmp__`` function for :py:class:`polib.POEntry`. This function acts like a workaround for https://github.com/izimobil/polib/pulls/95 and add custom entries ...
454e46abdef3b545a84bffeba47da6467a08fb81
659,417
import subprocess import shutil def download_with_conda(conda_binary_name, binary_name): """Install package with Conda.""" conda_command = f"conda install -y -c bioconda {conda_binary_name}" rc = subprocess.call(conda_command, shell=True) if rc != 0: print(f"Failed {binary_name} install with C...
cd61e90399a7d63a89692a7875058d3b10919a6a
659,418
import torch def transpose_batch(batch): """ ### Transpose batch `DataLoader` collects the batches on the first dimension. We need to transpose it to be sequence first. """ transposed_data = list(zip(*batch)) # Stack the batch along the second dimension `dim=1` src = torch.stack(tran...
1cf1fa6f521ae0657a15a77491c086fc04a5d152
659,419
def _range_intersection(a, b): """ Returns the range where the two given ranges intersect. Parameters ---------- a, b: Each is a list of two coordinate values designating a min-max range. Returns ------- A range (a list of two numbers) where the two given ranges int...
7baf50aa162a6ef2e71a98e64d483d18fc45a0ac
659,420
import hashlib import sys def get_file_hash(filepath, algorithm="sha256"): """return an md5 hash of the file based on a criteria level. This is intended to give the file a reasonable version. Parameters ========== image_path: full path to the singularity image """ try: hasher = ge...
6f5c716b739c4793578266a871bccb05a2c089b9
659,421
def index_of_value(a,value): """ Get value of index that is closest to value in the array/list a. """ return min(range(len(a)),key=lambda i: abs(a[i] - value))
80f780d4cccf8f92b6d151249ad3cfddb743a033
659,422
def convert_ube4b_seqid(seqid): """ convert the ube4b sequence ids in the raw data to the standard mutation format """ ube4b_wt = "IEKFKLLAEKVEEIVAKNARAEIDYSDAPDEFRDPLMDTLMTDPVRLPSGTVMDRSIILRHLLNSPTDPFNRQMLTESMLEPVPELKEQIQAWMREKQSSDH" positions, replacements = seqid.split("-") positions = [int(p) for p ...
6634884b06ff441192d16c3be0b1e992bbd7996d
659,423
def concatenate_output(entry): """ Deal with groups of resources in dicts with key of date :param entry: :return big_entry| """ big_entry = [] if isinstance(entry, dict): if list(entry.keys())[0] == 'entry': sub_entry = entry['entry'] for e in sub_entry: ...
1fc15ddbc5bf64d00cfc487cffd6258415af6830
659,424
import torch def gather_states(all_states, indices): """Gathers states from relevant indices given all states. Args: all_states: States for all indices (N x T x d) indices: Indices to extract states from (N) Returns: gathered_states: States gathers at given indices (N x d) ""...
0d1f37c8736e41afb14fd95d4cdf8a3057dd9338
659,425
def AddNoGlob(options): """ If the option 'no_glob' is defined, add it to the cmd string. Returns: a string containing the knob """ string = '' if hasattr(options, 'no_glob') and options.no_glob: string = ' --no_glob' return string
e44c34a7d9652886080ae4167d80b631ffa8b9f9
659,426
def selection_sort(m): """From left to right, replace each element with element with larger index and smallest value.""" for i in range(len(m)): min_pos = i # assume i has the smallest value. for j in range(i + 1, len(m)): # compare with the rest of elements. if m[min_pos] > m[...
8113830483651e20a6c9636516d527a4237b5adf
659,427
def parse_mime_type(mime_type): """Carves up a mime_type and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/xhtml;q=0.5' would get parsed into: ('application', 'xht...
00fa105b4175abb9175dc3cdedab3cdf7ee0869a
659,428
def sol(arr, n): """ We pick the smallest two, multiplying gives them a positive. The third number has to be always positive to we take the largest one. so multiplying these 3 can give the max and the obvious are the 3 largest. So we pick the max among the two """ arr = sorted(arr) retur...
ae257e4990ccab6b4476f610b5e7817b35feea3e
659,429
import torch def check_models_have_same_weights(model_1: torch.nn.Module, model_2: torch.nn.Module): """ Checks whether two networks have the same weights @param model_1: Net to be checked @param model_2: Net to be checked @return: True iff the two networks have the same weights """ model...
f6541d5abebdc28892556dacfc77135f29727596
659,430
import pkg_resources def package_version(package): """Retrieve python package version.""" try: version = pkg_resources.get_distribution(package).version except pkg_resources.DistributionNotFound: version = "0.0.1.dev1" return version
81156ba343580bb1682eb436adbe1299ab970033
659,431
import os def ReadBlackListFile(BlackListFile): """ Read the ``blacklist region file`` :param str BlackListFile: str of file to be read. :return: A list containing black listed regions. :rtype: list. """ blacklist = [] if os.path.isfile(BlackListFile): with open(BlackListFile...
30a712976be0a0cee732eb99bf6fed44516230fe
659,432
def solve_quad_mod (a, b, c, n): """ Solve a quadratic equation modulo n. Find all solutions to the quadratic equation a*x^2 + b*x + c = 0 mod n for integer n. Here a, b, c are integers. """ solutions = [] for x in range (n): poly_val = (a*x*x + b*x + c) % n if poly...
4675b8a83c0e11714c3ad0f2893a263de4332b82
659,433
def air2vac(air): """Conversion of air wavelenghts to vacuum wavelenghts. Adapted from wcal from Pat Hall's IRAF tasks for displaying SDSS spectra Input: Air wavelengths in nm Output: Vacuum wavelengths in nm """ print("Probably best to use pyastronomy versions !!!!!!!!!!!!!!!!!!!!!!!!") ...
e586079deb4b40ffc903f552aab7cfd2fa588e03
659,434
def case_insensitive_header_lookup(headers, lookup_key): """Lookup the value of given key in the given headers. The key lookup is case insensitive. """ for key in headers: if key.lower() == lookup_key.lower(): return headers.get(key)
32441029ac7bbf0bb5db4afa3a31b7ab067113e1
659,435
import os def source_hash(filepath, *args): """Generate simple identifier for a source file. This is used to identify whether a source file has previously been processe into the pipeline, e.g. a texture. The hash is based on source filepath, modification time and file size. This is only used to id...
b446c7df38cc479a3eed233085513054a3e5e182
659,436
def string_manipulation(ans_lst): """ change the type of answer from list to string :param ans_lst: list, the process of the answer with list type :return: str, the process of the answer with string type """ word = "" for i in range(len(ans_lst)): word += ans_lst[i] return word
0b99926d9ffdd436750562e19e9b14d3ceddf8f4
659,438
def key_to_idx(key): """convert a binary LMDB key to an integer index""" return int(key)
b12e813ceeb5909fbe8c57de3bfbd0110bfd2696
659,439
def wrap_markdown(text): """ Wraps text in multiline markdown quotes. """ return '```' + text + '```'
9dc497d09d4411302d31634520f218cdb4abc532
659,440
def image_extents(product, geotransform, step=1): """Get the corner coordinates from the opened raster. Fetches a list of latitude and longitude values for the boundary of a given satellite product with a given pixel step along the border. :param product: the opened Gdal dataset :type product:...
bc5f74c168118336603a05767e6c28cf82b7dff9
659,441
def midlat_summer_albedo( name, water, ozone, visibility, doy, lat, lon, time, sat_azimuth, elevation, sat_height, sat_view, albedo, filter_function, binary, ): """ MODTRAN 6.0.1 input: 'json' format template for mid latitude summer albedo """ ...
6cc02e23fbe42a5b07fd48addf25f90825939007
659,442
def add_boundary_ummg(ummg: dict, boundary_points: list): """ Add boundary points list to UMMG in correct format Args: ummg: existing UMMG to augment boundary_points: list of lists, each major list entry is a pair of (lon, lat) coordinates Returns: dictionary representation of u...
6274e3e04a73bbc42f33e89b46688c7f70c1ca26
659,443
def cli(ctx, task_id): """Remove task with the selected id Output: Dict """ return ctx.gi.task.remove(task_id)
5a3ba76340c425f2563011dd100966cf56604f26
659,444
def getOneFeatureAttrs(dataSet: list, feature_idx: int): """ 获取一个特征的所有属性值 @ param dataSet: 数据集 @ param feature: 指定的一个特征(这里是用下标0,1,2..表示) """ attrs = [data[feature_idx] for data in dataSet] return set(attrs)
02cf85831545c6e4e7e0a97c67fe65c75c34bceb
659,445
def reserved(word): """Parse for any reserved words. This is needed for words such as "class", which is used in html but reserved in Python. The convention is to use "word_" instead. """ if word == 'class_': return 'class' return word
0cc36290c0457e567584a2918aec8706e1f69ea5
659,446
def diz_oi(): """ Está função vai trazer uma variável no retorno :return: Oi """ return 'Oi!'
6f3b5ed2c135f09a1f3532dd08b8dc59d34b06b5
659,447
def CheckExtractedInformationValid(rootGroup, verbose=False): """ **CheckExtractedInformationValid** - Checks for valid extracted information given a netCDF root node Parameters ---------- rootGroup: netCDF4.Group The root group node of a Loop Project File verbose: bool A fl...
8a06f5034c7017a165ab8971bf3ce7ec02120c9c
659,448
def get_lineprotocol_bool(param): """lineprotocol expect boolean values to be string like true or false, not capitalize""" if param: return "true" else: return "false"
21401a417ff7db5d2e7902b85f511d5a861ba2be
659,449
def merge_pept_dicts(list_of_pept_dicts:list)->dict: """ Merge a list of peptide dict into a single dict. Args: list_of_pept_dicts (list of dict): the key of the pept_dict is peptide sequence, and the value is protein id list indicating where the peptide is from. Returns: dict: the key i...
e9f9f5d1a6cbbe4acb2f59ebb55e79d67db78b0b
659,450
def downsample(state): """Downsamples an image on the first 2 dimensions Args: state: (np array) with 3 dimensions """ return state[::2, ::2, :]
2956632153d7d9b1f294fd4e1e0dd7bd7ee234bc
659,451
def zonehemisf(lon, lat, feature, parent): """ Return the zone and hemisphere from longitude and latitude. <h2>Example usage:</h2> <ul> <li>zonehemisf("lon", "lat") -> 25S</li> </ul> """ # Calculo do Fuso fuso = round((183+lon)/6.0) # Hemisferio hemisf = 'N' if lat>= 0 else...
28c7304594b614bd3170e5571c7437d84650e3a1
659,452
import requests def request_local_secure_server(login, password): """ Authorization request to the local sec server :param login: Username, string :param password: User password, string :return: response.status_code """ try: response = requests.post('http://127.0.0.1:4000/auth', ...
0094566b05054482221ab2151d1874f15a1fb680
659,453
def find_preferred_mag(mags, prefmaglist=[]): """ Given a seq of mag dicts, return the id of the preferred one Note ---- Returns the preferred of the last of any given type, so multiple 'mw' magnitudes will return the last one. If using reverse-sorted time magnitudes, (like the Database...
70ab3208d05262b3cbf75fccceab1b2b7c8738ba
659,454
import string import itertools def _tokenize_by_character_class(s): """ Return a list of strings by splitting s (tokenizing) by character class. For example: _tokenize_by_character_class('Sat Jan 11 19:54:52 MST 2014') => ['Sat', ' ', 'Jan', ' ', '11', ' ', '19', ':', '54', ':', '52', ' ', 'M...
fb90698c8af15b596ac9850b41349d642b6d3b10
659,455
def _par_indices(names): """ Given a list of objects, returns a mapping of objects in that list to the index or indices at which that object was found in the list. """ unique = {} for idx, name in enumerate(names): # Case insensitive name = name.upper() if name in unique...
1694434c9de591af4f3c70ba63c2c19cc109d0e9
659,456
import os def get_package_name(filepath): """ Given a path where a package is installed, determine its name. Parameters ---------- filepath : str Path to a file. If the determination fails, "numpy" is returned. """ fullpath = filepath[:] pkg_name = [] while 'site-package...
a439b89fdc611fb75c128096b08eba0eefbb8265
659,457
import unicodedata as ud def retireAccent(texte): """ paramètre texte : (str) Le texte dont on veut retirer les accents valeur renvoyée : (str) Le texte sans les accents >>> retireAccent('Éternel été, être où ça à') 'Eternel ete, etre ou ca a' >>> retireAccent("à noël mon aïeul entend...
9cf57ae117516d5ac81776c1d26214a17351cabb
659,459
def offset_limit(func): """ Decorator that converts python slicing to offset and limit """ def func_wrapper(self, start, stop): offset = start limit = stop - start return func(self, offset, limit) return func_wrapper
85976c86ecf69a30b85832e0cb8d3024d8476f73
659,460
import logging import sys def setup_stream_logging(): """ Set up log format """ logger = logging.getLogger('CIVIS_PLATFORM_BACKEND') logger.setLevel(logging.INFO) # needed to remove duplicate log records..don't know why... logger.propagate = False # make sure to grab orig stderr since things s...
40a2acc666ebccbfa50c700abe06455caa1b64bb
659,461
from typing import Dict def readGenomeSizeFromTxt(fname) -> Dict[str, int]: """ Read genome information. Args: ----- fname: a txt file contains genome information Returns: ----- A dictionary contains SQ as key and SL as value, otherwise None """ # first check if fname...
4287936f24f409809758f45492b06ab7ea22fdd4
659,462
def filter_spider_job_id(jobs, spider): """ 从运行的job中取出指定爬虫的id :param jobs: [{"id": "422e608f9f28cef127b3d5ef93fe9399", "spider": "spider2", "start_time": "2012-09-12 10:14:03.594664"}] :return ["id1", "id2"] """ name = spider.name aim_jobs = list() for job in jobs: if job.get('sp...
0f2059a3721ceb2ab072da3bd51e687bf48fcf8c
659,463
def _get_range_float_message(arange): """ Get range warning/error message Returns: .str """ return ("Range is expected to be float." " Ex: [0.0, 1.0] or [-0.25, 2.0].\nYour range {0}" ).format(arange)
25d67383f2c7e74e07b2e13d60e019b1feaf3298
659,464
def parse_outlist_file(outlist_file): """ :param outlist_file: :return: """ outlist_info = {} seen_ga = False fp = open(outlist_file, 'r') for line in fp: # if not a comment line if line[0] != '#' and not seen_ga: line = line.strip().split() un...
b37badd9c28a2a460cc852ad36aaadc6beb47735
659,466
def verify_support_apple(link): """All pages on support.apple.com have mitigation information.""" return True
f41aa5ecaf803bebba0121e50413c43c7cb3ed3e
659,467
def input_yesno(prompt, default=None): """ ask the user to enter Yes or No prompt: string to be shown as prompt default: True (=Yes), False (=No), or None (can not leave empty) """ while True: value = input(prompt).strip() if not value: if default is None: ...
7e38febe24d59a215d4c369f53d4ab524799891d
659,468
def get_edge_string(edge, is_incoming_edge, to_node=True): """ Create string representing the edge. :param edge: Edge object :param is_incoming_edge: Boolean, True if edge is incoming from the perspective of a node :param to_node: Boolean, output both from and to node labels if True :return: Str...
596db7dd324e3d0341e90b9131a33075c3a01638
659,469
def get_pairwise_mask(node_mask): """ Args: node_mask: (B, N_max) Returns: pairwise_mask: (B, N_max, N_max) """ n = node_mask.size(1) return node_mask.unsqueeze(1).repeat(1, n, 1) * node_mask.unsqueeze(2).repeat(1, 1, n)
71a0168772c4ba86d1cb8a16e7c17c42f41b8a7a
659,470
import glob def get_files(root_dir): """ Get all files in the root directory. """ return list(glob.iglob(root_dir + '**/**', recursive=True))
cf6b88d32f8cc15c623037b5d6bf5c71b422c5cb
659,471
import glob import os def get_all_reports(root, pattern='rep*.html'): """Return all HTML reports, sorted in descending alphabetical order.""" return sorted(glob.iglob(os.path.join(root, pattern)), reverse=True)
acb9a2249a2afe48ee2c98a3d26fead3b7b2688e
659,472
def get_parm_val(parm=None,key=None): """ Return the value of a key >>> get_parm_val(parm={'test':'val'},key='test') 'val' >>> get_parm_val(parm={'test':'val'},key='foo') >>> """ if parm and key in parm.keys(): return parm[key] else: return None
5841986976bac3b86b84f7532b8871839b5e8e6e
659,473
import getpass import socket from datetime import datetime def update_header(header, comments=[], remove_keywords=[], update_keywords={}, remove_old_comments=False, write_meta=True): """Update FITS header. Parameters ---------- header : astropy.io.fits.Header FITS header. ...
c8e8e12d4ed0de95cdeada32fb268c431831b9c1
659,474
import threading import time def play_nice_with_threads(): """ Long-running batch jobs should call this now and then to pause their activities if there are other threads that would like to run. This is a bit of a hack! """ delay = max(0, 0.01 * (threading.activeCount() - 2)) if delay: ...
ee3cdada932799029c7026ad8d4e5c89f524ac5e
659,475
def convert_to_list(data): """Convert input into a list for further processing.""" if data is not None: if isinstance(data, list): return data else: return [data]
133eede8cf012ebf58b270ae8ef10dd33926b8e6
659,476
import yaml def load_yaml_file(filename): """Loads dictionary from yaml file. Args: filename: file to read from Returns: Dict """ with open(filename) as f: contents = yaml.load(f, Loader=yaml.FullLoader) return contents
a6e70c21d4f0001f301c519409abdf12a42d71b5
659,477
def is_balanced(dictionary: dict) ->bool: """This function tell us if the colors are balanced >>> is_balanced(dictionary) >>> True """ sum = 0 for items in dictionary.values(): sum=sum+items if sum==1: return True else : return False
21dacd6fffd17b155804e633eb7d0e10a31d6cf9
659,478
import string def get_objects_list(n, np_random_state = None): """ Generates a list of (object, weight) tuples of size n :param n: list size :return: (object, weight) tuples list of size n """ alphabet_string = string.ascii_uppercase weights = list(range(1, n + 1)) if np_random_state: ...
fe178484e25c39b1dcec9e6388d32141de02f080
659,479
def tokenize(entity, field_name): """Convert an entity and a field_name into a unique string token.""" return "%s###%s" % (entity.name, field_name)
d7b1f449b761f5db13b250a81d38d1d51f06fc92
659,480
from typing import Callable from typing import List def create_offsets(track_func: Callable, distance: int, frames: int = 100) -> List[int]: """創建軌跡 :param track_func: 所采用的轨迹函數 :param distance: 所要移動的距離 :param seconds: 操作執行時間 :param frames: 幀數 :param noice_func: 噪声函数, 计算的结果会叠...
f5889f8372553db83951e2582b5cdb66864c67cf
659,481
def validate_tax_id(nip_str): """ check tax id """ if '-' in nip_str: nip_str = nip_str.replace('-', '') if len(nip_str) != 10 or not nip_str.isdigit(): return False digits = [int(i) for i in nip_str] weights = (6, 5, 7, 2, 3, 4, 5, 6, 7) check_sum = sum(d * w for d, w in zi...
3d16c96024dfa7d56a101be4eee16679239579a3
659,482
def GetAllFieldInDocument(document, field_name): """Find and return all fields with the provided name in the document.""" fields = [] for f in document.field_list(): if f.name() == field_name: fields.append(f) return fields
9764951551b40e3c4e858d2bb6ffb688dd02f7a1
659,483
def generate_trip_reason(event): """ Generate a trip reason """ reason = "{} will give a contert in {}, {} soon. It is great reason to travel ;)".format( event["performer"], event["place"]["location"]["city"], event["place"]["location"]["country"] ) return reason
7c8989ecb6a122ef7083dd307e5ec78756f18caa
659,485
def get_po_line_created_date(po_line_record): """Get created date from PO Line record or return a note that it was not found.""" if po_line_record.get("created_date") is not None: po_line_created_date = "".join( filter(str.isdigit, po_line_record["created_date"][2:]) ) else: ...
6ab97ff4382d719d9c6692419428da0764ae2e6b
659,486
import json def __read_json_report(directory): """ Reads json report. :param directory: The path to store the report. :return returns json report. """ with open(directory + '/report.json', 'r') as f: json_report = json.load(f) return json_report
03bea580e1c8a55c2fe7e1bf2722df0bf886a73b
659,487
from datetime import datetime def myFLOformatTime(self, when): """ Log time in UTC By default it's formatted as an ISO8601-like string (ISO8601 date and ISO8601 time separated by a space). It can be customized using the C{timeFormat} attribute, which will be used as input for the underlying L...
f4aaa1e41c0b2ee15537931a91e5c6a3f270c452
659,488
def floyd_warshall(graph): """ Takes an adjacency matrix graph of edge distances and returns a matrix of shortest distances between all pairs of vertices. Distances of -1 indicate there is no path between a pair of vertices. See: http://www.cs.cornell.edu/~wdtseng/icpc/notes/graph_part3.pdf :r...
7a04809f47811ba93c5f310b9f2a1f3b44526c3e
659,489
def codegen_reload_data(): """Parameters to codegen used to generate the fn_cisco_amp4ep package""" reload_params = {"package": u"fn_cisco_amp4ep", "incident_fields": [], "action_fields": [u"amp_artifact_type_activities", u"amp_artifact_type_events", u"amp_artifact_type_...
d8231762be284d749295a3d8642d9485d1a3aeac
659,490
def _get_ad_id(soup_body): """ Helper function that extracts and returns advert id from page body Returns: dict: dict containing `id` key and list of services passed as a python list """ value = ( soup_body.find('head') .find('link', {'rel': 'canonical'}, hre...
af4e6b28938c068ae0cb86629c8ab884e0e8c182
659,491
def strip_from_end(s, c): """ Remove all 'c' from the end of 's' :param s: a string. :param c: character or substring to remove :return: remainder of 's' """ if c: while s.endswith(c): s = s[:-len(c)] return s
6b0eba07bc41e827d9791cf121855992f5ffe54c
659,492
def linear_service_fee(principal, fee=0.0): """Calculate service fee proportional to the principal. If :math:`S` is the principal and :math:`g` is the fee aliquot, then the fee is given by :math:`gS`. """ return float(principal * fee)
e2b4b87302109fd2980ad6632b2641fc410994c9
659,493
def path_to_DNA_read_pairs(path: list, dist: int) -> str: """Convert a path of substrings to a condensed string :param path: the ordered path of substring pairs :type path: list (of tuples (of strs)) :param dist: the distance between the read-pairs :type dist: int :returns: the overall string ...
ce04452dd5a03686cd98d0c274db1e6aa559ab25
659,495
def node_value(current_node): """ calculate value of node from its metadata and children """ total = 0 # If there are no child nodes, value is sum of metadata values if len(current_node.children) == 0: total += sum(current_node.metadata) # if there are child nodes, see if metadata r...
c14c7e5398f15dd2ecef4893243c031f31455f62
659,496