content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def col_dict_to_set(df, col, key): """Create a set from the values of the dictionaries given a key Args: df(pd.Dataframe): dataframe col(str): column containing list of dictionaries key(str): key to extract from the dictionaries Returns: A pandas Dataf...
351aeeacdfe8c8230472f5e97b6497af69e1e42e
657,279
def _tensor_name_base(full_tensor_name): """Removes the device assignment code from a tensor. e.g. _tensor_name_base("foo:3") => "foo" Args: full_tensor_name: A tensor name that is annotated with a device placement (this is what tensor flow introspection gives). Returns: A name without any devic...
e8f524d5d17f1c6d47f29f7af19f6bffbb851f71
657,283
from typing import NamedTuple def _to_dict(conf: NamedTuple): """Convert nested named tuple to dict.""" d = conf._asdict() for k in conf._fields: el = getattr(conf, k) if hasattr(el, '_asdict'): d[k] = _to_dict(el) return d
1ef32f61b3903ace12c80de78df934a50d6d14e1
657,284
import requests import json def vaultPutBulk(url, params, body, sessionId): """ Make an HTTP PUT request to Vault. :param url: the URL to PUT :param params: query parameters :param body: update body :param sessionId: vault sessionId :return: responseStr: JSON response string from Vault A...
8c8ddac049e4cbffced3af596ae7034e7692811c
657,285
import torch def to_one_hot_vector(num_class, label): """ Converts a label to a one hot vector :param num_class: number of object classes :param label: integer label values :return: a vector of the length num_class containing a 1 at position label, and 0 otherwise """ return torch.nn.function...
3ae1559db4d1a0f5174381ac2e70fc8df1f91aa1
657,289
def bswsa_should_halt(_seq, _stream, values, _context, _loaded_fields): """Halting function for :attr:`BasicStructWithSentinelArray.numbers`.""" if values and values[-1] == 0: # Hit sentinel, remove it from the end of the array. del values[-1] return True return False
89bfb45266199b21052faa089dde194c9345cc95
657,292
import torch def get_R_torch(angles): """Get rotation matrix R along verticle axis from the angle Args: angles (tensor[N]): In radian Returns: Rs (tensor[N, 3, 3]) """ cs, ss = torch.cos(angles), torch.sin(angles) zeros = torch.zeros(len(cs), device=angles.device) ones = ...
8b8ac6767444b7b561df98e930d55b1919203001
657,293
def fancy_join(lst, sep=", ", final_sep=" and "): """ Join a list using a different separator for the final element """ if len(lst) > 2: head, tail = lst[:-1], lst[-1] lst = [sep.join(head), tail] return final_sep.join(lst)
70a796fed566947cb2b26873a71b7e31a499bda1
657,294
from datetime import datetime def datetime_fromisoformat(dts): """ Take an ISO format datetime string and return a datetime type. The datetime.fromisoformat method was new in Python 3.7. This replacement works on 3.6.9, which the author is still has on some machines. It may work on older versions,...
f03072f65b585db88a33ec932c2d277c33e0b93f
657,298
import yaml def load_yaml(file_path): """Load a yaml file as a Python dictionary. Args: file_path: the absolute or relative path to the yaml file. Returns: the contents of the yaml file, as a Python dictionary. """ return yaml.load(open(file_path, "r"), Loader=yaml.Loader)
4957d93dba11cdfb28ddb6caec545bd7590f4fa4
657,300
def capitalize(s): """ Capitalize the first char of a string, without affecting the rest of the string. This differs from `str.capitalize` since the latter also lowercases the rest of the string. """ if not s: return s return ''.join([s[0].upper(), s[1:]])
5f07a8f3be64b4370827ae5ae94f67e2fafc2974
657,301
def get_normalized_list(input_str): """ Returns the comma-separated input string as a normalized list. """ items = input_str.split(",") total = 0.0 for item in items: total += float(item) temp_total = 0 for index, item in enumerate(items): temp_total += float(item) items[...
fcf89ca6dd0d03dd09f6927cde599f12084689e0
657,304
def cpf_is_digits(value): """ This function receives the Brazilian CPF and returns True if it contains only digits or False if not. :param value: A string with the number of Brazilian CPF :return: True or False """ if value.isdigit(): return True else: return False
84c3fca2c97ba84e892c9cbcc669c3b9c34c17a0
657,307
import six def key_by_value_dict(in_dict, value): """ Reverse dictionary lookup. Args: in_dict (dict): Input dict. value: Lookup value. Returns: Key in ``in_dict`` containing ``value`` if found. >>> key_by_value_dict({'key1': 42, 'key2': 'forty-two'},...
1a93146e6cd6a9ce6244ca19f7069a8c09f70bec
657,309
def moyenne_trois_nb(a : float, b : float, c : float) -> float: """Retourne la moyenne arithmétique des trois nombres a, b et c. """ return (a + b + c) / 3.0
e86f22f5ef9fbee2420cd11341272f6e8c54d895
657,311
from functools import reduce def solve(n, ar): """ Return the sum of the elements in array, ar of size n. This is the same problem as "Simple Array Sum" but the twist is that the elements of the array are in the order of 10^10. In python, however, values are autocast to whatever type/size they nee...
bae2fe96f0d05962cec6f9d45fffd3fcce0dc037
657,312
def bin_to_dec(bin_str): """Convert a string of bits to decimal.""" result = 0 for i, bit in enumerate(bin_str[::-1]): result += int(bit) * 2**i return result
f49a9f0ee25e886111407bd20688567ee7e9a16f
657,313
def purge_spikes_beyond_tracking(spike_train, tracking_ts, full_purge=True): """ Parameters ---------- spike_train : np.ndarray Spike times in seconds. tracking_ts : np.ndarray (2, ) The start and end of tracking relative to sessions start. full_purge : bool Remove spikes...
9cb7c2618b642206fed88693bb4ed5326cc5ee7e
657,315
def apply_antialiasing(kernel, kernel_width, scale_factor, antialiasing): """ Antialiasing is "stretching" the field of view according to the scale factor (only for downscaling). This is produces the low-pass filtering. This requires modifying both the interpolation (st...
96e2417722532634aba8a8ea85e4c30140dbf855
657,320
def _iterateTrixelFinder(pt, parent, max_level): """ Method to iteratively find the htmid of the trixel containing a point. Parameters ---------- pt is a Cartesian point (not necessarily on the unit sphere) parent is the largest trixel currently known to contain the point max_level is...
1cde08a587206b1028380f7376ab184d0143892d
657,322
def netids_above_cutoff(grades, cutoff): """Returns list of netids with grades above or equal cutoff Precondition: grades has netids as keys, ints as values. cutoff is an int.""" netid = [] for key in grades.keys(): if grades[key] >= cutoff: netid.append(key) return netid
f11987303955ac968769078ece49b9b4ed6cb011
657,326
import hashlib def PBKDF2(self, mnemonic, salt=""): """ Uses the PBKDF2 key-stretching function to stretch the mnemonic to a 512-bit value. The use of salt is optional Parameters: mnemonic (String): the mnemonic code words to stretch salt (String): An addi...
d333782599b2b75e3fad6a9b54575186aac24b2c
657,328
def update_store(coin_store1, coin_store2): """Updates the contents of a coin store with values from another store.""" for coin_type, coin_num in coin_store2.items(): coin_store1[coin_type] += coin_num return coin_store1
7f5d8620de39279e28cf52c73e12790bbeae7b8a
657,330
def user_converts(predicted_value): """ Converts the predicted value into text and styles for easy visualization :param predicted_value: :return: """ style = {"border-radius": "20px", "padding": "10px", "vertical-align": "middle", "margin": "auto"} if predicted_value == 'No Value': ...
289236e40dd9b57d110018b32a8f5cdcc589b74a
657,332
def tuples_to_dict(pairs, verbose=False): """ Take a list of paired tuples and convert to a dictionary where the first element of each tuple is the key and the second element is the value. """ d={} for (k, v) in pairs: d[k] = v if verbose: if isinstance(v,float):...
41e25f3e39b51743d4ea41666207ed7f42845a6d
657,333
def _append_docstring(func, supplement, insert_in="Parameters", at_end=True): """ Local helper to automate text insertions in docstrings Parameters ---------- func : callable Typically a (wrapped) Syncopy metafunction such as :func:`~syncopy.freqanalysis` supplement : str Te...
2a3e865d461c7d2dc2ff367a267e21c4b91676d9
657,337
def get_float(prompt, lower_bound, upper_bound): """Prompt the user for a number and return the number as a float. Parameters prompt: A string to display to the user. lower_bound: The lowest (smallest) number that the user may enter. upper_bound: The highest (largest) number that the us...
e935cf2b6946d8969863f0fc28342ca16b98a472
657,341
import re def parse_circle(msg): """Parse the message from CIRCLE and return the line numbers""" matches = re.findall(r"LINE NO.=\s*(\d*)", msg) if matches: return [int(match) for match in matches]
8d9ca1640691f74f84eb7da1db91b36a058ff743
657,343
from typing import List def _str2list(s: str) -> List[str]: """Converts str into list - use for list of OCLC numbers""" return [n.strip() for n in s.split(",")]
cc9a132b268759db01391291b6607c0c36e07ecb
657,349
import re def escape_name(name): """Escaped wheel name as specified in :pep:`427#escaping-and-unicode`.""" return re.sub(r"[^\w\d.]+", "_", name, flags=re.UNICODE)
08baa74768be4e0e002ed51d083f33c3e00989f1
657,350
def StrNoneChk(fld): """ Returns a blank string if none """ if fld is None: return "" return str(fld)
3f9e7c1fe2b9ee6986c2853be7cfdb3c64bfa3df
657,351
def get_coordinates_here(response): """ Returns a tuple with the lat/long :param response: dict - The here response object :return: double, double """ try: lat = response["Response"]["View"][0]["Result"][0]["Location"][ "NavigationPosition" ][0]["Latitude"] lo...
455727343db0874fd324e85a681798048690fbc3
657,354
def add_residue_to_dfix(dfix_head, resinum): """ Add a residue to a list of DFIX/DANG restraints DFIX 1.234 C1 C2 -> DFIX 1.234 C1_4 C2_4 >>> add_residue_to_dfix(['DFIX 1.456 C1 C2', 'DFIX 1.212 C3 C4'], 4) ['DFIX 1.456 C1_4 C2_4\\n', 'DFIX 1.212 C3_4 C4_4\\n'] >>> add_residue_to_dfix(['DF...
69fd5b22a6ef9c1ffe6956ce658a9761f1781238
657,355
def field_occurrence_predicate(field, args): """Return a function that checks for the occurrence of a field.""" newfield = field.lower() if args.ignore_case else field def _field_occurrence(entry): return bool(getattr(entry, newfield, None)) return _field_occurrence
b7ee2b5f9357648879764444bd01f9a7e30e8ca6
657,358
def _bit_is_set(bit_str: str, i: int) -> bool: """ Private helper function to check whether the i-th bit in the given bit string is set. :param bit_str: str :param i: int :return: bool """ return bit_str[i] == '1' # Running time complexity: O(1)
8410a90031fdbaa23f92e1873468aa34c13667fb
657,361
def S_ISDOOR(mode): # real signature unknown; restored from __doc__ """ S_ISDOOR(mode) -> bool Return True if mode is from a door. """ return False
7f756331e9bd3538df5457fc4dfe35f5cd6d5331
657,364
from typing import List from typing import Any def peek(array: List[Any]) -> Any: """ Returns the last element in the input array. Similar to the built-in Array.pop method, except that it does not remove the last element. This method is a convenient shorthand for array[array.length - 1]. """ r...
40e690da46ba4e7142fd0087a20cc553288e9b63
657,367
def _to_python_str(s): """ Convert to Python string """ if isinstance(s, bytes): return s.decode('utf-8') else: return s
f4a1967f64a30792346640b0e145f0038d7bf50b
657,374
from typing import Union def read_token() -> Union[str, None]: """ Reads token from the saved config file Returns: token string from file (or None if missing/invalid) """ try: with open("config/token", "r") as file: return file.readline().rstrip() except Exception ...
f548971b97cd06a0e86ab2152dc4452928da6b09
657,377
def add_user_to_groups(uname, grpstr, groups=["lsst_lcl", "jovyan"]): """Take a user name (a string) and a base group file (as a string) and inject the user into the appropriate groups, given in the groups parameter (defaults to 'lsst_lcl' and 'jovyan'). Returns a string.""" glines = grpstr.split("\n")...
ddf15d42fe57ba5dc96afea43a330d787fdbb909
657,379
import re def _replace_version(package_str, new_version): """ replaces the version tag in contents if there is only one instance :param package_str: str contents of package.xml :param new_version: str version number :returns: str new package.xml :raises RuntimeError: """ # try to repl...
913c844c9387b6fb1f91327fba7999a72e3b156f
657,380
def tocreset(I, Ipickup, TD, curve="U1", CTR=1): """ Time OverCurrent Reset Time Function. Function to calculate the time to reset for a TOC (Time-OverCurrent, 51) element. Parameters ---------- I: float Measured Current in Amps Ipickup: float ...
8c26a3aebcb5f51fe884724e4d9460f44454b3d1
657,381
def wigner_d_transform_analysis_vectorized(f, wd_flat, idxs): """ computes the wigner transform analysis in a vectorized way returns the flattened blocks of f_hat as a single vector f: the input signal, shape (2b, 2b, 2b) axes m, beta, n. wd_flat: the flattened weighted wigner d functions, shape (num_s...
7f1a32fea3a42f6bff7ae7295dfe0182c61c6a57
657,383
def add_make_abundance_io_arguments(arg_parser): """Add io arguments to parser.""" helpstr = "Input group file which associates collapsed isoforms with reads." arg_parser.add_argument("group_filename", type=str, help=helpstr) helpstr = "Input pickle file (e.g., hq_lq_pre_dict.pickle) which maps HQ " + ...
78bddd16f60f9055c532a1958cb7dff1398ca994
657,384
def remove_quotes(arg): """ This function returns two values: - The treated string (i.e., without surrounding quotes) - A boolean value informing whether it removed any quotes or not Note that it will only remove anything if the quotes at each end match. Therefore, strings like "foo' will be returned as they are...
94af94c99440dbc10f042210f4ae68feb2b68e0f
657,385
def is_video_file(filename): """ Check if file is a video :param filename: file name string :return: Boolean toggle """ return any(filename.endswith(extension) for extension in ['.mp4', '.avi', '.mpg', '.mkv', '.wmv', '.flv'])
fb112b094d13449026486e5e112ed4b41f19acf9
657,387
import six def convert_id36_to_numeric_id(id36): """Convert strings representing base36 numbers into an integer.""" if not isinstance(id36, six.string_types) or id36.count("_") > 0: raise ValueError("must supply base36 string, not fullname (e.g. use " "xxxxx, not t3_xxxxx)") ...
5ccd3661f6985c73e38ebcb6bbf9d0e242cddbb6
657,389
def normalize_df(series): """convenience function to normalize a signal (i.e., rescale to range from 0 to 1) """ series_norm = (series - series.min()) / (series.max() - series.min()) return series_norm
137433edddad2ef8e36a3369f194ff56e1015a13
657,391
def svid2gnssid(svid) -> int: """ Derive gnssId from svid numbering range. :param int svid: space vehicle ID :return: gnssId as integer :rtype: int """ if 120 <= svid <= 158: gnssId = 1 # SBAS elif 211 <= svid <= 246: gnssId = 2 # Galileo elif (159 <= svid <= 163...
10f8726577b7d973aaec0a04281bd6bdb8e30f8b
657,394
import hashlib def compute_hash(filename): """Returns the MD5 hash of the specified file""" with open(filename, 'r') as f: contents = f.read().encode('utf-8') return hashlib.md5(contents).digest()
f73983580eace66d9fe82156ac6cddb1576da58d
657,397
import json import base64 def get_service_account_cred_from_key_response(key_response): """ Return the decoded private key given the response from `create_service_account_key()`. This return from this function is the JSON key file contents e.g. response can be placed directly in file and be used a...
4ff6da5a134be890726d88848fd05a7f8a0b1e9c
657,398
from typing import List from typing import Tuple def get_new_gatecharacterization_range( current_valid_ranges: List[Tuple[float, float]], safety_voltage_ranges: List[Tuple[float, float]], range_update_directives: List[str], ) -> List[Tuple[float, float]]: """Determines new voltage range for a subseque...
a4e20fa9bda7f5be3f3ba054563a818ece8370d3
657,406
import torch import math def encode_μ_law(x: torch.Tensor, μ: int = 255, cast: bool = False)\ -> torch.Tensor: """ Encodes the input tensor element-wise with μ-law encoding Args: x: tensor μ: the size of the encoding (number of possible classes) cast: whether to cast to in...
b4bd30fcf9353b5895ca95309f60064deb0baa89
657,410
def to_minimal_df(df_in): """ Extracts a minimal df partof the given dataframe to be used with the implemented machine learning workflow. Also ensures that the indices are compareable """ df1 = df_in.copy().reset_index() if "Modified sequence" in df_in.columns: df2 = df_in[["Sequenc...
0e4d63abcf82e23d981a0cf8ebd54b8de54d749f
657,411
def get_FTPdetect_coordinates(FTPdetect_file_content, ff_bin, meteor_no = 1): """ Returns a list of FF*.bin coordinates of a specific bin file and a meteor on that image as a list of tuples e.g. [(15, 20), (16, 21), (17, 22)] and the rotation angle of the meteor. """ if int(FTPdetect_file_content[0].split(...
3a5adf21d545848ac8807d3bd03e0e2ef11eda77
657,419
def mirror(pt: float, delta: float): """Mirrors a value in a numberline Args: pt : real value in numberline delta: value to mirror Returns: pt - delta, pt + delta """ return pt - delta, pt + delta
5ec80a889422a961c0aa5906ed4990317876286f
657,420
def cw310_params( tags = [], timeout = "moderate", local = True, args = [ "--exec=\"console -q -t0\"", "--exec=\"bootstrap $(location {test_bin})\"", "console", "--exit-failure=FAIL", "--exit-success=PASS", "--timeou...
eb0147819c78584e8153bab8bafc9169a54f3278
657,422
import importlib def find_function(search_def): """ Dynamically load the function based on the search definition. :param str search_def: A string to tell us the function to load, e.g. module:funcname or module.path:class.staticmethod :raises ValueError: In case configuratio...
dd44ca63cf214f928667a704f8686739833775e5
657,424
def generate_matrix(dim): """Generate the matrix with enumarated elements. Args: dim: Dimension of the matrix. Returns: Generated matrix as a nested list. """ matr = [] for i in range(dim): # Start by 1 and increase the number for each new element by one. matr.a...
d4446ef3fc469050f6bd346182203c42cf6eefbd
657,436
def pack(join, alist): """Interleave a list with a value This function interleaves a list of values with the joining element. Params: join -- The value to be interleaved within the list alist -- The supplied list Returns: A new list pack("a",[1,2,3,4]) ==> ["a",1...
407c0f1133ecb42b466c54b41cdde56eea80bcb6
657,437
import re def read_d1_letter(fin_txt): """Reads letter aliases from a text file created by GoDepth1LettersWr.""" go2letter = {} re_goid = re.compile(r"(GO:\d{7})") with open(fin_txt) as ifstrm: for line in ifstrm: mtch = re_goid.search(line) if mtch and line[:1] != ' ':...
a05a944aa263c6682f3a2fed8a659f579bfcb950
657,438
def _has_numbers(text): """ Checks if any characters in the input text contain numbers """ return any(char.isdigit() for char in text)
c8992cfe40c310f07d292aa376aad8d766a5242b
657,440
def expect_lit(char, buf, pos): """Expect a literal character at the current buffer position.""" if pos >= len(buf) or buf[pos] != char: return None, len(buf) return char, pos+1
a90ab29f20bdc4733cfd331d2d58f7952c02ae62
657,441
def exactly(length:int) -> str: """ Match the previous pattern exactly `length` times. >>> import superexpressive as se >>> se.exactly(4) '{4}' >>> import superexpressive as se >>> se.DIGIT + se.exactly(6) '\\\\d{6}' """ return f"{{{length}}}"
01ba444356d213366b17d2d2d6aad832e054718e
657,442
def make_save_folder(hyps): """ Creates the save name for the model. hyps: dict keys: exp_name: str exp_num: int search_keys: str """ save_folder = "{}/{}_{}".format(hyps['exp_name'], hyps['exp_name'], ...
a13298979af2c615483432bb528cda6400e8c355
657,447
import textwrap def format_helptext(text): """Format help text, including wrapping.""" return "\n".join(textwrap.wrap(text))
a1e9baa8bd093802a76890c1e87876d751c280aa
657,448
def _energy_test_statistic_coefficient(n, m): """Coefficient of the test statistic.""" return n * m / (n + m)
0ce7d5d70ccd64fc6cf9343e673f8a8acf90fa97
657,449
def mul(c1, val): """Multiplies an encrypted counter by a public value""" a1, b1 = c1 return (val*a1, val*b1)
f51d578543c530abad2a1bb3680066f48b31c754
657,450
def FormatSubversionPropertyChanges(filename, props): """Returns Subversion's 'Property changes on ...' strings using given filename and properties. Args: filename: filename props: A list whose element is a (svn_prop_key, svn_prop_value) pair. Returns: A string which can be used in the patch file ...
f1cb0c1630e8b015ea284c7244619aa4d5e14c80
657,451
def try_attrs(obj, *attrs, **kwargs): """Try to find an available attribute. Args: obj (object): Object to get the attribute value for. *attrs (tuple/str): Tuple of different string attribute names to try (These names may include '.' attributes). default (object)[None]: Default Value to...
2dfb52432a5387c41e916c23d71c88f2536534d6
657,455
def groupby(iterable, key=None): """ Group items from iterable by key and return a dictionary where values are the lists of items from the iterable having the same key. :param key: function to apply to each element of the iterable. If not specified or is None key defaults to identity function and...
dccd69a0ffdc30e6d8b3950f14e3e2649e4c4409
657,456
def make_broadcastable(v, X): """Returns a view of `v` that can be broadcast with `X`. If `v` is a one-dimensional tensor [N] and `X` is a tensor of shape `[N, ..., ]`, returns a view of v with singleton dimensions appended. Example: `v` is a tensor of shape `[10]` and `X` is a tensor of shape...
f5178fd81a0b38217e5c66ab116e1781bc8d8a92
657,457
def point(value): """ Convert an integer to a string containing commas every three digits. For example, 3000 becomes '3,000' and 45000 becomes '45,000'. """ return "{:20,.2f}".format(value)
4570ae24cdb64ffce8b0aefdfd66684ed0db8f16
657,459
import itertools def multiindex_iterator (shape, *, melt_1_tuple=False): """ Provides a tuple-valued iterator to iterate over all multi-indices with given shape. For example, if shape is (2,3), then the iterated sequence is: (0,0), (0,1), (0,2), (1,0), (1,1), (1,2). If len(shape) is 1 and me...
2bee9b8f4094ec7f97eda3c3ca6bf20e23a4e0a2
657,460
def filter_and_sort(file_list): """ Out of a list of file names, returns only the ones ending by '.py', ordered with increasing file name length. """ file_list = [filename for filename in file_list if filename.endswith('.py')] def key(item): return len(item) ...
b87edcb318b49b5fcbd68ccb2397701e3518963d
657,462
def getComboIndex(combo_box, label, ignore_casing=False): """ This will return the index of the first matching label within a combo box qwidget. If no label is found 0 is returned :param combo_box: Widget to iterate through :type combo_box: QComboBox :param label: The combo label to match...
c67a7159e5a3875c53aed26c6a0a9c9ad78790be
657,463
def read_table (lines): """Reads to the next divider line. Read lines are returned, 'lines' is reduced to everything remaining. """ table_lines = [] while len(lines): popline = lines[0] lines = lines[1:] if popline[:6] == "======": break table_lines +...
bbc4a87f3e4ec62eca601c6b375f1c90091a4885
657,466
def arch_handler(value, **kwargs): """ Return a Package URL qualifier for the arch. """ return {'qualifiers': 'arch={}'.format(value)}
0e7ff319eb2f62a85dce90a13ce44325a548e163
657,467
def convert_tags(tags): """Will convert tags so the article can be uploaded to dev.to. This involves removing the `-` and making the tag lowercase. Args: tags (list): The list of tags to convert. Returns: list: The list of converted tags """ new_tags = [] for tag in tags: ...
70527344c1f19c2b2c96a3697e02262a14a3302d
657,469
def shall_exclude_diagnostic_message(message): """Exclude certain diagnostics messages""" exclusion_list = [ "-fno-canonical-system-headers", "-Wunused-but-set-parameter", "-Wno-free-nonheap-object", "-Werror=init-list-lifetime", "-Werror=class-conversion", ] retu...
68b9e005f08ddb41541bc4fafdcceecfbf8cfab4
657,470
def slurp(f): """ Returns file content as string """ fd = open(f) buf = fd.readlines() fd.close() return ''.join(buf)
f99a67e49f6e91594f38f85e7b0372f243d92b6a
657,472
def evaluate_velocity_at_bottom(layer, prop): """ Evaluate material properties at bottom of a velocity layer. .. seealso:: :func:`evaluate_velocity_at_top`, :func:`evaluate_velocity_at` :param layer: The velocity layer to use for evaluation. :type layer: :class:`~numpy.ndarray`, dtype = :py:const:...
3320c7a316cd9eb6539cf013be745b9e154dfdbe
657,474
def format_recursive(template, arguments): """ Performs str.format on the template in a recursive fashion iterating over lists and dictionary values >>> template = { ... 'a': 'Value {a}', ... 'b': { ... 'a': 'Value {a}', ... 'b': 'Value {b}', ... }, ... 'c': ['Value {a}'...
ce51eefc38288b86c08425c1bb8dea2c0769e239
657,475
def _get_block_sizes(resnet_size): """The number of block layers used for the Resnet model varies according to the size of the model. This helper grabs the layer set we want, throwing an error if a non-standard size has been selected. """ choices = { 18: [2, 2, 2, 2], 34: [3, 4, 6, 3], 50: [...
2093dc876e2f6db2cddb4bf836f1b8c3bcd6d789
657,478
async def get_manifest(db, ref_id: str) -> dict: """ Generate a dict of otu document version numbers keyed by the document id. This is used to make sure only changes made at the time the index rebuild was started are included in the build. :param db: the application database client :param ref_id: t...
bc24f543135b4773b55350e80b885b1a4051c8fb
657,479
def get_active_web_certificate(course, is_preview_mode=None): """ Retrieves the active web certificate configuration for the specified course """ certificates = getattr(course, 'certificates', {}) configurations = certificates.get('certificates', []) for config in configurations: if conf...
2fa136a2462582100cf1955039f095a8977f7db7
657,481
import ctypes def struct_pack(structure): """ Pack a :py:class:`ctypes.Structure` object and convert it to a packed string. :param structure: The structure instance to convert :type structure: :py:class:`ctypes.Structure` :return: The structure instance converted to a string. :rtype: str """ return ctypes.st...
e590f87d1b4f41f30feab2998ba7a381115654ba
657,483
def fivePercent(distances, percentage = 0.05): """ Calculates the cutoff by which a distance is considered close. Arguments: distances -- A dictionary with the distances as keys and their frequency as values Keyword arguments: percentage -- Float where the cutoff should be (i.e. 0.05 for the closest 5 percent o...
b6bd25665205fb3a9a6028d18de6bb00d65d41ee
657,488
import time def date_to_timestamp(date): """ Converts a date, format 2020-01-23 to a timestamp, format 12322342 """ return time.mktime(time.strptime(date, "%Y-%m-%d"))
eaac0c1f4ac6c003ff0d25ade3ec9f073b89ece3
657,490
def get_corner_points(contour): """ Get all corner points of the hexagonal target. Returns a list of 8 points, starting with the top left and going clockwise. """ # First actually convert to points points = [point[0] for point in contour] # Find the top left point # This should be the l...
d5a5bcf8c4d6c73b10f6aa4762f4769710f58a3a
657,491
import functools def delegate_manager(method): """ Delegate method calls to base manager, if exists. """ @functools.wraps(method) def wrapped(self, *args, **kwargs): if self._base_manager: return getattr(self._base_manager, method.__name__)(*args, **kwargs) return metho...
7a29e6986836881b6e47d99b33d8a09d1f627e11
657,492
def get_values(data, attribute): """gets all values from data[attribute] where data is a Pandas DataFrame >>> data = pd.read_csv('./datasets/credit.csv', delimiter = ',') >>> get_values(data, 'Housing') array(['own', 'free', 'rent'], dtype=object) """ return data[attribute].unique()
26b018b3b7fe0a6066477feba8f8e13eadbcda17
657,495
import re def tokenize_by_sentence(text: str) -> tuple: """ Splits a text into sentences, sentences into tokens, tokens into letters Tokens are framed with '_' :param text: a text :return: a tuple of sentence with tuples of tokens split into letters e.g. text = 'She is happy. He is happy.'...
5d32579334a714c9d9ba866b286d8bacecd202f1
657,496
def list_api_revision(client, resource_group_name, service_name, api_id): """Lists all revisions of an API.""" return client.api_revision.list_by_service(resource_group_name, service_name, api_id)
d0acd9099dfc3a4375731da8eacecfdb0c387b2f
657,499
def convertTypes(value): """Helper to convert the type into float or int. Args: value(str): The value that will be converted to float or int. Returns: The converted value. """ value = value.strip() try: return float(value) if '.' in value else int(value) except...
86e3ba932560621bcd3a85d71c375994373386bb
657,502
def collect_expected(dataset): """ Peel of the target values from the dataset """ expected = [] for sample in dataset: expected.append(sample[0]) return expected
8e9a39d8ac5e4a26a08ad2727ad0f7c009860de2
657,507
def get_perfdata(label, value, uom, warn, crit, min, max): """Returns 'label'=value[UOM];[warn];[crit];[min];[max] """ msg = "'{}'={}".format(label, value) if uom is not None: msg += uom msg += ';' if warn is not None: msg += str(warn) msg += ';' if crit is not None: ...
a1911bf827ef3111a2ca0a5e5cfdd727c98b09b1
657,509
def minmax(array): """Find both min and max value of arr in one pass""" minval = maxval = array[0] for e in array[1:]: if e < minval: minval = e if e > maxval: maxval = e return minval, maxval
3ade508ae82d60694968923ebdffef729a7af880
657,511
from datetime import datetime def valida_data(data: str) -> bool: """Valida a data de uma requisição Args: data (str): 2022-01-19 Returns: True: Se a data corresponder ao formato yyyy-mm-dd False: Se a data não corresponder ao formato yyyy-mm-dd """ try: datetime....
b9761974a115b1e26bdbf784177389c319d848a1
657,512
def prefixify(d: dict, p: str): """Create dictionary with same values but with each key prefixed by `{p}_`.""" return {f'{p}_{k}': v for (k, v) in d.items()}
aaad6b11640df7c5e288bdd039b039ce373dcba1
657,513