content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def get_label_filter(input_labels): """ Allow labels input to be formatted like: -lb key1:value -lb key2:value AND -lb key1:value,key2:value Output: key1:value,key2:value :param list(str) input_labels: list of labels, like, ['key1:value1', 'key2:value2'] or ['key1:value1,key2:valu...
787ce61c130432065c7d0f50e06fe1f3903dfd59
640,041
def csv2pretty(csvstr, sep='\t'): """ Format CSV text with the specified separator to 'pretty' text """ def formatted_line(words, maxes, pad): st = '' for j, item in enumerate(words): st += item.rjust(maxes[j] + pad) return st + '\n' result = '\n' lines = csv...
e274b54baea87a23f324243b1b43e99e11f3f782
640,042
import base64 def _quote_query_id(symbol): """返回请求合约信息的 query_id, 每个合约生成的 query_id 是唯一的""" return "PYSDK_quote_" + base64.urlsafe_b64encode(symbol.encode()).decode().replace('=', '')
df523c835e551c2c431d7057d3943ee6684afc1d
640,043
def is_hash160(s): """ Returns True if the considered string is a valid RIPEMD160 hash. :param str s: the considered string :return: Returns True if the considered string is a valid RIPEMD160 hash. :rtype: bool """ if not s or not isinstance(s, str): return False if not len(s) == 40...
b307b4d7a4cdafdb3ce34c10966d401d431f4633
640,044
def is_palindrome(num): """判断一个数是不是回文数""" temp = num total = 0 while temp > 0: total = total * 10 + temp % 10 temp //= 10 return total == num
8cdcfb70e88f29d8bc5c9d5e16ed0d46f794ba71
640,047
from typing import Optional from datetime import datetime import pytz def date_from_string(dtstr: str, fmt: str, timezone: str) -> Optional[datetime]: """Get datetime object from a date string. Args: dtstr: input date string fmt: datetime format string timezone: time zone string Return...
d114d9cb366ad70c89b38f16bbf80123d2dcd9f9
640,048
def is_merge_desired(name1, name2): """ Input: name1, name2: string parsednames as returned by parse_entity_name Output: True iff the two names have equal surnames and last first names are equal. """ if (name1 is None) or (name2 is None): re...
42c20e2b87b1616a3d2c345e34194793da82f731
640,051
def turn_check_perturb(base_dir, targ_dir): """ :param base_dir: the direction (NESW) from the previous step :param targ_dir: the target direction (NESW) :rtype: string :return: 'right' or 'left' depending on where the camera should turn, otherwise 'straight' if the camera is facing in the targe...
4fdcd680e027a7af2afaaef5e28a3658aa123e50
640,052
def AioNodeNameFromMotorNickname(motor): """Returns AIO node name for the specified motor.""" return 'kAioNodeMotor' + motor.capitalize()
12715b7b0273dac38a19e82ac9192205d7283c11
640,053
def time_to_minutes(string): """ :param string: string in format hh:mm:ss. :return: integer equivalent in minutes. """ try: h, m, s = string.split(":") return int(h) * 60 + int(m) + int(s) / 60 except ValueError: # print(string) return -1
6c5e96f9c0684091f9033117d8350131c989fb99
640,054
def get_rc(sequence): """Returns the reverse complement of sequence. Sequence may only contain letters A, C, G, or T (in uppercase).""" table = ['A', 'C', 'G', 'T'] sequence = list(sequence) for key, value in enumerate(sequence): sequence[key] = table[3 - table.index(value)] return...
43a180ca00d406230d42d0ecb157591208d531be
640,055
def _is_part_dsn(msg): """ Receive a MIME part and returns True if it is a DSN False is returned otherwise """ if len(msg) <= 1: return False if msg[1].get_content_type() != 'message/delivery-status': return False return True
31f6f8472676abfc0e94add96c47111cf19a4a74
640,056
def join_s3_uri(bucket, key): """ Join AWS S3 URI from bucket and key. :type bucket: str :type key: str :rtype: str """ return "s3://{}/{}".format(bucket, key)
9c5af83aea0f4a56996f29597dad91f232ba7c20
640,057
import numpy def get_bin(result, tan, dis=9): """ ~得到bin,默认分成9份~ 对整幅图像进行bin的计算 """ bin_dic = {} bin_matrix = numpy.zeros(result.shape) step = 360/dis/2 for i in range(1, dis+1): bin_dic[i] = [(i*step-step, i*step), (i*step-step-180, i*step-180)] for i in range(result.shape[...
d53291b4785f18419e66cacbe0938df354b971b5
640,058
from typing import List from typing import MutableMapping from typing import Dict from typing import Tuple import math def migrations_from_mm_list( mm_list: List[List[List[float]]], end_times: List[float], deme_names: List[str] ) -> List[MutableMapping]: """ Convert a list of migration matrices into a lis...
e4241945f6695a3755e9d5119b8fce2dc419d1a4
640,059
def lustre_ost_id(fsname, ost_index): """ Return the Lustre client ID """ return "%s:%s" % (fsname, ost_index)
582845e7762f8705d930a023a296dc68344d41b0
640,060
def trim_tweet(tweet): """Remove unused data from tweet """ tweet["id"] = int(tweet["id_str"]) tweet.pop("id_str") tweet.pop("truncated") if "in_reply_to_status_id_str" in tweet: if not "in_reply_to_status_id" in tweet: tweet["in_reply_to_status_id"] = int(tweet["in_reply_to_stat...
afc626e7fd33d4deda108b199fceb52c621a0705
640,062
def filter_score_min_play(ts, minutes=10): """ only mask those play no less than the minutes inputed """ return ts[[l for l in list(ts.index) if l[-1]>minutes]]
7953873d42cec58486a5309090530054296aa207
640,063
def _pad_norm_assert_noshape(outputs): """Assert Masked BN/GN w/o spatial shape returns None shape.""" outputs, spatial_shape = outputs assert spatial_shape is None return outputs, []
01a0fd4db122e1a649f186b017b438ae4416cf34
640,064
def default_authority(pyramid_request): """ Return the test env request's default authority, i.e. 'example.com' Return the default authority—this automatically has a `__world__` group """ return pyramid_request.default_authority
69310c71e6592d79bd5cfbe5821c09bd60807efa
640,065
def unsqueeze_image(input): """Reduce the number of channels by 4, but double the width and height of the image. Inverse operation of squeeze_image().""" b_size, n_channel, height, width = input.shape unsqueezed = input.view(b_size, n_channel // 4, 2, 2, height, width) unsqueezed = unsqueezed.permut...
50f4ea0c27ce69ef8d3cd8d892da4e73aff4468f
640,067
from typing import Dict from typing import Any from typing import Tuple from typing import Sequence def prepare_kwargs( kwargs: Dict[str, Any] ) -> Tuple[Sequence[str], Sequence[Any], Sequence[str]]: """Create three sequences from the provided kwargs. The first sequence is the keys of the kwargs. The second seque...
4c08d4572a2f8764abd70da15d7c716bf55a9360
640,068
import os def resolve_path(relative_path): """ Function that transform relative to absolute path :param relative_path: relative path :return: absolute path """ return os.path.abspath(os.path.expanduser(relative_path)) + "/"
8d5e318820d9f056abb3e3c28da4eae012e803d3
640,069
def ne(x, y): """Not equal""" return x != y
9e8f60889705122d0a6f98febdc689983a9e4cbf
640,071
import math def normalized(vector): """ normalized version of any vector, with zero division check """ norm = math.sqrt(sum(vector*vector)) return vector / norm if norm > 0. else vector
90d753fceb4577cde3aacf9640280560236b43bb
640,072
import os def Separate_Extension( string_file ): """ Given a string for a path name, separate the front from the extension return both [front, extension ] """ copy_out_index = string_file.rfind(".") slash_index = string_file.rfind( os.sep ) if(copy_out_index == -1 or copy_out_index < slash...
8c022e28283bef8764039ec656431e5c645be9db
640,074
def remove_anchor(url: str) -> str: """ Removes anchor from URL :param url: :return: """ anchor_pos = url.find('#') return url[:anchor_pos] if anchor_pos > 0 else url
fa10c7af5b86dcc41c79d054a4df249fa570e61b
640,075
def admin2_urlname(view, action): """ Converts the view and the specified action into a valid namespaced URLConf name. """ return 'admin2:%s_%s_%s' % (view.app_label, view.model_name, action)
1d95fccdb1a9abae1322087fdaf52061c12a4ac4
640,076
def get_kmer_from_index(kmax, index): """ takes a number (essentially base 4) and returns the kmer it corresponds to in alphabetical order eg. AAAA = 0*1 CA = 4*4 + 0*1 GC = 3*4 + 1 * 1 """ bases = 'ACGT' out = '' for k in range(kmax - 1, -1, -1): face, index = divmod...
5a9467a99af5e3a301b5ac60d3088a4e3da92586
640,078
import torch def IOU_tensor(box1, box2): """ box1: (batch, 4, S, S) box2: (batch, 4, S, S) """ # box1 = box1.to('cpu') # box2 = box2.to('cpu') IOU_map = torch.ones((box1.shape[0],1,box1.shape[-2],box1.shape[-1])).to("cuda") minX = torch.max(box1[:, 0:1], box2[:, 0:1]) maxX = torc...
e17fca1851a80159be216422e80cf7ad79a33fe4
640,079
from typing import Tuple from typing import Dict def bbox_to_geojson(bbox: Tuple) -> Dict: """Return bbox geojson feature.""" return { "geometry": { "type": "Polygon", "coordinates": [ [ [bbox[0], bbox[3]], [bbox[0], bbox[...
b708410cbeee3ec40e33b24e02d8927693c8e764
640,080
import __main__ as dput # if only we would get passed our config section... def _get_host_argument(fqdn): """ We have to jump through several hoops to get to our config section, which in turn is the only place where the host argument is available. """ config = dput.config # pylint: disable=no-memb...
26077330dc2b393459c5b20418046baf4b90710b
640,081
import os import argparse def mustExistDirectory(path: str): """ Argparse type specifying a string which represents an existing file path :param path: :return: """ if not os.path.isdir(path): raise argparse.ArgumentTypeError for root, dirs, files in os.walk(path, True): ...
ef55509ee45bc774235a9d01399ee8e8f33485bf
640,082
def float_converter(value): """To deal with Courtney CTD codes""" return float(value.split(":")[-1])
4f80bc3d7c2cc8405d2e9a847f77d66ef08f57fa
640,083
def plot_transient_lines(ax, time, u): """ Plot the stable/unstable and regular/oscillatory solutions for the contiuation INPUT: ax: matplotlib axes time: array containing the time values u: infinite norm of the variable""" ax.plot(time, u, "-", color="blue") return None
d80e9f295cb1585767e99ab8cdc43c1eb8cf50a4
640,084
def permute_data(x, pe_dir): """ This function permutes data of the tensor x of size (batch, n_channels, 1st_size, ..., nth_size) so that the PE direction become the first dimension (except the batch and n_channels dimensions). :param x: the tensor of size (batch, n_channels, 1st_size, ..., nth_size) ...
28ca89520f32203636465b44e263ee9f95da4491
640,085
def is_pandigital(n_str, k): """Verify number is pandigital.""" if len(n_str) == k and set(n_str) == set('123456789'[:k]): return True else: return False
98a6140d0e0e49cdb19013dae8bd180c7975e72e
640,086
def has_python_token(i, obj, tok, values=None, starting_with=False, ending_with=False): """Does this line have any of the token values? i is the line number, obj is the TOKEN_OBJECT""" try: if isinstance(values, str): values = [values] python_token_line = obj.extra['python_token_lin...
932f55934494632adf82278d2b4d3de2943bf5f4
640,087
def read_unicodestringnl(f): """ >>> import io >>> read_unicodestringnl(io.BytesIO(b"abc\\\\uabcd\\njunk")) == 'abc\\uabcd' True """ data = f.readline() if not data.endswith(b'\n'): raise ValueError('no newline found when trying to read unicodestringnl' ) data = data[...
80edd261e73a47b9d8532cde615d850d25d6d0d3
640,088
import itertools def construct_game_queries(base_profile, num_checkpts): """Constructs a list of checkpoint selection tuples to query value function. Each query tuple (key, query) where key = (pi, pj) and query is (p1's selected checkpt, ..., p7's selected checkpt) fixes the players in the game of diplomacy ...
1ffa16ebfd04f468cbde6db264ba33373c1b1d05
640,089
from typing import Callable from typing import List from typing import OrderedDict def order_json(data, sort_fn: Callable[[List[str]], List[str]] = sorted): """Sort json to a consistent order. When you hash json that has the some content but is different orders you get different fingerprints. .. cod...
657f932d54111405ee9ac606346d2b7cc02391eb
640,090
def quote(s, unsafe="/"): """Pass in a dictionary that has unsafe characters as the keys, and the percent encoded value as the value.""" res = s.replace("%", "%25") for c in unsafe: res = res.replace(c, "%" + (hex(ord(c)).upper())[2:]) return res
ff80c584ec4325a8ae29d88743aa0d7bc1b18c05
640,091
def dict_to_form(obj: dict): """Encode a form to dict""" return '&'.join('{0}={1}'.format(k, v) for k, v in obj.items())
80ede944b91690680a712e9a0082508b8e82a9bd
640,093
from collections import defaultdict def get_strongly_connected_components(edges, num_vertex): """ edges: {v: [v]} """ reverse_edges = defaultdict(list) for v1 in edges: for v2 in edges[v1]: reverse_edges[v2].append(v1) terminate_order = [] done = [0] * num_vertex # 0...
262a5cb5da0026b2d9ae3e26ec50e23e6650e573
640,094
import requests import pprint def _request(yt_token, url, data): """ :param yt_token: :param url: :param data: :return: """ headers = {'Authorization': 'Bearer {0}'.format(yt_token), 'Content-Type': 'application/json'} data = dict(params=data) response = requests.ge...
ee8c7fae485a7c5120a6340ce482e9f4d87c2281
640,096
import gzip def smart_open(path, *args, **kwargs): """Opens files directly or through gzip depending on extension.""" if path.endswith('.gz'): return gzip.open(path, *args, **kwargs) else: return open(path, *args, **kwargs)
57c40c5e1eaa4db03629b9cad22cc1a0e7601be0
640,097
from typing import Callable def predicate(function: Callable) -> Callable: # pylint: disable=invalid-name """ This is intended to be used as a decorator when you are implementing your ``DomainLanguage``. This marks a function on a ``DomainLanguage`` subclass as a predicate that can be used in the lan...
5e9b935f5319f66d09df2b570301c5aee12285a8
640,098
def tcp_traceflow(frame, *, data_link): """Trace packet flow for TCP. Args: frame (pcapkit.protocols.pcap.frame.Frame): PCAP frame. Keyword Args: data_link (str): Data link layer protocol (from global header). Returns: Tuple[bool, Dict[str, Any]]: A tuple of data for TCP reass...
b23ffa745e962c9501030024620c70e069061116
640,099
from typing import Tuple def ip_port_hostname_from_svname(svname: str) -> Tuple[str, int, str]: """This parses the haproxy svname that smartstack creates. In old versions of synapse, this is in the format ip:port_hostname. In versions newer than dd5843c987740a5d5ce1c83b12b258b7253784a8 it is hostname_...
a5cf4eeb9c085c693ae66bb5a1a55586942948b7
640,100
import torch def load_model(GAN="PGAN"): """ Download and caches the GAN model into models directory :param GAN: Type of GAN to be downloaded :return: Freezed Generator of the GAN """ torch.hub.set_dir("../models") use_gpu = True if torch.cuda.is_available() else False model = torch....
4f12a3f1512ce1e984be3066372a7779ea8d2b2a
640,101
def ConstantTimeIsEqual(a, b): """Securely compare two strings without leaking timing information.""" if len(a) != len(b): return False acc = 0 for x, y in zip(a, b): acc |= ord(x) ^ ord(y) return acc == 0
f2c12ba1ca50737ea3d219f952dc7d917bcd7385
640,102
import signal def _getmask(): """Gets signal mask of current thread.""" return signal.pthread_sigmask(signal.SIG_BLOCK, [])
2d55d2d9fd18db6c5245b43f76ee04b3e1b09a06
640,103
import glob def list_arduino_ports(): """ Lists all UNIX device that match /dev/ttyACM0 or /dev/ttyUSB0, for example. @rtype: C{list} """ ttys = glob.glob("/dev/tty*") PROSPECTS = [ "ttyACM", # GNU/Linux for Uno or Mega 2560 "ttyUSB", # GNU/Linux for older board "tty.us...
3b02711ee42b31385ac71b6d89a2ef8ec80c0b3f
640,105
import math def make_ids(n: int, prefix: str = "id_"): """ Return a length ``n`` list of unique sequentially labelled strings for use as IDs. Example:: >>> make_ids(11, prefix="s") ['s00', s01', 's02', 's03', 's04', 's05', 's06', 's07', 's08', 's09', 's10'] """ if n < 1: ...
14b5651b7d8208d75936d769427700f2bd4dfaef
640,106
def adjust_reg(reg, epoch, total_epochs, max_reg=1.0): """Reconfigures the regularization strength""" return min(reg * epoch / total_epochs, max_reg)
1adf081ca5bd40fed3d2c0591fe1e5588374b832
640,107
import math def generate_IDF(corpus, corpus_dict, total_queries): """ Function to generate IDF for all the words in the vocab. :param corpus: Corpus of words in the queries. :param corpus_dict: Mapping of query number and its corpus. :param total_queries: Total number of queries. :return idf_d...
7ac0724c7b95f0ba2261934fccea5e89be7d3717
640,108
def save_as_pdf(file_name='table'): """Save the file that is returned as a pdf.""" def decorator_func(func): def decorator(*args, **kwargs): image_list = func(*args, **kwargs) pdf_name = f'{file_name}.pdf' print(f"Saving tables to {pdf_name}") first_table ...
3b4162ac4ba1778d6c4c29f5b32074943952f89d
640,110
def find_segmented_open_source_library_test_file(project_root, test_base_fn): """This style defines tests/unit and tests/system in the project root.""" test_fn = project_root.joinpath('tests/unit', test_base_fn) if test_fn.exists(): return test_fn
26d5fbbea20c8bcdaf5f5a7d7fec4cba8b7eb1d4
640,111
def update_parameter_with_momentum(parameter, grads, v_momentum, beta=0.9, learning_rate=0.0075): """ :param parameter: -- python dictionary contains "Wl", "bl" :param grads: -- python dictionary contains "dWl","dbl" :param v: -- python dictionary contains the current velocity: v["dW"+s...
4359fc2ccf7cc34cf7b93c844e262d987febf0db
640,112
import re def truncate(text, max_len=250, suffix="..."): """ Truncate a text string to a certain number of characters, trimming to the nearest word boundary. """ stripped = text.strip() if len(stripped) <= max_len: return stripped substr = stripped[0:max_len + 1] words = " ".jo...
537e90638400c6c53b9fa82068f2c3dfbcaae179
640,113
from typing import OrderedDict import sys import subprocess def remove_packages(founds): """ prompt the user, if they agree remove package """ removed = OrderedDict() present = OrderedDict() if not founds: return False else: print("\t4. Auto removal of fake pypi packages u...
9c06e219ab1dc06fcf25a4e6402403e13e2a7973
640,114
def coding_problem_08(btree): """ A unival tree (which stands for "universal value") is a tree where all nodes have the same value. Given the root to a binary tree, count the number of unival subtrees. Example: >>> btree = (0, (0, (0, None, None), (0, (0, None, None), (0, None, None))), (1, None, N...
76ffd44b8483757c5e967ae70f6261d820f17ec2
640,115
def plot_curves(precision, recall): """ add points to compute the p/r curves """ precisions_plot = [[0]] recall_plot = [[recall[0]]] precisions_plot.append(precision) recall_plot.append(recall) precisions_plot.append([precision[-1]]) recall_plot.append([0.5]) precisions...
45e93f4d1b82d0e7ef43531804175784f694d76b
640,116
def get_first_years_performance(school): """ Returns performance indicator for this school, as well as an indicator (1-5; 3 is average, 1 is worse, 5 is better) that compares the school to the national average. """ performance = {} ratio = school['renondb'].strip() # bolletje compare...
a5bd840059bfc423a9646e404a2e17829c14ce4c
640,117
from typing import List def prepend_escape_character(escape_character_list: List[str], keyword: str) -> str: """Add escape character. If the argument 'keyword' contains the characters specified in 'escape_character_list', an escape character is added to the target character. Args: escape_cha...
650d93053b01c1583a0af7498f5a8290556e4a21
640,118
def timetostr(dtime): """ Convert datetime into a string """ return dtime.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
d68933261615b4398667fea7ac2b180c7c4d96c2
640,119
def ngrams(input, n): """ Creates a set of strings with 'n' words :param input: The string to be split :param n: integer :return: set of strings with 'n' words """ input = input.split(' ') output = [] for i in range(len(input) - n + 1): output.append(input[i:i + n]) retu...
79b812393c5eaa6bf58eee334620eadee3bc71ae
640,120
def add2(x, y): """ Add up two numbers """ return x + y
a04a3ef369cf3734d88bd40beb7291427644c53d
640,121
def scale(v, num): """ :param v: The vector we want to scale :param num: Scale amount :return: vector scaled by num """ a, b, c = v return (a*num, b*num, c*num)
d5da3484e67443e1f1ec38ab73a41dacfc81691c
640,122
def all_indices(a, b): """ This function returns all indices in *a* where *b=a[indices]*. *a* must be a list-like object with a .index() method. This function does not use recursion, and is not for arbitrary iterables *a*, but instead provides speed. For the former generalization, use *where_true...
4db30d839e8be60ad9cede024378310461d11e77
640,123
def has_cyber_observable_data(instance): """Return True only if the given instance is an observed-data object containing STIX Cyber Observable objects. """ if (instance['type'] == 'observed-data' and 'objects' in instance and type(instance['objects']) is dict): return Tru...
95851ddbaee6c9844412fd28fb85fdd8b0d5af67
640,124
def package_url(package_name): """Return fully-qualified URL to package on PyPI (JSON endpoint).""" return "https://pypi.python.org/pypi/%s/json" % package_name
8ecc47be770bd7108d0ca1e7f78348bfbfed9791
640,125
def parse_matrix(path): """ Doc string. """ matrix = [] with open(path) as f: for line in f: data = line.rstrip("\n").split(sep=" ") matrix.append(data) return matrix
a26f682b465e412e33a81ec31ba656714de9b2be
640,126
def factorial(num: int) -> int: """ >>> factorial(7) 5040 >>> factorial(-1) Traceback (most recent call last): ... ValueError: Number should not be negative. >>> [factorial(i) for i in range(10)] [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] """ if num < 0: raise ...
9c5c7d9b963a67cae08355c61b0e83fb3e8aefe0
640,127
from typing import Dict from typing import List import os def get_include_paths(config: Dict[str, str]) -> List[str]: """Calculate the list of directories where files should be searched for.""" colon_sep_values = config['include_paths'] path_list = [value.strip() for value in colon_sep_values.split(':')] ...
822182af1e55b749a41fb1b5acb55a9afe4be518
640,128
def sub_with_none(v1,v2): """ Substract treating None as zero """ p1 = v1 is None p2 = v2 is None if p1 and p2: return None elif p1: return -v2 elif p2: return v1 else: return v1 - v2
44df881adc0b1b464eb3b39907880f057a75debc
640,129
def make_depth_safe(cube): """ Make the depth coordinate safe. If the depth coordinate has a value of zero or above, we replace the zero with the average point of the first depth layer. Parameters ---------- cube: iris.cube.Cube Input cube to make the depth coordinate safe Ret...
06bb9ce9732a51337f7ccd758ffdb72a6cf765e7
640,130
import zipfile import os def unzip(file_path: str, target_dir=None): """ 解压 zip 文件 :param file_path: :param target_dir: 解压目录,如果不指定则默认解压到 file_pth_unzip 下 :return: """ zip_files = zipfile.ZipFile(file_path) tmp_file = (file_path + "_unzip") if target_dir is None else target_dir if...
8a8c5b97d139c5cc3eced954ec46a4e9c0b40e49
640,132
def is_windows_ready(path): """ windows下的文件是否已经准备好 :param path: :return: """ try: with open(path, 'r'): ready = True except Exception: ready = False return ready
02fb4a6a140b5eee13bdd1afc58ec1654b133f4e
640,133
import os def get_all_files_in_folder(file_path, file_extensions=None): """ This function returns all files in a given directory. If file_extension is specified, only files with that file extension will be returned. """ if not file_extensions: return [file for file in os.listdir(file_path) if os.path.isfile(os...
f0cbb042a504d783bd7b2db0d797532a54a1e578
640,134
def __access_member_by_string(x, member): """ Return the result of x.#member or x.#member() where member is the name of the function/variable. :param x: Element to operate on :param member: Function or value member :return: """ action = getattr(x, member) if callable(action): ...
20efb5e0eeccdfebb2a72a201732d24fa89472b3
640,135
def get_version_mapping_directories(server_type): """ This function will return all the version mapping directories :param server_type: :return: """ if server_type == 'gpdb': return ( {'name': "gpdb_5.0_plus", 'number': 80323}, {'name': "5_plus", 'number': 80323},...
2f8c20602fff37ab5b922c7e3d11ea29b8e82705
640,136
import subprocess def has_git() -> bool: """Returns whether git is installed. :return: True if git is installed, False otherwise. """ try: subprocess.check_output(['git', '--version']) return True except FileNotFoundError: return False
6ffe202c34e4bdfcde044d921a9b9dfca162cd94
640,137
def sponsors_benefit_is_complete(orm, sponsor, name): """Return True - benefit is complete, False - benefit is not complete, or None - benefit not applicable for this sponsor's level """ if orm.BenefitLevel.objects.filter(level=sponsor.level, benefit__name=name).exists(): try: ...
4be095eec96da78168d1dcabc6f60b4dabaf6e29
640,138
import json def transform_kval_json_str(st): """ BQ + python transforms hist `values` attribute from {"k": v} => [{'key': k, 'value': v}]. This undoes this. """ d = json.loads(st) values = d.pop("values") values_dct = {str(d["key"]): d["value"] for d in values} d["values"] = values...
cd468e7ed88edfb4b3ef655082c1f6da925e03bf
640,139
def overlap(a, b, min_length=3): """ Return length of longest suffix of 'a' matching a prefix of 'b' that is at least 'min_length' characters long. If no such overlap exists, return 0. """ start = 0 # start all the way at the left while True: start = a.find(b[:min_length], start) # look for b's suffx in a...
7c488fedb8be32174d55f6cd3ac572c4abd03f36
640,141
def halve_res_quick(array): """ Halves the resolution of the input 2D array, e.g. from 0.5km to 1km, by averaging every 2x2 grid of pixels into 1 pixel. :param array: 2D numpy array of data. :return: 2D numpy array with half the resolution of the input array. """ # Define ne...
23eadd26c2891852dfa776f2b894299fdaa188f3
640,142
from typing import Any from typing import List def is_list(arg_type: Any) -> bool: """Check if the input type is `list` Args: arg_type (typing.Any): input type. Returns: bool: True if input type is `list` """ try: return arg_type is list or arg_type is List or arg_type.__...
dff1651a3fc59e1524f52bf8464673118c2b98bf
640,143
def uniquify(s, delimiter=";"): """ Helper function It simplifies a delimited string with redundant fields if one unique field exist, a string is returned otherwise a list of the unique elements from the string is returned """ s = s.split(delimiter) s = list(set(s)) if len(s)==1: return s[0] ...
731c3b0fa4f77ff1b325906404363eaab9582090
640,144
def args_from_id(id, arg_ranges): """Convert a single id number to the corresponding set of arguments""" args = list() for arg_range in arg_ranges: i = id % len(arg_range) id = id // len(arg_range) args.append(arg_range[i]) return tuple(args)
32d696148ea8ff78f1db2b0a95cbe9c3c69ef79d
640,145
def extract_headers(event): """ Returns the headers from the request The format is: a dict of {name: value_list} where value_list is an iterable of all header values. Supports regular and multivalue headers. """ headers = event.get('headers') or {} multi_headers = (event.get('multiValueHea...
042258e528bf5172c06fedb01b3bb4a199657db4
640,146
import os def get_ros_version(): """Return ROS Version and Distro.""" env = os.environ version = env.get('ROS_VERSION') distro = env.get('ROS_DISTRO') if version and distro: return int(version), distro return version, distro
0e5dfc093a3373c2f121388b192125b7d640b769
640,147
import os def get_list_of_posts(startdir, strippath): """ Returns a dict of {slugified-post-title: filename} to work on. If strippath is not None, then we remove every strippath from the slugified entry. """ postlist = {} for dirname, _dirs, fname in os.walk(startdir): if len(fname...
31f09aae7499252c954809798c6b7b6cd39545a4
640,148
def interval_overlap_length(i1,i2): """Compute the length of overlap of two intervals. Parameters ---------- i1, i2 : pairs of two floats The two intervals. Returns ------- l : float The length of the overlap between the two intervals. """ (a,b) = i1 (c...
a22fdd3cf76a503700055bc4077ef9584b6b394b
640,149
def is_good_status_code(status_code): """ :param status_code: HTTP status code :type status_code: int :rtype: bool """ return 200 <= status_code < 400
666587a5a8a7f6e5937c4ff5b3c71bacefdf6bcb
640,150
def format_translation_changes(old, new): """ Return a comment stating what is different between the old and new function prototype parts. """ changed = False result = '' # normalize C API attributes oldargs = [x.replace('struct _', '') for x in old['args']] oldretval = old['retval'].replace('struc...
6eb2c6a1da609e57b20d069eeddb8bb8d864a0ac
640,151
def getTableTex(table, captionTex, **additionalPars): """Produce a Latex table from the structured array in "table" and the caption text in "captionTex". It is assumed that the headers of the table are given in the names of the structured array. To avoid long tables, print only up to 30 lines. """ ...
7f011fa3c041e948e885734cd1264a14348bcef8
640,152
import base64 def _urlsafe_b64encode(s: bytes) -> bytes: """ Base 64 URL safe encoding with no padding. :param s: input str to be encoded :return: encoded bytes """ return base64.urlsafe_b64encode(s).rstrip(b"=")
50b007c54f516b4ccc3b48ca89b10bed3853517a
640,153
def get_clinical_Y_range(): """ Returns clinical Y range """ return (-100.0, 100.0) # in mm
e6d7a9302ac41e9a29db32e14dfdcabf02634924
640,154
def myTwistFunction(Epsilon): """User-defined function describing the variation of twist as a function of the leading edge coordinate.""" RootTwist = 0 TipTwist = -2 return RootTwist + Epsilon * TipTwist
98531342166f17258357d08b468e90fd44127ecb
640,155