content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import torch def complement_idx(idx, dim): """ Compute the complement: set(range(dim)) - set(idx). idx is a multi-dimensional tensor, find the complement for its trailing dimension, all other dimension is considered batched. Args: idx: input index, shape: [N, *, K] dim: the max ind...
e68582ffb6ac74b3481dc5da1ab5b2cbc2eaf23b
645,840
import pickle def load_meta(fname, data_id=''): """Load a metadata file. Parameters ---------- fname : str Path to TFRecord folder Returns ------- meta : dict Metadata file """ with open(fname+data_id+'_meta.pkl', 'rb') as f: meta = pickle.load(f) ret...
2f63d0f2fc1c25fbab59b3c667458e2daf397526
645,841
def sum_squared(variable_list): """Takes in an array and returns the sum of an array with each element squared""" return sum([el * el for el in variable_list])
0bb9e3394c66c111a1c7edb4eb07c5df3eb2328d
645,842
def composite_identity(f, g): """ Return a function with one parameter x that returns True if f(g(x)) is equal to g(f(x)). You can assume the result of g(x) is a valid input for f and vice versa. >>> add_one = lambda x: x + 1 # adds one to x >>> square = lambda x: x**2 >>> b1 = compo...
df89773a3a01bf7d8b3ba5e33ec4866a0f365026
645,843
from typing import Dict import json def load_dict(filepath: str) -> Dict: """ Load JSON data from a URL Args: uri(str): URL of the data source Returns: A dictionary with the loaded JSON data """ with open(filepath, 'r') as fp: d = json.load(fp) return d
91775470118e37af47fd735ee2655166f70692e3
645,844
def all_min_dist(min_dist, x, n): """ all_min_dist(min_dist, x, n) Ensures that the differences of all pairs (i !=j) are >= min_dist. """ constraints = [] for i in range(n): for j in range(i): constraints += [abs(x[i]-x[j]) >= min_dist] # Nope! return constraints
3e93753a83e12ac09d17efd6b9229df0632b74ff
645,845
import contextvars def RunInNewContextMiddleware(app, wsgi_env, start_response): """Runs the app in a copy of the current context. Start every request by calling contextvars.copy_context() and running the rest of the request in the newly copied context. This ensures that each request has its own context that...
cfa96f2011610beb4f2af030ce39e4c62f0f7931
645,846
def strip_comments(content): """Manual striping of comments from file content. Many localized content pages contain original English content in comments. These comments have to be stripped out before analyzing the links. Doing this using regular expression is difficult. Even the grep tool is not su...
3fdad45d48e0e14a1ef3eeef0520b1b154c9ca52
645,847
def ee_collections(collection): """ Earth Engine image collection names """ dic = { 'Landsat4': 'LANDSAT/LT04/C01/T1_SR', 'Landsat5': 'LANDSAT/LT05/C01/T1_SR', 'Landsat7': 'LANDSAT/LE07/C01/T1_SR', 'Landsat457': ['LANDSAT/LT04/C01/T1_SR','LANDSAT/LT05/C01/T1_SR', 'LANDSAT...
5f55630fd51e3a8336e7509281bb3ba5d335014b
645,848
import random def _get_question(question_set, question_type): """ :param question_set: :param question_type: :return: """ num_questions = len(question_set[question_type]) question_index = random.choice(range(num_questions)) question = question_set[question_type].pop(question_index) ...
7aabb84e98143d52c1629b566a31bc4909356ecd
645,849
def calc_in_relation_to_average(x) -> float: """ Support function to calculate the "in_relation_to_average" statistic. i.e How much a tweet has been retweeted given the avg of the retweets of the user. E.g user's X retweet_count average is 100. One of his tweets is retweeted 80 times then this tweets ...
61aed00194b7f27f6f7b2c0b5e2e8b81eb281d41
645,850
def hsl_to_str(hue, sat, light): """ Convert an HSL color value into a string. Args: hue (int): value between 0-360 sat (int): value between 0-100 light (int): value between 0-100 Returns: str: string representation of the HSL tuple. Note that the hue is an integer...
ed0bd6ce344fe1f8333155e68b7dd0ac2de15c73
645,851
def get_city_view(): """Get delivery city""" return {'text': "Укажите город доставки"}
afee04d6b001e1ceac005ecb528de129c5f26212
645,852
def mean(values, empty=0): """ calculates mean of generator or iterator. Returns `empty` in case of an empty sequence """ n, mean = 0, 0 for value in values: n += 1 mean += (value - mean) / n return mean if n > 0 else empty
b697a34a0cf311daea06f5d5fbe0a5ba58e6aec0
645,853
def sum_payout(cost_matrix, confusion_matrix): """ Calculate the profit from cost and confusion matrices. """ return (confusion_matrix * cost_matrix).sum()
8b1b0fe44a283582625ad2cdee91411b59cfb105
645,854
import argparse def get_arguments(args): """ Parse command line arguments. Not sure whether that is the correct place for that function in the long run. """ parser = argparse.ArgumentParser() for item in args: parser.add_argument( item[0], item[1], action='store_true', help...
49f046e8a81197cd762c10b387c6d55ac1292f7a
645,856
import torch def batch_matmul(input: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: """ Batch matrix multiply different batch elements of the input with different weights. If weights are 3D, Input batch is divided in N groups, and each group element is matrix multiplied by a different filter. I...
2b2865bb7af23fbb6801a733a99787ed8d520e7a
645,857
def calculateMetrics(class_labels, lbl_pool): """ this method will calculate the tp, tn, fp, fn metrics for each class of documents from the pool labels provided tp: number of documents in the class that are correctly labeled as belonging to class tn: number of documents not in the class tha...
0e7e070fa5bd59d01332204abaa86b2edfc52f5b
645,858
def spawn(awaitable): """Start running a coroutine asynchronously. Returns the associated task.""" return (yield ("create_task", awaitable))
9cecbb28a953d844e48c352163886738b3edcca4
645,859
def _is_dense_dictionary_argument(argument, dense_indices): """Check whether all keys of the dictionary argument are also dense indices. We cannot check whether all dense indices are in the argument because `splitted_df` in :func:`split_and_combine_df` may not cover all dense combinations. """ ret...
204896ebeb900a7037b64a105de1a3850b213bdf
645,860
import re def convert_value_with_unit(s, baseunit="mm"): """Handle conversion of number strings ending with "in", "mm", "studs" or "%". If a baseunit is provided, force values for in or mm to that unit; if not provided, return the float without scaling. Always return non-number strings unchanged and p...
70b96449ebb8759301d22da928fb17592c089152
645,861
import collections def unique(iterable): """ http://stackoverflow.com/questions/12878833/python-unique-list-using-set """ keys = collections.OrderedDict.fromkeys(iterable).keys() return [k for k in keys]
9235dc5d0cf2f78f7a7ac968a5f630e0a7c6affc
645,863
def get_iso_time(date_time): """ Converts the provided datetime object to an ISO-format time-tag. Parameters ---------- date_time : datetime.datetime Datetime object to convert to ISO format. Returns ------- time_in_iso : str Provided time in ISO format: YYYY-MM-DDTHH:M...
8d819a00c43850fb75a48135b3bd413efff60107
645,864
def p2ps_nonexact_seek(i_dev, r_dev, svc_name, srv_info=None, adv_num=None): """P2PS nonexact service seek request""" if adv_num is None: adv_num = 1 if srv_info is not None: ev1 = i_dev.global_request("P2P_SERV_DISC_REQ 00:00:00:00:00:00 asp 1 " + svc_name + " '" + srv_info + "'") else: ...
62cb641eab991bc0a21c2f22cb5272eae04666e6
645,865
def is_any_in_txt(txt_list, within_txt): """ Within (txt_list), is there one item contained in within_txt ? Example: (['a', 'b'], 'ab') --> Yes, a is contained in ab """ for x in txt_list: if x in within_txt: return True return False
24b72856e2febce9bdc4dabc857ef1842c19317b
645,866
def get_login_decorator(function): """Try and get any login decorator Parameters: function -- the function to examine, as a _fn_type object Returns - tuple (true if login_required exists, login decorator) """ login = None if function.decorators is not None: for item in function.decorators.get_children(): ...
c73d1560e38610eff2abdb66ccc54c087a9abbca
645,867
import math def format_count(number, maxlen=3): """ Returns a formatted count number, e.g. "1.3K" if number is longer than allowed maximum. """ result = str(number) if len(result) > maxlen: UNITS = "KMGTPEZY" log = min(len(UNITS) - 1, math.floor(math.log(number, 1000))) ...
a14ce97025dae2eb47ebc0a571ec059b9a29d17f
645,868
def get_state_hash_and_winner(env, i=0, j=0): """Recursive function that will return all possible states (as ints) and who the corresponding winner is for those sates (if any). (i,j) refers to the next cell on the board to permute (we need to try -1, 0, 1). Impossible games are ignored; i.e. 3x's and 3o's in a...
c83fdf09d90297d8636ddd948c501c584d5d37f1
645,871
def redcap_default_ship_to_vbr_location() -> str: """Returns the VBR Location ID shipment location for UCSD""" # Response is a location_id mapped to these locations # See src/scripts/data/location.csv return "1"
992e103d5ea9d43b88967adae9cf582abe2c353e
645,873
import re def process(s): """Process the file name as input string s to ensure that it adheres to Windows file naming requirements. """ if len(s) > 240: s = s[0, 240] return ''.join(re.split(r"[\\\:\*\?\"\<\>\|]", s.strip()))
88481e7121f2a33d7ea5e7a5b108adcd78350105
645,874
def ignore_filename(fn, include_dotdirs=False): """ Ignores particular file name patterns output by TSK. Detecting new and renamed files becomes difficult if there are 3+ names for an inode (i.e. "dir", "dir/.", and "dir/child/.."). """ return (not include_dotdirs and (fn.endswith("/.") or fn.e...
c3bf8c2f4c2674e2d4ea98eb5794a558446ce68f
645,875
def find_neighbor(x,y): """if y is within +-10bp of x""" # print (x,y) chr_x = x[:-1].split(":")[0] start_x = int(x[:-1].split(":")[-1].split("-")[0]) chr_y = y[:-1].split(":")[0] start_y = int(y[:-1].split(":")[-1].split("-")[0]) # print (chr_x,chr_y,start_x,start_y) if chr_x != chr_y: return False if abs...
590d917bf71e7dd357a9b24e16f22a4cea597787
645,876
def getOSVersion(): """ Return a string identifying the host OS. """ try: with open('/proc/version_signature', 'r') as source: return source.read().strip() except: return None
34e308947c8a02416f706c61c7a8c4df69aa9dfc
645,878
def exclude(counter, signal): """ decide which counters/signals to include in our end2end coverage metric """ return signal['port'] not in ['auto_cover_out']
25882a139ec1fd6437e6349711abe4d1ad1a9a8f
645,879
def mask_sequence(seq, maskchar, fpos, tpos): """Given a sequence, mask it with maskchar starting at fpos (including) and ending at tpos (excluding) """ if len(maskchar) > 1: raise RuntimeError("Internal error: more than one character given to mask_sequence") if fpos < 0: fpos = 0 ...
8e6dfca2c1575da4f31fd1c9c07fd20a8eb78271
645,881
def fibonacci(n): """ this function has one parameter (n). this function should return the nth value in the fibonacci series. the function is implemented using recursion. each number in the fibonacci sequence is the sum of the two numbers that precede it. the sequence goes: 0, 1, 1, 2, 3, 5, 8...
f307fae836c5e9c45b032cf8fe63786d35ac3ab9
645,882
import re def _unify_sql(sql): """ function: unify sql format """ index = 0 sql = re.sub(r'\n', r' ', sql) sql = re.sub(r'/\s*\*[\w\W]*?\*\s*/\s*', r'', sql) sql = re.sub(r'^--.*\s?', r'', sql) sql = re.sub(r'([!><=]=)', r' \1 ', sql) sql = re.sub(r'([^!><=])([=<>])', r'\1 \2 '...
f3dc56f136147e4f33951449dfc06b38a26b8d02
645,883
def get_jinet_fit_args( input_image, batch_size, total_num_patches, img_val, create_patches_for_validation, train_valid_ratio, ): """ Parameters ---------- input_image batch_size total_num_patches img_val create_patches_for_validation train_valid_ratio R...
9edbf749b14675abda812512adaece36b35e219a
645,884
def clear(df,col,val): """ Check distribution of variable This function accepts a dataframe,column(feature) and value which returns count of the value, containing the value counts of a variable(value_counts) Keyword arguments: df - Pandas dataframe col - Feature of the datagrame va...
80f756d5d23f8bfa8c0eb4b2182ec1db158d0581
645,885
def gen_backend_tfvars_files(environment, region): """Generate possible Terraform backend tfvars filenames.""" return [ "backend-%s-%s.tfvars" % (environment, region), "backend-%s.tfvars" % environment, "backend-%s.tfvars" % region, "backend.tfvars" ]
7c05061d2fed80e81900b529d5849959ba06dff2
645,886
import os def increment_until_new_file(str_file): """Will increment given file path with number until file path does not exist yet""" i = 0 str_final_file = str_file while os.path.exists(str_final_file): i += 1 if os.path.dirname(str_file) is "": str_final_file = os.path.sp...
e414cd07dc052343f60427596ab7dc9916e42915
645,887
import os def run_job(params): """<bot> <executor> <command> Runs the specified task/job command on a executor/container in a bot/pod bot: Name of bot/pod executor: Name of executor/container in the bot/pod command: Name of task/job command to be ran in the executor/container""" bot = params...
dab50f5b800ba9fd8bac39da4888622747b36080
645,888
def api_module_rest(request): """Pass.""" return request.param
3f254c4dc59397f11cf6e4bd1efc215f369475b1
645,889
import os import json def load_cookiecutter_json(): """ Load the cookiecutter.json file and return it as dict """ cookiecutter_json_file_path = os.path.join( os.path.dirname(__file__), os.pardir, "cookiecutter.json" ) with open(cookiecutter_json_file_path) as fp: data = json.lo...
d6a55aa85390ea20cc88535e3b92fa526d079b8e
645,890
def get_prot_res_seq_cif(CifDict, EntNum): """ Gives sequence as taken from mmCIF file, entity poly pdbx seq section Takes the canonical sequence. Parameters ---------- CifDict: dict EntNum: int Returns ------- canonseq: str """ # canon_seqlist = CifDict["_entity_poly.p...
8a078ee039cc4439806448c77d512a3bea807afa
645,891
def calc_roi(revenue_time_series, opex_time_series, cogs_time_series, interest, tax_time_series, capex): """ Return on Investment Equation Notes ----- Calculates ROI by calculating profit divided by total investment, and then multiplying by 100 for a percentage. The p...
927c6bb334f06c45fb555fff30d8387701a3dabb
645,892
def get_direct_deps(graph, top_node): """Gets the direct dependencies of given top_node. @param graph The graph to read for dependencies. @param top_node The node, which dependencies are wanted. @return The dependencies in a set. """ deps = set() for i in range(len(graph.body)): if ...
9392b31a9ecf6081f86454455fdfa32c501fa20b
645,893
import os import sys def pyc_file(filename): """Put the interpreter-tagged .pyc next to the .py so that __file__ directives in benchmarks work.""" basename = os.path.basename(filename) stem, _ = os.path.splitext(basename) containing_dir = os.path.dirname(filename) return os.path.join(containin...
a3c73d86e38b0f60442b05ae8d22403f8e5112fe
645,894
def simple_bed(tmp_path): """ A simple bed for excluding sites 0-7. This should exclude the first 2 sites of r001. """ f = tmp_path / "simple.bed" f.write_text('ref\t8\t46\n') return str(f)
dd4b6a2d44e817bd0526ba1cdd2f0f5fa92db343
645,895
def get_query_from_sequence(id: tuple, start: int, end: int, input_list: list): """ :param id: :param start: :param end: :param input_list: :return: a list """ try: input_dict = dict(input_list) # validate by converting input_list into a dict except (TypeError, ValueError):...
791b94f52c8a54b119c9d57aa103d08e648b6421
645,896
import math def applyDeadZone(val, deadZone): """ Apply a dead zone to an input with no other smoothing. Values outsize the dead zone are correctly scaled for 0 to 1.0 :return: The float value of the adjusted intput """ sign = 1.0 if val < 0.0: sign = -1.0 val = math.fabs(val)...
42937474a10065efe793ce09f1b4625676c7d733
645,897
import os def identifier_from_path(path): """ Gets the arxiv identifier from a path >>> identifier_from_path("0507037v3.pdf.txt") '0507037v3' >>> identifier_from_path("0705.4676v8.pdf.txt") '0705.4676v8' >>> identifier_from_path("data/txt/0705.4676v8.pdf.txt") '0705.4676v8' """ ...
ba6f01f615ecbb04aa08ec236b335e530dcbf760
645,898
import torch def xyxy2xywh(box: torch.Tensor) -> torch.Tensor: """ Returns the xywh format of the input bounding box tensor Arguments: box (torch.Tensor): Bounding box tensor in xyxy format Output: output (torch.Tensor): Bounding box tensor in xywh format """ ...
d119f7b436cfbaadcb940b335fe6cda39d145fb1
645,899
def parse_email_remediation_key(key): """Returns the tuple (message_id, recipient) for the key created using create_email_remediation_key.""" return key.split(':', 1)
495eff306e89ada4430bc4995d96fb88e0c4f032
645,900
def get_github_headers(api_token): """ Load GH personal access token from file. """ gh_headers = {"AUTHORIZATION": f"token {api_token}"} return gh_headers
29319c0b7cba7d1c3881fbf039a0f3f33c3a109d
645,901
def get_E_E_hs_cm_d_t(E_E_HP_cm_d_t, E_E_aux_cm_d_t): """日付dの時刻tにおける制御モードcmの1時間当たりの給湯機の消費電力量(kWh/h)(2) Args: E_E_HP_cm_d_t(ndarray): 日付dの時刻tにおける制御モードcmの1時間当たりのヒートポンプの消費電力量 E_E_aux_cm_d_t(ndarray): 日付dの時刻tにおける制御モードcmの1時間当たりの補機の消費電力量 Returns: ndarray: 日付dの時刻tにおける制御モードcmの1時間当たりの給湯機の消費電力量 ...
486cbc27a3de0ffa69f9c0eb6e41387f2fbc9f75
645,902
def read_text(file_name): """ Parameters ---------- file_name : string, name of file to read Returns ------- line : string of the file contents """ inFile = open(file_name,'r') # Python function to open a file via name line = inFile.read() # Function to read contents into ...
51dbcd5bb28a78980201906a4a7f5dbef50cef8f
645,903
from unittest.mock import patch def patch_androidtv_update( state, current_app, running_apps, device, is_volume_muted, volume_level, hdmi_input ): """Patch the `AndroidTV.update()` method.""" return patch( "androidtv.androidtv.androidtv_async.AndroidTVAsync.update", return_value=( ...
cc2c8b5a9d845a582aac8a4d07c41da8b692ef73
645,904
import copy def merge_sort(data, reverse=False): """ Implement merge sort. :param data: [] :param reverse: if reverse is True, DESC, else ASC. :return: [] """ iter(data) copy_data = copy.deepcopy(data) if len(copy_data) < 2: return copy_data def _merge(_left, _right, _...
871b1d8c134c0e5e24acdfe78c313498404e8eb3
645,905
def read_input(filename): """ >>> read_input('sum1') [[[1, 1], [1, 2]], [[2, 3], [2, 4], [1, 5]]] >>> read_input('explode1') [[[5, 9], [5, 8], [4, 1], [3, 2], [2, 3], [1, 4]]] >>> read_input('explode2') [[[1, 7], [2, 6], [3, 5], [4, 4], [5, 3], [5, 2]]] """ puzzle = [] with open(...
95d499b9ef1cbe8913b69367f7afc2ce1bee2aa9
645,907
import pathlib def check(): """Check bitcoind filesystem structure""" bitcoind_dir = "/media/archive/archive/bitcoin" bitcoind_dir_exists = pathlib.Path(bitcoind_dir).is_dir() if bitcoind_dir_exists: print("bitcoind directory exists") else: print("bitcoin folder missing") bit...
727f536231ba08eea6909a465f01ac5293d09b1f
645,908
def newclass(name, *bases, **attribs): """Returns a new class with given name, bases and class attributes.""" class _NewType(type): def __new__(cls): return type.__new__(cls, str(name), bases, attribs) def __init__(self, *args, **kwargs): pass # XXX quick fix for python 2...
3a8d79a9a29e639e2846fb212639fdd4cd3f958a
645,909
def bezier2(t, ps): """ evaluate quadratic bezier curve at t given three points in list ps """ umt = 1 - t return umt * umt * ps[0] + 2 * umt * t * ps[1] + t * t * ps[2]
71b6873d823cef7854bc8b56a874815c52362545
645,911
def get_time_coordinate_axis(dataset): """ It is common to pass an argument to scipy.signal methods axis=int where that integer specifies along which dimension we are applying the operator. This method helps ensure that we have the correct axis. Parameters ---------- dataset : xarray.Datase...
a140c380e8369ef6156a57827917084b67c50ce9
645,912
def is_valid_filename_extension(ext: str) -> bool: """ By convention extensions are the initial `.`. E.g., "tgz" is valid, but not ".tgz". """ valid = not ext.startswith(".") return valid
21cf0eae149567d34d24a3066727076b98dc6f20
645,914
def beautify_url(url): """ Remove the URL protocol and if it is only a hostname also the final '/' """ try: ix = url.index('://') except ValueError: pass else: url = url[ix+3:] if url.endswith('/') and url.index('/') == len(url)-1: url = url[:-1] return ur...
5c0ba43534758eb5d90ade1531881006ef58e8a8
645,915
import json def story(request): """ Provides a detailed HPACK story to test with. """ path = request.param with open(path, 'r', encoding='utf-8') as f: details = json.loads(f.read()) return details
aecf93441c62aa1671bb343275d96ab5b8f68614
645,917
def line_sep_before_code(ls): """for markdown""" r, is_code = [], False for ln in ls: if not is_code: if ln.startswith(' '): r.append('') is_code = True else: if not ln.startswith(' '): is_code = False r.ap...
a35a727d75f2802eee8fb648fa91a6a34916b7b8
645,918
from datetime import datetime import time def get_current_datetime_for_filename(): """Return a date & time timestamp that can be used for filenames.""" return datetime.fromtimestamp(time.time()).strftime(r'%Y%m%d_%H%M%S')
773c21fdded1466989300a031d41efef4271d510
645,919
def __verify_source_is_supported_extension(file_extension): """This function very if source is supported extension""" supported_extensions = [".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".txt", ".xml"] return file_extension in supported_extensions
74f68bae77600e94ac8cf5728040d2b6b39c2b31
645,920
def parse_model_cfg(path): """Parses the yolo-v3 layer configuration file and returns module definitions""" file = open(path, 'r') lines = file.read().split('\n') lines = [x for x in lines if x and not x.startswith('#')] lines = [x.rstrip().lstrip() for x in lines] # get rid of fringe whitespaces ...
f3eed138eeeb446b31ad75b11253b1649f69c49a
645,921
def make_str_content(content): """ In python3+ requests.Response.content returns bytes instead of ol'good str. :param content: requests.Response.content :return: str representation of the requests.Response.content data """ if not isinstance(content, str): content = str(content.decode()) ...
c8ccdf34a4e3375ebd09c15c94651e74f6af4f2b
645,922
def beta(R0, gamma): """ R0 from model parameters. """ return R0 * gamma
1c21be0be39e0b2ab6e1807e110adf892e13f15a
645,923
def alt_file_map_term_mixed(): """ Sample alternate file map with DOS line endings. """ return """abc 123\tMY NEW FILE 1\nxyz 999\tMY NEW FILE 2\r\n"""
04f83c29723d571987716fb0c4f53d02c685c787
645,924
import re def get_build_number_from_body(body): """Extracts the build number from the given body. Arguments: body {dict} -- The body as extracted by `extract_body()` Returns: str -- The build number if given. If there's an error extracting this or if the build numb...
0132f9bd41b4b4f4f2018c29f5a314ee9d2bf9db
645,925
def format_time(decisecond): """ Convert time in tenths of seconds into formatted string m:ss.t :param decisecond: int >= 0 :return: str """ assert isinstance(decisecond, int) assert decisecond >= 0 decisecond, tenths = decisecond//10, decisecond % 10 minutes, seconds = decise...
006489e1849642a5d63db32e08f535d8a6182fba
645,926
def make_iterator(args, lock, queue): """ Makes an iterator over args and passes the lock an queue to each element. """ return ((arg, lock, queue) for arg in args)
2eb2aefda8f29dd5dc776dd5b646f9f1ff4ba7a9
645,928
import pickle def pickle_save(obj, fp, verbose=1): """Save an object as a pickle file.""" try: with open(fp, 'wb') as f: pickle.dump(obj, f) except Exception as err: if verbose: print("Saving object failed. Error:", err) return False else: if verbose: print(...
eb536e4eacff6daae371b8b68b839c14f42a0366
645,929
import socket def is_valid_ip_address(ip_addr): """This method checks if string provided is a valid IP address Args: ip_addr (str): IP Address String Returns: (boolean): True/False """ try: socket.inet_aton(ip_addr) return True except (socket.error, TypeError): ...
9ff7cec7eaaa77ece911baaf11b0391d5c5c150b
645,930
import sys def is_windows(): """ Check if windows os >>> print(is_windows()) True or False Returns ------- bool: bool True or False. """ if sys.platform == 'win32': return True return False
855dde37d866a40998f31b161885764a32f91f03
645,932
def get_expected_text_data_header( identifier_name: str, use_header_guard: bool, string_literal_contents: str ) -> str: """:returns: the contents of the header file""" if use_header_guard: header_guard = identifier_name.upper() return f'#ifndef {header_guard}\n#define {header_guard}\n\nconst...
bf1aa08b28a32f130116603474cdd1bec82142c8
645,933
import argparse def get_args(): """get arguments""" parser = argparse.ArgumentParser( description='Create Python script', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('program', help='Program name', type=str) parser.add_argument( '-a', '...
9b40afe156a8d05c1a897f787035f129fb87c257
645,934
import json def pretty_print_json(obj) -> str: """Helper, takes generic python class/object and convert into pretty json str""" return json.dumps(obj, default=vars, indent=2, sort_keys=True)
f9565105ce5c7fb1d0dc11c3ec368c90cbe8c891
645,935
import os def make_folder(path, folder_name): """ Technical function to create folders to manage data of the project Arguments: path -- path where to create folder folder_name -- the nale of the folder to be created """ if os.path.exists(path+'/'+folder_name): return path+'/'+folder_na...
923663ce1a790952053bae39002d51e02228c514
645,936
def _parse_special_key(keystr: str) -> str: """Normalize a keystring like Ctrl-Q to a keystring like Ctrl+Q. Args: keystr: The key combination as a string. Return: The normalized keystring. """ keystr = keystr.lower() replacements = ( ('control', 'ctrl'), ('wind...
db399f710b0a4e7028071943444eb062188ab9c5
645,937
def sync_batch_request(func, params, get_data=lambda x: x["info"], limit=500): """ 同步请求接口 :param func: 请求方法 :param params: 请求参数 :param get_data: 获取数据函数 :param limit: 一次请求数量 :return: 请求结果 """ # 如果该接口没有返回count参数,只能同步请求 data = [] start = 0 # 根据请求总数并发请求 while True: ...
59d9dfe6c4503f3b7e11937091f33b8106746429
645,938
import torch def batch_torch_denormalize_box_params(box_params, scale=3): """ Denormalize the box parameters utilizing the accumulated dateaset statistics :param box_params: float tensor of shape [N, 6] containing the 6 box parameters, where N is the number of boxes :param scale: float scalar that scales...
28846d5e8e09542bb873d7cb2e57e67099a1da4d
645,939
def read_voca(path): """ open file from path and read each line to return the word list """ with open(path, 'r') as f: return [word.strip() for word in f.readlines()]
2ae35bc9918217c30dbfb7d3cc6e168424854d06
645,940
import locale def get_day_name(day): """ Get the short day name in the currently activated locale. :param day: :return: day 0 = Sunday """ # Locale keys are 1=Sun, 2=Mon, ... locale_key = "ABDAY_%d" % (1 + day) option = getattr(locale, locale_key) day_name = locale.nl_langinfo(...
b3326f4a1cab553fdd92a033002e70f4f69765c2
645,943
import torch def logsumexp1(X): """ X - B x K returns: B x 1 """ maxes, _ = torch.max(X, 1, True) lse = maxes + torch.log(torch.sum(torch.exp(X - maxes.expand_as(X)), 1, True)) return lse
960a514b2a4a8d59c443cc92ffcb9012087193e9
645,945
def color_to_str(C): """Convert color value to hex string.""" # Scale from [0-1] to [0-255] V = [int(round(c * 255)) for c in C] # Clamp values to [0-255] for i in range(len(V)): V[i] = max(min(V[i], 255), 0) return '#{:02X}{:02X}{:02X}'.format(V[0], V[1], V[2])
6b93f2484fabb237f1d9cf2c505c986043648a95
645,947
def num_permutations_filter_add(n_l, n): """ n_l 중에서 두개를 골라 합이 n 인 list of tuple 반환 중복 고려 x """ # from itertools import permutations # result = [] # for c in permutations(n_l, 2): # if c[0] + c[1] == n: # result.append((c[0], c[1])) result = f'from itertools import pe...
f934ae1613dcd10bc1243b30f1829cb45d9f8e6a
645,948
def findUTMZone(lon, lat): """Find utm zone for lon and lat values. lon -180 -- -174 -> 1 ... 174 -- 180 -> 60 lat < 0 hemisphere = S, > 0 hemisphere = N Parameters ---------- lon : float lat : float Returns ------- str : zone + hemisphere """ zone = int((int(l...
0b5d7323c1b84c8cf4429cb1e8a992bfacd803df
645,949
import struct def decode_ga(ga: int) -> str: """ Decodes a group address into human readable string representation >>> decode_ga(270) '0/1/14' """ if not isinstance(ga, int): ga = struct.unpack('>H', ga)[0] return '{}/{}/{}'.format((ga >> 11) & 0x1f, (ga >> 8) & 0x07, (ga) & 0xff)
c65d2f1808077bf0a34d1054bf7409f0c1c854af
645,950
def compare(reference, tested): """ Compare the two outputs according to a specific logic :return: True iff both input are equal """ epsilon = 0.01 for k,v in reference.items(): tested_vals = tested[k] ok = all (map( lambda x: (abs(x[1] - x[0])) <= epsilon, zip(v,tested_vals))) ...
24d2b3799263d8d79f273bc5b0506d1f5f5040ee
645,951
def generate_token() -> str: """Abstractly, generates a client Bearer token that passes auth with the Argo server for workflow submission""" return 'my-bearer-token'
4d15e4625d5635099b744b08bc77e5f9cbcc37ae
645,952
def create_case_footer(): """Create footer.""" return '\n'.join(( ' },', '', ))
b84a2f267e20f1b816a24a097c858a0d1ee51987
645,953
def ccw(a, b, c): """ 1: c is left of the line a->b -1: c is on the right of line a->b 0: c is on the line a->b >>> ccw(Vector(0, 0), Vector(3, 4), Vector(6, 8)) 0 >>> ccw(Vector(0, 0), Vector(3, 4), Vector(6, 9)) 1 >>> ccw(Vector(0, 0), Vector(3, 4), Vector(6, 7)) -1 """ ...
c445d11d2fe82236ae4aa42c2e21dfc33942bda2
645,954
import ast def get_literal_tuple(param_type): """ get literal option from annotation string and return result in tuple. """ s_index: int = str(param_type).index('[') e_index: int = str(param_type).index(']') str_list = str(param_type)[s_index + 1:e_index] res = ast.literal_eval(str_list) ...
8ee28a06fa10bc5ed8ac524c15bbd0bef0d2e1df
645,955
from pathlib import Path from typing import List def get_all_files_in_directory(path: Path) -> List[Path]: """ Returns all the files in a directory structure. For example, given a directory structure like:: dir_a: dir_b, file_a, file_b dir_b: file_c and you provide the path to ``dir...
339bade149a145336e68e3958b437937a89c720e
645,956