content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def copy_analysis_project(project,fastq_dir=None): """ Make a copy of an AnalysisProject instance Arguments: project (AnalysisProject): project intance to copy fastq_dir (str): if set then specifies the Fastq subdirectory to use in the new instance Returns: AnalysisProject: n...
31f3abb44f41b886bca02098ff616f2daa25b5e6
3,596,393
def get_native_backend_config_dict(): """ Get backend_config_dict for PyTorch Native backend (fbgemm/qnnpack). """ return { # optional "name": "native", "configs": [ *_DEFAULT_OP_INT8_CONFIGS, *_get_linear_configs(), *_get_conv_configs(), *...
a613e32dafce598020ff2bb93cd14d195fcd615c
3,596,395
from typing import List from typing import Dict from typing import Tuple from pathlib import Path def create_structure(structure: List, options: Dict, prefix=None) -> Tuple[List, Dict]: """Creates a directory structure in the file system. """ if prefix is None: # pathlib.Path can handle filesyste...
92addf65855d3fe7640a7e557bf38c78d951e8e6
3,596,396
def stepper(library, keep, step_tag, new_step_input_file, input_file_dict, new_step_name, new_step_output_arg, additional_input=None, organism='human', no_output=False, tag=''): """This functions packs the core of wfr check, for a given workflow and set of input files, it wi...
0972fdaf21c8b30036a57a0e2ae1e15d6fe277b7
3,596,397
import copy def return_prim_graph (dag, innodes, outnodes): """ remove input and output nodes from a graph """ G_primitive = copy.deepcopy(dag) nonprims = innodes+outnodes for node in nonprims: if node in dag.nodes(): G_primitive.remove_node(node) return G_primitive
e59fcfcb5796739cc940f6052e56aa5a4837fd47
3,596,398
def circle_3p(A, B, C): """get center and radius of a circle given 3 points in space""" a = np.linalg.norm(C - B) b = np.linalg.norm(C - A) c = np.linalg.norm(B - A) s = (a + b + c) / 2 R = a*b*c / 4 / np.sqrt(s * (s - a) * (s - b) * (s - c)) b1 = a*a * (b*b + c*c - a*a) b2 = b*b * (a*a ...
7cc90426447a0da119dbd6c6e61dfc8e68e8be79
3,596,399
from typing import Any def _format_value(value: Any) -> str: """Internal function for formatting values.""" value = base.to_numpy(value) if isinstance(value, (float, np.number)): return f'{value:0.3f}' return f'{value}'
f57ed7839c1d4dabe5adc6889bb2e48250801f61
3,596,400
def create_context(system, integrator, platform=None): """Create a Context. If platform is None, GLOBAL_ALCHEMY_PLATFORM is used. """ if platform is None: platform = GLOBAL_FORCES_PLATFORM if platform is not None: context = openmm.Context(system, integrator, platform) else: ...
75b99862875efd3ef6147b3334c2ed0459a6de11
3,596,401
def normalize_key(key: t.Sequence[str]) -> SettingKey: """Normalizes a key value into a tuple of strings. The given key can be a string or a sequence of strings. An empty string or iterable will result in an empty tuple, representing the root of the setting tree. Args: key: String or itera...
c503abfcf2ca6155c6f28921cebe06a5e0cfd146
3,596,402
def witchingHoursDF(symbol="", **kwargs): """This is when option contracts and futures contracts expire on the exact same day. https://iexcloud.io/docs/api/#witching-hours Args: symbol (str): symbol to use """ return _baseDF( id="PREMIUM_WALLSTREETHORIZON_WITCHING_HOURS", symbol=sym...
a8bedc98ad45dfb91d7d20a61471111d65127856
3,596,403
import re def convert_doctoc(html): """ Convert doctoc to confluence macro :param html: html string :return: modified html string """ toc_tag = '''<p> <ac:structured-macro ac:name="toc"> <ac:parameter ac:name="printable">true</ac:parameter> <ac:parameter ac:name="style">disc<...
b2a52126d6a234894dcf6f98f0d399c309587a7e
3,596,404
def flip_case(phrase, to_swap): """Flip [to_swap] case each time it appears in phrase. >>> flip_case('Aaaahhh', 'a') 'aAAAhhh' >>> flip_case('Aaaahhh', 'A') 'aAAAhhh' >>> flip_case('Aaaahhh', 'h') 'AaaaHHH' """ return ''.join(letter.lower() if letter.lower...
ab3a18249e882bb0e8fda35a903048a20bd667e6
3,596,405
def batch_multiclass_non_max_suppression( boxes, scores, score_threshold, iou_threshold, max_boxes_per_class, num_classes): """Same as multiclass_non_max_suppression but for a batch of images. Arguments: boxes: a float tensor with shape [batch_size, N, 4]. scores: a floa...
8e24e34f5846fc27002080b80cf5ed8405aa3d15
3,596,406
def apply_class_label_replacement(X, Y, replacement_method): """ Replace class labels using the replacement method :param X: data features :type X: numpy.Array() :param Y: data labels :type Y: numpy.Array() :param replacement_method: Method to update targets :type replacement_method: me...
eac01d31ff63e39d8c203803ae14c08365ec20a5
3,596,407
from typing import Tuple from typing import List def get_series_ids(series_term: str, num: int) -> Tuple[List[str], List[str]]: """Get Series IDs. [Source: FRED] Parameters ---------- series_term : str Search for this series term num : int Maximum number of series IDs to output ...
5717b16f4cae1e4478309e7916472908f755968e
3,596,408
import torch def nt_xent_loss(out_1, out_2, temperature): """ Loss used in SimCLR """ out = torch.cat([out_1, out_2], dim=0) n_samples = len(out) # Full similarity matrix cov = torch.mm(out, out.t().contiguous()) sim = torch.exp(cov / temperature) # Negative similarity mask =...
6634e42f540835f5a45c4812e54455d0328b6ec2
3,596,409
def fromScopus(scopus_author): """Fetch all publications associated with Scopus author Parameters ---------- scopus_author : AuthorRetrieval Scopus author retrieval object (scopus.author_retrieval.AuthorRetrieval) Returns ------- bibs : list List of Scopus search publi...
88aeca0f28af9ca3256e77f6e77207ffb51cefa0
3,596,410
def init_containers(): """Initialized containers """ cont_p_re = qr.TwoDSpectrumContainer() cont_p_re.use_indexing_type("integer") cont_p_nr = qr.TwoDSpectrumContainer() cont_p_nr.use_indexing_type("integer") cont_m_re = qr.TwoDSpectrumContainer() cont_m_re.use_indexing_type("integer")...
d39e08d7812da4a5c7db73d32e3a749e4080e43d
3,596,411
def list_to_string(list_objects, obj: DataGetter = None): """ This function formats list of an objects into single string. """ return ', '.join(map(lambda x: str(x), list_objects))
809df4a48a5a37b8f39b779c4867ac1afc8d4291
3,596,412
def create_klr_model(kernelized_features=4096, kernelized_scale=10., only_digits=True): """Create a Kernelized Logistic Linear Model (for federated) When `only_digits=True`, the summary of returned model is Model: "sequential" Args: only_digits: A boolean that determines whether to only use the digits in...
8d8097f9dfa1107d0474f2205a45bb3a7489d035
3,596,413
def alexnet_owt(inputs, training): """Alexnet One Weird Trick model https://arxiv.org/abs/1404.5997 """ builder = nvutils.LayerBuilder(tf.nn.relu, args['image_format'], training) # Note: VALID requires padding the images by 3 in width and height x = inputs x = builder.conv2d(x, 64, 11, 4, 'V...
d2bc0ff53f6bc2cb7ab628a999babdd573988d98
3,596,414
def simple_gre_packet(pktlen=300, eth_dst='00:01:02:03:04:05', eth_src='00:06:07:08:09:0a', dl_vlan_enable=False, vlan_vid=0, vlan_pcp=0, dl_vlan_cfi=0, ip_src='192.1...
277077d65f6cad11276df274d27d9619a3e5eb00
3,596,415
import mimetypes import google def inspect_file(project, filename, info_types, min_likelihood=None, max_findings=None, include_quote=True, mime_type=None): """Call Data Loss Prevention API to analyze a file for protected data. Args: project: The GCP project id to use as a parent reso...
b5cd12707d47f9b123c4254cd03b9371c9ab9a5f
3,596,416
import functools def lru_iter_cache(func=None, *, maxsize=128, cache=None): """Decorator to wrap a function returning iterables If maxsize is 0, no caching will be done. If maxsize is None, the cache will be unbounded. See LRUIterableCache for more info. """ if func is None: return ...
4e64a85cc82c95e9f7f80c379a3f115cbb565014
3,596,419
def CV_IS_SEQ_CURVE(*args): """CV_IS_SEQ_CURVE(CvSeq seq) -> int""" return _cv.CV_IS_SEQ_CURVE(*args)
383559d92a59f8f681016f6fe712d20967c7bbc4
3,596,420
import unittest def create_part_b_testcase_class(): """ Class factory function which creates new subclasses to JmsMessageTypeTestCase. Creates a test case class for a single JMS message type containing a combination of JMS headers """ def __repr__(self): """Print the class name""" ...
d32658b7a388b08da025fdf02b9257d6dd0b5c5e
3,596,421
import yaml def yaml_parse(yaml_dict): """Convert from YAML to python. Args: yaml_dict: Absolute or relative file address. Returns: dict: Returns the python dictionary. """ yaml_file = open_file(yaml_dict) return yaml.safe_load(yaml_file)
70d4d75d9a399e081eec27d6b9ed72e6fe78c6f7
3,596,422
def W(H) -> int: """ Default image width (equal to height) """ return H
4b3fdaaba9f5100096ca1ebbc22442de21b34ad5
3,596,425
def func(x,*args): """evaluate function L=sum_{samples}[E(pmd)-E(ref)]^2. This will be called from scipy.optimize.fmin_cg(). The 1st argument x should be 1-D array of variables. """ global _valmin t0= time.time() #.....write parameters to in.params.????? file dir= args[0] ...
343295b15bae220f983ad73a3a86612d81943a69
3,596,426
def decode_mobile_platform_type(platform_type): """Return the MpnPlatformType corresponding to the provided token.""" if platform_type == NULL_VALUE: return None if platform_type == EMPTY_VALUE: return '' if platform_type in [c.value for c in MpnPlatformType]: return MpnPlatfor...
15d35693270416e6a19c66c390c5bb2625cea417
3,596,427
def _evalPoint2LineDistAndParmam( data , coef ) : """ Evaluates distance of a point from line and parameter of the closest line's ponit (projection) . The line is given by the coeficients (a,b,c,dx,dy,x0,y0). The distance is calculated as d(x,y) = a*x + b*y + c The p...
8573e5fe5a4f3998bd58ec01fb2555f489afce71
3,596,428
def compute_model(mri, grid, morphology={}, functional={}): """Mmake the full morphology and functional models (if present). Parameters ---------- mris : dict fields "dura" (necessary), "pial" (optional), "func" (optional) grid3d : (n_rows, n_cols) array 3d grid with positions and n...
b4c702772a79e5f7cfb173b495905e6d7ca5f11b
3,596,429
import re import logging def metasysid_to_real_estate(metasysid: str) -> str: """Takes something like 'GP-SXD9E-113:SOKP16-NAE4/FCB.434_121-1OU001.VAVmaks4' and spits out 'kjorbo' using BUILDING_MAP (dict) This is used when we push data into the Bas API. """ try: rx = re.compile('^([^:]...
2ca6077dcea4076b10280eebc667b54022086505
3,596,430
import ast def _astnode(s): """Return a Python ast Node compiled from a string.""" try: except ImportError: # Fallback to eval when ast package is not available, # e.g. IronPython 1.0. return eval(s) p = ast.parse("__tempvalue__ = " + s) return p.body[0].value
4843819c072738db6543ffb89f182526f46513ef
3,596,431
def sort_words(event_window, args, result_file=None): """ Sort words based on the assigned weight parameters ----------- :param event_window: object EventWindow object :param args: JSON JSON of arguments :param result_file: str, optional File path to save weight deta...
8e7715fbc345a34272444a8203c7f5f5eb648bb5
3,596,432
def get_CHAM_instance(CHAM_instance): """Return an instance of the CHAM family as a `Cipher`.""" if CHAM_instance == CHAMInstance.CHAM_64_128: default_rounds = 80 n = 64 kappa = 128 w = 16 elif CHAM_instance == CHAMInstance.CHAM_128_128: default_rounds = 80 n ...
b884ca80bc91fc6300d1a0005185316eabf09324
3,596,434
def _get_config_kwarg_overrides(): """Returns overrides to the configs that insert the correct local paths.""" data_path = _get_data_path() label_map_path = _get_labelmap_path() return { 'train_input_path': data_path, 'eval_input_path': data_path, 'label_map_path': label_map_path }
bb3d54b1b5ecab3bb22f2db23c756b7ce3e4a5e4
3,596,435
def intersection(boxes1, boxes2): """Compute pairwise intersection areas between boxes. Args: boxes1: a numpy array with shape [N, 4] holding N boxes boxes2: a numpy array with shape [M, 4] holding M boxes Returns: a numpy array with shape [N*M] representing pairwise intersection area ...
b395f1a8f9b1b3b900c373e23aa03d14e6d58fb0
3,596,436
import math def _spherical_to_euler(angles): """Convert angles from spherical coordinates to Euler angles.""" pol = angles[..., 0] az = angles[..., 1] el = math.pi / 2.0 - pol # Polar angle to elevation [-pi/2, pi/2]. euler_z = az # Azimuthal angle = rotation of base waveform about z axis. euler_y = el ...
6de9142a0a0e275613737c1809f72de1d86cd293
3,596,438
import yarl def _async_get_external_url( hass: HomeAssistant, *, allow_cloud: bool = True, allow_ip: bool = True, prefer_cloud: bool = False, require_ssl: bool = False, require_standard_port: bool = False, ) -> str: """Get external URL of this instance.""" if prefer_cloud and allow...
61634c4216bf95cc2dbf4aae144400fad9cbd042
3,596,440
def hit_boundary(model): """Returns True if any Fitted objects are close to their min/max value""" components_list = [model.get_dependence("drift"), model.get_dependence("noise"), model.get_dependence("bound"), model.get_dependence("IC"), ...
c93e4f018571e24add68071b0373c1525f5d6513
3,596,442
from typing import Tuple from typing import List def generate_2_pos_cycs() -> Tuple[Graph, List[Node]]: """ generate a graph with a single node returning to itself with value 2 :return: Graph, nodes """ s0 = Node(0) s1 = Node(1) s2 = Node(2) s3 = Node(3) s4 = Node(4) s5 = Node(...
33623f8db2e04ac489b874fbb6d8c8419ec002e6
3,596,443
import time def main(path, task, n_trials, test_set_size, use_rmse_conf, kernel, N): """ :param path: str specifying path to dataset. :param task: str specifying the task. One of ['Photoswitch', 'ESOL', 'FreeSolv', 'Lipophilicity'] :param n_trials: int specifying number of random train/test splits to ...
f3f4d1ba3f78686618a2a85fb461d019976be8f2
3,596,444
def org_commits_by_day(df_raw): """Returns all commits with a count and a date index by day""" odf_day = df_raw.resample('D').sum() return odf_day
bb003b8ce1a0a28e632cfc78ffa3483359259e49
3,596,445
def make_queue_name(mt_namespace, handler_name): """ Method for declare new queue name in channel. Depends on queue "type", is it receive event or command. :param mt_namespace: string with Mass Transit namespace :param handler_name: string with queue time. MUST be 'command' or 'event' :return: ...
f74a7be8bf46a56f760b087fe47c9eda58d9f51e
3,596,446
def load_dataset(dataset): """ Return the specified dataset. """ if dataset == "uci7" : data = load_uci(7) elif dataset == "uci10" : data = load_uci(10) elif dataset == "uci7robustinf" : data = load_uci(7, add_labels_as_views=True) elif dataset == "uci10robustinf" : ...
90eb325c89454172ee7e81943b165e85e15babd2
3,596,447
import requests def usgs_query_call(lat, lon): """ Build and run the query to the USGS API endpoint """ URL = 'https://nationalmap.gov/epqs/pqs.php' lat = str(lat) lon = str(lon) UNITS = 'feet' OUTPUT = 'json' query = '{url}?x={lon}&y={lat}&units={units}&output={output}'.format( ...
182a155882e9155a44da76134711b33fbb9252cb
3,596,448
def apply_transform(matrix, image, params): """ Apply a transformation to an image. The origin of transformation is at the top left corner of the image. The matrix is interpreted such that a point (x, y) on the original image is moved to transform * (x, y) in the generated image. Mathematically sp...
529b7b52eda8e24e1d13109903ad29c87686db10
3,596,450
from datetime import datetime def _make_link_from_row(row): """Build a link from a database row Parameters row -- A single row from the database """ markdown_ext = ('markdown.extensions.tables', 'markdown.extensions.fenced_code', 'markdown.extensions.nl2br', 'markdown_checklist.extension') raw_desc = row['de...
025bdeb1ed9a9b2d3b181ee824ada84ab57ea4f5
3,596,452
import math def prime(n): """returns true if prime number, false otherwise""" if n<2: return False return sum(map(divides(n), range(2, int(math.sqrt(n))+1))) == 0 """ def mod(x): if(n % x!=0): return 0 #if there is a remainder return false return 1 ...
1d21b94abae66644ba9dcd7694d0462ecddc79d3
3,596,453
import re from datetime import datetime def parse_sms(text: str) -> dict: """ Parses SMS using re, example of a valid SMS (only sberbank is supported ATM): VISA1234 21.12.16 22:12 зачисление зарплаты 12345.57р Баланс: 16063.28р """ sms_data = {} sms_pattern = re.compile(r''' # mat...
d8096b79558031b57d5df1e70d76a107e787807b
3,596,454
def _query_profile_body(selected_query) -> dcc.Markdown: """ Returns the formatted SQL body of the selected query. """ # Build query body in markdown code block query_code = " ``` \n " + selected_query.source.body + " \n ```" return dcc.Markdown(query_code)
2f67790546c4ea833bf6784a18ee7a879647b8e5
3,596,455
def facility(): """ e.g. Training Venues """ # Open record in this controller after creation s3db.configure("org_facility", create_next = URL(c="vol", f="facility", args = ["[id]", "read"], ), ...
cec8a56e4edd4c6add5cce897c303f8b76084961
3,596,456
def _fix_cookiecutter_jinja_var(value, replace='cookiecutter.'): """Remove 'cookiecutter.' string from 'cookiecutter.varname' jinja strings Can be used to remove different substrings as well by passing a string to the optional ``replace`` parameter. :param value: The string value within which to repla...
fc04d36a368fe7dd8c21a8dd3abe46f60d4d3d5e
3,596,457
import types from typing import Optional def get_column(record_batch: pa.RecordBatch, feature_name: types.FeatureName, missing_ok: bool = False) -> Optional[pa.Array]: """Get a column by feature name. Args: record_batch: A pa.RecordBatch. feature_name: The name of a feature ...
cbf23170079e42bb097801616b9a72d5d41b59b9
3,596,458
def oracle(data, target): """ fake metric data generator """ loss = np.random.rand() acc1 = np.random.rand() + 70 acck = np.random.rand() + 90 return loss, acc1, acck
b9fa8d75d5f1aef9b89879bfbd4fca931048c905
3,596,460
import json def get(): """ 获取推荐结果 :return: 推荐结果 """ test_set=filter_json(JSON_LIST) res = system.result(test_set,5) def _filter(j): """ 将comment_list弄成字符串 """ nj = j.copy() nj["comment_list"] = "|".join(nj["comment_list"]) return nj return json.dumps( [ _filter(JSON_LIST[i]) for i in res] )
1d275414d4d5126fdc707fb3694d751b239a3ba4
3,596,461
def flatten_dict(row, keys=[('title',), ('street', 'city', 'postalCode')]): """Flatten a dict by concatenating string values of matching keys. Args: row (dict): Data to be flattened Returns: flat (str): Concatenated data. """ flat = '' # The output d...
b4bafb0ec19a19d4223d7e9a94e3b8630cad1066
3,596,463
import logging import torch def keyword_model(key, model, input_dir, fake=False, args=None): """Train a model for given keyword Args ---- key : str target keyword to train model : str model name to train input_dir : str root directory to load data fake : bool ...
ac95fa02b6518e8d532caf90676351fae66df720
3,596,464
import math def rotation_matrix(axis, theta): """ Return the rotation matrix associated with counterclockwise rotation about the given axis by theta radians. """ axis = np.asarray(axis) axis = axis/math.sqrt(np.dot(axis, axis)) a = math.cos(theta/2.0) b, c, d = -axis*math.sin(theta/2.0...
db31590590a82bbe3e38f316b42deed221213a74
3,596,465
from typing import Dict import json def _get_summary_fnames(cache=True) -> Dict[str, str]: """ Returns {filename: download_url} """ _cache = _get_cache() p = _cache / "summaries.json" if not p.exists(): fnames = _web._get_summary_fnames_web() with open(str(p), "w") as f: ...
729c4895900a799b40ff028245b935697a66ba81
3,596,466
from evennia.scripts.taskhandler import TASK_HANDLER as _TASK_HANDLER def delay(timedelay, callback, *args, **kwargs): """ Delay the return of a value. Args: timedelay (int or float): The delay in seconds callback (callable): Will be called as `callback(*args, **kwargs)` after...
9acb1a2675f5b9488cb89c56e391e0cb1cb15ad1
3,596,467
import ast def mock_LocIdx(): """Mock Single Location Index, not a valid target member of file.""" return LocIndex(ast_class="BinOp", lineno=1, col_offset=2, op_type=ast.Add)
8ee707a9c5dcca8fb633476fd1c3d996d75466cd
3,596,468
import re def task_dependencies_from_dotfile(stream): """ Read programme task specified in dot file format """ decorator_regex = re.compile(r"([a-z_]+) *(\(.*)") attributes_regex = re.compile(r"\[.*\]") which_task_follows = defaultdict(list) task_decorators = defaultdict(list) ta...
d995b615c7aaf49c17e0065366ebf53aafa163ef
3,596,469
from re import S def sim_sir_df( p) -> pd.DataFrame: """Simulate the SIR model forward in time. p is a Parameters instance. for circuluar dependency reasons i can't annotate it. """ return pd.DataFrame( data=gen_sir(S, total_infections, recovered, beta, gamma, n_days), columns=("S...
ad0d5a8de1cdb2c87e14a55f9f234c3a2faa6972
3,596,470
def hill_formula(comp: Composition) -> str: """ :return: Hill formula. The Hill system (or Hill notation) is a system of writing empirical chemical formulas, molecular chemical formulas and components of a condensed formula such that the number of carbon atoms in a molecule is indicated first, the n...
70fce0bcdbaa26462e087bd2bffb0971b4f8abae
3,596,472
def create_codeable_concept(system: str, code: str, display = None) -> dict: """ Create codeable concept following the FHIR format (http://www.hl7.org/implement/standards/fhir/datatypes.html#CodeableConcept) """ return ({ "coding": [create_coding(system, code, display)] })
8d5b66f4344585dd26421a1570498eac2662a27c
3,596,473
def sam_flag_check(query, subject): """ Check two numbers, query (for filtering) in subject or not convert to binary mode q: 0000010 (2) s: 1011011 (91) q in s range: 0 - 2048 (SAM flag) """ def to_bin(n): return '{0:012b}'.format(n) # convert to binary mode q = to...
939109ad1c1668327cb4af4fcada818cea4653f4
3,596,474
def cosine_similarity(array1, array2): """Function to input two arrays and calculate the cosine similarity. Args: array1 (ndarray): Values for first vector. Note: will try to coerce into ndarray. array2 (ndarray): Values for second vector. Note: will try to coerce into ndarray. Returns: ...
0df7bf801fdec209e358ee057bcaaba9a07d8584
3,596,476
import requests def get_image_workdir(hostname, image, tag, token=None): """Query the docker API to get the workdir of an image.""" headers = { "Accept": "application/vnd.docker.distribution.manifest.v2+json", } if token is not None: headers["Authorization"] = f"Bearer {token}" try...
019da9bc2c841d0033b865019d2df46bf82fc3b1
3,596,477
from typing import Tuple def string_choice_or_blank(card: BDFCard, ifield: int, fieldname: str, choices: Tuple[str], default=None): """ Parameters ---------- card : BDFCard() BDF card as a list ifield : int field number fieldname : str name of field default : str, N...
4c86585e7f4299f1f6b4fa0f720aaf8ca321f2bf
3,596,478
def draw_world(arm, ax, theta1, theta2, obstacles, obstacle_colors, show_obstacles=True, show_angles=False): """ Returns a tuple with the three handles necessary to update the graph dynamically. """ if show_obstacles: for i, obstacle in enumerate(obstacles): xs, y...
bd175b89bbc7ca4c5ce43f1a5b39937f166c5281
3,596,479
import string def get_range_to_here_hashes(repo, start): """Return a list of strings corresponding to commits from 'start' to here. The list begins with the revision closest to but not including 'start'. Raise a ValueError if any of the returned values are not valid hexadecimal. :repo: a callable su...
41a8795f489d1646ba48366c791308a6d1435b3e
3,596,480
import random def api_random(): """GET random quote""" return random.choice(quotes)
9fb2dce438b2e0a1a37171e7848ac2b1d0e03b6a
3,596,481
def get_energy(W, b, s, beta=1.): """returns the energy of a state in a boltzmann machine""" return -1. * beta * (0.5 * np.dot(s.T, np.dot(W, s)) + np.dot(b, s))
3948a9590b0ef06b0c1a7e4ac547ead24c9e16e8
3,596,482
def init_app(name, module="aops"): """ Init application Args: name(str) Returns: app configuration """ module_name = '_'.join([module, name]) app = Flask(name) module = __import__(module_name, fromlist=[module_name]) for blue, api in module.BLUE_POINT: ...
710296c76e8d94d883710dc85c68cc597b02b60f
3,596,484
def softmax(Z): """Softmax operator. Parameters ---------- Z : ndarray, shape (m, n) input vectors. Returns ------- ndarray, shape (m, n) data after the softmax has been applied to each row. """ _check_size("mn", Z) # Subtracting the maximum improves numerical...
81edb6f4e5335db6ee35c2af80ba0f271af0fc77
3,596,485
def concatenate_features(df, feat1, feat2): """ Make a dataframe of feat1, feat2 and the two concatenated into one string """ feat1_feat2_combo_list = make_combinations(df, feat1, feat2) feat1_feat2_combo_df = pd.DataFrame(feat1_feat2_combo_list, columns=[feat1, feat2]) feat1_feat2_combo_df[...
acf466e73a3bd5f57636e85d3f7c85148bf8696b
3,596,486
from datetime import datetime async def app_factory(): """ App Factory :return: """ # init db if necessary await init_db(config=config) # Database connection mongodb_connection_string = ( f"mongodb://{config['database']['admin_username']}:{config['database']['admin_passwor...
4ff18c2ad16c35ed3684aa4cf638317875df6f5f
3,596,487
def hash_MD5(data): """ Shortcut function to directly receive the hex digest from MD5(data).""" h = MD5() if isinstance(data, str): data = bytes(data, encoding='utf8') h.update(data) return h.hexdigest()
80b894c2ac2f8bd4a25efee03ce32c988d536f78
3,596,488
def pull_request_url(pull_request_number): """Returns a GitHub pull request URL given a PR number.""" return '{base}/{pr}'.format( base=GITHUB_URL, pr=pull_request_number)
d47e5597f6229f4580bf3e95e2a07b5c5912b554
3,596,491
def _ExtractKeyValueFromLabel(label): """Extracts key and value from label like 'key=value'. Args: label: str, the label to extract key and values, i.e. 'foo=buz'. Returns: (k, v): k is the substring before '=', v is the substring after '='. Raises: LabelsFormatError, raises when label is not for...
fe26537f8e0bf581e4ce5409cb9384e90e11b88a
3,596,492
def eval_linear_baseline(X, y, eval_X, eval_y): """ evaluate linear regression model :param X: :param y: :param eval_X: :param eval_y: :return: predict_y, mse, mape """ lr = LinearRegression() lr.fit(X, y) pred_y = lr.predict(eval_X) return pred_y, np.sqrt(mean_squared_e...
518131d12ebce00dc8b02e4a081e5bb1ca74a857
3,596,493
def kron(*args) -> np.ndarray: """Computes the Kronecker product of two or more arrays. Parameters ---------- *args : list of array_like or array_like Input arrays. Returns ------- out : np.ndarray The Kronecker product of the input arrays. Examples -------- >>...
9f5f42760a19fb08c099ff59a879ec77ade222a4
3,596,494
def train(network_def, target_params, optimizer, states, actions, next_states, rewards, terminals, loss_weights, kappa, num_atoms, cumulative_gamma, double_dqn, rng): """Run a training step.""" online_params = optimizer.target def loss_fn(params,rng_input, target, loss_multipliers): def q_online(st...
71a024422aa6f2e58ae6912102fd52ea59ec2252
3,596,496
def GetChatID(message: Message): """ Get the group id of the incoming message""" return message.chat.id
1cf3c76b84b3c7d5fd10817652ed67e4883033c2
3,596,497
def _dayOfWeek(year, month, day): """ INTERNAL: calculates the day of week (0=Sun, 6=Sat) for the given date. """ return _julianDay(year, month, day) % 7
0d83869d5bf2bd2ede53937d9ce1be6a330ba165
3,596,498
def starts_expanded(name): """Return True if directory is a parent of initial cwd.""" if name is '/': return True l = name.split(dir_sep()) if len(l) > len(_initial_cwd): return False if l != _initial_cwd[:len(l)]: return False return True
b454812986853a65804968e249b35c4250b21a25
3,596,499
def simple_translate(english): """Simplest translation""" words = english.lower().translate(str.maketrans("", "", punctuation)).split() return " ".join([word[1:] + word[0] + "ay" for word in words])
be8eb204a51edeac24c04f829dab7099c6d238bc
3,596,500
def init_node_get_by_cluster_id(context, cluster_id, session=None): """Get init node ref by cluster id.""" return IMPL.init_node_get_by_cluster_id(context, cluster_id, session)
17fe0ddf8203ca284c790949e3202ea5a1bcc084
3,596,501
def make_label_button(window, text, command, width): """ Creates a button to be used as a widget label, grids it, and returns it based on the input parameters. The button is given solid relief, coloured white, and given a 2px thick black border. The button is padded 15px from the left and 15px above an...
030be37c065f6e11cae638de540418eec2a15cb6
3,596,502
def get_output_groups(targets, group_name): """Returns files in an output group from each target in a list. The returned list may not be the same size as `targets` if some of the targets do not contain the requested output group. This is not an error. Args: targets: A list of targets. ...
95282a6657520e364a965b2c9cd73daadac6c660
3,596,504
import re def check_token(token): """ Checks if the given token is a valid UUID.""" valid = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-" r"[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$") return valid.match(token)
be675b2fa04aac96b006ab94d8c0f65d8c02132f
3,596,505
def weightedLuminance(grayImg, kp=None): """ Foreground is middle 1/2x1/2 and bottom 1/4 strip Background is the rest """ wlMaskFg = np.zeros(grayImg.shape, dtype=grayImg.dtype) height, width = grayImg.shape cv2.rectangle(wlMaskFg, (width/4, height/4), (3*width/4, 3*height/4), 255, -1) ...
0bcb30751d7824cff05116669e904d3f26665102
3,596,506
def plug_in_body(tree, offsets, fields, objective_id, body="", conditions=None, cmv=None, ids_path=None, subtree=True, attr=None): """Translate the model into a set of "if" statemets in tableau syntax `depth` controls the size of indentation. As soon as a value is missing ...
64d7fd6ecc39d2773a0b52ac3836d7826a6c7535
3,596,507
def _unmix_various_gefs_intervals(init_time, start_floored, end_ceil, cloud_cover_mixed): """unmix intervals for each kind of interval length in GEFS forecast""" end_3h = init_time + pd.Timedelta('192hr') cloud_covers = [] if start_floored < end_3h: cloud_cove...
18b78c94efbdfc5889a9b87e7f37847bce7b0765
3,596,509
import torch import jax import tensorflow as tf def classical_jacobian(qnode): """Function to extract the Jacobian matrix of the classical part of a QNode""" def classical_preprocessing(*args, **kwargs): """Returns the trainable gate parameters for a given QNode input""" qnode.con...
6fa487fb6ee257b9f083c50f42b2a54d2977cb8a
3,596,510
from typing import List def lshift(array: List) -> List: """ Example ------- >>> lshift([0, 1, 2, 3, 4]) [1, 2, 3, 4, 0] >>> lshift([0]) [0] >>> lshift([]) [] """ return (array[1:] + [array[0]]) if len(array) > 1 else array
dbd9e23120eb136fb9beb02fda027174e75905da
3,596,511
import traceback def replay_walk(walk_to_run, step=False, log_errors=True, state=None): """ Run a single :class:`combtest.walk.Walk` :param Walk walk_to_run: self evident :param bool step: if True, step Action-by-Action through the Walk; the user hits a key to proceed to the nex...
7cf60a93cc2702968ff3d7b0d4db76189ac3c0c7
3,596,512
import math from typing import Optional def hybrd( fcn: CallableHybrd, x: np.ndarray, fvec: np.ndarray, xtol: float = math.sqrt(np.finfo(real).eps), *, maxfev: Optional[int] = None, ml: Optional[int] = None, mu: Optional[int] = None, epsfcn: float = 0.0, diag: Optional[np.ndarr...
e827775e6163c5718a1e573b4b26ff504d9d2b42
3,596,513