content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def CountName(name): """Returns the name of the auxiliary count member used for array typed.""" return '%s_bytes' % name
e6d0b0bc6f0209a2e29a4afa6b2052b9e924e7bb
658,061
import random def any_int(min_value=0, max_value=100, **kwargs): """ Return random integer from the selected range >>> result = any_int(min_value=0, max_value=100) >>> type(result) <type 'int'> >>> result in range(0,101) True """ return random.randint(min_value, max_value)
2253de803c8b577fc8318673805ac85304f20320
658,070
def _get_field_name(svl_axis): """ Extracts the name of the field for the SVL plot. Parameters ---------- svl_axis : dict The SVL axis specifier. Returns ------- str The name of the field in the axis, or the transform statement. """ if "transform" in svl_axis: ...
243eac630f2e8e892b41d8ac0bee5088d6ac7dc8
658,072
def copy_factory(src, dest): """Copy Dash I/O Factory When a Dash component has been wrapped in additional layout to make a composite it is necessary to copy the embedded component I/O definition to the outermost component. This will then allow the composite component to be referenced in Dash callb...
3e6fe3d644f81f9f884bdae3312ffcda0fc2d56e
658,073
def read_file(file_path, ignore_error=False): """Safely read file and return empty str in case ignore_error fla is set.""" try: with open(file_path, encoding="utf-8") as file: return file.read() except OSError as err: if ignore_error: return '' raise err
2f280de8c9b36ef98ff07bca3fb09564acc65808
658,078
def read_input(input_path: str) -> list: """take input file path and return appropriate data structure""" with open(input_path, 'r') as input_file: lines = list() for line in input_file.readlines(): lines.append(line.strip()) return lines
3e239d9599e76ff19a865236ed0c127903c2d308
658,082
import json def get_sub_suite(database, sub_suite_id): """Sub suite gets a sub suite by suite_id from database. :param database: The database to get sub suites from. :type database: :obj:`etos_lib.lib.database.Database` :param sub_suite_id: The suite ID of the sub suite in database. :type sub_sui...
70b895211dfa8b7a1c240384fccdd66f0d1eaf9a
658,083
from typing import Type import enum def is_enum(typ: Type) -> bool: """ Test if class is Enum class. """ try: return issubclass(typ, enum.Enum) except TypeError: return isinstance(typ, enum.Enum)
428dd504a570bbf1dcf616a970ff2ee37c25cc72
658,085
def get_iou(pred_box, gt_box): """ pred_box : the coordinate for predict bounding box (x, y, w, h) gt_box : the coordinate for ground truth bounding box (x, y, w, h) return : the iou score """ # 1.get the coordinate of inters ixmin = max(pred_box[0], gt_box[0]) ixmax = min(pred_box[0...
cc9008f243b736a2bac0a0656d29591bea9bba3e
658,096
def distance(coords): """Calculate the distance of a path between multiple points Arguments received: coords — list of coordinates representing a path Arguments returned: distance -- total distance as a float """ distance = 0 for p1, p2 in zip(coords[:-1], coords[1:]): distance...
c0d353f374aef11bda019077616cf2b4f57c3ba6
658,097
def compute_indentation(props): """ Compute the indentation in inches from the properties of a paragraph style. """ res = 0 for k, v in props.items(): if k in ['margin-left', 'text-indent']: try: res += float(v.replace('in', '')) except: ...
d422421560de9d7eff6831773a23c6fb5a823cca
658,101
def unbalance(A, B, C, all=False): """ Voltage/Current Unbalance Function. Performs a voltage/current unbalance calculation to determine the maximum current/voltage unbalance. Returns result as a decimal percentage. Parameters ---------- A: float Phase-A value ...
4c5ba17ed1ce0e94e77ef02c9d8bc6e05ec64cf8
658,105
def valiant_license() -> str: """The expected app license.""" return "MIT"
33f24faa78da605b8c66aac5daa0b6ca73a71eed
658,106
import uuid def nsuuid_to_uuid(nsuuid): """Convert Objective-C NSUUID type to native Python UUID type.""" return uuid.UUID(nsuuid.UUIDString())
304b7c7ff5299bfec6224e22e624dc47079589ac
658,112
import operator def size_maxed(inner, outer, exact=False): """Return True if the inner QSize meets or exceeds the outer QSize in at least one dimension. If exact is True, return False if inner is larger than outer in at least one dimension.""" oper = operator.eq if exact else operator.ge ret...
c0649f7f8da62fcac89a47fe7ad498390c0b1791
658,113
import json import base64 def json_safe(string, content_type='application/octet-stream'): """Returns JSON-safe version of `string`. If `string` is a Unicode string or a valid UTF-8, it is returned unmodified, as it can safely be encoded to JSON string. If `string` contains raw/binary data, it is Base6...
49014fde3b769cebfbebd66033c6d4762193179a
658,114
def get_multiplicative_cooling_schedule_function(cooling_ratio_multiplier): """ Returns a cooling schedule function of the form f(T) = a*T, "a" being the cooling ratio multiplier - a real number between 0 and 1 (As specified in the proforma) :param cooling_ratio_multiplier: real number a, 0 <= a <= 1 :...
6770781ebab8c570370d95d7bd21206f7e3534bb
658,119
def prepare_id(id_): """ if id_ is string uuid, return as is, if list, format as comma separated list. """ if isinstance(id_, list): return ','.join(id_) elif isinstance(id_, str): return id_ else: raise ValueError(f'Incorrect ID type: {type(id_)}')
81e2ef42edb05d707f8378123709364408ba4690
658,122
def make_description(comment): """Construct a single comment string from a fancy object.""" ret = '\n\n'.join(text for text in [comment.get('shortText'), comment.get('text')] if text) return ret.strip()
27ba0272bda866732225b53d3ad28447432890b8
658,124
import calendar def _month_number(x): """Return the month number for the fullname of a month""" return list(calendar.month_name).index(x)
1756fe82f1ea82e879bddd1a262feaa319ffbae5
658,125
import torch def tlbr2cthw(boxes): """ Convert top/left bottom/right format `boxes` to center/size corners." :param boxes: bounding boxes :return: bounding boxes """ center = (boxes[..., :2] + boxes[..., 2:])/2 sizes = boxes[..., 2:] - boxes[..., :2] return torch.cat([center, sizes], d...
15dff8e597e1386e88a8a0417cf5061e830c863f
658,127
from typing import Iterable def ensure_list(obj): """Accepts a thing, a list of things or None and turns it into a list.""" if isinstance(obj, Iterable): return list(obj) if obj is None: return [] return [obj]
6e28324d0c430f6481c748dccd3b6d38270ce898
658,128
import re def parse_results_with_regex(output, regex): """Find and returns the regex matching results in output Looks through the output line by line looking for a matching regex. The function assembles a list of lists where each parent list is the results for that position in the regex string and ea...
434fd7114001d2a250eca81b74050c52082b2993
658,131
def parse_none(data: bytes) -> bytes: """Return `data` as is.""" return data
ba1977dbc79503d5ae0d7a6c86d29e76f5628e33
658,133
from datetime import datetime def convert_to_date(s): """ Convert the date into a useful format. """ return datetime.strptime(s, '%m/%d/%Y')
e78409f75814e7505a0ddfcdfe3787659dc52c03
658,134
def linear_growth( start: float, end: float, start_time: int, end_time: int, trade_time: int ) -> float: """ Simple linear growth function. Grows from start to end after end_time minutes (starts after start_time minutes) """ time = max(0, trade_time - start_time) rate = (end - start) / (end_time...
a33c019fd6e6658dc6be4c8437772ce4dc9cd88a
658,136
def policy_compare(sen_a, sen_b, voting_dict): """ Input: last names of sen_a and sen_b, and a voting dictionary mapping senator names to lists representing their voting records. Output: the dot-product (as a number) representing the degree of similarity between two senators' voting p...
0fedbcc46c57a9ec6b57d6dd7566281b7557af1d
658,137
def get_leaves(nodes): """Return a list containing the leaves of the graph defined by nodes.""" leaves = [] for n in nodes: if not n.children: leaves.append(n) return leaves
891b06a2d4180e63682b5118128bbad70a24e1af
658,144
def H_to_Rt(H): """Converts 4x4 homogeneous transformation matrix into 3x3 rotation matrix and 3x1 translation vector.""" return H[0:3, 0:3], H[0:3, 3]
06323455de3c837eff9164b82ec7d74b729e705f
658,146
def comparePoEVREQ(po1, po2): """ Compare two Package or PackageEVR objects for equality. """ (e1, v1, r1) = (po1.epoch, po1.version, po1.release) (e2, v2, r2) = (po2.epoch, po2.version, po2.release) if r1 != r2: return False if v1 != v2: return False if e1 != e2: return False return...
28acb829c88ae715198d06619c215e38e4ac1ef7
658,147
def _FindRuleTriggerFiles(rule, sources): """Find the list of files which a particular rule applies to. Arguments: rule: the rule in question sources: the set of all known source files for this project Returns: The list of sources that trigger a particular rule. """ rule_ext = rule['extension'] ...
f408ce191d64c8e03d724e95a41eed4fb83d9791
658,148
import yaml def load_yaml(filename): """ Load YAML data from a file """ with open(filename) as f: # yaml.BaseLoader leaves everything as a string, # so doesn't convert "no" to False data = yaml.load(f, Loader=yaml.BaseLoader) return data
47bec93ca134df2b6d9ee25d3695ab6c111fb784
658,149
def aggregate_sart(data, sub_num): """ Aggregate data from the SART task. Calculates various summary statistics for the SART task for a given subject. Parameters ---------- data : dataframe Pandas dataframe containing a single subjects trial data for the task. sub_num : str ...
6e1185942b503718e9dcae0bcb8547c9d4175eab
658,153
def stat_to_string(name, value, nice_names): """ Method that converts a metric object into a string for displaying on a plot Args: name: (str), long name of a stat metric or quantity value: (float), value of the metric or quantity Return: (str), a string of the metric name, ...
aff5fc209904fd35a11b8baed6de0972b61f0300
658,155
def tail(iterable): """Returns all elements excluding the first out of an iterable. :param iterable: Iterable sequence. :returns: All elements of the iterable sequence excluding the first. """ return iterable[1:]
e8e3b68f6081dd32374a4ef892273ad3e24ed034
658,158
def to_title(text): """ Description: Convert text to title type and remove underscores :param text: raw text :return: Converted text """ return str(text).title().replace('_', ' ')
8ea42ce65725c82d7b41462916170229dc54db96
658,159
def first(x, y): """First argument""" return x
2ec921a2be88257b7aa5427df8e3b079f3d64bed
658,167
def diff_view(str1, str2): """ Calculate the lengths of the longest common prefix and suffix between str1 and str2. Let str1 = axb of length m and str2 = ayb of length n, then this function finds and returns i and j such that: str1[0:i] = str2[0:i] = a and str1[m-j:] = str2[n-j:] = b. In the ca...
997f5a0ff4d054b59bf08618ba0f15d9c4b2f0d1
658,173
def parse_list_to_string(tags): """ Parses a list of tags into a single string with the tags separated by comma :param tags: A list of tags :return: A string with tags separated by comma """ return ', '.join(tags)
e6443a5941a0ba9a2488735e651c1dcca81dba5f
658,176
def parseResult(rst): """Parse the results returned by snopt and convert to a dict.""" return {'flag': rst.flag, 'obj': rst.obj, 'x': rst.sol, 'f': rst.fval}
38f819e474fa95032917969fb0b80d4ba52c8ad3
658,180
def sum_env_dict(envs): """Sums counts from the data structure produced by count_envs.""" return sum([sum(env.values()) for env in envs.values()])
d4525044a50b70a80a73d6f77b366e980ce14de5
658,187
def has_file_extension(file_path: str, file_extension: str) -> bool: """ Checks if a file path ends with a given file extension. """ return file_path.lower().endswith('.' + file_extension)
3d1acc4b915a7c7735420dade97d2b3eb2fc2f4c
658,188
def sekunde_v_format(sek): """ Pretvori sekunde `sek` v format hh:mm:ss. """ if isinstance(sek, str): return sek h = sek // 3600 m = (sek % 3600) // 60 s = sek % 60 return "{:0>2d}:{:0>2d}:{:0>2d}".format(h, m, s)
4373b8999b665f67fdba1e87c3922e65ad498a0f
658,189
def colon_labels2binary(report_labels): """ Convert the pre-defined labels extracted from colon reports to binary labels used for classification Params: report_labels (dict(list)): the dict containing for each colon report the pre-defined labels Returns: a dict containing for each colon report the set of binary...
04819e1d77821d568320059eff90aefc816d275a
658,190
def grain_to_dry_malt_weight(malt): """ Grain to DME Weight :param float grain: Weight of Grain :return: DME Weight :rtype: float """ return malt * 3.0 / 5.0
168103d8b91e4d5da2db5667d2129f04a290b07d
658,195
import re def get_title_display(title: str, year: int, url: str) -> str: """ Extract simplified title. Parameters ---------- title (str): movie title year (int): date of the movie url (str): url of the movie poster Returns ---------- title_display (str): format "title, year, ...
d5990d309b179c464589d2de3ad527cf7862556c
658,200
from typing import List from typing import TextIO def read_pvarcolumns(path: str) -> List[str]: """Get the column names from the pvar file (not constrained like bim, especially when converted from VCF)""" f_pvar: TextIO = open(path, 'rt') line: str = '#' header: List[str] = [] while line.startswit...
fa2990d0c753048468e22dc0b17c9a0228fe27f5
658,201
def _get_taxon(tid, taxdump): """Get information of a given taxId from taxonomy database. Parameters ---------- tid : str taxId to query taxdump : dict taxonomy database Returns ------- dict information of taxon Raises ------ ValueError If t...
a791b16bca9ade2f1d11f5eee4e282048bfc8832
658,205
import pathlib def product_filename_retrieve(filename): """ Retrieve information from the standard product filename. :param filename: file name. :return: filename information dictionary. """ file_name = pathlib.PureWindowsPath(filename) file_stem = file_name.stem.split("_") return di...
ad09a431eea489466e0f1622234c5192e9331e30
658,206
def get_text_color(background_color): """Select the appropriate text color (black or white) based on the luminance of the background color. Arguments: background_color (tuple): The record color (RGB or RGBA format). Returns: tuple: The chosen text color (black or white). """ # Cou...
c31e894f39cb84c505ec7b10d14988a142d3a916
658,213
def transition_filename(tr): """Get the part of the filename specifying the transition (e.g. BKstar) from a transition string (e.g. B->K*).""" return tr.replace('->', '').replace('*', 'star')
ba653344ccbf88af0d813aebe5e5b5dfb966d4e2
658,221
def assert_endpoint_capabilities(endpoint, *interfaces): """Assert the endpoint supports the given interfaces. Returns a set of capabilities, in case you want to assert more things about them. """ capabilities = endpoint["capabilities"] supported = set(feature["interface"] for feature in capabi...
a01ed447a19f589db8b06ff6212aa534b876a6c4
658,223
def normalize(numbers, total=1.0): """Multiply each number by a constant such that the sum is 1.0 (or total). >>> normalize([1,2,1]) [0.25, 0.5, 0.25] """ k = total / sum(numbers) return [k * n for n in numbers]
1114c7831d8c957972a0f80f539661424f04f469
658,225
def convert_ms_object(ms_object): """ Converts the list of dictionaries with keys "key" and "value" into more logical value-key pairs in a plain dictionary. """ out_dict = {} for item in ms_object: out_dict[item["Key"]] = item["Value"] return out_dict
70e005bc2e495b4e891212994142fad2b507ccf5
658,228
def percentage_scores(hits_list, p_list, nr_of_groups): """Calculates the percent score which is the cumulative number of hits below a given percentage. The function counts the number of hits in the hits_list contains below a percentage of the maximum hit score (nr_of_groups). It then subtracts the expected...
601f67fef87418d90e3a699e26f46a7479a253aa
658,229
import collections def get_interface_config_common(device, mtu=None): """ Return the interface configuration parameters that is common to all device types. """ parameters = collections.OrderedDict() parameters['BOOTPROTO'] = 'none' parameters['ONBOOT'] = 'yes' parameters['DEVICE'] = de...
2ff7818a1f8cdb0ceae0a6cb7c5a8f466037a0e4
658,230
from typing import List def get_angles_2qutrit() -> List[str]: """Return a list of angles for 2-qutrit gates.""" l = [] l.append("90") l.append("180") return l
318ef86194e119a016459490a07bec1b467684e0
658,231
from typing import Sequence def filter_overrides(overrides: Sequence[str]) -> Sequence[str]: """ :param overrides: overrides list :return: returning a new overrides list with all the keys starting with hydra. filtered. """ return [x for x in overrides if not x.startswith("hydra.")]
37750b6a9699e258c7b0f35b24342e56e8a1c34e
658,232
def get_attribute_terms(product): """ Function to iterate through all variants of a variable product and compile a list of attribute terms from them. :param product: Variable product and variants information :return: list of term names """ attribute_terms = list() for variation in product['...
3a785220eadffe20241116036e08c00b41e232fc
658,235
def convert_feature_to_result_document(feature): """ "feature": { "number": 6, "type": "number" }, "feature": { "api": "ws2_32.WSASocket", "type": "api" }, "feature": { "match": "create TCP socket", "type": "match" }, "feature": { ...
00bb1eefdacaba65af92590d698617e5a546d00d
658,236
def tensor_unsort(sorted_tensor, oidx): """ Unsort a sorted tensor on its 0-th dimension, based on the original idx. """ assert sorted_tensor.size(0) == len(oidx), "Number of list elements must match with original indices." backidx = [x[0] for x in sorted(enumerate(oidx), key=lambda x: x[1])] re...
da1a92565fb13a4e0212c2e54bb4e12a7e1fe510
658,237
import re def remove_duplicate_sentencestops(text, stop_chars=".;!?:"): """Remove duplicate sentence stops eg hello world... --> hello world. Args: text (str or list): text to be cleaned. stop_chars (str, optional): Sentence stop characters to check for duplicates. Defaults to ".;!?:". ""...
affde0a4ba9e478165c06fcb7c3e53eb0eb0228b
658,239
def calc_rho_and_rho_bar_squared(final_log_likelihood, null_log_likelihood, num_est_parameters): """ Calculates McFadden's rho-squared and rho-bar squared for the given model. Parameters ---------- final_log_likelihood : float. ...
b36a8eb7ab854a038d3e6a0dbc85d976d66a2111
658,242
def d1r(dx, fc, i): """ first-order, right-sided derivative at index i """ D = (fc[i+1] - fc[i])/dx return D
ad3da8382fe32b2279b7d8ffb32dabd35ae2d3c1
658,243
import re def get_initial_query_limit(query: str): """Returns the LIMIT within a SPARQL query string. Args: query (str): SPARQL query string. Returns: int: Limit or 0 if no limit. """ pattern = r"(LIMIT )([\d]+)" match = re.search(pattern, query) if match is None: ...
71939899919c65ac97c71bb6e93cd33813b6444a
658,244
def _get_resource_name(user_id, name): """ Get resource name by resource type. :param str user_id: PipelineAI 8 character user id that uniquely identifies the user that created the resource for super users this user_id is not ...
11ad89677f7a03055fa1593f7aa2b125a43c0ec5
658,247
def coalesce_volume_dates(in_volumes, in_dates, indexes): """Sums volumes between the indexes and ouputs dates at the indexes in_volumes : original volume list in_dates : original dates list indexes : list of indexes Returns ------- volumes: new volume array dates: new dates array ...
461c5cc8c3831ef618dbc5e15f4cee2fa468974c
658,248
def is_solution_valid(board, solution): """ Check if a generated solution is valid for a given board. :param board: The original, starting board. :param solution: A full solution, i.e. a list of Coordinates. :return: True if the solution is valid; False otherwise. """ if not solution: ...
ecd7e0b7784e5317fc9db62a5b5e4a8a4527a4ce
658,249
def map_phred33_ascii_to_qualityscore(phred33_char: str) -> float: """Maps a ASCII phred33 quality character to a quality score >>> map_phred33_ascii_to_qualityscore("#") 2 >>> map_phred33_ascii_to_qualityscore("J") 41 """ return ord(phred33_char) - 33
d93bb06bb6f7294260f27f08070fa0dffb7acc74
658,251
def assert_keys(source_dict, keys): """ Check key presence within a dict. Args: - source_dict (dict): the dict for which key presence should be checked - keys (list): the list of keys whose presence should be checked Returns: list: empty list if all checks succeeded, list of erro...
f1ee7235ef4922b27c874c2c40076c989136aa50
658,252
def get_tri_category(score): """Get a 3 class integer classification label from a score between 0 and 1.""" if score >= 0 and score < 0.3333333333: return 0 elif score >= 0.3333333333 and score < 0.6666666666: return 1 else: return 2
54306667882448925361bcb12e0bade4ddbcacf2
658,253
def _get_nested(data, key): """ Return value for a hierrachical key (like a.b.c). Return None if nothing found. If there is a key with . in the name, and a subdictionary, the former is preferred: >>> print(_get_nested({'a.b': 10, 'a':{'b': 20}}, 'a.b')) 10 >>> print(_get_nested({'a': {'...
9b3b86b0f6f4138e2b558820d59104ff98aacd46
658,254
from pathlib import Path def build_pwsh_analyze_command(file: Path) -> str: """ Build command for powershell analyze Args: file(Path): files to execute lint Returns: str: powershell analyze command """ # Invoke script analyzer command = "Invoke-ScriptAnalyzer" # Return exi...
7328938fd84a9b28c0c2122dcf0d37ad7841c72a
658,255
def l2i(path): """ Formats a list (['bla',0,'bla']) into a IMAS path ('bla[0].bla') :param path: ODS path format :return: IMAS path format """ ipath = path[0] for step in path[1:]: if isinstance(step, int) or step == ':': ipath += "[%s]" % step else: ...
879615b59fa7fb2b9814beb4c794759162314939
658,257
def logOutUser(command): """ Check if command is to log out (o | logout). """ return (command.strip().lower() == "o" or command.strip().lower() == "logout")
cb0ba11282a0e867f681e8bc006e98dafaa588fe
658,261
from typing import Iterable import functools from operator import getitem def get_in(keys: Iterable): """Creates a function that returns coll[i0][i1]...[iX] where [i0, i1, ..., iX]==keys. >>> get_in(["a", "b", 1])({"a": {"b": [0, 1, 2]}}) 1 """ def get_in(coll): return functools.reduce(...
b04c67beb2a9bf6f969b0f4193e5dc49f4d9bbf4
658,263
import re def escapeRegexChars(txt, escapeRE=re.compile(r'([\$\^\*\+\.\?\{\}\[\]\(\)\|\\])')): """Return a txt with all special regular expressions chars escaped.""" return escapeRE.sub(r'\\\1', txt)
cc2afea8e9bb0c9a56b9a3a31cb2370205d88558
658,267
from typing import Dict def is_coco_polygon(coco_label: Dict) -> bool: """Check if a given label is a valid polygon only label.""" has_bbox = "bbox" in coco_label and len(coco_label["bbox"]) == 4 has_segment = len(coco_label.get("segmentation", [])) > 0 no_keypoints = not coco_label.get("keypoints") ...
2880a2c6a734098427121385c382c2ea39bcb422
658,268
def _equivalence_partition(iterable, relation): """Partitions a set of objects into equivalence classes canned function taken from https://stackoverflow.com/a/38924631 Args: iterable: collection of objects to be partitioned relation: equivalence relation. I.e. relation(o1,o2) evaluates to ...
c57818f1adc8bcaf6651b9bd9c6fb3fb8af56133
658,269
def _select_month_reindex(indices, month): """Subsets indices for given month then reindexes to original size.""" select_month = indices[indices.index.month == month] return select_month.reindex(index=indices.index)
590e006418178bccdf2bd2ebbfb09a383f0716f2
658,270
import re def old_to_new_tracks(old_tracks: str) -> str: """ >>> old_to_new_tracks(EXAMPLE_INPUT) 'make_tracks li1 -x_offset 0.23 -x_pitch 0.46 -y_offset 0.17 -y_pitch 0.34\\nmake_tracks met1 -x_offset 0.17 -x_pitch 0.34 -y_offset 0.17 -y_pitch 0.34\\nmake_tracks met2 -x_offset 0.23 -x_pitch 0.46 -y_offse...
9bc45cc3ea1e51a6fa52dd53d6e4af6dc6adef6e
658,272
import ast def parse(data:str) -> object: """ Given a string with python source code, returns a python ast tree. """ return ast.parse(data)
b28ce6220d54e330b84d5856dfbc68566b61c3c6
658,273
def get_frame_durations(sentences, timestamps): """Given a list of sentences and timestamps of all words, return timestamps of each sentence Args: sentences (list): List of sentences timestamps (list): [ [<word_string>, <start_time_float>, <end_time_float>], ... ...
7063e2d5df87c430384cd506b27671bf64ffcf2e
658,274
def _token_addresses( token_amount, number_of_tokens, deploy_service, participants, register): """ Deploy `number_of_tokens` ERC20 token instances with `token_amount` minted and distributed among `blockchain_services`. Optionally the instances will be registered with ...
7f9a79e03de4d5d876fcd8a05663d80c5c83740f
658,275
def get_attack_rate(df, location): """ Get the attack rate for the location. Args: df (pd.DataFrame) : pandas DataFrame with attack rates for this scenario location (str) : name of the location Returns: float: Attack rate as a fraction from SIR model, values between 0 and 1....
05e27abfd3046a6b455d1a1606ad1591d637e50f
658,281
import tarfile def extract_tarfile(file_path): """Extract a .tar archive into an appropriately named folder, return the path of the folder, avoid extracting if folder exists.""" new_path = None with tarfile.open(str(file_path)) as archive: new_dir = file_path.name.split('.tar')[0] new_path...
a0daf1796599293220272bf842e7d3482f51f533
658,282
import math def get_epsilon_of_fedmd_nfdp(n, k, replacement=True): """Return epsilon of FedMD-NFDP Args: n (int): training set size k (int): sampling size replacement (bool, optional): sampling w/o replacement. Defaults to True. Returns: float: epsilon of FedMD-NFDP "...
e5cff34f217fec38ca896f955c450db093ae0eaf
658,283
def compute_line_intersection_point(x1, y1, x2, y2, x3, y3, x4, y4): """ Compute the intersection point of two lines. Taken from https://stackoverflow.com/a/20679579 . Parameters ---------- x1 : number x coordinate of the first point on line 1. (The lines extends beyond this point.) ...
4e9de8ec15635aadccfa93a18750065005f087e4
658,285
def padded_concat(*values: str, strip: bool = True, sep: str = " ") -> str: """ >>> padded_concat(" hello", " yolo", "", " ", "yo", strip=True) 'hello yolo yo' >>> padded_concat(" hello", " yolo", "", " ", "yo", strip=False) ' hello yolo yo' >>> padded_concat(" hello", " yolo", "yo"...
e7dc78d42303a98a9fdf2964c461e75a5b9ef672
658,287
def income1(households): """ Dummy for for income group 1 """ return (households['income_category'] == 'income group 1').astype(int)
26f4c5f9f1cb6c56bfc4d5bb8410d4b31516d628
658,288
def get_android_data_path(language: str, word_type: str): """ Returns the path to the data json of the Android app given a language and word type. Parameters ---------- language : str The language the path should be returned for. word_type : str The type of word...
81b02e0cddc5ec4d7c9377513c43d6fadbc2d918
658,289
def build_company_name(name_dict, _emptyString=u''): """Given a dictionary that represents a "long" IMDb company name, return a string. """ name = name_dict.get('name') if not name: return _emptyString country = name_dict.get('country') if country is not None: name += ' %s' %...
70d2fb6e42bc6ad52a2e88ec9027bd9d76870d89
658,291
def remove_namespaces_whitespaces(type_str): """ Clear type name from namespaces and whitespaces """ return type_str.replace('sycl::', '').replace( ' ', '_').replace('std::', '')
49301d01b7d809fdbf74c429273ca58283854edc
658,294
def listSum(SumList): """ 递归求和函数 :param SumList: 求和列表 :return:求和之后的值 """ if len(SumList) == 1: return SumList[0] else: return SumList[0] + listSum(SumList[1:])
6e4a5f9fe0a66251ca4b044e9b45bfab8c167112
658,296
def get_to_folder_name(folder_name, date_stamp): """ From the date_stamp return the S3 folder name to save published files into """ return folder_name + date_stamp + "/"
65de65718a1c3d09f99c7fdadad644edc944efc8
658,297
from typing import List def parse_combined_columns(eval_data: List[List[str]], index_a: int, index_b: int, delimiter: str = ' - ') -> str: """ Combines two columns worth of data into a single list of comments, separated by a delimiter """ if len(eval_data) <= 1: return '' return_val = "\\b...
0911ae650287acb9ebe4a0dbb7b86f4cae46a499
658,298
import math def get_prime_factors(n): """Return prime decomposition of an int n """ prime_factors = [] while n % 2 == 0: prime_factors.append(2) n = n / 2 for i in range(3, int(math.sqrt(n))+1,2): while n % i== 0: prime_factors.append(i) n = n / i...
0e669ba330b72bd446002d8daf0d5ec715b698aa
658,299
def load_figer_set_present_in_conll(file_path): """ Load the freebase types that were present in conll dataset. """ types_covered_local = set() with open(file_path) as file_i: for row in file_i: fb_type, _ = row.split('\t') types_covered_local.add(fb_type) return ...
aacbcb8ad40335f0b196fea56b6d83e8423bc599
658,301
def get_percentile_dict(yhat_name, valid, id_): """ Returns the percentiles of a column, yhat_name, as the indices based on another column id_. :param yhat_name: Name of column in valid in which to find percentiles. :param valid: Pandas validation frame. :param id_: Validation Pandas frame con...
cde37a38be2238fa27032fbac27846dad596ee18
658,302
def get_container_indicators(item_json): """Returns container indicator(s) for an archival object. Args: item_json (dict): ArchivesSpace archival object information that has resolved top containers and digital objects. Returns: string or None: A concatenated string containing t...
cb8313bcf6d473e793bca59862b7704ab4f422b5
658,303