content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def score_best(proposed, existing): """Score a proposed change primarily by dependency score""" return 0
b6aeb2dde0d573269564d4edf0d04a9f3eaeeb94
652,911
def multiply_by_10(x): """Multiply a number by 10 Parameters ---------- x : float value to multiply Returns ------- y : float multiplied value """ return 10 * x
0a3f689e048c26ee6ae5e0ef0cc2e8b6ee6227f3
652,912
def get_volume_fn_from_mask_fn(mask_filename): """Extract volume path from mask path""" return mask_filename.replace("S-label", "")
a85bca3624b317fa9c85d15cc4141cbb4e9ab6ef
652,913
def get_colour(series_options, series_name): """Return the graph colour for the series specified.""" if series_options is None: return None if series_name in series_options: if "colour" in series_options[series_name]: return series_options[series_name]["colour"] return None
baacaf514f9ec27df96f90c23b5f18283c7da38c
652,914
import sympy def logarithm(argument, base=10, **kwargs): """Enforce that the default base of logarithms is the more intuitive base 10. SymPy does what many maths packages do, and defaults to the natural logarithm for 'log'. """ return sympy.log(argument, base, **kwargs)
4c26a4262e128f0162f98609d0d2712380584469
652,915
def task_pydocstyle(): """Run docstyle check.""" return { 'actions': ['pydocstyle pyppeteer'], }
0a8b66ee9d56db603187f07ca1493a4af0a6c925
652,916
def text_to_paras(text, aux=""): """ :in: str text list of str: paras = text_to_paras(text, aux='') aux = '.' for use in baidutr batch translate seg text to paras newline delimiters a para empty lines ignored """ # lines = text.split('\n') lines = text.splitlines() lines = ...
ea4b3cf7ecf906ace038fba1f6596c6a8611e066
652,918
def pay_excess(principal, minimum, remainder): """Pay any excess remaining after making minimum payments.""" excess = remainder if principal - excess <= 0: excess = principal remainder = remainder - principal else: remainder = 0 return principal - excess, minimum + excess, ...
5ed7133f23430aa7373d172516e29b6e29d9db1d
652,919
def protocol_to_ethertype(protocol): """Convert the int protocol to a two byte chr. :param protocol: The protocol to be used such as 0x8015 :type protocol: int :rtype: str """ return chr((protocol & 0xFF00) >> 8) + chr(protocol & 0x00FF)
11490bb8f47735894df2e49d87ffdd7fdd04f9fd
652,920
def sanitize_column_list(input_column_list): """Remove empty elements (Nones, '') from input columns list""" sanitized_column_list = [input for input in input_column_list if input] return sanitized_column_list
77b635cd5589f46b9381803893b2c8d36cdcdcae
652,921
from functools import reduce def compose(*args): """Composes all the given function in one.""" return reduce(lambda fun, tion: lambda arg: fun(tion(arg)), args, lambda arg: arg)
e67ff42d3e006fc43e2d5e4a801cdb68f1f2e61e
652,922
def text(): """Return a sample text string.""" return 'this is a text'
36af472a9973e4694b9b6188c03e15cd0a33b4b5
652,923
import csv def read_data(path): """ 从文件中读取数据 :param path: str 文件路径 :return: int 知识点数量, sequence 原始数据序列 """ with open(path, 'r', encoding='UTF-8') as f: skill_dt = {} seq_dt = {} readlines = csv.reader(f) for i, readline in enumerate(readlines): if i ...
c5c788aa38b798f34dda9eb67f560f79803c01d4
652,924
def amp_img(html_code): """Convert <img> to <amp-img>""" return html_code.replace("<img", "<amp-img")
e1759f093d37244ef9ff797b78243edda4f94a58
652,925
def _multiplicative_inverse(num, modulo): """ Return the multiplicative inverse of the given number in given modulo or raises a ValueError if no inverse exists. :param num: Number to be inverted :type num: int :param modulo: :type modulo: int :raises ValueError if num has no inverse :ret...
e8d367c5feb51a93fc26b07af2a0c8cf8872a365
652,926
def suppressed_zcta3(df, category, prevalence_type): """ Return an array of suppressed ZCTA3 values for the specified category and prevalence type suppressed zcta3s. Parameters: df: DataFrame of prevalence data category: Weight category/class prevalence_type: Prevalence type, one of ['Age-A...
c24209153753f04c6c601cd4a279a108d94964de
652,927
def take_list_first_item(any_list): """It returns the first item on a nested list """ list2 = [] for item in any_list: list2.append(item[0]) return list2
eb7b62e3ea9f39621f2766bade3c946ee5799ebd
652,929
def c_intent(parameter): """Work out intent for use in opencmiss_iron_c.F90""" intent = parameter.intent # C pointers to arrays must be passed by value if parameter.array_dims > 0 and not parameter.pointer: intent = 'IN' if parameter.array_dims == 0 and parameter.intent == 'INOUT': ...
bfdbb3bf34eb39f69b97da154fb6d57874bd4b5c
652,930
def _split_var_path(path): """ Split the given OpenMDAO variable path into a system path and a variable name. Parameters ---------- path : str The variable path to be split Returns ------- sys_path : str The path to the system containing the given variable. var_name...
654f3be82cb73b4eb56c72981ab89f12832eaf9c
652,931
def _get_max_page(dom): """ Try to guess how much pages are in book listing. Args: dom (obj): HTMLElement container of the page with book list. Returns: int: Number of pages for given category. """ div = dom.find("div", {"class": "razeniKnihListovani"}) if not div: ...
8a7a4c2e1a8a05a27215d3f0ec91faa07b6664ff
652,933
import hashlib def seed_from(*args): """ hashes any arguments to create a unique seed. This is useful for reproducibility, e.g. when generating same data for different models (which increment the seed differently). ------------- Example usage: with local_seed(seed_from("train", 10)): x...
ee76ed89ed00625f3433bb105d1bc1e2fc16bfdd
652,934
import logging def logger_has_filter(logger, filter_class): """ Will `logger` execute a filter of `filter_class`? :param logging.Logger logger: the logger to examine :param class filter_class: the filter class to search for :return: :data:`True` if the `logger` contains a `filter_class` f...
d00fec09b59e6186995af88371d7e0e5e50d049d
652,935
def rescale(X, x_min, x_max): """ Rescaled the array of input to the range [x_min, x_max] linearly. This method is often used in the context of making maps with matplotlib.pyplot.inshow. The matrix to be accepted must contain arrays in the [0,1] range. :param X: numpy.ndarray This is the in...
6f002651a48519e1f2a82365ba1c03f2e6a7c828
652,937
def exclude_entry(enabled, filter_type, language_list, language): """ Exclude bracket wrapping entry by filter """ exclude = True if enabled: # Black list languages if filter_type == 'blacklist': exclude = False if language != None: for item i...
43ad2361d908439a63aabf51ca27a17f2eda9283
652,938
def kelvin2celcius(K): """ Convert Kelvin to Celcius :param K: Temperature in Kelvin :return: Temperature in Celcius """ return K - 273.15
9e05374cdd986020678695a8aea83e155d4dcaac
652,939
def avg_salary(all_salary: dict) -> dict: """ Функция обработки всех найденных зарплат :param all_salary: словарь с зарплатами и количеством вакансий :return: обработанный словарь """ # Вычисляем среднее значение зарплат по разным категориям if all_salary['Senior'][2] != 0: all_...
6a5db2df9c41a5db4b63926536f5eaeb94f84c6a
652,940
def one_value_features(df): """ 値が1種類の意味のない変数を特定する """ one_value_cols = [] for c in df.columns: if df[c].nunique() == 1: one_value_cols.append(c) return one_value_cols
2a26ff4d53f3900de43bd81c8d25ac7765393b4e
652,941
def comp_div_list(name_list): """ Given stock name, return cash dividends collected Inputs name_list: e.g. ['Dividends/Cash/UOL.txt'] Outputs div_list: e.g. [100] """ div_list = [] for name in name_list: sum = 0 print("name = " + name) try: ...
394e613ace882b2c65cd9c4ce6b8749a91a57484
652,942
from typing import Collection from typing import Any def has_duplicates(itera: Collection[Any]) -> bool: """Determine if ``itera`` contains duplicates. Args: itera (Collection): a sized iterable Returns: bool """ seen = set() for i in itera: if i in seen: ...
44325db654023577c4fa38ad4693b1e5f79021d9
652,943
def parse_docs(hunter, docs): """returns tuple of (name, docs)""" if not docs: return hunter.__name__, "<no documentation>" docs = docs.strip().split('\n') for i, line in enumerate(docs): docs[i] = line.strip() return docs[0], ' '.join(docs[1:]) if len(docs[1:]) else "<no documentat...
b7836a4371d3fc97bc4ab25598a6b3c4c576e95b
652,944
def series_to_dict(influx_raw_data, tag_name): """{'series': [{'values': [[value1, value2, ...]], 'tags': {'tag': 'tag_val'}, 'name': 'series1', 'columns': ['col1', ...]}, ...] >>> {'tag_val': {'col1': value1, ...}} NB! tag_name should be unique in the set for a deterministic result """ ...
07528fe9082015a379192a0477824039295e8023
652,945
import requests def _check_blacklist(ddd, phone): """Função privada para checar se o número está na blacklist. Args: ddd (int): ddd enviado phone (int): telefone a ser checado """ complete_phone = str(ddd) + str(phone) check = requests.get(f'https://front-test-pg.herokuapp.com/bla...
93299fc6125ef264dbc0739ad1708576fb06838a
652,946
def get_summary(soup): """ 百度百科名目 """ summary = soup.find("div", {"class": 'lemma-summary'}) if summary == None: return "没找到相关的条目哦!" return summary.get_text().strip()
05f2dc5e5844eb91d61b0cde4b9b57668a5b2a49
652,947
def gmas(ipe, gmpe, sx, rx, dx, oqimt, stddev_types): """ This is a helper function to call get_mean_and_stddevs for the appropriate object given the IMT. Args: ipe: An IPE instance. gmpe: A GMPE instance. sx: Sites context. rx: Rupture context. dx: Distance cont...
662e1466a0aedc8d7030c4a84f0b34fecac4d2fc
652,948
from typing import Counter def Proportions(y): """ Returns Counter(y) as proportions """ c = Counter(y) n = len(y) return {k: c[k] / n for k in c.keys()}
7adaa433145e11a42ddbaecf5d40a66d7deacffc
652,949
import os def is_valid_json_output(parser, x): """ Checks if argument given to parser is valid path to export to :param parser: the parser :type parser: :class:`argparse.ArgumentParser` :param x: the value of the argument :type x: str :returns: the value if its valid, False otherwise ...
0b4ebcc20d557215b296753a709224c1f7cc496a
652,950
def get_default_dims(dims): """Get default dims on which to perfom an operation. Whenever a function from :mod:`xarray_einstats.stats` is called with ``dims=None`` (the default) this function is called to choose the default dims on which to operate out of the list with all the dims present. This f...
752aca06ced4bd1edb421bc03b2c26c06bc4a450
652,951
def unsafe_version(version): """Undoes what safe_version() does. See safe_version() for the details. Args: version: string, The safe version string. Returns: The string with '_' replaced with '.'. """ return version.replace('_', '.')
3b4243ecc999a5a6377ad06835f5a1d08c475e82
652,952
def sourceArguments(o): """ Return the LaTeX source of the arguments """ return o.argSource
a21e3ff520b3e219cb38dc8cf44f2888290a94f1
652,954
def _invert_indices(arr, range_max): """return all indices from range(range_max) that are not in arr as a list""" inv = [] for j in range(range_max): if j not in arr: inv.append(j) return inv
610cc79ae4bde74d64425e9e6c41fa252bcf2cdc
652,955
def not_none(x): """ Invariant for the PRecord such that the field value is not None :param x: :return: """ return x is not None
5f89c8e3536131d73de4ef6cc1df5445ad8e7aa9
652,957
def ValuesQuerySetToDict(vqs): """ Helper to convert queryset to dictionary """ return [item for item in vqs]
e4fb420348067b5f33e69f51d46ecf6b9e609dab
652,958
import copy def weigh_volume_old(volume, labels_to_lin_ids, dbn, scene): """Create a copy of the volume, where each category-slice is weighted by the dbn score of adding a NEW object of that category NOTE: new object only, does not score the current volume """ out = volume.copy() assert out is...
231425e69dc1c979eb4a5681361695e25a8af607
652,959
def first_non_repeated_character(str): """finds the first character in a string that's not repreated""" for i, char in enumerate(str): if i - 1 >= 0 and char == str[i - 1]: continue if i + 1 < len(str) and char == str[i + 1]: continue return char
421caa9fa1565054654eaf3c00feb1db5904c5b0
652,960
import torch def lincomb(rp: torch.Tensor, coeff: torch.Tensor) -> torch.Tensor: """Returns the normal distributions for w linear combinations of p portfolios Args: rp (torch.Tensor): p-by-n matrix where the (i, j) entry corresponds to the j-th return of the i-th portfolio coeff...
b1328f9004ee18ad1a8f0ea9e84ed10d31681ff3
652,961
def rindex_str(text, sub, start=None, end=None): """ Finds the highest index of the substring ``sub`` within ``text`` in the range [``start``, ``end``]. Optional arguments ``start`` and ``end`` are interpreted as in slice notation. However, the index returned is relative to the original string ``te...
1d575404632e4618e3193e29ac22daf3e82aebc7
652,962
import re def sort_hosts(hosts): """ Sort the hosts by name and take into account the numbers. :param hosts: Dictionary from host name (e.g., perf-9-test, perf-62-test), to the IP :return: Sorted list of tuples """ host_names = hosts.keys() sorted_host_tuples = [(None, None),] * len(hosts) pattern = ...
5730b83543bd5ec565b3683c6c518a9d0932c7eb
652,964
import re def MigrateDataProviders(content): """TestNG allows a DataProvider to be renamed.""" # Make a list of tuples mapping the # new name to original name. # @DataProvider(name="MillisInstantNoNanos") # Object[][] provider_factory_millis_long() { data_provider_regex = re.compile( r'@DataProvider...
49d5dd6818107021e8a36f0e3d1a33dcd7ac489b
652,965
def print_street(street_dict): """This will print text describing a random street""" output = f""" This {street_dict["moods"]} {street_dict["infastructure_type"]} is primarily used for {street_dict["use"]} purposes. (A/An) {street_dict["sights"]} catch(es) your eye. You hear {street_dict["sounds"]} and smell {...
d28e1b02b4fc2cec491d98de53243eb23ec5f5c9
652,966
import pathlib def parse_bind_mount(bind_arg): """unpack bind-mount bind_arg (e.g., src=/foo,dst=/bar) to dict where the key is a resolve pathlib.Path and the value is an unresolved (in-container) pathlib.PosixPath.""" mount_dict = dict([kv.split("=") for kv in bind_arg.split(",")]) source_key = n...
03a2632a7412f878cc3e67ae7e82cf216e51a31d
652,967
def redis(create_redis, server, loop): """Returns Redis client instance.""" redis = loop.run_until_complete( create_redis(server.tcp_address, loop=loop)) loop.run_until_complete(redis.flushall()) return redis
73acb25c069669043a1a1898adf2ba2b424e3101
652,968
import os def convert_wav(path: str): """ new_path = convert_wav(path) output: новое имя файла """ new_path = path.replace(".wav", "_16.wav") os.system(f'ffmpeg -i {path} -loglevel quiet -acodec pcm_s16le -ac 2 -ar 16000 {new_path}') os.remove(path) return new_path
6e720db65aff5b538e42b6defb55a6e883428392
652,969
def time_correct(mjd, zed): """Corrects for time dilation. Keyword arguments: mjd -- Python list, contains measurements epochs in MJDs. zed -- float, redshift to use for correction. """ return [el/(1.+zed) for el in mjd]
1a72ddb866643561a694527d42b74ff71b89a4c6
652,970
def int_to_sequence(integer): """Return a list of each digit in integer For example: 1111 -> [1, 1, 1, 1] 451 -> [4, 5, 1] """ return [int(n) for n in str(integer)]
3982564f921dc795cce67acd74592c8041273c98
652,971
def moeda(valor=0.0, moeda='R$'): """ Funçao que formata um valor ao formato de moeda :param valor: Valor a ser formatado :param moeda: Moeda ao qual deve ser formatado :return: Valor formatado na moeda desejada """ return f'{moeda} {valor:.2f}'.replace('.', ',')
01f023e374de72adff4ae72f7f8de310d183cd72
652,972
def make_func(test_dict, test_func, feature_shape, mod): """Returns a mean function from specified name present in test_dict""" kwargs = test_dict[test_func] func_class = getattr(mod, test_func) func = func_class(feature_ndims=len(feature_shape), **kwargs) return func
6bde6d2bbe3940c28ea3deb9eda32694120e7be6
652,973
def construct_test_result_metrics_data(stdout, test_path): """ construct test results metrics data to be sent to cloudwatch :param stdout: <int> 0/1. 0 indicates no error during test execution, 1 indicates errors occurred :param test_path: <string> With Scheduler/Without Scheduler :return: <dict> ...
17b6be4441d057ddc6a5c8319eae3f84a9ef235f
652,974
import numpy def feedForwardAutoencoder(theta, hidden_size, visible_size, input): """ Define limits to access useful data """ limit0 = 0 limit1 = hidden_size * visible_size limit2 = 2 * hidden_size * visible_size limit3 = 2 * hidden_size * visible_size + hidden_size """ Access W1 and b1...
4d61f39989dac1099aa415a79fbb24914a3bf90b
652,975
import numpy def mask_object(filename): """ To read a masked image file into a NumPy array. Parameters ---------- filename = full path of the NumPy file (.npy) Returns ------- mask = NumPy array of the mask where int = object, 0 = background """ # Segmenting C2 for c...
da47587df2dff889ca946c4f4054b5760ecc07c0
652,976
from typing import Any def is_fixture(obj: Any) -> bool: """ Returns True if and only if the object is a fixture function (it would be False for a Fixture instance, but True for the underlying function inside it). """ return hasattr(obj, "ward_meta") and obj.ward_meta.is_fixture
b319c0b0da526142c541164694143411443dd1a1
652,977
from typing import Union def convert_rpn(tokens: list[str]) -> list[Union[int, str]]: """ Convert a list of token into a RPN sequence :param tokens: list of tokens :return: list of tokens in RPN sequence """ output_queue = list() operator_stack = list() for t in tokens: if t...
ad1f19410457506e092bc604f2438aa0cf97ca44
652,978
def find_allowed(ranges, limit=4294967295): """Find allowed IPs for ranges and with limit.""" last_number = 0 allowed = [] for minimum, maximum in ranges: if last_number + 1 >= minimum: last_number = max(last_number, maximum) else: while last_number + 1 < minimum:...
592684a6d96f69deebaffec62cad016f10431976
652,979
import os def event_is_important(event): """Assert event is valid command and not posted by dungeonbot.""" suffixes = ["++", "--"] if ( event['user'] != os.getenv("BOT_ID") and ( event['text'][0] == "!" or event['text'][-2:] in suffixes ) ): ret...
efea1ae9051f9b84c728bb0774fdcb6156c7b3ad
652,980
import argparse def get_args(): """ get args from command line """ parser = argparse.ArgumentParser("cifar10") parser.add_argument("--batch_size", type=int, default=128, help="batch size") parser.add_argument("--optimizer", type=str, default="SGD", help="optimizer") parser.add_argument("--epoc...
083aea1064d7f09f017d883c62565c5d61db82fe
652,981
from typing import List import os def get_backends_in_dir(path:str)-> List[str]: """Get all evaluated backends in the directory Args: path (str): to the directory Returns: List[str]: backend names """ backend_names = [] for (dirpath, dirnames, filenames) in os.walk(path): ...
524f5192842d95378ad415ce337f0078af8002aa
652,982
def normal_round(num: float, ndigits: int = 0) -> float: """Rounds a float to the specified number of decimal places. Args: num: the value to round ndigits: the number of digits to round to """ if ndigits == 0: return int(num + 0.5) else: digit_value = 10 ** ndigits ...
bd24e33da0f1b2a51788b0ebcd1b669a5eb56cb0
652,983
def make_pairs_for_model(model_num=0): """ Create a list of pairs of model nums; play every model nearby, then every other model after that, then every fifth, etc. Returns a list like [[N, N-1], [N, N-2], ... , [N, N-12], ... , [N, N-50]] """ if model_num == 0: return pairs = [] pai...
c9465a50a02486475420376db73fad4fa98a9b28
652,986
from datetime import datetime import logging def set_logger(FLAGS): """set logger for training recording""" if FLAGS.logging: logfile = '{0}/training_logfile_{1}.log'.format(FLAGS.logdir, datetime.now().strftime("%Y%m%d_%H%M%S")) formatter = '%(levelname)s:%(asctime)s:%(message)s' logg...
5bddc6ec00ea6c0b8d2bdb3b840f4a38522e3c67
652,987
from functools import reduce def compose(*functions): """ Returns a function which acts as a composition of several `functions`. If one function is given it is returned if no function is given a :exc:`TypeError` is raised. >>> from brownie.functional import compose >>> compose(lambda x: x + 1...
e3f5a58b9a36f463ed4869592de723df31abc6bd
652,988
def _formatwarning(message, category, filename, lineno, line=None): # pylint: disable=unused-argument """ Replacement for warnings.formatwarning() that is monkey patched in. """ return "{}: {}\n".format(category.__name__, message)
e7fc82637cf37738fa9d230b818bc40ca8e08a3c
652,989
def live_points_1(model): """Second set of live points""" return model.new_point(N=200)
4671b6101f7c8ae4556a446081b5d3d0337aa306
652,990
def showtermwidth(context, mapping): """Integer. The width of the current terminal.""" ui = context.resource(mapping, b'ui') return ui.termwidth()
c37f89125be7c06ab265aa7045022698f2fcaacc
652,991
def flip_arr_values(arr): """Simple helper function used by accuracy()""" arr[arr == 1] = 2 arr[arr == 0] = 1 arr[arr == 2] = 0 return arr
307f73aa412b2ef02d50dcbe127adc274127f114
652,993
import argparse import sys def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='evaluate segmentation result') parser.add_argument('--pred', dest='pred_dir', help='prediction result dir', default='./result/eva...
f7953495de17b743a2f1d2983229213ac2e222d4
652,994
import re def is_text(email_message): """Whether a message is text""" return re.match(r"^text/.*", email_message.get_content_type(), re.IGNORECASE)
47d94159ef028e9e5940766a922556eacf1a2c81
652,996
def to_upper_snake_case(s: str) -> str: """Converts a string from a MixedCaseString to a UPPER_SNAKE_CASE_STRING.""" s = s.upper() r = '' for i in range(0, len(s)): r += s[i] if s[i].isalnum() else '_' return r
3e5df924f0ccf980d1170eb1d3a720087e2328a1
652,997
import json def parse_sthv2_splits(level): """Parse Something-Something dataset V2 into "train", "val" splits. Args: level (int): Directory level of data. 1 for the single-level directory, 2 for the two-level directory. Returns: list: "train", "val", "test" splits of Somethin...
ee38c715a562c1185c2da1aec4be46ee9e3e1dca
652,998
def dfs_topological_sort(arr, n): """ Topological sort with DFS. Return an empty list if there is a cycle. """ graph = [[] for _ in range(n)] for u, v in arr: graph[u].append(v) visited, stack = [0] * n, [] def dfs(u): if visited[u] == -1: return False i...
8c917f372029a7a4e7f132a5141d05a69d8fb227
652,999
import os import json def get_rule(): """load rules pattern from rules.json""" base = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(base, 'rules.json'), 'r') as rule_data: data = json.load(rule_data) return data
07474bb889c7c3a4d83f1efe5e9fe37faf76de39
653,000
from typing import OrderedDict def get_profile(line, listOfFeatures): """ Returns a tuple of feature values for the profile in question. line is a string that contains key:value pairs separated by whitespace. Each key is a feature and each value is its value. profile is a list of f...
a8325a2b15e341f1cf07d522b8d39dc29d613477
653,001
def convert_to_html(model): """ Takes a model instance and produces an HTML table that represents the results in a nice way for us to look at. Parameters ---------- model : dict Dictionary of layers and their properties as a list in the form of [Vp, Vs, rho, thickness, top] Returns...
f5ecc9677f7bfc0692e7f58b3dc6ce4f1955ee44
653,002
import torch def _reward_grab_effort(actions: torch.Tensor) -> torch.Tensor: """calculates grab-effort part of the reward. Args: actions (tf.Tensor): Shape: [n, actdim] Returns: tf.Tensor: [n] """ return (torch.clamp(actions[:, 3], -1, 1) + 1.0) / 2.0
4057ca21453cdc7dc2c6b8de69bb83bb001bbfcd
653,003
def first_and_last(sequence): """Return 1st and last sequence elements""" return sequence[0], sequence[-1]
dc06f413ef6f4d64611b292a6fcf9c34d35da107
653,004
import requests import sys import json def get_api_response(full_url): """ send request to HGNC and get json response """ try: response = requests.get( full_url, headers={"Accept": "application/json"} ) except Exception as e: print("Something wrong: {}".for...
772975c9f37c136059d95ffd5a56867f634295c4
653,005
import pkg_resources def matched_by_list(package, version, requirements): """ Verify whether the given version of the package is matched by the given requirements file. :param package: Name of the package to look for :param version: Version of the package to look for :param requirements: A list o...
054994cfb2bc2e953ff11be59071f5a74ebfdb68
653,006
import math def downsampled_image_dims_from_desired_num_pixels(image_dims, num_pixels, maximum=False): """ Compute the best downsampled image dimensions, given original image dimensions and the ideal total number of pixels for the downsampled image. The final number of pixels in the downsampled image dime...
e5197efba1141c4af38b4a8659f02cd9fb8bf246
653,007
def _annotate_short_answer(predict_fn, question_tokens, context_tokens): """Applies the model to the (question, contexts) and returns long answer. Args: predict_fn: Predictor from tf.contrib.predictor.from_saved_model. question_tokens: List of strings. context_tokens: List of strings. Returns: l...
dcc2dfa97cc53fbdefc3b92a76518c444f9d4888
653,008
def csvservermems(mems): """ Return a csv string of this server memory (total, free). """ return ", ".join(str(x) for x in mems)
07a2c72d40ba66cf9456a51204aaf9d71f877f6e
653,009
def with_cmp(attrs): """ A class decorator that adds comparison methods based on *attrs*. Two instances are compared as if the respective values of *attrs* were tuples. :param attrs: Attributes to work with. :type attrs: `list` of native strings """ def attrs_to_tuple(obj): """...
f9674c892cfd01e76f29596dc0ca3651e291c43c
653,010
def ParseSortByArg(sort_by=None): """Parses and creates the sort by object from parsed arguments. Args: sort_by: list of strings, passed in from the --sort-by flag. Returns: A parsed sort by string ending in asc or desc, conforming to https://aip.dev/132#ordering """ if not sort_by: return N...
901d3fa9c23f715c85c395409db4499c8e542cd5
653,011
def hex_to_bin(x): """Converts hexidecimal string to binary.""" return x.replace(' ', '').replace('\n', '').decode('hex')
1fb295abdd1eed3f3a9c183485b22f38c1d838db
653,012
def round_corner_2_sides(result_list): """Permet de traiter les résultats d'une opération round_corner appliquée en série sur un ensemble de sommets. Une polyligne composée de segments et d'arc est composée. """ sides = list() # ? à la bonne place ? for i, rslt in enumerate(result_list): ...
4d5603f776fccd2df31ce845823781f6a180b47f
653,014
import re def find_exported_class_path(spark_config_env_sh): """ find any current class path :param spark_config_env_sh: all the text from the cloudera manager spark_env.sh :return: the entire line containing the exported class path """ return re.search('SPARK_CLASSPATH=.*', spark_config_env_s...
0724db979a8af3aaa5aac58edc8eb3ffbd61a19b
653,015
def dictify(x): """Ensure `x` is a dict. """ if isinstance(x, dict): return x elif x: return dict(x) else: return dict()
d25f79b6d521cd3650b8e0f314230246d3208657
653,018
from typing import Union def _check_criteria(last_nouns: list, looking_for_singular: Union[bool, None], looking_for_female: Union[bool, None], looking_for_person: bool, is_exact: bool) -> list: """ Checks the values of the nouns in last_nouns for matches of the specified gender/number ...
114cc1fedfb0ac533551fae45176176fdc6c9c87
653,020
import argparse def parse_args(): """ Parses arguments provided through the command line. """ # Initialize parser = argparse.ArgumentParser() # Mandatory args parser.add_argument("centrimo_dir", metavar="centrimo-dir") return(parser.parse_args())
91ac41204272d9f223d297425a7c87ac9943dda3
653,021
def string2fields(string, lengths): """Slice string into fixed-length fields.""" return (string[pos:pos + length].strip() for idx, length in enumerate(lengths) for pos in [sum(map(int, lengths[:idx]))])
92a08198f496bf0b2a2981824d6b3fd13255494d
653,022
import requests from bs4 import BeautifulSoup def extract_url(url, values=None): """Given an url, extracts the contents as a BeautifulSoup object. Args: url: URL to parse. Returns: The site contents as a BeautifulSoup object """ if values: r = requests.post(url, data=value...
56ea95796cb718634390ac595d74f637bc8385d6
653,023
def l1_bit_rate(l2br, pps, ifg, preamble): """ Return the l1 bit rate :param l2br: l2 bit rate int bits per second :param pps: packets per second :param ifg: the inter frame gap :param preamble: preamble size of the packet header in bytes :return: l1 bit rate as float """ return l2br...
bb060b30a283d6b0c9ae761bd23c7bda4a1d838a
653,024
def imap_helper(args): """ Helper function for imap. This is needed since built-in multiprocessing library does not have `istarmap` function. If packed arguments are passed, it unpacks the arguments and pass through the function. Otherwise, it just pass the argument through the given function. ...
96facdd07c0af4c85bcfb7b9998d6e3eedbeec15
653,025