content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def checkValidity() -> bool: """ Checks whether the inputted matrix is square and non-singular. Returns True if this is the case, false otherwise. """ if numRows != numCols: print("inputted matrix is not square :(") return False if np.linalg.det(inputMatrix) == 0: pr...
24c796fd99124c1a200b245b3800ea1cae1f12eb
74,020
def new_ca(request, sa_id): """Create a new competency area for a given general subject area.""" sa = SubjectArea.objects.get(id=sa_id) organization = sa.organization # Test if user allowed to edit this organization. if not has_edit_permission(request.user, organization): redirect_url = '/no...
0c7cf2bcc6b5ed90e5ee3dec7c5905b84ff5b1cf
74,021
def expected(player1, player2): """ Calculate expected score of player1 vs player2 given elo rankings. Args: player1 (BaseAgent): Agent for whom the score is being calculated. player2 (BaseAgent): Agent against whom player1 played. Returns: The expected score of the matchup. ...
90551b04b15ce62a1d2c5d7022d9402b3efdba60
74,022
def sorted_pos(labels): """ Return unique positive labels in ascending order""" idx = sum(labels, []) pos = [i for i in idx if i > 0] return list(np.sort(np.unique(pos)))
90c80e75f8f1c4ec6e03f5629fcff7a1090eda78
74,023
from warnings import warn from functools import reduce def rreduce(fn, seq, default=None): """'readable reduce' - More readable version of reduce with arrity-based dispatch; passes keyword arguments to functools.reduce""" warn(DeprecationWarning( "rreduce is deprecated and will be removed in futur...
bb82cdf712c87885103d61f7c37fa588e8bdac6b
74,024
import hashlib def write_to_blobstore(content, old_blobinfo=None): """Write content to blobstore. Args: content: A byte-string. old_blobinfo: An optional BlobInfo object used for comparison. If the md5_hash of the old blob and the new content are equal, the old blobkey is returned and not...
77654e8ee9d6065f741634d06554ab3dc1929d42
74,025
def compute_trunc_basis(D,U,eng_cap = 0.999999,user_rank={}): """ Compute the number of modes and truncated basis to use based on getting 99.9999% of the 'energy' Input: D -- dictionary of singular values for each system component U -- dictionary of left singular basis vector arrays eng_cap -- f...
cdd4837802934203e7c4d85a6874ce3d8d9747c6
74,027
def valid_pass(password): """ Validar valores ingresados de password. """ return PASS_RE.match(password)
be8888a4499db2465db71b2ac741fbaf80b001a3
74,028
def retirement_401k_report(income=None, retirement=None, start=PeriodStart.this_year, end=PeriodEnd.this_year, contribution_limit='18000.0'): """ Report that will calculate how much has been contributed to the retirement accounts from the income accounts provided. :param incom...
04f8c8786f74d8f03d9af42ad18c22d62109fc55
74,029
def policy_query(policy, database): """ Renders a stripped policy creation query :param policy: Policy config dictionary :param database: Name of the database :return: Stripped policy query """ return strip_query( config['policy_template'].format( policy=policy_name(poli...
4065ee3f8bf1b55109117faa91ce4a3dc39d24ca
74,030
def round_state_to_increment(state, increment): """ Extension of round to increment to the state vector :param state array(3)[float]: [x, y, theta] :param increment float: increment to round state to (just the position) :return array(3)[float]: rounded state """ new_state = np.array(state) ...
11bb9e5d9d6a30b2ceb664af086094b84ae67153
74,031
from numpy import dot, floor from numpy.linalg import inv from method import error def are_periodic_images(pos0, pos1, invcell=None, cell=None, tolerance=1e-8): """ True if two vector are periodic images of one another :param pos0: First position :param pos1: Second positi...
4b28530d69baa54fd763703086ba110737261bda
74,032
def get_contents_entry(node): """Fetch the contents of the entry. Returns the exact binary contents of the file.""" try: node = node.disambiguate(must_exist=1) except SCons.Errors.UserError: # There was nothing on disk with which to disambiguate # this entry. Leave it as an Ent...
44bdfe0ec5c118992896fca53658abf28d99c207
74,033
def make_page(s: str, f=lambda: {}, methods=['GET']): """ Takes in a string which specifies both the url and the file name, as well as a function which provides the kwargs for render_template. """ title = s.split("/")[-1] def func(): val = f() if isinstance(val, dict): return fla...
74123efcff97040934fae635d1c393b243069e95
74,034
import torch def lane_nms_gpu_old(dets, scores, pad_shape, iou_threshold=0.05): """ :param dets: (torch.Tensor): boxes in shape (N, 4). :param scores: (torch.Tensor): scores in shape (N, ). :param thresh: :return: """ #print('nms_before_len', len(dets)) order = torch.argsort(scores, d...
a771a93a702d6e2d876093aa885c08c4ec4f522b
74,035
def topography(x,y): """Complex topography defined by a function of vectors x and y.""" z = -x/100 # Step id = ( 2 < x ) & (x < 4) z[id] += 0.4 - 0.05*y[id] # Permanent pole id = (x - 8)**2 + (y - 2)**2 < 0.4**2 z[id] += 1 # Pole 2 #id = (x - 14)**2 + (y - 3.5)**2 < 0.4**2 ...
dba3e02ff5c5dd11c60901318bc9550f2eecea60
74,036
def get_predictors(results): """Get predictors for logistic regression.""" assert len(results) == 200 y = [] x = [] for (_, trial1), (_, trial2) in zip(results.iloc[:-1].iterrows(), results.iloc[1:].iterrows()): transition = 2 * int(trial1.common) - 1 reward = 2 * trial1.reward - 1 ...
240a0d32221e32eda58b86568b5975cdcdd3c475
74,037
def sanitized_string(text): """ Ensures strings are properly sanitized and no special characters are present. """ r = inflection.transliterate(text) r = r.replace(' ', '-') return inflection.underscore(r).lower()
b5b22465a878ca2dceb194c4f0f09b3f5277b755
74,038
def graph_coordinates(list_of_chromosomes): """Iterate through list of chromosomes and return X (as center for graph) and Y coordinates for plotting. Args: Returns: chrom_ybase(int) chrom_centers(int) """ ybase = YBASE chrom_ybase = {} chrom_centers = {}...
145af5cac524c8de8eea46d2c59e92b2a0d8cf48
74,039
def preprocess(path2sample, config, config_Dataset): """ preprocess each sample""" data_list = [] label_list = [] # imread data and label for time_iter in xrange(len(path2sample)): data = cv2.imread(path2sample[time_iter][0], 3) if config_Dataset.USE_IMAGE_ROI: d...
e227c881186eac8d20f5838cad2bf304df43cbe0
74,040
def class_img2sino(x, phi, size, sinogram_shape): """Compute the mapping of the orientation class entry of the Wavefront set from images to sinograms Parameters ---------- x : numpy array, position of the singular point in the image phi : float, orientation angle of the singular point in the i...
9eaf0db4633ec7e66c3b270c09dea99d204c3762
74,041
def get_data_set(set_name, data_type, unique_answers=False): """ Retrieve all the question and their respective answers from a data set (possible options are "test", "valid", and "train"). :param set_name: Name of data set. :param unique_answers: Flag to indicate whether duplicate answers to a ques...
be6c4c977db897f3376f73a863a5b2cb534e1591
74,042
def offset_random_web(seed, amount=1): """ Given a seed color, generate a specified number of random colors (1 color by default) determined by a randomized offset from the seed. :param seed: :param amount: :return: """ return rgb_to_web(offset_random_rgb(seed, amount))
b07cfec9bd175c907345aa47d13b536e9f448c6d
74,043
import re def check_password_format(password): """校验密码格式 Args: password (str): 密码 Returns: boolean: 格式符合返回True,格式错误返回False """ pattern = re.compile('\w{8,16}') if pattern.match(password): if re.search('[0-9]', password) and re.search('[a-z]', password): re...
b0923972f22b08298df8aa9c83314787ebefb8a8
74,044
from .dc_mosaic import (ls7_unpack_qa, ls8_unpack_qa, ls5_unpack_qa) processing_options = { "LANDSAT_5": ls5_unpack_qa, "LANDSAT_7": ls7_unpack_qa, "LANDSAT_8": ls8_unpack_qa } clean_mask = None # Keep all specified cover types (e.g. 'clear', 'water'), so logically or the separ...
8749873fd96cec9faf046140728a9a01e41bab61
74,046
def MultipleRegression(x_names=None, y_name=None, df=None, alpha=0.05, precision=4, show_summary=True, assessment=True, t_test_c=0, t_test_option='two-tail'): """ assessment is equivalent to t_test: boolean """ res_dict = dict() y_data = df[y_name] X_data_T = np.array(df[x_names]) X_data = p...
b2b6e48e66f04e9b9141338c03010ec224013bd2
74,047
def calc_pmi(counts, cds): """ Calculates e^PMI; PMI without the log(). """ sum_w = np.array(counts.sum(axis=1))[:, 0] sum_c = np.array(counts.sum(axis=0))[0, :] if cds != 1: sum_c = sum_c ** cds sum_total = sum_c.sum() sum_w = np.reciprocal(sum_w) sum_c = np.reciprocal(sum_c...
6686a7a1c9b11707c206734cfd096e5e24100271
74,049
def corpus(request): """ A utility fixture to merely execute the actual fixture logic as necessary. Args: request: The pytest indirect request object, which has a param object for the underlying fixture argument. Returns: The value of the execution of the corpus fixture. ...
3c6986296a17145bc3b40cc84e2b62acb5c8f00c
74,050
def filtre_operations(operations: dict[int, any], objectif: int) -> dict[int, any]: """Exclus les opérations qui s'éloigne de l'objectif au lieu de s'en approcher""" operations_filtrees = {} for resultat in operations: formules = operations[resultat] min_distance = abs(objectif - resultat) ...
171bfa62850fe8bcf6802a13e56f6b16cb77499f
74,051
def generate_delay_matrix(pre_population, post_population, delay=0.25, std=0.1): """generate delay matrix between two populations""" if type(pre_population) == int: N = pre_population else: N = pre_population.N if type(post_population) == int: M = post_population else: M = post_population.N ...
8b30fb9ee06c02d3d4ab0f03c5b855b516397cdb
74,052
import random def get_http_header(): """ 模拟浏览器爬取代理 http 头信息 :return: """ return { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'h-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0....
8194714dadd305bdc3af28fb77ff570c1afefbf4
74,053
import math def scaled_init_method_normal(sigma, num_layers): """Init method based on N(0, sigma/sqrt(2*num_layers).""" std = sigma / math.sqrt(2.0 * num_layers) def init_(tensor): return nn.init.normal_(tensor, mean=0.0, std=std) return init_
3d648e741b2ff423117b9a6d3f42dd3ae2dcfa87
74,054
def mat_toeplitz_1d(h, x): """ Constructs a Toeplitz matrix for 1D convolutions Parameters ---------- h: list[] The filter's vector x: list[] The signal's vector Returns ------- list[list] A Toeplitz matrix T such that y = T(h) * x """ Nh, Nx = len(...
45b03ecceb9663676d400dae06af57987f95f3b2
74,055
def viewCourse(request: HttpRequest): """ 展示一门课程的详细信息 GET参数: ?courseid=<int> 用户权限: 不对用户类型作出限制,均正常显示内容 """ valid, user_type, html_display = utils.check_user_type(request.user) try: course_id = int(request.GET.get("courseid", None)) course = Course.objects.filter(id=co...
312b63339067801bcd4901b6a8b4085ffbd0d7d0
74,056
def parse_input_file(input_dir, stopwords=False): """ Parses 'contexts.xml' and 'substitutions' files. Takes the directory of input files the only argument. Returns list of tasks in form of pairs (sentence, list of possible subs). Each sentence is a pair (list of strings, 0-based index of a st...
7559ae44d6fd540ecbecbae5d3edb1211a5dc03a
74,059
from math import floor, log10 def findSizeInt(number): """ #EN-US: → Calculates the number of digits in a number. :param number: the number to be calculated. :return: the number of digits of the number entered. #PT-BR: → Calcula a quantidade de dígitos em um número. :param number: o n...
8b174183520337f31f17bfb4163d5ed5ff90e896
74,060
import operator def _get_operator(comp_str): """Returns the operator function corresponding to the given comparison. Args: comp_str: str. One of: '<', '<=', '=', '>=', '>'. Returns: callable. The binary operator corresponding to the comparison. Raises: ValueError. The compar...
123ca1e2be8abf81387fb5d2ffa559082116b959
74,061
def clean_text_simple(string): """ Remove all \x19 from the string formatted with simple colors: \x198 """ pos = string.find('\x19') while pos != -1: string = string[:pos] + string[pos+2:] pos = string.find('\x19') return string
a067f164be5677f6fb2029d5b839849ca50a230e
74,062
import math def knn(pnts, p, k): """ Calculates k nearest neighbours for a given point. :param points: list of points :param p: reference point :param k: amount of neighbours :return: list """ s = sorted(pnts, key=lambda x: math.sqrt((x[0]-p[0])**2 + (x[1]-p[1])**2))[0:...
2da3d4481db78910548eee04e0532e701e4c4201
74,063
def update_ip(ip_type, cache, dns, proxy_list): """ 更新IP """ ipname = 'ipv' + ip_type domains = get_config('ipv' + ip_type) if not domains: return None address = get_ip(ip_type) if not address: return False elif cache and (address == cache[ipname]): print('.',...
f6c9bda9e5617bd210731a17f34b456ff52ed43f
74,064
def one_sampling_round(model, dataset, Q, n_samples_per_round): """ Generate one round of samples """ samples_df = get_new_samples(model, dataset, Q, n_samples_per_round) samples_df = compute_modlamp(samples_df) mask_accept = samples_df['accept_z'] samples_df['accept'] = mask_accept retu...
4da5a58a7ff9e10bc99d1f77886ea968a25db6d8
74,065
from typing import Union from typing import List from typing import Any def band_matrix( band_coeffs: Union[List[float], List[complex], ndarray], band_offsets: Union[List[int], ndarray], dim: int, dtype: Any = None, has_corners: bool = False, ) -> dia_matrix: """ Returns a dim x dim sparse...
2f50f2b9255aaeb42ab43e9e6f04780b0d2fbdba
74,066
import struct def read_section_header(stream): """ Read a section header block from a stream. .. note:: The byte order magic will be removed from the returned data This is ok as we don't need it anymore once we determined the correct endianness of the section. :returns: a dic...
bd93af921b4aa3b7d3912eb0c2c4071715b2bca9
74,067
from typing import Pattern def matches(tag_idx: int, tag: Tag, pattern: Pattern) -> bool: """ A predicate for use in :func:`remove_tags`. Returns ``True`` if _tag_'s ``name`` is matched by ``pattern``. .. note:: While this function can be imitated with ``lambda _, tag: tag.name in {...}``, th...
6a213c37343b42efecf2d57f541a1f59516604b4
74,068
def aes_encrypt(msg, aes_key): # type: (bytes, bytes) -> Tuple[Union[bytes, bytearray, memoryview], bytes, bytes] """ Encrypt a bytes message :param msg: Message to encrypt :param aes_key: AES encryption key :return: (tuple) encrypted message composed of nonce, tag and ciphertext """ ...
b571f0d46672e61e9de414596888dd6301437a96
74,069
from datetime import datetime import time def tdiff(times): """ This function calculates daytime and nighttime, as well as sunrise/sunset times. It accepts two datetime.time objects and a string, and returns four floats of the data needed for plotting. """ thyme = [times[0], times[2], times[3]...
b4e89aace9edb9bf7e505d1de5d65e4099928d94
74,070
import requests from bs4 import BeautifulSoup def scrape(start, end, logging=True): """ Scrape all the reviews from dealerrater.com for the McKaig Chevrolet Buick dealership. Parameters: start: the page of reviews to start scraping end: the last page of reviews to scrape Ret...
03dfd059a82c4c56dec47d772ef2e6ade905fac7
74,071
def _cubeplane_ray_intersection(xyz, dxdydz, extent): """Intersects rays with a plane of cubes and returns data about intersections Suppose the walls of the cube are on integer boundaries in the space of extent[0] <= x <= extent[1], extent[2] <= y <= extent[3], extent[4] <= z <= extent[5] Para...
9bdb800ccf2a389d4933145e3537140b04453084
74,073
def _get_sparsity(matrix, tolerance=0.01): """Returns ~% of zeros.""" cnt = len(matrix.flatten()) non_zeros = np.count_nonzero(np.abs(matrix) > tolerance) return (cnt-non_zeros) / cnt
7ae83ae978892fa5e400db46565681e9d896cfb1
74,074
def get_most_popular_three_articles_of_all_time(): """Return what are the most popular three articles of all time.""" conn = psycopg2.connect("dbname=news") cur = conn.cursor() cur.execute(most_popular_three_articles_of_all_time) results = cur.fetchall() conn.close() return results
3f582a1559a1f0bdd80348983e8f446ba22ea731
74,076
def __process_args(args): """ Process the command-line arguments. :param args: the command-line arguments list :raises CLAException: if an error occurs while validating and processing the command-line arguments """ _method_name = '__process_args' cla_util = CommandLineArgUtil(_program_name,...
5bee03658ed053262dd1bb99fc4dd05b207d6260
74,077
def monotonic_decreasing(func): """Correctly round monotonic decreasing function.""" # pylint: disable=invalid-name, protected-access @wraps(func) def _wrapper(it): inner = func(it) return Interval(inner(it._upper, RM.RD), inner(it._lower, RM.RU)) return _wrapper
18fbcd3403c921fba6be1fecfc96ab966ef99a0e
74,078
import re def multiple_replace(string, replacements): """ Given a string and a dictionary of replacements in the format: { <word_to_replace>: <replacement>, ... } Make all the replacements and return the new string. From: http://stackoverflow.com/questions/2400504/ """ pattern = re.co...
bdaf05f2f9c5de2c0742c12219e2984ed3e7699e
74,079
import six def sanitise_args(config): """ Sanitise command-line configuration. :param config: Config dictionary (from docopt) :returns: Config dictionary with all keys stripped of '<' '>' and '--' """ sane_conf = {} for key, value in six.iteritems(config): if value is not None: ...
575d8bedf81ba3cf8b0436a9c837e12e6face548
74,080
def run_benchmark( benchmark_config: BenchmarkWrapper, result_name: str, fp16=False, training=False ): """Run Huggingface's PyTorch benchmarks. args: benchmark_config: BenchmarkWrapper result_name: str = Name prepended (without spaces or special characters) for the saved result fp16: bool = If ...
3deae95485478da40c8ec887381cd0260020cf6f
74,081
def find_strings(project_path,outfile, branch, depth, from_date, to_date, regex): """ Read the repo. Check the active branch. If branch args is not specified scan the repo as it is. Else If active branch !== branch_args; then checkout branch_args. If depth is not specified; Initialize scan_depth= MA...
49d71562816ed089f0e22f31ecb7c3b19eec1d09
74,082
def images_2D(image1, image2, vector_of_euler_changes_2D=None, max_intensity1=255, max_intensity2=255): """ Euler characteristic curve of a pair of 2D images. This uses the vector of all possible Euler characteristic changes produced by a pixel insertion in 2D images. This is recompu...
01e5c79b1bdf8e0dfd36faaf2e14fbdefc59da79
74,083
from functools import reduce def apply_filter_conditions(df, conditions): """ return a function to apply filtering conditions on df """ if len(conditions) == 0: return df elif len(conditions) == 1: return df[conditions[0]] else: return df[reduce(lambda c1, c2: c1 & c2, ...
43f218069b535aa29e1c6855befd488449cffc06
74,084
import requests def get_client_info(client_ip, dnac_jwt_token): """ This function will retrieve all the information from the client with the IP address :param client_ip: client IPv4 address :param dnac_jwt_token: DNA C token :return: client info, or {None} if client does not found """ url ...
2cf92a4ff95549a49524e7df51cb9fa207cde2b3
74,085
import random import string def new_identifier(context): """ Create a new identifier or return an existing one. """ def random_identifier(length): random_letter = lambda: random.choice(string.ascii_lowercase) name = ''.join(random_letter() for _ in xrange(length)) + '_' return name if not context.has_names...
24ce035b486c686c8fdef704db2f77aaf58c5b73
74,086
def process(json_path, output_format = 'csv'): """ Entripoint function. Parameters: json_path (string): input path of json file ouput_format (strint) : csv/json, ouput file format Returns: over_weight_count (integer) : number of overweight people count """ t...
e0bb62588017521bb19f9be067c30d9660ab99da
74,087
def filter_country(df, countryiso, country_of="originating"): """Keep only rows for one country - originating or residing. A column "Country" with column names of the variable country (residing or originating) is created. """ countries_table = evaluate( "countries" ).get() # evaluate rather...
d9b4523084ea3523305cf1db50a99db1d0296d25
74,088
def TraceActiveVars(): """Return a list of active trace variables""" ret = [] for i in range(TRACE_VAR_CT): dat = SendCmd(OP_TRACE, [SUBCMD_TRACE_GET_VARID, i]) var_id = Build16(dat)[0] var = FindVarByID(var_id) if var: ret.append(var) return ret
c2e9871775d96ff8aae597134adabb55b17ff2ce
74,089
from io import StringIO def create_current_save_file(): """ :return: a string that looks like a current, valid save file, whatever we are using """ persistor = PickleFilePersistor( persist_root=None, save_file_name="current_pickle", testing=True, ) buffer = StringIO() persistor.wri...
2b86de15d1d18c4183e58307c25a3949793a375e
74,093
def getter_generator(field_name, short_description): """ Generate get_'field name' method for field field_name. """ def get_translation_field(self, language_id_or_code=None, fallback=False): try: return getattr(self.get_translation(language_id_or_code, ...
c8773b46f527ad99c40f3003a7ab35cd05062ac2
74,094
from typing import Sequence from typing import Any from typing import Optional def create_POUCT( actions: Sequence[Action], sim: Simulator, num_sims: int, init_stats: Any = None, leaf_eval: Optional[Evaluation] = None, ucb_constant: float = 1, horizon: int = 100, rollout_depth: int = 1...
b1ce2a3178caf336921af23970bc247f03757986
74,096
def find_serial_devices(serial_matcher="ED"): """ Finds a list of USB devices where the serial number (partially) matches the given string. :param str serial_matcher (optional): only device IDs starting with this string are returned :rtype: List[str] """ objWMIService = win32com.client...
ab89435b379b004ec4cd075fb0157059df3a4fd7
74,097
def GetOutputFileUrl(test_run, attempt, file_path: str = '') -> str: """Get URL for a command attempt's output file. Args: test_run: test run attempt: command attempt file_path: optional file path Returns: attempt's output URL """ return GetAppStorageUrl( [test_run.output_path, attempt....
c28743e379d13e89c4f75fc29cef213708c4bbe4
74,098
from typing import Dict from pathlib import Path from typing import Optional import csv def write_results( result_dict: Dict[str, Dict[str, str]], trans_dict: Dict[str, str], input_filepath: Path, output_filepath: Path, write_csv: Optional[bool] = False, ) -> Dict[str, Dict[str, str]]: """ ...
a791f47c9d16b451db14cd599cf2f15f04f0637c
74,099
def admin_download_request_file(lic_id): """Generate admin version of the view for downloading request files.""" lic = License.query.get_or_404(lic_id) response = make_response(lic.request) response.headers['Content-Type'] = 'application/octet-stream' response.headers['Content-Disposition'] = ( ...
85ecbb1666a56d6f864a61c29db927e9d90fa7c7
74,100
import base64 def dict_from_payload(base64_input: str, fport: int = None): """ Decodes a base64-encoded binary payload into JSON. Parameters ---------- base64_input : str Base64-encoded binary payload fport: int FPort as provided in ...
98277b109af80d0bbe24b38ce164d053109875fb
74,101
import requests def post_service2(url, scale_key_pair): """Using our existing user data from s1, we use this function to send a post request to s2, for a new note pitch. Keyword Arguments: url: The url of service 2. scale_key_pair: A key pair scale list dictionary. """ service_2...
113a47b8f004646007d8ab1b408facc18cf33c23
74,102
from typing import Set def is_vararg(leaf: Leaf, within: Set[NodeType]) -> bool: """Return True if `leaf` is a star or double star in a vararg or kwarg. If `within` includes VARARGS_PARENTS, this applies to function signatures. If `within` includes UNPACKING_PARENTS, it applies to right hand-side ext...
0c83dc2993afedebfd80f0213b2a44f8898485a8
74,103
def mass_function_abc(m, a, b, c): """The parametrized surpression function of the halo mass function""" return (1 + (a / m)**b )**c
d4e0b1d39a67baa121a28fc644b75c9bfd714c5e
74,104
def get_processing_output( pipeline_execution_arn: str, step_name: str = "BaselineJob", output_name: str = "monitoring_output", ): """Filters the model packages based on a list of model package versions. Args: pipeline_execution_arn: The pipeline execution arn step_name: The option...
47f68636abf993ab4c779054a68f1bce39481582
74,105
def upload_album( self, photos, caption=None, upload_id=None, from_video=False, options={}, user_tags=None, ): """Upload album to Instagram @param photos List of paths to photo files (List of strings) @param caption Media description (String) @param upload_id Uniq...
8b9e0a92c973ea90018f1356c44fe6e9047229f3
74,106
async def _build_sequence(ctx): """Construction d'une séquence-réaction par l'utilisateur""" reponse = "" fini = False while not fini: message = await ctx.send( "Réaction du bot : prochain message/commande/média, " "ou réaction à ce message" ) ret = await ...
b118ab23c14ac59671592190ecb805671399f45f
74,107
import math def ffn_layer(x, d, d_o, dropout=None, scope=None, numblocks=None): """ FFN layer in Transformer :param numblocks: size of 'L' in fixup paper :param scope: """ with tf.variable_scope(scope or "ffn_layer", dtype=tf.as_dtype(dtype.floatx())) as scope: ...
2f2f3a194042cd1d99f1471a079b8a69f1700e48
74,108
def retain(foo): """This method is very important for live source code manipulation. It ensures, that every reference to an object's method is going to change when the method has been edited (and therefore been overridden). If a reference to a method is made by providing the method object without calling re...
f615cd295648bc0ef266e9e1f25e60985cc1a1d5
74,109
def add_config_template(project_id): """add a new Config Template :param project_id: :return: """ parent_project = Project.query.filter(Project.id == project_id).first_or_404() form = ConfigTemplateForm(request.form) if form.validate_on_submit(): try: config_template =...
bf3a9b37408ba0d19b6c26d60ea99d48270cb5ac
74,110
import torch def scale_invariant_loss(predicts: torch.Tensor, targets: torch.Tensor, reduction="mean"): """ outs: N ( x C) x H x W targets: N ( x C) x H x W reduction: ... """ predicts = predicts.flatten(start_dim=1) targets = targets.flatten(start_dim=1) alpha = (targets - predicts).m...
ee07477c4a380e46b8d27e424d79827b268a3524
74,111
def convert_tan(node, **kwargs): """Map MXNet's tan operator attributes to onnx's tan operator and return the created node. """ return create_basic_op_node('Tan', node, kwargs)
a0f2e904ddf57244cf5c8b89ccaa4f41507c7ec3
74,112
import logging def set_logger(log_path): """Set the logger to log info in terminal and file `log_path`. In general, it is useful to have a logger so that every output to the terminal is saved in a permanent file. Here we save it to `model_dir/train.log`. Example: ``` logging.info("Starting t...
da915706e363fe8e84be67d7b9dfafe7a4487d14
74,113
def is_hinted(value): """ Check if a value is a tuple of data item and its type hint. """ return ( isinstance(value, tuple) and len(value) == 2 and issubclass(value[1], IgniteDataType) )
7680a6ccbc06ae8fdbfaadeac6b31f04cd2e843f
74,115
def cyclic_index_i_minus_1(i: int) -> int: """A helper function for cyclic indexing rotor scans""" return i - 1 if i - 1 > 0 else -1
ae133f686eb9145da5ed39d7acf37d1385e2687f
74,116
def runtime(permutation): """Calculate and return the estimated runtime of a given permutation of the job ordering. Also return a trace of how the jobs go through the pipeline.""" queue = list(permutation) running = {x: build_times[x] for x in queue[:QUEUE_LENGTH]} del queue[:QUEUE_LENGTH] t = 0...
c03ceb129c1fc65ef94c65857cabfa5cb8edaf36
74,117
import torch def natural_mask(o): """Applies natural missingness in a batch to non-nan values in the next sample""" mask1 = torch.isnan(o) mask2 = rotate_axis0(mask1) return torch.logical_and(mask2, ~mask1)
2794ced9714ab5db3a2448599dbf28eb95460b9f
74,118
import json def loadMetadata(fn): """ Load Metadata JSON File Parameters: ------------- fn : str - filename Returns: ------------- data : dict """ data = json.load(open(fn)) return data
4fa9aceed53cab0c076d4bdc474a08ebccae5ef6
74,119
def cancel_query(service, last_query_handle): """Cancel a query on a keyboard interrupt from the shell.""" # Cancel sets query_state to EXCEPTION before calling cancel() in the # co-ordinator, so we don't need to wait. rpc_result = __do_rpc(lambda: service.Cancel(last_query_handle)) _, status = rpc_...
6c838f16168d8d344173caf56cd9e8df72a682d8
74,120
def getCorners(max_cnt): """Returns the edges of the contour if the approx polygon is a quadrilateral""" perimeter = cv2.arcLength(max_cnt, True) epsilon = 0.1 * perimeter approx = cv2.approxPolyDP(max_cnt, epsilon, True) boundary_pts = None if len(approx) == 4: x2, y2, x1, y1, x3, y3, ...
3d9d5fca715c8e2fb4978b2beef49ee1119f4032
74,121
def __get_regulargrid__(shape, kernelarea, sampling, center): """ Create a regular grid through tuple 'center'. Creates a regular grid of values for the given array shape. Such that there are approximately n samplings per kernelarea, where n is given by the sampling parameter. The array will be sam...
e193eb89df58bc221de21641f9d33af18815dc61
74,122
def read_data_chunked(path, table_name, chunksize, columns=None): """ Reads data from hdf5 file given as PATH and yields dataframes for each chunk """ return HDFDataIterator( path, table_name, chunksize, columns, )
43900a94c1506a816f3cee2f831a1dca33fa38c0
74,123
def load_json(json_file_path): """ Loads json file. :param str json_file_path: path of json file that will be loaded :rtype: list :return: list of json (dictionary) objects """ assert (isinstance(json_file_path, str)) with open(json_file_path) as f: data = load(f) return data
b8f5a199765b2a8a5056f806507c306841e4a32e
74,124
def update_tuple(origin_tuple, update_value, update_index): """Update tuple/namedtuple for specified update_index and update_value.""" # Namedtuple is inherit from tuple. if not isinstance(origin_tuple, tuple): raise ValueError("Only tuple/namedtuple supported. Origin_tuple type: " "%s." ...
1956777840fe30db01f1a4526e8e79d0ceac8534
74,125
def decompose_matrix(matrix): """ :param matrix: :return: """ return np.linalg.svd(matrix)
1e110cfcf62f2e35406a6dbd93ce94e65dff1189
74,126
def generate_diff_output(board, iostandard, drives, slews): """ Generates a design which outputs 100Hz square wave to a number of pins in which each one has different DRIVE+SLEW setting. The IOSTANDARD is common for all of them. """ num_ports = len(drives) * len(slews) iosettings = {} ...
18c1bdbe0afa2093a46a792aced3f7aad5375345
74,127
def get_variation(variation_key, variations_dict, defaults_dict): """Convert a string to a tuple of integers. If the passed variation_key doesn't follow this pattern '0 100', it will return default values defined in defaults_dict. This is currently used for defining the variation data of the A/B e...
24e069fabcb9bd4dbfbd3c1ea17e859f27fdcceb
74,128
def _serialize_list_value(value, charset) : """ Serialize list value """ error_code = Error(errOk) if value is None : return error_code, NULL_STRING result = "[" comma = "" for child_value in sorted(value.value, key = lambda value: (value.order_number)) : result += comma...
db56a4b44b8fca1205add7c155e4810d9dc5b459
74,129
def get_engine(db_url=None, echo=False): """ :param db_url: "mysql://user:password@localhost/mydatabase" :param echo: :return: """ assert (db_url is not None) engine = create_engine(db_url, echo=echo) return engine
f51301f3239b974e8ca68011adc6c78c25181c20
74,130
def generate_network(dataset): """ @params: [dataset (Pandas Dataframe)] @returns: None Generates a directed graph networkx between users with edges defined by interaction types from INTERACTIONS using Pandas dataframe dataset. Saves the graph to filepath graph_out. Currently not decomposed, to...
add7188913e02608e03621de33bcfbc151d27fd2
74,132