content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def create_single_port(client, **params): """Call the client to create a port. :param client: ironic client instance. :param params: dictionary to be POSTed to /ports endpoint. :returns: UUID of the created port or None in case of exception, and an exception, if it appears. :raises: Invalid...
ea6b96b19f41b6c9866e86520d6ff5ce62d71a60
606,929
import re def _StripWS(s): """Strips all whitespace from a string.""" return re.sub('\s+', '', s)
aba95e2712cdfd62b1faf162a1c825b4b31c7d62
606,932
def is_verb_relation(token1, token2): """Return True if `token1` is a verb with subject `token2`.""" return ( (token1.upos == "VERB") and (token2.upos in ["NOUN", "PRON"]) and (token2.deprel == "nsubj") and (token2.head == token1.id) )
1887b109a4c4e87ea94ead24c82d17931f28b676
606,939
def lower64(candidate): """ Returns last 64 bits from candidate. """ return candidate & 0xffffffffffffffff
342aa3fe2fd00e30e103fb89a722fb84ec53744b
606,940
def generate_preprocessing(templates_names, preprocessing): """Generate preprocessing dict. Args: template_names (list): List of templates. preprocessing (int, list or dict): Number of preprocessing steps to be used. Returns: preprocessing (dict): ...
accdcacfe056343216f85041b67ec013f4227979
606,942
def get_foreign_keys(conn): """Return foreign_keys value.""" cur = conn.cursor() cur.execute('PRAGMA foreign_keys') return cur.fetchone()[0]
aafe486e74365d36443d087e378a0f67c3624414
606,943
from pathlib import Path def build_args(parser): """Constructs the command-line arguments for ``image2mask``.""" parser.add_argument( "--in-dir", required=True, type=Path, help="Path to directory with dataset", ) parser.add_argument( "--out-dataset", req...
1dde0e3310aa5fca26e334a430763e4d9ca8a69b
606,944
def get_datetime_fmt_len(datetime_fmt): """ Get the lenght of a string line needed for a specific datetime format Parameters ---------- datetime_fmt : (str) Formatting string used to convert between datetime and string object Returns ------- str_len : (int) Minimum length o...
5d91b03bb720d1419e1c5c3222e048079ed1fc68
606,949
def unique_repr(obj): """Return a deterministic representation of the given object. >>> unique_repr({'b','a','ab','c'}) "{'a', 'ab', 'b', 'c'}" >>> unique_repr({3: {5,4}, 8: {3,6,0}}) '{3: {4, 5}, 8: {0, 3, 6}}' """ if isinstance(obj, dict): sorted_dict_reprs = sorted(unique_repr(k...
ab508681748b5e17402a587bd96f431c0bd3d76f
606,952
def normalize_mean_std(data, data_mean=None, data_std=None): """Normalizes the data by removing the mean and scaling the features to unit variance (or std). If data_mean or data_std are None, one or both of these values are computed from the given data. """ if data_mean is None: data_mean = dat...
d05b749c1be6729a4856d17cbd53e00af6b7f1bf
606,953
import re def topic(agent, other_agent, current_topic, scale, logger): """ Calculate topic trust by reading from logger all past topic trust for other agent and topic, and then averaging all values or giving out default_value. :param agent: The agent which calculates the trust. (start of relationship...
927f87e40c7bb3331d8acd260187136cab4a4933
606,955
def calc_cost(kWh, cost): """Calculates the cost of the kilowatts based on the cost provided""" return kWh * cost
2a3adb603b46a052d638a8dffe9970cece7fe5c6
606,956
def _PreviousNondeletedLine(file_lines, line_number): """Returns the line number of the previous not-deleted line, or None.""" for line_number in range(line_number - 1, -1, -1): if not file_lines[line_number].deleted: return line_number return None
066089ee462a0b2833075a49bd53a53cc5b6275e
606,957
from PIL import Image def image_file_dims(filename): """Return the image size (height, width) without loading all the pixels""" img = Image.open(filename) return img.size[::-1]
7d92f21116bfd36731a743aeacc2885df0b87d46
606,960
def chunk_list(list_to_chunk: list, chunk_size: int) -> list: """Chunk given list into chunks of a given size.""" return [ list_to_chunk[i : i + chunk_size] for i in range(0, len(list_to_chunk), chunk_size) ]
9a4d5b6951ba63fdef058f533df781fdd59402f5
606,963
import random import string def randomString(n = 10): """ Generate a random string of form [a-zA-Z]{n}(ascii letters of length n). Parameters ---------- n : int, default 10 The length of the random string. Returns ------- str A random string consisting ascii lette...
ea16d211330275f859d28b088521750097626c50
606,964
import asyncio def run_async_method(loop, method, *args): """ Run async method. :param loop: the loop to run method until complete. :param method: method to run. :param args: arguments of method. :return: result of "method". """ if not loop: loop = asyncio.get_event_loop() ...
852ff87d9766a57227f466bd68b6825c17c840b6
606,966
def read_gene_table(f): """Read coordinates of genes on genomes. Parameters ---------- f : file handle Gene table file. Returns ------- dict of list of tuple of (int, bool, bool, str) Flattened list of gene coordinates per nucleotide. Coordinate (nt). ...
8f80e634a20d5544a793048c6c523c2c6b9e6630
606,967
def relevant_event(event): """Check if an event is relevant and returns the inner event dict if it is""" if "event" in event.keys(): e = event["event"] # only handle message type events if e["type"] == "message": return e return None
b556797b78633fd6603dafb640307aa2fd7c31e2
606,973
def get_image_crops(image, crop_size): """ The function create crops of provided image of size specified by crop_size. :param image: Input image :param crop_size: Required crop size :return: List of image crops (each crop is of size 'crop_size') """ width, high = image.size crop_x = [in...
407bd7d5106efd180c4c0255273bad8881cdb4b0
606,975
def hoffman(mu_1, mu_n): """ Calculates the Hoffman bound of a graph given the largest and smallest eigenvalues of the adjacency matrix. """ return 1 + (mu_1 / abs(mu_n))
65b472a382754c244fd30851c00c1f2306724945
606,976
def is_open(request): """Check if the request is open.""" return request.is_open
24129c2e255793c3e47a6de8e6b04ae45eb6f976
606,977
def strip_root(path): """ Removes the root slash in a path. Example: /srv/data becomes srv/data """ path = path.strip() if path.startswith('/'): return path[1:] return path
2fa7888282b818204284ce2674e2604e7f3f1449
606,980
def _resolution_estimate(ordered_pair_list, cutoff): """Come up with a linearly interpolated estimate of resolution at cutoff cutoff from input data [(resolution, i_sigma)].""" x = [] y = [] for o in ordered_pair_list: x.append(o[0]) y.append(o[1]) if max(y) < cutoff: ...
07e5c549028e5b6c8ca8072bed373ccb3903a240
606,981
import inspect def get_param_names(method): """ Returns a list of keyword-only parameter names that may be passed into method. Parameters ---------- method : function The method for which to return keyword-only parameters. Returns ------- parameters : list A list ...
5bebb2024ab8619313c8ef16b1b718552e89a264
606,984
import re import string def normalize_answer(s): """Lower text and remove punctuation, articles and extra whitespace. This function is an extended version of the SQuAD evaluation script. Arguments: s: ``str`` String to normalize. """ def remove_articles(text): regex = re.compile(...
c729aaa797847c5db4be04939bfa649e8c8d5606
606,985
def identity(x, /, *args, **kwargs): """ A simple identity function that accepts a single positional argument and ignore keywords. """ return x
3618ef99aa26e38b259d82a6d9d47c8b716bccde
606,988
def get_tuple_defragmentation_fn(pegasus_graph): """ Returns a de-fragmentation function that is specific to pegasus_graph. The returned de-fragmentation function, defragment_tuple(..), takes in a list of K2,2 Chimera coordinates and returns the corresponding list of unique pegasus coordinates. Det...
dfedebb70400a2542a89d1dd805cf5618a36b8ad
606,992
def create_lookup_url(usernames, user_fields): """ Parameters ---------- usernames : str Username that you want to search. => Sample: usernames=TwitterDev <= user_fields : str User fields are adjustable, options include: created_at, description, entities, id, locatio...
4cdf31b97c2ae8b987d87ca28a6740976d525df9
606,994
from datetime import datetime def _safe_string_to_date(dstring): """ tvdb format date '2004-11-12' to python datetime.date Returns None in case of failure. """ try: dt = datetime.strptime(dstring, '%Y-%m-%d') except (ValueError, TypeError): return None else: ...
f9811eb90ccdfb73b99089f58df3e4a2924c62e9
607,003
def levenshtein_distance(s1, s2): """ Performs Levenshtein distance on two strings :param s1: String 1 :param s2: String 2 :return: L-Distance between two s1 and s2 """ if len(s1) > len(s2): s1, s2 = s2, s1 distances = range(len(s1) + 1) for index2, char2 in enumerate(s2): ...
ae264de708a808e99adff56a847c394db40a3387
607,005
import hmac def apply_HMAC(text, key=b'YELLOW SUBMARINE'): """Apply SHA1-HMAC.""" return hmac.HMAC(key, text, digestmod='sha1').hexdigest()
bcf1fb2ef2d31fcc271d33dc18db99926fcb9780
607,008
def isopt(c): """Function that checks wheter the passed character is an operator.""" if c == "+" or c == "-" or c == "*" or c == "/": return True else: return False
ec6c4ef16a48ecdd514a856ec30914ad58395de4
607,009
import requests def check_url(url, timeout=5, **kwargs): """Return true if `url` is returns a status code < 400. Otherwise, raise an error. `kwargs` are arguments for `requests.head()`. Parameters ---------- url : str The URL to check. timeout : numeric Number of seconds to wa...
79947c589cbdcd08b87226842be0a7a7090509c3
607,014
def total_ret(x): """ Calculates Total cumalative Return """ return (x.add(1).prod() - 1) * 100
5bddf551fa2293749f576fc06028a3fc5d177543
607,019
def dropna_mean(x): """Drop NA values and return the mean """ return x.dropna().mean()
0785c6d7336cb1370904db1d66224f9314dae905
607,020
def nodeHasContent(tree): """ Returns True if any leaf contains a content word """ return tree.has_content()
22424bab7439f04872f3ccfcb4281d82116b62de
607,024
def cycle_prev(id,cycle_length): """ computes the previous id in a cycle Parameters ---------- id : integer The index of an item in the cycle. cycle_length : integer The length of the cycle. Returns ------- integer The index of the previous item in the cycle...
c7358c6735c8210c17d74623336fbf73d7728fe5
607,026
import struct def bytesInt128(data): """Convert a 128 bit packed binary string to an integer. Args: data (str): 128 bit packed binary data Returns: An integer. """ (a, b) = struct.unpack('<QQ', data) intval = 0 | a << 64 | b return intval
ecb3249bfb4b479d97695878a1c04f10decd7b73
607,029
def length_sqrd(vec): """ Returns the length of a vector2D sqaured. Faster than Length(), but only marginally """ return vec[0] ** 2 + vec[1] ** 2
1950a086cd136abc923a4377356b68e7e1c728c2
607,030
def regions_unflatten(regions): """ Reverse regions_flatten, return a dict to update a book with. For example:: book.update(regions_unflatten(regions)) """ out = {} for r in regions: if r[0] not in out: out[r[0]] = [] out[r[0]].append(( int(r[1]), # ...
7e84a696073d5c26ee440953003e17d5ace8cff1
607,031
def toHex(value: int) -> str: """Return the hex representation of an integer.""" return hex(value)[2:].upper().zfill(2)
41220b1144365185a06aa8b6a84e0358d05aba7a
607,039
from pathlib import Path from typing import Dict import json def load(file: Path) -> Dict[str, str]: """Load the JSON file containing all words and their details.""" with file.open(encoding="utf-8") as fh: words: Dict[str, str] = json.load(fh) print(f">>> Loaded {len(words):,} words from {file}", ...
35ba700035eba5b82b0ad9aaa9077bfc67e5bcec
607,040
def _check_version(module_name): """Get the version of an installed package""" module = __import__(module_name) return module.__version__
4088f6529d37ae684e979362f39f9eed82b1745b
607,041
def get_is_active(language, order): """ Checks if order is active or no and creates response in appropriate language :param language: language of conversation :param order: client order :return: string with info about if order is active or no """ output_string = "" if language == 'pl': ...
15e065cc545cf6aa9c471b36c73400317d43b4bc
607,042
def calcul_proba_classe(points): """ Calcul les probas pour les points de `points` d'être dans chaque classes. Paramètres ---------- points : array_like Liste de la forme (nb_point, nb_parametre + 1) contenant des points représenter par les listes de leurs coordonnées avec leurs cla...
1d316603889cfd8a2730b67838ac33debe1a55c3
607,043
from typing import Any def optional(**kwargs: Any) -> dict: """ Take a set of keyword arguments and return a dict with only the not-None values. Returns: dict """ return {key: value for key, value in kwargs.items() if value is not None}
97b50729f2749088b189f2aeddae96d00bc9163e
607,044
import json def load_json(json_path): """ json 파일 읽어오기 :param json_path: json 파일 경로 :return: json 파일 데이터 """ with open(json_path, 'r') as f: data = json.load(f) return data
cd533be2d00c6c10075147fbab81cc3b3b8469e9
607,046
import torch def next_batch_in_tensors(obj, batch_size, device): """ DataSet object returns np arrays. This function converts the batch into tensors :param obj : DataSet object :param batch_size: Batch size :param device : cpu or gpu :return : batch and labels as tensors ...
dcd1a40657f8421badc273d2798f27c5564dfcaa
607,047
def datetime_to_iso(date): """Returns an ISO 8601 format 2017-08-08T21:06:49Z :param datetime date: Datetime object """ return date.strftime("%Y-%m-%dT%H:%M:%SZ")
14b1359f1483c15324d278b71e5a6302fb311ea6
607,051
def _rect(x: float, y: float, boxwidth: float, boxheight: float, fill: str = 'white', strokewidth: float = 1): """Draw an SVG <rect> rectangle.""" return f'<rect x="{x}" y="{y}" width="{boxwidth}" height="{boxheight}" ' \ f'stroke="black" fill="{fill}...
ce0b88a946dc1f1d65a3ffe5fa81920be06a294b
607,055
def calcCenter(ps): """ calculate incenter of a triangle given all vertices""" mid1 = ((ps[0][0]+ps[1][0])/2, (ps[0][1]+ps[1][1])/2) mid = ((mid1[0]+ps[2][0])/2, (mid1[1]+ps[2][1])/2) return mid
9157f6b11a4b6c964753f3dd0e116385ca3e5731
607,059
def split_commas(s): """Split a string on commas and return a list of tokens""" return [token.strip() for token in s.split(",") if token]
7b155d5654639a897e8a1fa28eadbc38522241ed
607,060
import math import string import itertools def generate_shard_names(num_shards): """Generates strings of of ASCII sequence permutations for naming shards. Usage: >>> generate_shard_names(3) ['abc', 'acb', 'bac'] Args: num_shards: The number of shard names to generate. Returns: A list of gener...
80a81967948a4a8e61e83867e344e47a9afb6f83
607,061
from pathlib import Path from typing import Union def join_diff_path(data_path: Path, otu_id: str, otu_version: Union[int, str]) -> Path: """ Derive the path to a diff file based on the application `data_path` configuration and the OTU ID and version. :param data_path: the application data path :para...
ee846df387f61d9864c50f6a9b50f072bf6bbf3f
607,063
def iso_time(time_string): """Return a iso formated datetime: 2013-04-15T19:50:23Z""" ts = time_string.replace(' ', 'T') try: micro = ts.rindex('.') ts = ts[:micro] except ValueError: pass return '%sZ' % ts
0521e9f078e16434c029eea35515d5617081dca0
607,064
def invite_url(invite): """ Returns the invite's url. Returns ------- url : `str` """ return f'http://discord.gg/{invite.code}'
5e6ba2daec8193739a21d9f32c87b9b520ee8fb6
607,067
def is_valid_mutation_record_to_process(raw_header_line, header, line): """ Determines whether the current line is a valid record in the mutation file that should be processed. A record is considered invalid if: - it is a duplicate of the header line - the line begins with a...
86513d1f98db38f64bc332d27c474a9798b2153d
607,068
import unittest import torch def require_cuda(test_case): """ Decorator marking a test that requires CUDA. These tests are skipped when there are no GPU available. """ return unittest.skipUnless(torch.cuda.is_available(), "test requires a GPU")(test_case)
25e2472fad6e7041248d7cc1fa4b68b506a4b4c5
607,072
import re def check_molecule(molecule): """ Check if the given string is a molecule Parameters ---------- molecule : String Molecular formula. Returns ------- True if the given string is a molecule, false otherwise (if it is an atom). """ match = re.match('^[A-Z]{1}[...
4b95218ba7fcd855dc7e5aa661b26abe9e394920
607,073
from typing import Iterable from typing import Tuple def max_bbox(boxes: Iterable[Tuple[int, int, int, int]]) -> Tuple[int, int, int, int]: """ Calculates the minimal bounding box containing all boxes contained in an iterator. Args: boxes (iterator): An iterator returning tuples of the format...
d7299f3c68344d64e4bc5e327a96a1b59ad250e9
607,078
def get_user_specific_state(uid, context): """Get the user-specific UI. Args: uid (str): A user's unique ID. context (dict): A dictionary of existing page context. Returns context (dict): The context updated with any user-specific state. """ context['uid'] = uid context['...
7b1743cc88f076f889dd1f8bfb32864bf2855431
607,081
def percent_diff(val1, val2): """Returns what percentage a change val2 is from val1. For example, if val=10 and val2=15, returns '+50%'. Args: val1: Base number. val2: Number to compare against the base number. """ diff = (val2 - val1) / val1 * 100 return f"+{diff:.1f}%" if diff >= 0 else f"{diff:...
31877be92cb6a1423059cc503be59adc9197ccfb
607,084
def tree_to_newick(t) -> str: """ Function to convert tree to Newick, slightly modified form of the tree.py version. Takes the root node of an UPGMA tree as input """ if t.right == None: return t.left + ":" + str(t.uh) else: return ( "(" + ",".join([tree_t...
1778b0510c0370156dbe7fb7e20c7a0cbb2a93c7
607,085
from pathlib import Path def get_pkgfile_path(pkgfile_dir, ecosystem): """Get path to pkgfile for given ecosystem.""" return str(Path(pkgfile_dir) / Path('{e}-packages'.format(e=ecosystem)))
35b610211ba9cab63a8b845373f833af109e2efa
607,088
def convert_attr_name(s): """Convert all underline in string name to space and capitalize """ return " ".join(map(str.capitalize, s.strip().split("_")))
6ba56ccef5091ae33588c9a48a244bfefebd9d45
607,089
def get_mave_csv_schematype_from_exception(exception): """Get MAVE CSV schema type from exception string. E.g. get 'score' from: Error [400]: [...] No such file [...]: '/Users/[...]/9ff4b4d6-daea-4178-b170-7b24c77ce0c0-score.csv' Args: exception (str): Exception messaged raised due to a MAVE CS...
007d94e9afce703e3066a27354837deb2dbaa691
607,091
def sign(number: int | float) -> int: """ Return the number sign. >>> sign(5) 1 >>> sign(-5.2) -1 >>> sign(0) 0 """ if number > 0: return 1 elif number < 0: return -1 return 0
e6360520f746db5bed8511faf6796d04f032c9df
607,094
def get_file_list(input_file="test_data.txt"): """ Read a file to a list with an item per line :param input_file: :return: List, one item per line """ with open(input_file) as file: urls = file.read().splitlines() return urls
cee9841a13472240793a201065151485efcf0a47
607,096
def roundup(n, k=64): """Round up to the next multiple of 64.""" return k * ((n + k - 1) // k)
08e04cd4cb2b24e123d28deeea5f49ba8f423565
607,098
import hashlib def md5_hash(string): """ Return md5 has for a string (force encode utf-8) """ return hashlib.md5(string.encode('utf-8')).hexdigest()
436c7e6869b0e8cca7ce45c3c5ff5177b1ebd89d
607,103
def meta(model, attr): """ Return the specified Meta attribute of a model. This is needed because Django does not permit templates to access attributes which begin with an underscore (e.g. _meta). Args: model: A Django model class or instance attr: The attribute name """ return ...
7c1debf103fc1b0703efe347e4aec93b168cab62
607,104
def prime(num: int) -> bool: """Returns a boolean if the number is prime""" divisors = [i for i in range(1, num + 1) if num % i == 0] print(divisors) return True if len(divisors) == 2 else False
976b84a5946679dba8f248426842ecc1e81b576b
607,106
def blocksize_limit_for_txs(txps, txsize=226): """ Given a transactions per second figure, calculate the equivalent bitcoin blocksize. """ mbs = (txps * txsize) / (1024 * 1024.0) # megabytes per second return mbs * 600.0
fd485be11dbe46b1f0b3764cd18f8d36f2df2d7e
607,107
def convert(val): """A simple function for a testing example""" return val
4f0f0d8fc145695f0de9235099153ffc80781258
607,112
import torch def flipx4_forward(model, inp): """Flip testing with X4 self ensemble, i.e., normal, flip H, flip W, flip H and W Args: model (PyTorch model) inp (Tensor): inputs defined by the model Returns: output (Tensor): outputs of the model. float, in CPU """ with torch...
325507b2d3be4d1b7d6effbc6c33cf5cb5b4feef
607,114
def valideFloat(values, length): """This function takes a single float, or int or a list of them and a requested length and returns a list of float of length 1 or length.""" if type(values) == float: return [values] elif type(values) == int: return [float(values)] else: if le...
299ae6c04844992f2f8606c8fb874ab717954bb9
607,121
from unittest.mock import patch def method_mock(request, cls, method_name, autospec=True, **kwargs): """Return mock for method *method_name* on *cls*. The patch is reversed after pytest uses it. """ _patch = patch.object(cls, method_name, autospec=autospec, **kwargs) request.addfinalizer(_patch.s...
fe8b38524cffe12d2b3a07d6afa0d1c374455341
607,123
def is_public_function(function_name): """ Determine whether the Vim script function with the given name is a public function which should be included in the generated documentation (for example script-local functions are not included in the generated documentation). """ is_global_function =...
f807a159d66978426604ae9cad382505be55b2b7
607,124
def cup(die1, die2): """Construct a cup that contains die1 and die2. >>> cup(dice(1, 1), dice(1, 2)) [[1], [1, 2]] """ return [die1] + [die2]
64d24022791aad4f9d4d46e907623c9e9ee0b593
607,130
import struct def encode_big_endian_32(i): """Take an int and return big-endian bytes""" return struct.pack('>I', i)[-4:]
6e84903955e71ca3ed8c72652d28356c35fb1f8b
607,133
def get_test_info(test_file): """Obtains information about gninatypes file. Arguments: test_file: text file containing labels and paths to gninatypes files Returns: dictionary containing tuples with the format: {index : (receptor_path, ligand_path)} where index is t...
5d6d2457c299097565ab193556da06f0228e9434
607,135
def corr(self, parameter1, parameter2, method='pearson', min_periods=1): """ Compute pairwise correlation of data columns of parameter1 and parameter2, excluding NA/null values. Parameters ---------- parameter1: str Key name of the column 1 to correlate. parameter2: str ...
5f544f27300b3143465a55a68b2f012711835b81
607,137
def true_or_false(in_str): """Returns True/False if string represents it, else None.""" in_str = in_str.lower() if in_str.startswith(('true', 'y', '1', 'on')): return True elif in_str.startswith(('false', 'n', '0', 'off')): return False else: return None
e23adf40237d6111cb0a6388a95aab79ba2aa35b
607,138
def get_prompt_save_file_name(name: str) -> str: """ Derives a file name to use for storing default prompt values. Args: name (str): The unique identifier of the file-name. Returns: str: The file name. """ return f"{name}.sav"
10f398bb03a5e50aea120952538ab1e70c440949
607,140
def get_slug(path): """ Return the page's slug >>> get_slug('/test/function/') function """ if path.endswith('/'): path = path[:-1] return path.split("/")[-1]
55c675588784d9980d579e83911b728dfb3b3ccd
607,141
def vertices_to_tuples(vpts): """ Returns list of vertex tuples from a list of Vertex objects """ tpts = [] for pt in vpts: tpts.append(pt.toTuple()) return tpts
a110084b8d1a81c3fc61881f941b57c748deda9f
607,142
import re def glob2like(s): """ Convert a file glob pattern to an equivalent SQL ``LIKE`` pattern """ def subber(m): x = m.group(1) if x == '*': return '%' elif x == '?': return '_' elif x in (r'\*', r'\?'): return x[-1] elif x in (r'...
760efbe003aafbe78eb59e9cb629cf8b202ac4cc
607,144
def get_domain_concept_id(domain_table): """ A helper function to create the domain_concept_id field :param domain_table: the cdm domain table :return: the domain_concept_id """ return domain_table.split('_')[0] + '_concept_id'
3843636ea7c0bdd9f791ef100c9d6ea5bcb06750
607,146
from pathlib import Path from typing import List def remove_unused_files(directory: Path, module_name: str, need_to_remove_cli: bool) -> None: """Remove unused files. Args: directory: path to the project directory module_name: project module name need_to_remove_cli: flag for removing ...
1ce15a23a06a20b7f8be6fc583699289c7a76251
607,148
def area_triangulo(base, altura): """ Calcula el área de un triángulo dada su base y altura. >>> area_triangulo(3, 6) 9.0 """ return base * altura / 2.
4ac0670f720aa0af9ecdd49f9a26c638af5a994d
607,150
import pickle def decrypt(token, fernet): """Decrypt a token into a serializable object using the given fernet.""" return pickle.loads(fernet.decrypt(token))
eb0cd43e1ac5d2e34b6782fa005b2e24201ebe6a
607,155
from typing import Dict from typing import List from typing import Tuple def get_sentences_bounds(text_info: Dict) -> List[Tuple[int, int]]: """ Create bounds for each sentence (start word, end word + 1) Parameters ---------- text_info: Dict Returns ------- out: List[Tuple[int, in...
6237f627db5f0a0c0068112a1d70ffb62ff1f3df
607,160
def peek_reward(grid, state, action): """For a given grid, state, and action return the reward in the transition matrix. Parameters ---------- grid : ndarray of ints The transition matrix. state : int The current state of the transition matrix (represented as a row number) actio...
75e18fa29ed040295c3369934e294e14ba6507be
607,163
def pip_has_version(package): """ For pip install strings: Checks if there is a part that mentions the version """ for c in ["<", "=", ">"]: if c in package: return True return False
17f7d7b5f532e4c750c4b2ab592aa41f075e5c9d
607,168
def create_facet_regions(dim, points, cells, cell_data): """ Create a dictionary mapping from facet (via vertex coordinates) to facet region. Returns an empty dictionary if there are no facet regions (physical regions in gmsh) defined """ if dim == 2: facets = cells.get('line', []) ...
456bdcd6cbcadd941cf00e767ab75b4e59603b09
607,176
import re def fix_unk_from_text_without_tokenizer(span, text, unk='<unk>'): """ Find span from the text to fix unk in the generated span Example: span = "<unk> colo e Bengo" text = "Angola International Airport is located at Ícolo e Bengo" fixed_span = "Ícolo e Bengo" """ if unk not in...
1785b53d31203bd7b6f484ad44cbad725769ce9d
607,178
def is_team(xml_obj): """Return true if the XML object has a Team tag""" return xml_obj.tag == "Team"
b50d10185c9683a7ca17d8c8337b138ab3f85557
607,180
def sumsq(data, start=0): """Return the sum of the squares of a sequence of numbers. >>> sumsq([2.25, 4.5, -0.5, 1.0]) 26.5625 If optional argument start is given, it is added to the sequence. If the sequence is empty, start (defaults to 0) is returned. """ return sum((x*x for x in data), ...
2c91606097ea6cb5a39269cf514ed26e28a88769
607,181
def fix_fits_keywords(header): """ Update header keyword to change '-' by '_' as columns with '-' are not allowed on SQL """ new_header = {} for key in header.keys(): new_key = key.replace('-', '_') new_header[new_key] = header[key] return new_header
a73cf1f139b3e7f1ec8366188c42b670b7f2674e
607,182