content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def FindOrderNums(orders, wavelengths): """ Given a list of xypoint orders and another list of wavelengths, this finds the order numbers with the requested wavelengths """ nums = [] for wave in wavelengths: for i, order in enumerate(orders): if order.x[0] < wa...
40f974709e37a6df3cb9bb8f1dd040904669eb76
627,510
import uuid def unique_str(): """Generates and return a unique string""" return str(uuid.uuid4())
792f8a23f818d1bad3e81beee2931079e501cc37
627,511
def merge_clusters(articles): """Merges articles of every cluster into one article object.""" clusters = [] cluster_ids = set([article['cluster_id'] for article in articles]) for id in cluster_ids: body = [] for article in articles: if article['cluster_id'] == id: ...
bd5965b331519423322d146d3ce065885d44a760
627,512
import os def get_instance_name_to_id_dict(root): """ Returns a dict with instance names as keys and is as values """ name_to_id_dict = {} for line in open(os.path.join(root,'instance_id_map.txt'),'r'): name, id_num = str.split(line) name_to_id_dict[name] = int(id_num) return...
fd61818fbbccb14a42dc7dcb4ac99c6460034979
627,513
def provider2network(p): """ Convert a MADIS network ID to one that I use, here in IEM land""" if p in ['KYMN']: return p if len(p) == 5 or p in ['KYTC-RWIS', 'NEDOR']: if p[:2] == 'IA': return None return '%s_RWIS' % (p[:2],) print("Unsure how to convert %s into a ne...
75328bf129f3619b63d24b4cbe6f70037aefc3ad
627,514
def usage_quirks(): """ display the available quirks in this tool Returns a string of available quirks in this tool. Returns: the quirks string """ return """releng-tool quirks releng.cmake.disable_parallel_option disable parallel cmake releng.disable_prerequisites_check disable...
9b785134a87a5f12f5491755b80b4b713d44ff05
627,515
import pickle def load(filename): """Loads elements from Pickle file Args: - Filename - str of location Return: Tuple with: - Lists of Activity Names - Lists of Activity Types """ assert type(filename) == str, 'Filename must be a str' with open(filename...
7d18a745c896342107c5815939471da58ba906d1
627,516
def treat_tunnel(tunnel_model, ts_sadpt, ts_nobarrier, radrad): """ decide to treat tunneling """ treat = True if tunnel_model != 'none': if radrad: if ts_nobarrier in ('pst', 'rpvtst', 'vrctst'): treat = False else: if ts_sadpt == ('pst', 'vrctst'...
de1319fc056b5a11e6b8cf169d11382de6886597
627,517
def figshare_stem(stem: str = '', production: bool = True) -> str: """ Construct Grouper figshare stems :param stem: string corresponding to the sub-stem. Options are: 'quota', 'portal'. Default: root stem :param production: Bool to use production stem. Otherwise a stage/test is u...
929acec5e0a467ddd24d54751bf3f0747f66faa3
627,518
import math def create_circle_polygon(number_verts, axis, radius=1.0, head_tail=0.0): """ Creates a basic circle around of an axis selected. number_verts: number of vertices of the polygon axis: axis normal to the circle radius: the radius of the circle head_tail: where along the l...
7aa4de8a457fbeb7035b76c7f1e3523af85dc2e1
627,519
def build_client_user_topic(user_id: str): """ Builds the topic name where user push notification are received :param user_id: :return: """ return f"/app/{user_id}/subscribe"
b9bf7dec85cfec7d818b9091f1e0a5b784e5dbb9
627,520
def convert(hours: int, minutes: int) -> int: """Convert hours and minutes to total seconds.""" total_seconds = (minutes * 60) + (hours * 3600) return total_seconds
b9aa43a2009dd9561829a934d2bac424bbc88460
627,521
def forced_mass_spring_damper(t, y, k_and_c, forcing_functions): """ Inputs: t is a float for time y is a list [x, x'] c is a float which is infact c/m k is a float which is infact k/m x_forced is an interp1d function which returns a x_forced value for a given t within the domain v_force...
5308ba6ce274e1fc3bcb60dee561a7120d032f40
627,522
def findall_lod(lst, key, val): """get list of dicts of all matches of key-value pair in list of dicts""" return [x for x in lst if x[key] == val]
17c101399367443a1ac40030a14110325f09920f
627,523
import hashlib def hash_from_url(url: str): """Hash url to create a unique ID.""" return hashlib.sha256(url.encode("utf-8")).hexdigest()
bda9aceca362d9b57780d0d333320eaccc556a91
627,524
def health_check(): """Can be called by e.g. Kubernetes to verify that the API is up Returns: str: the static string "Comet-API", could be anything """ return "Comet-API-v0"
41855fa47aef2f9b842e3637277005bbdf5ad109
627,525
def back2dim(x, xdim=-1): """ Transpose ndarray so that the back dimension is moved to a given position. Parameters ---------- x : ndarray Input array. xdim : int, optional Dimension at which to put the back "x" input array dimension. (default=-1) Returns ------...
6db1b8ca2398e7fe7e90010598944823bf770148
627,526
def maximum_element_size_for_length(length): """ Returns the maximum element size representable in a given number of bytes. :arg length: the limit on the length of the encoded representation in bytes :type length: int :returns: the maximum element size representable :rtype: int """ return (2**(7*length)...
69e2577d1b7b489ed159339dcc32d4a441dace36
627,527
def model_function(X, a, b, c): """ - the analytical expression for the model that aims at describing the experimental data - the X argument is an array of tuples of the form X=[,...,(xi_1,xi_2),...] """ nw1, nw2, I = X f = a * pow(I, 2) * (nw1 + 0.5) + b * I * (nw2 + 0.5) + c return f
04aa013210b265cf69e83a7defdfc8c09f558183
627,528
def force_agg(self, func, axis=0, *args, **kwargs): """ Force the aggregate function to work on all items instead of try Series.apply()""" axis = self._get_axis_number(axis) result, how = self._aggregate(func, *args, **kwargs) if result is None: kwargs.pop('_axis', None) kwargs.pop('_lev...
c16433bb1ed6513464be2db60695ea7fa01f8571
627,529
def first(iterable): """Returns the first item of 'iterable' """ try: return next(iter(iterable)) except StopIteration: return None
ef3a589f21c89a59a73e117463ecdb4c341bb7b0
627,530
def _translate_slice(exp, length): """ Given a slice object, return a 3-tuple (start, count, step) for use with the hyperslab selection routines """ start, stop, step = exp.indices(length) # Now if step > 0, then start and stop are in [0, length]; # if step < 0, they are in ...
ba91234e21c1f32dcf44440580dbc7f590e320e7
627,531
def get_measurement_variable(gt_id, shift=None): """Returns measurement variable name for the given ground truth id Args: gt_id: ground truth data string accepted by get_ground_truth shift: (optional) Number of days by which ground truth measurements should be shifted forward """ ...
6d4aa672d04b896f8963b4ebe36d7b056b7a4c6c
627,532
def bracket(s,m=''): """add a bracket around s and append m. @rtype: string @return: a bracketed string s and a suffixed message m """ return '[%s] %s' % (s,str(m))
a810722f335bc61dc9317b9348a7c72b6d8f62ec
627,534
def readDictionary(input): """ Read file to a dictionary data structure: Input file is a lexicon consisting lines of the word and the most frequent associated tag """ dictionary = {} lines = open(input, "r").readlines() for line in lines: wordtag = line.strip().split() ...
543261fe7cbff53b4dc3082d56687aa3d2cef336
627,535
import random def randomize_list_of_words(input_words): """ Returns the same list of words in a random order. Input: -input_words list of strings Output: -output_words list of strings """ output_words = [] random_order = random.sample(range(len(input_words)), len(input_word...
cbe19aa8cddddedcb439245cfc9ad67e20d7e382
627,536
import http def invalid_token_callback(error): """we have to keep the argument here, since it's passed in by the caller internally""" data: dict = { "success": False, "message": "invalid_token", "description": "Signature verification failed.", "errors": [], } return...
9b89dd264c025b9ace9726b03be2ffde9f6a018b
627,537
import os def readPath(path): """Get a Totoro-formatted path and returns the real path. Paths are expanded depending on the first character of the input string. If the first character is '+', the path is considered to be Totoro-internal relative to the root of the package. Otherwise, the path is ...
bd5e4c48077ef021deca6f93bb0a4f559e6b9635
627,538
def only_hostname(s): """ Given an SSH target, returns only the hostname. e.g. only_hostname('user@mydomain:port') == 'mydomain' """ return s.split('@')[-1].split(':')[0].strip()
256d21128c14072ce915d70492f79d6c21e1d24b
627,539
import collections def log_string_to_dict_list(log_string): """ Take a single string representing the contents of a jewel::Log file, and return a list of OrderedDicts representing the logging events in the log file. """ record_separator = "{R}" field_separator = "{F}" raw_records = log...
44f144c05a4584aece82abc6d31607fa60199911
627,540
import json def dump_json_from_file(file_name): """ Dumps the given json file to dictionary. :param file_name: Name of json file :return: Dictionary representing the json """ with (open(file_name)) as json_file: loaded_json = json.loads(json_file.read()) return loaded_json
8482333bf417e03044dab3a1116b9ecd13a758e4
627,541
def value_to_string(value, name): """Translates values (e.g. lists, ints, booleans) to strings""" def last(name): *prefix, base = name.split(".") return base if isinstance(value, list): return "x".join(map(str, value)) if isinstance(value, bool): return last(name) if va...
77b7d1585022bf344dbb003e2512d5422f4f78d8
627,542
def limitValue(value, min, max): """Limits value to a min or max value Arguments: value {int, float} -- value min {int, float} -- minValue max {int, float} -- maxValue Returns: int, float -- limited value """ if value > max: out = max elif value < min: ...
6280ee2e4b414a1020f225ff8a588394bd3c0a53
627,543
def get_diffs(t1_list, t2_list, slices): """ Function comparing the difference between two topics. input: t1_list (list): list of words representing a topic. t2_list (list): list of words representing a topic. slices (pair): pair indicating which slice the two to...
884b8d700c5d38993d4a97553d40b751592aaea5
627,544
def delete_replace_str(filename, replaces): """ :param filename: :param replaces: :type filename: str :type replaces: list[str] :return: """ for rep in replaces: filename = filename.replace(rep, '') return filename
9b26ff4608c1c87cfc1d8b1511c5d2f43798bd04
627,545
def int_depth(h_int: list, thickness: float): """ Computes depth to the interface for a three layer model. :param h_int: depth to to first interface :param thickness: thickness :return: d_interface: interface depths """ d_interface = h_int d_interface.append(d_interface[0] + thi...
816bc15b51668fb2f8376826c065197802e88c98
627,546
def remove_subdomain(name: str) -> str: """Removes the subdomain from a given URL. Example: >>> remove_subdomain("www.example.com") '.example.com' Arguments: name: the domain Returns: the string with the subdomain removed. The string starts with the dot. """ tr...
e507a4dedc6eb9a9ca8e2f6e1db2cb9dc399283d
627,548
def euclid(a:int, b:int, Verbose=False): """Return the Greatest Common Divisor (GCD) of number a and b.""" # The GCD of two relative integers is equal to the GCD of their absolute values. a, b=abs(a), abs(b) # The largest of the two numbers is replaced by the remainder of the Euclidean div...
3172e024b2782f1077673f05d732607ecf3e59f7
627,550
def get_crop(params, shape): """ Parses crop from params object. Parameters ---------- params : object object holding configuration parameters shape : tuple shape of image array, i.e. the array to be cropped Returns ------- crop : list crop in each...
0bdeeed81c3578301654df72d97e27dce9326dba
627,551
def btc_to_satoshi(btc): """ Converts a value in BTC to satoshi outputs => <int> btc: <Decimal> or <Float> """ value = btc * 100000000 return int(value)
c75fe3bec4389b8fc332188edfeda575766aeae2
627,552
from functools import reduce def ichain(obj, *items): """ Gets through a chain of items handling exceptions with None value. Useful for data restored from a JSON string: >>> ichain(data, 'result', 'users', 0, 'address', 'street') """ def get_item(obj, item): if obj is None: ...
b4f4bf3da2a57ec95af6779f3fbd67c351414045
627,553
import argparse def get_args(): """ Arg Parser """ parser = argparse.ArgumentParser(description="Model Options") parser.add_argument( "--local", type=bool, default=True, help="True if running on local machine, False if running on AWS", ) parser.add_argument( "--load_weights", type=bool, default...
3555e455aa6bd7cc71e4c08b2cf83925a3c24cb8
627,556
import torch def transform_coords(Ms, coords, wrap_around=False): """ Ms - affine transform matrices, (B,2,3), assumes x-y coordinate system in math coords - (B,dimx,dimy,2) """ B, dimx, dimy = coords.size()[0], coords.size()[1], coords.size()[2] augmented_coords = torch.cat((coords, torch.one...
b3093ce3a58a83125744265ab70394643888df71
627,557
def treat_input(data): """ Treats the input json to keep it in the same format as the coeficcients """ treated_data = dict() for key, value in data.items(): if key[0] == 'Q': treated_data[value] = 1 else: treated_data[key] = 1 return treated_data
c9dc294034f3a9857a3b35e26c3169bb81bf9f18
627,558
def dp_edit_distance(str1, str2): """ Finds the minimum edit displace between two strings I use 1 """ n = len(str1) m = len(str2) optimal_edit_distances = {} i = n - 1 j = m - 1 for i in range(n - 1, -1, -1): for j in range(m - 1, -1, -1): if str1[i] == str2[j]: if i == n - 1 a...
6989de5fca82cbd10b73d8854ed918cf662b7e5d
627,559
def clamp(val, low, high): """Return val, within [low,high]""" if val < low: return low elif val > high: return high return val
58c0c8afbfa8527617a15c20989fe4b0c1fd2db9
627,560
def _bin_to_hex(bitstring): """Convert bitstring readouts (memory) to hexadecimal readouts.""" return hex(int(bitstring, 2))
ebd5197ee5956d388ee1ea1b365a0b3fbba7c804
627,561
import numpy as np def dl_ia_utils_vertical_translation(y): """ detects in exist a zero value and translate the time series with the minimum value :param y: :return: """ if np.isin(0, y): # exists a zero value, find the minimum distinct from zero delta = np.min(y[y > 0]) # ...
5d2e68850e5ccb457ac322e26d9a7b8eb239ad67
627,562
def list_apim_nv(client, resource_group_name, service_name): """List all Named Values of an API Management instance. """ return client.named_value.list_by_service(resource_group_name, service_name)
d14f5d8e4fba0fe08d158cfbf099228fda5599e0
627,564
import time def get_system_time(pretty=True): """ 该函数用于返回系统当前时间 :return:当前系统时间 """ if pretty: ISOTIMEFORMAT = "%Y-%m-%d-%X" current_time = time.strftime(ISOTIMEFORMAT, time.localtime(time.time())) else: current_time = time.time() return current_time
cba622601346c1170ce1419ca88b1268aa5932df
627,565
def mock_post(mocker): """ Creates a mock response for the dataservice """ post = mocker.patch("requests.post") class MockResp: def __init__(self): self.status_code = 201 def json(self): return { "_links": { "collection": "/studie...
f37d70c6cd94500e517fec34ce2531da1e6ad79f
627,566
def remove_collided_carts(carts, repeated_position): """Remove carts colliding on the repeated_position.""" return [cart for cart in carts if cart[0] not in repeated_position]
6786a0e01b397d00fd959e5a912b766c5659b90a
627,567
import time def is_bst(st: time.struct_time) -> bool: """ Calculates whether the given day falls within British Summer Time. .. note:: This function does not consider the time of day, and therefore does not handle the fact that the time changes at 1 AM GMT. :param st: The :class:`time.struct_time` represen...
7428810629c417cb8a55994b3086a7e9515194b7
627,570
def request_memory_generation_lookup(duration, roq=False): """ Function to determine memory required at the data generation step """ if roq: return int(max([8, min([60, duration])])) else: return 8
190e723ddc8f3e91371ce541920fbcbe1204f41a
627,571
def convert_masking(sentences): """Converts hash masking to internal [MASK] tokens""" converted_sentences = [] for sent in sentences: sent = list(sent) for i, c in enumerate(sent): if c == "#": sent[i] = "[MASK]" converted_sentences.append("".join(sent)) ...
2ae095b06694d8f592159f5f5eee6491fe479d23
627,572
def calGasVisEq2(eqExpr, T): """ gas viscosity equation - Pa.s args: eqExpr: equation expression T: temperature [K] """ # try/except try: return eval(eqExpr) except Exception as e: raise
b56d1a267777bbc6803f65937f2a5d96c00f284d
627,573
def get_security_group_rules(body_response_sec_group_list, sec_group_name): """ Retrieve security group rules list :param body_response_sec_group_list: Parsed response (python dic). List of sec. groups :param sec_group_name: Name of Sec. Group to look for :return: Return the first sec. group with se...
0ec23f16fcc3bd166ed8fa4412bd768e6e9c72da
627,574
def judge(filename): """ 读取文件判断文件类型 输入:文件名 返回:1到6表示文件类型 """ with open(filename) as file_obj: header_name = file_obj.readline().split('\t') header_len = len(header_name) if header_len == 13: return 1 if header_len == 5: return 2 ...
7868d0b572fb9bc5f2d3a37e6e7e800c0a07d743
627,575
def merge(line): """ Function that merges a single row or column in 2048. """ line_t1 = [] for num in list(line): if num != 0: line_t1.append(num) for dummy_num in range(len(line)-len(line_t1)): line_t1.append(0) line_t2 = [] idx = 0 while True: ...
ec8cce907d3ce86e7e82876f06f6f820f2245add
627,576
def greater_than(quant1, quant2): """Binary function to call the operator""" return quant1 > quant2
54c22b96caf9e9c32de2974c799ae8c81f997fd0
627,577
def pressure_NORMALIZED(p_num, norm_ref): """ Calculation of the normalized pressure as a function of frequency. :param p_num numerical results. :param norm_ref reference pressure for the normalization. :param p_norm normalized pressure. :return The normalized pressure as a funct...
2c3719d5df5f0f0c4b8021761ef5264939759f86
627,578
def calcRCutIsolate(rh): """ For isolated star clusters, set rcut to 20 * half-mass radius Return ---------- rcut: float escaper distance criterion """ return 20*rh
c4a37a1145270fee17a67f944dec9ecfbce93ea4
627,579
def _testinfra_validator(instruction): """ """ try: compile(instruction, '_testinfra_validator', 'exec') except SyntaxError as exc: return str(exc)
c52c7e3b358134eed73c2dcba8200fe32de3ed93
627,580
def anomalize(data_array): """ anomalizes the data_array and returns a new data array and the climatology inputs ------- data_array (xarray data array) : data array of 2m temperature ouputs ------ anomalized data array, climatology data array (xarrays) ...
2573780ec0731815175de5246230aecf04f91157
627,581
import random def prune_zero_depth(pc): """ Input: pc (N, 6, p), where dim 6 represents (x, y, z, R, G, B) Output: pc (N, 6, p), replace points where z = 0 with points where z != 0 """ N, _, _ = pc.shape for i in range(N): idx = (pc[i,2] <= 0).nonzero().view(-1) non_idx = ((pc[...
db279e6bbd3a93380c8ea9e8b2c4824c77e50d7a
627,582
def _pre_commit_has_hallmark(pre_commit_file): """ Looks at a pre-commit file and determine if it was created by Jig. :returns: True if Jig created it """ with open(pre_commit_file) as fh: script = fh.read() if u'from jig' in script or u'jig init' in script: return True ...
d55b5ea21c69558d8937296b518d058db9334e6a
627,583
def extract(d, keys, exclude=False): """ Helper function to extract keys and values from dictionary Parameters ---------- d : dict Dictionary from which to extract keys keys : list of keys List of keys to exclude or include exclude : boolean If true, excludes the...
ef9e526b2db018e8adc53f14c67d5c316495858e
627,584
def calc_ins_mean_std(x, eps=1e-5): """extract feature map statistics""" # eps is a small value added to the variance to avoid divide-by-zero. size = x.size() assert (len(size) == 4) N, C = size[:2] var = x.contiguous().view(N, C, -1).var(dim=2) + eps std = var.sqrt().view(N, C, 1, 1) me...
26d9c922e4155825922559aec91ba059982212c5
627,585
def emulator_files(emulator): """Files that are runtime dependencies of this emulator.""" return emulator["extra_files"]
62f627b573e8136cc2076cda0abe04e470975f5e
627,586
def merge_ranges(ranges, max_gap): """ Merge ranges which are closer than max_gap """ merged_ranges = [] for range in ranges: if merged_ranges: curr_start, curr_end = range # compare against last interval in merged_ranges pre_start, pre_end = merged_ra...
981ae0dedb9ef5df5852994a7f7712953f2a5d3e
627,587
def _is_power_of_two( n ): """ bit manipulations, suggested via https://stackoverflow.com/a/57025941 """ n = int(n) return (n & (n-1) == 0) and n != 0
c55cb84ee0cae80a78814707ec6122260332c4fb
627,588
def freq(T): """ Convert array of periods in days to frequencies in Hz. """ return 1./T/86400.
d4b1e31ec6468141803405d82535330803a03869
627,589
def pd_applyfun_col(df, newcol, ff, use_colname="all/[colname]"): """ use all Columns to compute values """ if use_colname == "all/[colname]": df[newcol] = ff(df.values) else: df[newcol] = ff(df[use_colname].values) return df
0e7e03576615f5695f33c8044abcc7bb36e830fc
627,590
import re def psplit(texts): """ Phrase splitting. """ if isinstance(texts, str): texts = [texts] ssplit_p = re.compile(r'(\S.+?[.!?\n;:])(?=\s+|$)') sections = [] for text in texts: if not text: continue text = text.strip() + '\n' if text == '' or text == '...
f87a5e9caec4d0260371194ebd9570060fc7715b
627,591
def RemoveDotSegments(path): """ Supports Absolutize() by implementing the remove_dot_segments function described in RFC 3986 sec. 5.2. It collapses most of the '.' and '..' segments out of a path without eliminating empty segments. It is intended to be used during the path merging process and may ...
68f453e948e920f301f434f4c1dde1a5ef557758
627,592
import os import subprocess def get_env_from_sh(scriptfn, shell='sh', inheritenv=False): """Get a dict containing the environment after sourcing scriptfn""" if not os.path.isfile(scriptfn): raise ValueError(f'{scriptfn}: file does not exist') if inheritenv: command = f'{shell} -c ". {scr...
0fd988928910816e56e8c8c776cb714a88254e0e
627,593
def _parse_fingerprint_awsconsole(line, host=None): """Parse SSH host fingerprint from AWS console output""" fingerprint = None if line.startswith('ec2:'): host = host fingerprint = line.split(': ', 2)[1] return host, fingerprint
f114c138fb7c1fe10e9a2db5d105f6587520742d
627,594
def display_name(user): """ take a User instance and return the full name of the user regardless of whether the user is authenticated or not. This filter is used by changing quota holders. """ if user.first_name: content = "{fn} {ln} ({un})".format(fn=user.first_name, ln=user.last_name, ...
86c09b263ee9a036e7bb8967e9c726226003b8f4
627,595
import re def libraryRemover(code): """ function which removes pragma""" return re.sub(r'^library.*\n?', '', code, flags=re.MULTILINE)
100809244ea66a723772cfdcc4089702700648af
627,596
def _savings(energy_by_month, kwh_cost): """ Returns savings by month. """ savings = {} for month, energy in energy_by_month.items(): savings[month] = energy*kwh_cost return savings
ea2eff71a654aa00660900683f90b56c0ac07af7
627,597
import logging import socket def check_port_in_use(host, port): """Check if port is already in use. Arguments --------- host: str The current host. port: int The host port to be checked. Returns ------- bool: True if port is in use, false otherwise. """ ...
7351f26ae44d19d6640999ffee3e9c61cffb7770
627,598
import argparse def get_args(): """ parse args """ description = "Dataset Debiasing by GAN" parser = argparse.ArgumentParser(description) parser.add_argument("-d", "--device-id", type=int, default=0, help="Device ID of the GPU for training") parser.add_argument("-c"...
420359dcb37298750db32593ea4ac445c94330ab
627,599
def format_health_text(playersData, monster): """ [playersData] - A dictionary of players' data which contains their statistics [monster] - A monster object that contains its relevant statistics Beautify indentation in the text to be display in embed message """ # Finds longest length of strin...
d8380c0c99476d2625235bf3402d4bd6e191a887
627,600
def make_sic_div_lookup(sic): """Creates lookup between SIC class and division.""" return ( sic.assign( Division=lambda x: x.Class.str[0:2], Class=lambda x: x.Class.str.replace(".", ""), ) .set_index("Class")["Division"] .to_dict() )
1c0ceae74334c06e0f69e6d33d7120f4ec0105c0
627,601
def get_main_domain_name(url_str) -> str: """get url domain texts Args: url_str (str): url string Returns: str: domain name of url """ domain_name = url_str.split("/")[2] main_domain_name = domain_name.split(".")[-2] return main_domain_name
ddc3fc8aa2b0b61eafd84ac9754c271f011ac8d2
627,602
import subprocess def command_with_output(command: str) -> str: """Run command and return it's text with output.""" output = subprocess.run( command, shell=True, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ).stdout return f"# {command}\n\n{output}"
034f68fc67665dad103c5f47b63dd715eeeb5af0
627,603
def force_console_input( query: str, allowable, onfail: str = "Input not recognised, please try again.\n", case_sensitive=False, ): """Get an input from the user matching some string in allowable. Args: query (str): The query to issue the user with. allowable (str or container):...
d43e98f77a14f0045117738900128bf779cba173
627,605
def did(tag_class, is_constructed, tag_id): """ Calculate decoder_id as <tag id > | tag_class | constructed :param tag_class: :param is_constructed: :param tag_id: :return: """ did = tag_class >> 5 if is_constructed: did |= 1 return did | (tag_id << 3)
1fa8a0b11b7260a4f607eb79770fd76a87bfbdb1
627,607
def similarity (set1, set2): """ Similarity function used. Input: two arbitrary python sets. Output: floating point measure of similarity between 0.0 and 1.0. """ i = len (set1 & set2) return i * 1.0 / (len (set1) + len (set2) - i)
a8de2a8b1c820dfd3f3e7d2eabf625349a479f8f
627,608
def compute_wave_height(crest_height, trough_depth): """Computes wave height from given crest height and trough depth.""" assert crest_height > trough_depth return crest_height - trough_depth
b259e28afa3c6ef4514a087490b62a70f6a0b1f6
627,609
import configparser import logging def read_config(filename): """Reads a config file. Args: filename (str): Filename of config file to be read. Returns: configparser.ConfigParser: Read config file. """ parser = configparser.ConfigParser() parser.read(filename) logging.inf...
2336979a44246a93fbb4a563e54ebb9f5a356d23
627,611
def UsersInvolvedInComponents(component_defs): """Return a set of user IDs referenced in the given components.""" result = set() for cd in component_defs: result.update(cd.admin_ids) result.update(cd.cc_ids) if cd.creator_id: result.add(cd.creator_id) if cd.modifier_id: result.add(cd.m...
431d63647d8cf6f8588700015ef94b46d96ce651
627,612
import torch def calc_accuracy(mdl: torch.nn.Module, X: torch.Tensor, Y: torch.Tensor) -> float: """ Get the accuracy with respect to the most likely label. ref: https://stackoverflow.com/questions/51503851/calculate-the-accuracy-every-epoch-in-pytorch/63271002#63271002 :param mdl: :param X: ...
73ebe04e5819d51946b3a04abbdd29af018352dd
627,613
def parse_none_or_string(value): """ This function is primarily used to parse command-line arguments. Whenever the string 'None' is passed, it will return it as None, otherwise it will return whatever it was passed as a string. """ if value == 'None': return None return value
5ebbce7afe13e9fa5de3233c41d54ae036c88dfe
627,614
def number_of_friends(user): """how many friends does _user_ have?""" return len(user["friends"])
cc741d5be79b4a94ecbed32174548e3b5b9124a7
627,617
def FindOutEdges(edges, num_of_points=-1): """ Fuction """ if type(num_of_points) != int: raise ValueError("Type of parameter 'num_of_points' must be integer") if num_of_points == -1: num_of_points = max([max(i) for i in edges]) + 1 elif num_of_points < 2: raise ValueErro...
4f22ca87a99781f8b940a3f3c5d76027cb284355
627,618
def _nonstrict_write_rosetta_fragments( df, frag_size, n_frags=200, prefix='rosetta_frags' ): """:func:`.write_rosetta_fragments` with ``strict`` as :data:`False`. :return: :class:`str` - name of the newly generated file. """ _STRING = " {:4s} {:1s} {:5d} {:1s} {:1s} {:8.3f} {:8.3f} {:8.3f}\n" _HEA...
49dd8117aa69beb8fd11a31a310e38e6c64af84b
627,619
def naive_auc(labels, preds): """ AUC值的概率法计算 """ n_pos = sum(labels) n_neg = len(labels) - n_pos total_pair = n_pos * n_neg # 总的正负样本对的数目 labels_preds = zip(labels, preds) labels_preds = sorted(labels_preds,key=lambda x:x[1]) # 对预测概率升序排序 count_neg = 0 # 统计负样本出现的个数 satisfied_pai...
3bf44cbb001e440e17e58de43ac292f01f12e1a8
627,621
def slashescape(err): """ codecs error handler. err is UnicodeDecode instance. return a tuple with a replacement for the unencodable part of the input and a position where encoding should continue""" #print err, dir(err), err.start, err.end, err.object[:err.start] thebyte = err.object[err.start:err....
ae485d86795f655b71b26b684101f0ef08a6e0b5
627,622
import torch import builtins def reshape_for_broadcasting( tensor: torch.Tensor, *, ndim: builtins.int ) -> torch.Tensor: """expand dimensions of a 0- or 1-dimensional tensor to ndim for broadcast ops""" assert tensor.ndim <= 1 dims = [1 for _ in range(ndim - 1)] return tensor.view(-1, *dims)
71a6518bfa4d58bfdc534769951e7283269794ac
627,623