content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import os def env(varname, default=None): """ Use an environment variable's value inside your template. This filter is available even when your data source is something other that the environment. Example: ```jinja2 User: {{ user_login }} Pass: {{ USER_PASSWORD|env }} ...
e1abf62bfca433ff19f8be06be4f49cc87b5d777
689,692
def find_threshold_value(energy_element="Au", above_or_below="above", modality="esrf"): """We return the energy corresponding attenuation value used for bone segmentation Args: energy_element (str): what k-edge element are we trying to quantify (Au, I, Gd..) above_or_below (str): aobe or below ...
a840ff9d1795fe1134bf4e236447076154e8c79d
689,693
def order_processes(proc_metrics, metric_type): """ Orders results in generation directory in subdirectories numbered from 0 and up, the best result stored in the '0' subdirectory. The ranking is done by numbers in evals list, which are the results of the generation's metric to the image array. Parameters ...
b55f5a34f96c56606e557017deb5b5869625f030
689,694
def pluginName(): """ Return name of UnityFbxForMaya plugin @ingroup UnityFbxForMayaPluginVersion """ return 'UnityFbxForMaya'
61d9e6c623db1c5531b0519e8e8dbdbc702b50f9
689,695
def redistribute_area_isobar(temp_df, label, labeltypes, area_col, labeltype): """for tmt/itraq""" # with_reporter = temp_df[temp_df['QuanUsage'] == 'Use'] q = ".*{}.*".format(labeltype.lower()) with_reporter = temp_df[temp_df["SequenceModi"].str.contains(q)] reporter_area = ( with_reporter[...
71ea4d38b2962c643c26cd0858b73d544df2acee
689,696
import os def filename(path): """Return the filename without extension.""" return os.path.splitext(os.path.basename(path))[0]
291aecd951f68cacaeb0fb854a1839b6a85893e0
689,697
def letter(m) -> str: """One letter in the alphabet""" return str(m)
f34c971c74d9d86b60a80a7234889857b7093bd1
689,698
def roman_to_int(roman_string): """converts a Roman number to an integer""" if type(roman_string) is not str or roman_string is None: return 0 conversion = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} max_val = 0 total = 0 for roman_numeral in roman...
b8804037cd3905331ca0ea06793d209a4600c9d5
689,699
import asyncio def await_(coroutine): """Run coroutine in the current event loop""" loop = asyncio.get_event_loop() return loop.run_until_complete(coroutine)
efc74cb3448bc9d4b6d50de6bb77391ea2341e73
689,700
def get_total_roof_area(total_floor_area, total_roof_area, f, building_floors): """階層fにおける単位住戸の屋根面積の合計(m2)…………式(32) Args: total_floor_area(float): 階層fにおける単位住戸の床面積の合計(m2)…………入力1.2(2)6 total_roof_area(float): 階層fにおける単位住戸の屋根面積の合計(m2)…………入力1.2(2)10 f(int): 階層(-) building_floors(int): 建物の階数(...
409293abd805df0fd13f663db41af17fc92eee68
689,701
def compute_rsi(df, window=14): """Return RSI.""" delta = df['Price'].diff()[1:] up, down = delta.copy(), delta.copy() up[up < 0] = 0 down[down > 0] = 0 roll_up = up.rolling(window=window).mean() roll_down = down.abs().rolling(window=window).mean() # Calculate the RSI based on ...
8ad76cea4917acac5b777c37d3072a533d35493d
689,702
def build_response_body(sentiment_prediction, confidence): """ Returns a formatted dict containing sentiment prediction. :param sentiment_prediction: :param confidence: :return: """ return dict(sentiment='{}'.format(sentiment_prediction), confidence=confidence)
2095c382a62040535118c4eb377920739f403dd1
689,703
import json def get_original_trace_data(traces): """ 将traces处理成目标输入数据:每条记录包括id、pid、serviceId、serviceName、serviceType、startTime、traceId等字段 hadoop的traces是将traces组织在一起的 :param traces: :return:目标格式的List """ traceData = list() for trace in traces: i_dict = json.loads(trace) ...
5f92081ba49efccc9296c0abae7113076663580a
689,704
def is_mapping_table(table_id): """ Return True if specified table is a mapping table :param table_id: identifies the table :return: True if specified table is an mapping table, False otherwise """ return table_id.startswith('_mapping_')
165e69766713a8e612f2823790363128c16d090e
689,705
def fsplit(pred, objs): """Split a list into two classes according to the predicate.""" t = [] f = [] for obj in objs: if pred(obj): t.append(obj) else: f.append(obj) return (t, f)
c5a9c9a952d07218408c6cd869ca95d2051ba1ec
689,707
from functools import reduce def combine_result_list(name, taskdep) : """ 该函数用来组合之前的若干任务的输出,将它们的stdout联结起来。 task关键字可以帮助我们获得任务的所有的参数的信息 previous_result_key_list : 之前的结果被传递的key 这里的result是新的结果。 以后建议可以自定义相应的reducer """ reducer_builder = lambda prev_result, sep, init : reduce (lambda x, y...
447e38d9df80b559f3fbc8842144dd91da2ae103
689,708
import os def extract_env_name(file_path): """Return environment name for given requirements file path""" return os.path.splitext(os.path.basename(file_path))[0]
f0785f0fca53beb0ec101cfedd027a1c63fa1b95
689,709
def are_connected(graph, start, end): """DFS.""" visited = set() q = [start] while len(q): at = q.pop() visited.add(at) for next in graph[at].keys(): if next not in visited: q.append(next) return end in visited
0432fd785f9eea57ed092b25003f0bf013701318
689,710
def get_sample_sequence_ids(samples_lst): """list of just sample prefix""" sample_sequence_ids = [] for sample in samples_lst: sample_sequence_ids.append(("_".join(sample.split("_")[0:2]))) sorted_sample_sequence_ids = sorted(set(sample_sequence_ids), key=lambda x: float("." + x[3:8])) retur...
1d4472dbb52e666f4f1e61c4e196e849175eeb60
689,712
from typing import Sequence def strong_british_accent( text: Sequence, *, add_dashes: bool = True, _print: bool = False ): """Converts your given string/array to a kind-of strong british accent (if you're nonsensical about it...) :param text: The text/array you want to convert to :param add_dashes: A...
cec811bac8f9bd11f109676a63611eea7e8ab126
689,713
import torch def pad_collate_fn(data): """ parameters: ----------- data (tupple): features has shape (T,F) returns: -------- packed_features (PackedSequence) : frame_lengths (tensor) : dtype = torch.long t...
4d98f87c75a2fb3b487f640f4d6293803dfbb3f6
689,715
import struct def Codingfunc(N,L): #Coding:[N:number of repetitions, L:length of single/multiple sequence] """This is the version 'A' of coding function, that codes compression data into one byte as a signed char variable. Maximum length of repeates sequence: 8 bytes, maximum number of repeated sequen...
d518f4a768cde2be5994ed46cf88432b655da674
689,716
def _attr_key(attr): """Return an appropriate key for an attribute for sorting Attributes have a namespace that can be either ``None`` or a string. We can't compare the two because they're different types, so we convert ``None`` to an empty string first. """ return (attr[0][0] or ''), attr[0][...
6f29da6f0906a9403150667b93f24f5b37386a1f
689,717
import sys import os def terminal_supports_color() -> bool: """ Determine whether the current terminal supports colored output. """ platform = sys.platform is_supported_platform = platform != 'win32' or 'ANSICON' in os.environ is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty() if ...
bbc921726a93269ae1c936bf7374ea5f0a1d1c2a
689,718
import bz2 def unpack(requests): """Unpack a list of requests compressed in bz2""" return [bz2.decompress(request) for request in requests]
b4df59d4c6e9f47558c36aaaa5f42d73bd590d23
689,719
def get_subdivision_resource(country_alpha2: str, subdivision_code=None) -> str: """Get the """ if subdivision_code is None: return 'country/{country_alpha2}/subdivision'.format(country_alpha2=country_alpha2) else: return 'country/{country_alpha2}/subdivision/{subdivision_code}'.format(count...
bf5d73a28e2e08ae06a1be3c7cefebb501c04885
689,720
import functools def asynccached(cache, key): """ Returns decorator function to cache async function results. """ def decorator(func): if cache is None: async def wrapper(*args, **kwargs): return await func(*args, **kwargs) else: async def wrapper(*a...
e984fa60523618d5d00ebd476f54c1574acd1ade
689,721
def track_revised_properties(cls): """Tracked properties """ cls.on_create = [] cls.on_modify = [] for method in dir(cls): fcn = getattr(cls, method) if hasattr(fcn, "on_create"): cls.on_create.append(fcn) if hasattr(fcn, "on_modify"): cls.on_modify.ap...
6d79db33084f64ccf1fe5fe99893e7b48d74c485
689,722
import torch def my_l1(x, x_recon): """Calculate l1 loss Parameters ---------- x : torch.cuda.FloatTensor or torch.FloatTensor Input data x_recon : torch.cuda.FloatTensor or torch.FloatTensor Reconstructed input Returns ------- torch.cuda.FloatTensor or torch.FloatTen...
a7736bd2d4160546176520a6adbd1c218dc5cc14
689,723
def create_params(): """max_results max =100""" return {"tweet.fields": "lang,author_id", "max_results": "100"}
cea94aa3aa1ab30f6bd21a93d9aba77922fb8352
689,724
def is_upper(val): """Checks all upper case in the string""" return True if val.upper() == val else False
367e46d63f66c38d1f5b56ac9823b89b75953433
689,725
def play_again(): """Solicits a y or n from the user to see if the user would like to play again""" user_input = "" while user_input != "y" and user_input != "n": try: user_input = input("Would you like to play again? (y/n): ").lower() if len(user_input) > 1: ...
de48d998b10a522bf08161ba845adf930ecf5cdd
689,726
def getCityLocs(city): """ 城市边界信息列表 :param city: """ newCitylocslist = { 'beijing': { 'north': 41.0500, # 41.050, 'south': 39.4570, # 39.457, 'west': 115.4220, # 115.422, 'east': 117.5000, # 117.500 } } return newCitylocslist[city]
f83f27dc2f7e2bf18206be0546c00c6ebd16b101
689,729
def step_lstm(lstm, input_, h_0_c_0=None): """LSTMCell-like API for LSTM. Args: lstm: nn.LSTM input_: [batch_size, input_size] h_0_c_0: None or h_0: [num_layers, batch_size, hidden_size] c_0: [num_layers, batch_size, hidden_size] Returns: output: [batc...
3172267af8463dd491a9f58425bc5d8788fc119c
689,730
import string def title_to_url(title): """ Converts a title string to a valid string for a url. White space will be replaced by dash, case will be set to lower and all punctuation marks will be removed. :param title: the title string. :type title: str :return: a valid url string. :rty...
a077b425dd1b472d11ae178e8477577353120efa
689,731
def create_prediction_series(lis, predictor): """ this function returns a list, lets call it p, of the length of the given lis such that p[i] = the prediction of the i'th element in lis given the first i-1 elements to make things nice, p[0] would be equal to lis[0] :param lis: :param predictor:...
34ae81eaa8ed9287088c1fa726029953db728e6f
689,732
def usable_class_name(node): """Make a reasonable class name for a class node.""" name = node.qname() for prefix in ["__builtin__.", "builtins.", "."]: if name.startswith(prefix): name = name[len(prefix) :] return name
f5f6b9a8e8da69cc7d04ea177b9a93ef823ef7e1
689,733
def normalize_url(url): """Normalize the url by removing the final "/" if it exists :param url: The given url :type url: str :return: The normalized url :rtype: str """ if url.endswith("/"): return url.rpartition("/")[0]
2d567bf5bd33bc343d867b46f10bc1ede6ea88ae
689,734
def is_pass_transistor(pip_json): """ Returns boolean if pip JSON indicates pip is a pass transistor. Always returns False if database lacks this information. """ if 'is_pass_transistor' in pip_json: return bool(int(pip_json['is_pass_transistor'])) else: return False
6a6180f116dc3155450abb70ddde5884184af7cf
689,735
def task10(number: int) -> None: """ Function that take an integer number as string and print the "It is an even number" if the number is even, otherwise print "It is an odd number". Input: number Output: None """ if number % 2 == 0: print("It is an even number") else: p...
fba82df5a9bb5c1490ae5c25d778c73b8c973121
689,736
def has_method(obj, method_name: str) -> bool: """ Returns True if the provided object (`obj`) has the named method (`method_name`). """ return callable(getattr(obj, method_name, None))
123d65b3d86427f3f7703cacac3580d818f96c22
689,737
def _search_info(input, kb, db): """ search_info - function to search info in Knowledge base given input tokens Inputs: - input : dict Dictionary of entity-key and list of words - kb : Pandas dataframe Dataframe of tokens x documents - db : list List of texts Outputs: - output : TBD """ # retriev...
772508b62271c46ac8cc50a886c1c6abeb8daac8
689,738
import os import fnmatch def FindInDirectory(directory, filename_filter): """Find all files in a directory that matches a given filename filter.""" files = [] for root, _dirnames, filenames in os.walk(directory): matched_files = fnmatch.filter(filenames, filename_filter) files.extend((os.p...
cce91c0331c5b32c8185e5a72783e76ac00b85c2
689,739
def make_naive(value, timezone): """ Makes an aware datetime.datetime naive in a given time zone. """ # If `value` is naive, astimezone() will raise a ValueError, # so we don't need to perform a redundant check. value = value.astimezone(timezone) if hasattr(timezone, 'normalize'): # ...
6b0464882cc50c80f410a3d78bd6baff3024da89
689,740
def ensure_other_is_scalar(matrix_method): """Simple decorator to check if second argument to a matrix method is a scalar.""" def wrapper(self, other, *args, **kwargs): if not isinstance(other, (int, float, complex)): raise ValueError(f"Cannot use {matrix_method} with 'other' of type {type(o...
216c74420bc7ffeb043ce004c1922e7f6f484f58
689,741
def switch_team(team): """ Returns the opponent team given the specified team. """ if team == 'home': return 'road' elif team == 'road': return 'home'
ab60a23b89046ebc1483576b260dd2b6edd6ea98
689,742
def get_extension(local_file: str) -> str: """Extract the file extension of a file.""" return local_file.rsplit(".", 1)[1].lower()
13a02190f04a42374466b93ba70d0fa5264ba306
689,743
import re def parse_overlaps(overlaps_file): """ External overlap [SS] of CM000298.1/96020656-96020744 with RF00998:CM000298.1/96020650-96020744 by fullOL External overlap [SS] of CM000316.3/123249182-123249270 with RF00998:CM000316.3/123249176-123249270 by fullOL """ overlap_accs = set() with...
8e7db20229f3444801f524ba5a72797965d0e3bc
689,744
def normalize(vector, size): """ Normalizes a vector given the vector and the corresponding document length """ for word in vector: vector[word]=vector[word]/float(size) return vector
ca8f8827c0c70283d38e7caa8786e171ef8e40bc
689,745
def _is_overlap(reg_start, reg_end, start_loop_idx, all_idx, regions): """ Chech whether [reg_start, reg_end] overlap with `regions` """ overlap_idx = [] first_time_ovlp = True next_start_idx = start_loop_idx for i in all_idx[start_loop_idx:]: if reg_start > regions[i][1]: ...
b21d090366296e4d1815ecfe1be8ceac5d2a05fd
689,746
def get_complex_replay_list(): """ For full replays that have crashed or failed to be converted :return: """ return [ 'https://cdn.discordapp.com/attachments/493849514680254468/501630263881760798/OCE_RLCS_7_CARS.replay', 'https://cdn.discordapp.com/attachments/493849514680254468/4971...
62aad17eb62002ac6923f0ae11e9776a374839ae
689,747
def is_same_dictionary(a, b): """Shallow dictionary comparison""" keysA = set(a.keys()) keysB = set(b.keys()) sharedKeys = keysA & keysB if len(keysA) != len(keysB) or len(sharedKeys) != len(keysB): return False for k, v in a.items(): if b[k] != v: return False re...
6bb18387bcee5c605845a80975af9c9446ef6dc8
689,748
import pickle def load_pkl(path: str, load_mode: str = 'rb'): """ Read a pickle file. :param path: str, filepath to read :param load_mode: str, read mode :return: contents of the pickle file """ return pickle.load(open(path, load_mode))
14397cc224f73ba917b9be80f79a2d98df65fcae
689,751
def first_neighbours_last(batches, current_batch_idx, nb_left, nb_right): """Build a sublist from a large batch list. This is used to display batch links for a large table. arguments: * :param batches: a large sequence (may be a batches as well) * :param current_batch_idx: index of the current b...
472d5bce1d137742f6844222c148d2063306c688
689,752
def get_instance_from_class(klass, **init_parameters): """Return a class instance given class-name-prefixed init parameters""" # Filter backend-related parameters. Parameter name is supposed to start # with the backend name names = filter(lambda p: p.startswith(klass.name), init_parameters.keys()) ...
b4497589145eaefa7e65c5f9b707b99a3f0154ac
689,753
def limit_x(x, limit): """ This module limits the values to the range of [0,limit] """ x_gr_limit = x > limit x_le_limit = x_gr_limit * limit + (1 - x_gr_limit) * x x_gr_zero = x > 0.0 x_norm = x_gr_zero * x_le_limit return x_norm
7cc96bc7ef7d0b653fb2a798350001574d8a02e0
689,754
from typing import Counter def choose_top_pos_from_data(df): """ :param df: dataframe(dtype:pandas dataframe) :returns: a dict with the top three pos tags associated with a token in the entire dataset. """ counter_dict = {} unique_tokens = df['inputs'].unique() for token in unique_tokens: ...
1f1110149601f7a3716d688af0154d63919cc001
689,755
import numpy def p_adjust_bh(p): """ Using implementation from https://stackoverflow.com/questions/7450957/how-to-implement-rs-p-adjust-in-python/33532498#33532498 Benjamini-Hochberg p-value correction for multiple hypothesis testing. """ p = numpy.asfarray(p) by_descend = p.argsort()[::-1] ...
6c4d743c7a42bbd5a5b1f687e4d684e9ea1b945c
689,756
def add_table_ends(para, oformat='latex', caption="caption-text", label="table", np=2, align='c', header=None): """ Adds the latex table ends :param para: :param oformat: :param caption: :param label: :return: """ if len(align) == 1: a_str = "".join([align] * np) else: ...
35d3f6e602dc3a8c30760f9faaaa0f7957d99188
689,757
import csv def fetch_education_urls(input_file): """ Given a local input file, parse it and return a list of GOV.UK URLs. """ documents = [] with open(input_file, 'r') as f: reader = csv.reader(f) # skip headers next(reader, None) documents = list(reader) retur...
b171eb2b961c68752bffc7acc2ae028fc07e82db
689,758
import torch def ripple_linear(input:torch.Tensor, out_features:int, weight:torch.Tensor, bias:torch.Tensor): """ Assuming we flatten everything if there are more than 2 input dimensions Input dimension: BS x IN Weight dimension: OUT x IN x 2 Bias dimension: OUT x (IN + 1) Output dimension: BS...
5d454ccc95673b438119dc5ef7107a3eeeae14d0
689,759
import sys def chose_proper_resolution(args, old_width, old_height): """ according the ratio or weight and hegiht to chose a proper resolution return the proper resolution """ if args.ratio > 0: """ use ratio to resize (0,1) . It's very dangerous action which will modify...
b688db79c57280277c965fce7662bbbf4f28cf8c
689,760
def createPointWkt(coords): """Create WKT POINT string. Args: coords (list): Two item list representing single point coordinate. Returns: str: WKT POINT string. """ return 'POINT(' + str(coords[0]) + ' ' + str(coords[1]) + ')'
13b1a4864bb9cccc56e3c34bc340f1a2f4d4c3ee
689,761
def mu_lambda(E=None, nu=None, lam=None, mu=None): """Get lame's parameters. Build the lame constants of a material using the elastic constants for isotropic materials. You must specify exactly two of the four available constants. For example, you can provide E and mu as arguments. Args: ...
665891693e265a485d2a618e70f4bb01f209b1c1
689,762
import os import csv def read_infomap(args): """ Read infomap data as generated by CLICS3. """ with open(os.path.join(args.input, "infomap.tsv")) as tsvfile: reader = csv.DictReader(tsvfile, delimiter="\t") data = { row['concepticon_id'] : row for row in reader...
f3268fed55f10a701e88fb31b206a828c2008240
689,763
import re def _match_regex(pattern: str, path: str) -> bool: """True if `path` matches `pattern`.""" return re.match(pattern, path) is not None
d25fdfc6c87486b081f549e553a09e1d5d19cfdf
689,764
def cleanup_dfm_multidomains(grid): """ Given an unstructured grid which was the product of DFlow-FM multiple domains stitched together, fix some of the extraneous geometries left behind. Grid doesn't have to have been read as a DFMGrid. Cell indices are preserved, but node and edge indices are...
d8a47efedd0cbdd7628f94674cc44054f028dc16
689,765
def clean_path(source): """ Replace backslashes from source.file_name with a slash """ source.file_name = source.file_name.replace('\\', '/') return source
eb9cef7fd346b79630fce9d09c3748ca5cacbd4d
689,766
def complaint_notification_query(self): """查询投诉通知回调地址 :param: url: 通知地址,仅支持https。示例值:'https://www.xxx.com/notify' """ path = '/v3/merchant-service/complaint-notifications' return self._core.request(path)
924bd484a48d213a6f3d28f25ce04669aba21c1f
689,767
import re def remove_non_alphanumeric_symbols(s): """Make text usable for attribute name""" return re.sub(r"\W", "_", s)
01e2db12df4baaee11fbdb1ec2f6684b4d1a3f0c
689,768
def load_module(name): """Load module in the format 'json.tool'""" mod = __import__(name) for sub in name.split('.')[1:]: mod = getattr(mod, sub) return mod
0d6ee3f72c1ac960972d7ec75c4c9fe003711923
689,769
def build_falloff(parameters, falloff_function): """Creates falloff reaction Troe parameter string Parameters ---------- parameters : numpy.ndarray Array of falloff parameters; length varies based on ``falloff_function`` falloff_function : {'Troe', 'SRI'} Type of falloff function ...
c7937f524f720e903998fcf38f6f5bed9e361d94
689,770
import time import hmac import hashlib def verify_request( *, timestamp: str, signature: str, request_data: bytes, signing_secret: str ) -> bool: """ This function validates the received using the process described https://api.slack.com/docs/verifying-requests-from-slack and using ...
e3901cf8abc467e2203d8faca638754b6042bdf6
689,771
def add_fit_args(parser): """ parser : argparse.ArgumentParser return a parser added with args required by fit """ # Training settings parser.add_argument('--batch-size', type=int, default=128, metavar='N', help='input batch size for training (default: 64)') parser.ad...
2312324be9bd0b0dd95dd57b799496b9bf74c31b
689,772
from functools import reduce def bytes_to_int(bindata): """Convert a sequence of bytes into a number""" return reduce(lambda x,y: (x<<8) | y, map(ord,bindata), 0)
9ab8e1c2f66d0d385cf394c9a674e09d9b8bbded
689,773
import re def word_filter(word): """ The filter used for deleting the noisy words in changed code. Here is the method: 1. Delete character except for digit, alphabet, '_'. 2. the word shouldn't be all digit. 3. the length should large than 2. Args: word Returns: ...
c29e80c7e6839a576b95ee99b18e81a31b95a020
689,774
def vocabulary_json(): """Returns the schema location.""" return { "$schema": "local://vocabularies/vocabulary-v1.0.0.json", "description": { "en": "Test affiliation description", "es": "Descripcion de una afiliacion de test" }, "icon": "test.png", ...
dcff81116ac3b14455093cf8b5e9a91d15f65062
689,775
from datetime import datetime def iso_8601_to_date(string): """YYYY-MM-DD --> datetime""" if ":" in string or len(string.split("-")) != 3: raise ValueError(f"Date format should be 'YYYY-MM-DD' got '{string}'") return datetime.strptime(string, "%Y-%m-%d")
158970ab0e284ab064cbdff90ed00512a39e957c
689,776
import subprocess def call(*args) -> bytes: """Call args in shell and return stdout.""" result = subprocess.run(args, capture_output=True) result.check_returncode() return result.stdout
0bda032dc75450c2c948c3e26805ae801c0318fb
689,778
def page(document): """ second page of three page document """ next(document) return next(document)
3ddfd661dd68d4ab81a374d3589c34f64c49cb25
689,779
def brightness_correlate(bRGB_o, bL_or, Q): """ Returns the *brightness* correlate :math:`B_r`. Parameters ---------- bRGB_o: ndarray, (3,) Chromatic adaptation exponential factors :math:`\\beta_1(R_o)`, `math:`\\beta_1(G_o)` and :math:`\\beta_2(B_o)`. bL_or: numeric ...
745df4a94a43c70113b4905cdd0b9fc852390f05
689,780
import json def get(event, context): """Handle the GET request and return the full lambda request event""" return { "statusCode": 200, "body": json.dumps(event) }
f55c3c8ae3387a8019d601fc0c597840cf73c929
689,781
import importlib def import_model(type_module, type_name): """ :param str type_module: :param str type_name: :return: Model type :rtype: type :raise ImportError: When the model cannot be found. """ try: mod = importlib.import_module(type_module) except ImportError as e: ...
0cbda14880f73854edec6d67445aee9b5528e07e
689,782
def combine_query(self, combine_out_trade_no): """合单查询订单 :param combine_out_trade_no: 合单商户订单号,示例值:P20150806125346 """ params = {} if not combine_out_trade_no: raise Exception('combine_out_trade_no is not assigned') else: params.update({'combine_out_trade_no': combine_out_trade_no...
a8b41a6605588ebdd864034631519d55de3df098
689,783
def rgb_to_hex(rgb): """ [255,255,255] -> '#FFFFFF' """ # Components need to be integers for hex to make sense rgb = [int(x) for x in rgb] return "#"+"".join(["0{0:x}".format(v) if v < 16 else "{0:x}".format(v) for v in rgb])
9db27a9744e1bf8de46eff901d423de9be12426a
689,784
import re def float_from_str(text): """ Remove uncertainty brackets from strings and return the float. """ return float(re.sub("\(.+\)", "", text))
4567abb8ba6c52efa3b37bddcb17dc351ba37dcd
689,785
import string def capwords(value, sep=None): """ Split the argument into words using str.split(), capitalize each word using str.capitalize(), and join the capitalized words using str.join(). If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a sin...
e481cab8af670b41130a1728869fa424e07ed5b8
689,786
def relevance_gain_np(grading, max_grade): """Plain python version of `relevance_gain`, see the documentation of that function for details.""" inverse_grading = -grading + max_grade return (2 ** inverse_grading - 1) / (2 ** max_grade)
2a54037924f0995756e2448e7ac0135d5ded3fcb
689,787
import os def get_current_working_directory(): """Return the current working directory Return: - String: File path of the current working directory """ return os.path.abspath(os.path.dirname(__file__))
d66331b4e66edf750fdcc7d4b2f772f317925bf2
689,789
def is_float(v): """if v is a scalar""" try: float(v) return True except (ValueError, TypeError): return False
bff78eb344434272dea65e4cdcff1dea52a1e255
689,790
def discrete(vector_1, vector_2): """ compute DISCRETE metric """ for i in range(len(vector_1)): if vector_1[i] != vector_2[i]: return 1 return 0
b40f021c2bb0ecc0d5be730262e93c83f4f27053
689,792
def sql_name_pattern(pattern): """ Takes a wildcard-pattern and converts to an appropriate SQL pattern to be used in a WHERE clause. Returns: schema_pattern, table_pattern >>> sql_name_pattern('foo*."b""$ar*"') ('^(foo.*)$', '^(b"\\\\$ar\\\\*)$') """ inquotes = False relname = "" ...
43dc720998ce063c6d5b20897bb1a1058063073e
689,793
def escape_generic_filter_value(anything: str) -> str: """ Escape anything, so that it can be used in ldap queries without confusing the server. According to the LDAP spec, there's a set of common characters that need escaping: rfc4514 (https://tools.ietf.org/html/rfc4514). RFCs that define new LDAP at...
fb23a7210c5adfac9faff2b1da44110cf72af867
689,794
def filter_OD(origins, destinations): """ takes lists of origins and destinations in (1D notation) and returns list of tuples with OD coorinates """ if len(origins) == len(destinations): return list(zip(origins, destinations)) else: return []
b46f50a3fcc3a602116eda549eb2fdec31c95bcb
689,795
import os def get_files(directory): """Get all relevant files and output an artist-album-filename dict""" if not os.path.isdir(directory): raise ValueError(f"Directory {directory} does not exist") output_dict = {} for root, _, files in os.walk(directory): for filename in files: ...
f7d5008a6c6479dfc23ceed25bc4a8304ae8981e
689,796
import math def calculate_decay_factor(dc, segments): """ McDougall and Harrison p.75 equation 3.22 the book suggests using ti==analysis_time-end of irradiation segment_i mass spec uses ti==analysis_time-start of irradiation segment_i using start seems more appropriate ...
5c766a5610d0e1df49f425aaf67a696f32477765
689,797
import os import yaml import base64 def get_test_data(): """All variables are stored in this encoded block""" encoded = os.getenv("TEST_DATA") if not encoded: return {} data = yaml.safe_load(base64.b64decode(encoded.encode()).decode()) return data
950476cb6cd515cfb4ac7f7237e34b9966000b52
689,798
from typing import Tuple def do_instruction(current_position: int, accumulator_value: int, instruction: int, instruction_value: int) -> Tuple[int, int]: """Perform instruction.""" if instruction == 0: current_position += 1 elif instruction =...
5fcdd85e875fbd65a295f4c25e5f14cb7a786d4f
689,801
def _check_imports(): """ Dynamically remove optimizers we don't have """ optlist = ['ALPSO', 'CONMIN', 'FSQP', 'IPOPT', 'NLPQLP', 'NSGA2', 'PSQP', 'SLSQP', 'SNOPT', 'NLPY_AUGLAG', 'NOMAD'] for optimizer in optlist[:]: try: __import__('pyoptsparse', globals(), locals...
6cdcd7a27da0c1275f41161cfb6e98330bb23630
689,802
def get_vertex_names_from_indices(mesh, indices): """ Returns a list of vertex names from a given list of face indices :param mesh: str :param indices: list(int) :return: list(str) """ found_vertex_names = list() for index in indices: vertex_name = '{}.vtx[{}]'.format(mesh, inde...
19ba81833a825310ae6e8958500ab60fe4ea3ac9
689,803