content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import json def main() -> int: """ Builds/updates aircraft.json codes """ craft = {} for line in AIRCRAFT_PATH.open().readlines(): code, _, name = line.strip().split("\t") if code not in craft: craft[code] = name json.dump(craft, OUTPUT_PATH.open("w")) return 0
e35bc5b5f8be2452d60b73b891bc5756931b18aa
3,650,100
def bootstrap_mean(x, alpha=0.05, b=1000): """ Calculate bootstrap 1-alpha percentile CI of the mean from a sample x Parameters ---------- x : 1d array alpha : float Confidence interval is defined as the b : int The number of bootstrap samples Returns ------- lb...
10b240f97196c7e2922574230a675d7e7c89038e
3,650,101
def _penalize_token(log_probs, token_id, penalty=-1e7): """Penalize token probabilities.""" depth = log_probs.shape[-1] penalty = tf.one_hot([token_id], depth, on_value=tf.cast(penalty, log_probs.dtype)) return log_probs + penalty
af8bf807438ff7ae96be0c5be0ec37fdbf81a5d1
3,650,102
import os def get_data_home(data_home=None): """ Returns ------- path: str `data_home` if it is not None, otherwise a path to a directory into the user HOME path. """ if data_home is None: user_home = os.path.expanduser('~') if user_home is None: r...
0cf23de46d9c4c54f1937d55cf14cdd0aeb6ceda
3,650,103
from typing import Iterable def minimize(function, vs, explicit=True, num_correction_pairs=10, tolerance=1e-05, x_tolerance=0, f_relative_tolerance=1e7, initial_inverse_hessian_estimate=None, max_iterations=1000, ...
22659e37afa29fde75ba344e0054207582e44fb3
3,650,104
def variation_reliability(flow, gamma=1): """ Calculates the flow variation reliability Parameters ---------- flow: numpy array flow values gamma: float, optional soft threshold Returns ------- variation reliability map (0 less reliable, 1 reliable) """ #comput...
cbdc4ab49402239e5e0fd484e5bf7bceaca383d4
3,650,105
import os def create_experiment_dirs(exp_dir): """ Create Directories of a regular tensorflow experiment directory :param exp_dir: :return summary_dir, checkpoint_dir: """ experiment_dir = os.path.realpath(os.path.join(os.path.dirname(__file__))) + "/experiments/" + exp_dir + "/" summary_d...
9707152a57a322ad2d935c2614386218c2c66ee9
3,650,106
def sutherland_hodgman_polygon_clipping(subject_polygon, clip_polygon): """Sutherland-Hodgman polygon clipping. .. note This algorithm works in regular Cartesian plane, not in inverted y-axis image plane, so make sure that polygons sent in are ordered clockwise in regular Cartesian sense! ...
f9ca2abfc00e17618c003debea1c77b1943b84ec
3,650,107
def get_means(df: pd.DataFrame, *, matching_sides: bool, matching_roots: bool) -> pd.Series: """ Calculates mean conditional probabilities from a given co-occurrence table with filters restricting for matching sides and roots. Args: df: The co-occurrences. matching_sides: ...
e6318fe4d284b134a8b655003b074ec554abca82
3,650,108
from typing import Dict import math def main( pathname: str, sheetname: str='Sheet1', min_row: int=None, max_row: int=None, min_col: int=None, max_col: int=None, openpyxl_kwargs: Dict=None ): """ main is the main function. It accepts details about a excel sheet and returns an HTML ...
b44884bf84909b3bb76553aff247df6a961f3289
3,650,109
def get_go_module_path(package): """assumption: package name starts with <host>/org/repo""" return "/".join(package.split("/")[3:])
1443d59391a36c7b9ba1d72ade9fd51f11cc1cc3
3,650,110
def get_hports(obj, *args, **kwargs): """ get_hports(obj, ...) Get hierarchical references to ports *within* an object. Parameters ---------- obj : object, Iterable - required The object or objects associated with this query. Queries return a collection of objects associated with the ...
f4a18a43018c10ef5860e974ed1d3eaf0ab73ac3
3,650,111
import argparse import logging def _command_from_cli() -> Command: """ Parse CLI arguments as a command. :return: parsed command. """ parser = argparse.ArgumentParser(prog="curl") parser.add_argument("url", help="Gemini URL to fetch") parser.add_argument( "-v", "--verbosity", acti...
6eb6f105485623d0f6212d1cf9657328a73d7418
3,650,112
def binary_cross_entropy(preds, targets, name=None): """Computes binary cross entropy given `preds`. For brevity, let `x = `, `z = targets`. The logistic loss is loss(x, z) = - sum_i (x[i] * log(z[i]) + (1 - x[i]) * log(1 - z[i])) Args: preds: A `Tensor` of type `float32` or `float64`. ...
b56e8bbaf16c688ebeb8be05b15a8c63745def3d
3,650,113
from typing import Optional def get_organization(name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetOrganizationResult: """ Use this data source to retrieve basic information about a GitHub Organization. ## Example Usage ```python import ...
f534525be6bc7bc7e6e3c80be9b94543b327a8e7
3,650,114
import array def numerator_LGG(mfld_dim: int, ambient_dim: array, vol: array, epsilon: array, prob: float) -> array: # our theory """ Theoretical M * epsilon^2 / K, our formula Parameters ---------- mfld_dim K, dimen...
b8f22f269cfb5a42ebb60118e6715c812d18ef73
3,650,115
from typing import OrderedDict def group_nodes(node_list, tree_height): """ Groups a list of nodes. """ dict = OrderedDict() for node in node_list: nodelist = _make_node_list(GroupNode(node), tree_height) if nodelist.get_name() not in dict: dict[nodelist.get_name()] = n...
50dc5f0356bed740e8b88e8bc05df01057fab29d
3,650,116
def power_over_line_rule_pos_rule(m, i, j, t): """ If decision variable m.var_x[i, j, t] is set to TRUE, the positive power over the line var_power_over_line is limited by power_line_limit :param m: complete pyomo model :type m: pyomo model :param i: startnode index of set_edge :type i: int...
c4d5a70f4cc2a67a45f11b3072fcb98c9f54e4e2
3,650,117
def join_tiles(tiles): """Reconstructs the image from tiles.""" return np.concatenate(np.concatenate(tiles, 1), 1)
559b88d8bdd42662961669050d29b6583dfbc706
3,650,118
from typing import Union from typing import List from re import T def parallel_imap(func, args, pool: Union[Pool, DumbPool]) -> List[T]: """@TODO: Docs. Contribution is welcome.""" result = list(pool.imap_unordered(func, args)) return result
0f250c0db3e534c10972c7866d101cb792ae7164
3,650,119
def solve2(lines, max_total): """Solve the problem for Part 2.""" points = parse_points(lines) xmin = min([p[0] for p in points]) xmax = max([p[0] for p in points]) ymin = min([p[1] for p in points]) ymax = max([p[1] for p in points]) size = 0 for x in range(xmin, xmax+1): for y ...
1e743f736f92f60df960d4946f89ae222054d4aa
3,650,120
import random import json def main(): """ 関数の実行を行う関数。 Return: """ def shuffle_dict(d): """ 辞書(のキー)の順番をランダムにする Args: d: 順番をランダムにしたい辞書。 Return: dの順番をランダムにしたもの """ keys = list(d.keys()) random.shuffle(keys) re...
eca402495d47c8d856568c2271f3de92b1ca2d4f
3,650,121
def scheme_load(*args): """Load a Scheme source file. ARGS should be of the form (SYM, ENV) or (SYM, QUIET, ENV). The file named SYM is loaded in environment ENV, with verbosity determined by QUIET (default true).""" if not (2 <= len(args) <= 3): expressions = args[:-1] raise SchemeError...
d41bb38e60d5e82022c0857629937774c6b180d5
3,650,122
import torch from typing import Optional from typing import Tuple def mask2idx( mask: torch.Tensor, max_length: Optional[int] = None, padding_value: int = 0, ) -> Tuple[torch.Tensor, torch.Tensor]: """ E.g. input a tensor [[T T F F], [T T T F], [F F F T]] with padding value -1, ret...
b0900aadd14c9eff8af4fcf8e9043127d2a3562c
3,650,123
def generate_paths(data, path=''): """Iterate the json schema file and generate a list of all of the XPath-like expression for each primitive value. An asterisk * represents an array of items.""" paths = [] if isinstance(data, dict): if len(data) == 0: paths.append(f'{path}') ...
367f244b44c254b077907ff8b219186bd820fccd
3,650,124
import argparse import sys def parseCommandArgs(argv): """ Parse command line arguments argv argument list from command line Returns a pair consisting of options specified as returned by OptionParser, and any remaining unparsed arguments. """ # create a parser for the command ...
ea7507851a71cff71f076db6eaaf35130f477efa
3,650,125
def run_hybrid_endpoint_overlap(topology_proposal, current_positions, new_positions): """ Test that the variance of the perturbation from lambda={0,1} to the corresponding nonalchemical endpoint is not too large. Parameters ---------- topology_proposal : perses.rjmc.TopologyProposal To...
2e966bd39296651c029c75936091a5377b63772c
3,650,126
import os def _node_list(rawtext, text, inliner): """ Return a singleton node list or an empty list if source is unknown. """ source = inliner.document.attributes['source'].replace(os.path.sep, '/') relsource = source.split('/docs/', 1) if len(relsource) == 1: return [] if text in ...
c27c7aa3c4a62a550ec6c2495237fecd969e97c5
3,650,127
def enable_heater_shaker_python_api() -> bool: """Get whether to use the Heater-Shaker python API.""" return advs.get_setting_with_env_overload("enableHeaterShakerPAPI")
f849413c072034a15f0242e4b65dd36753a8d6f1
3,650,128
def solidityKeccak(abi_types, values): """ Executes keccak256 exactly as Solidity does. Takes list of abi_types as inputs -- `[uint24, int8[], bool]` and list of corresponding values -- `[20, [-1, 5, 0], True]` """ if len(abi_types) != len(values): raise ValueError( "Length ...
2e31d05404b204a233694f14e808c78e96e67aed
3,650,129
def check_segment_end(segment, duration): """ not all segments have an end set... helper to check for that without concern duration should be passed in to handle no segment end """ end = duration #TODO: What about no end on segment? # get end of content (total length) if segment.end...
ccb226f7ff9ff886b9b9cfcb2df2677ecf250b43
3,650,130
def run_fib_recursive_mathy_cached(n): """Return Fibonacci sequence with length "n" using "fib_recursive_mathy_cached". Args: n: The length of the sequence to return. Returns: A list containing the Fibonacci sequence. """ return [fib_recursive_mathy_cached(i + 1) for i in range...
7cdd01ab747bccbd95dbb886e680c9214c2f883d
3,650,131
def binning(LLRs_per_window,info,num_of_bins): """ Genomic windows are distributed into bins. The LLRs in a genomic windows are regarded as samples of a random variable. Within each bin, we calculate the mean and population standard deviation of the mean of random variables. The boundaries of the bins ...
bc872aa9d32545a91d9854d83ba2efb238cbfc02
3,650,132
from typing import Optional from typing import List def conj(node: BaseNode, name: Optional[Text] = None, axis_names: Optional[List[Text]] = None) -> BaseNode: """Conjugate a `node`. Args: node: A `BaseNode`. name: Optional name to give the new node. axis_names: Optional list of nam...
9baffa5ad00289b0f44ad4953dc12931eccb8ed9
3,650,133
from typing import Union import torch def f1( predictions: Union[list, np.array, torch.Tensor], labels: Union[list, np.array, torch.Tensor], ): """Calculate F1 score for binary classification.""" return f1_score(y_true=labels, y_pred=predictions)
e35fa02281351a2c2003982fc6450aa4d8e5561b
3,650,134
def length(v, squared=False, out=None, dtype=None): """Get the length of a vector. Parameters ---------- v : array_like Vector to normalize, can be Nx2, Nx3, or Nx4. If a 2D array is specified, rows are treated as separate vectors. squared : bool, optional If ``True`` the sq...
16caea4730b7dfd7cfcc71d253ee1fc7691fe05d
3,650,135
def generateUniqueId(): """ Generates a unique ID each time it is invoked. Returns ------- string uniqueId Examples -------- >>> from arch.api import session >>> session.generateUniqueId() """ return RuntimeInstance.SESSION.generateUniqueId()
f5dd066c1f9e6670b1e0949c890d5abc9931142a
3,650,136
def order_rep(dumper, data): """ YAML Dumper to represent OrderedDict """ return dumper.represent_mapping(u'tag:yaml.org,2002:map', data.items(), flow_style=False)
6b455d49cd5702324f4b1e825dabb4af90734730
3,650,137
def match_format( format_this: spec.BinaryInteger, like_this: spec.BinaryInteger, match_pad: bool = False, ) -> spec.BinaryInteger: """ will only match left pads, because pad size cannot be reliably determined """ output_format = get_binary_format(like_this) output = convert(data=forma...
0a9638cbe5e522b1c7dc9ee316e559f9238b9abe
3,650,138
def parse_nonterm_6_elems(expr_list, idx): """ Try to parse a non-terminal node from six elements of {expr_list}, starting from {idx}. Return the new expression list on success, None on error. """ (it_a, it_b, it_c, it_d, it_e, it_f) = expr_list[idx : idx + 6] # Match against and_n. if ...
1c82d6b0654cf15c5aafec2c08e92c86cb5a4543
3,650,139
def make1d(u, v, num_cols=224): """Make a 2D image index linear. """ return (u * num_cols + v).astype("int")
1f37c7ae06071ce641561eadc1d0a42a0b74508d
3,650,140
def xkcd(scale=1, length=100, randomness=2): """ Turn on `xkcd <https://xkcd.com/>`_ sketch-style drawing mode. This will only have effect on things drawn after this function is called. For best results, the "Humor Sans" font should be installed: it is not included with Matplotlib. Parameters...
1ce7aed60b2b67febb1658e98f14434005f3434a
3,650,141
def team_size(data): """ Computes team size of each paper by taking the number of authors in 'authors' Input: - df: dataframe (dataset); or just the 'authors' column [pandas dataframe] Output: - team: vector of team_size for each paper of the given...
76a5aafe90cf63fb0506525e566ca7759d0e27ce
3,650,142
from datetime import datetime def header_to_date(header): """ return the initial date based on the header of an ascii file""" try: starttime = datetime.strptime(header[2], '%Y%m%d_%H%M') except ValueError: try: starttime = datetime.strptime( header[2] + '_' + he...
3e2757ae39a2a9008a5f0fb8cd8fe031770c83ad
3,650,143
def PhenylAlanineCenterNormal(residue): """ Phenylalanine """ PHE_ATOMS = ["CG", "CD1", "CD2", "CE1", "CE2", "CZ"] return RingCenterNormal(residue, PHE_ATOMS)
4d96c7fe14bd411749136cf1569f32bd1c01679d
3,650,144
import os def get_labels(input_dir): """Get a list of labels from preprocessed output dir.""" data_dir = _get_latest_data_dir(input_dir) labels_file = os.path.join(data_dir, 'labels') with file_io.FileIO(labels_file, 'r') as f: labels = f.read().rstrip().split('\n') return labels
6251ab3f6e03fb254a1786f686fb11a54e6fea52
3,650,145
from datetime import datetime def documents_concordance(response: Response, request: Request=Query(None, title=opasConfig.TITLE_REQUEST, description=opasConfig.DESCRIPTION_REQUEST), paralangid: str=Query(None, title=opasConfig.TITLE_DOCUMENT_CONCORDANCE_ID, descript...
c053a8da79173dbc6cbd7a5a53414e594bf972f0
3,650,146
import sys def query_yes_no(question, default=True): """Ask a yes/no question via intput() and return their answer. "question" is a string that is presented to the user. "default" is the default return value True or False The "answer" return value is True for "yes" or False for "no". https://st...
529d03035b0d782a8a53c4c39b162fc9b81d9ad8
3,650,147
def diamBiasK(diam, B, Kexcess, RshellRstar=2.5): """ diameter bias (>1) due to the presence of a shell only works for scalar diam, B and Kexcess validity: Kexcess>0 and Kexcess<0.1 and B*diam <~ 500 return 1 if Kexcess <= 0 """ global __biasData, KLUDGE d = np.abs(__biasData['Rshell/...
6754ee70c64b2028cd5b72d3331e65bb64ea53b4
3,650,148
def interpolate_poses_from_samples(time_stamped_poses, samples): """ Interpolate time stamped poses at the time stamps provided in samples. The poses are expected in the following format: [timestamp [s], x [m], y [m], z [m], qx, qy, qz, qw] We apply linear interpolation to the position and use SLERP for ...
3131fe895a53b7d6c262930c635ce8cfa1c277f2
3,650,149
def test_add_client(case, client_name, client=None, client_id=None, duplicate_client=None, check_errors=False, log_checker=None): """ UC MEMBER_47 main test method. Tries to add a new client to a security server and check logs if ssh_host is set. :param case: MainController object ...
0b15ee41c8a61c0602e89e59a6343e67c6dc712f
3,650,150
from typing import List def get_data_unit_labels(data_unit: DataUnit) -> List[Attributes]: """ Extract important information from data_unit. That is, get only bounding_boxes and associated classifications. Args: data_unit: The data unit to extract information from. Returns: list of pairs ...
36577b13713258fe1542c9bfc377a469ed5d6fd6
3,650,151
def calc_4points_bezier_path(svec, syaw, spitch, evec, eyaw, epitch, offset, n_points=100): """ Compute control points and path given start and end position. :param sx: (float) x-coordinate of the starting point :param sy: (float) y-coordinate of the starting point :param syaw: (float) yaw angle at...
455225b10c034895c32329bc14ce6dc384f5e0b3
3,650,152
import copy def permutationwithparity(n): """Returns a list of all permutation of n integers, with its first element being the parity""" if (n == 1): result = [[1,1]] return result else: result = permutationwithparity(n-1) newresult = [] for shorterpermutation in result: ...
218b728c2118a8cca98c019dff036e0ae2593974
3,650,153
from typing import List import torch import logging def _train_model(model: BertForValueExtraction, optimizer, scheduler, train_data_loader, val_data_loader) -> List[int]: """ Main method to train & evaluate model. :param model: BertForValueExtraction object :param optimizer: optimizer :param sch...
fbf5a588d9da24f72c0955c767f454297d91e74d
3,650,154
def mass_at_two_by_counting_mod_power(self, k): """ Computes the local mass at `p=2` assuming that it's stable `(mod 2^k)`. Note: This is **way** too slow to be useful, even when k=1!!! TO DO: Remove this routine, or try to compile it! INPUT: k -- an integer >= 1 OUTPUT: a r...
35f85dd32e3c81a4921c5d5a87ab4cdc13e8ae46
3,650,155
import logging def get_paginiation_data(first_pagination_url, family, cazy_home, args, session): """Parse the first paginiation page and retrieve URLs to all pagination page for the Family. :param first_pagination_url: str, URL to the fist page of the family :param family: Family class instance, represen...
89cdd6e0d333cc69f0b92c202b6f0d4257849382
3,650,156
def gravitationalPotentialEnergy(mass, gravity, y): """1 J = 1 N*m = 1 Kg*m**2/s**2 Variables: m=mass g=gravity constant y=height Usage: Energy stored by springs""" U = mass*gravity*y return U
f4fcfc9e7ddac8b246b2200e3886b79f6706936e
3,650,157
from dateutil import tz import os def subset_by_supported(input_file, get_coords, calls_by_name, work_dir, data, headers=("#",)): """Limit CNVkit input to calls with support from another caller. get_coords is a function that return chrom, start, end from a line of the input_file, ...
16d83a8128ae646dd9e3d343bd5c137b33625ea2
3,650,158
def to_list(obj): """List Converter Takes any object and converts it to a `list`. If the object is already a `list` it is just returned, If the object is None an empty `list` is returned, Else a `list` is created with the object as it's first element. Args: obj (any object): the object...
3ca373867ea3c30edcf7267bba69ef2ee3c7722e
3,650,159
from molsysmt.basic import select, extract def remove(molecular_system, selection=None, frame_indices=None, to_form=None, syntaxis='MolSysMT'): """remove(item, selection=None, frame_indices=None, syntaxis='MolSysMT') Remove atoms or frames from the molecular model. Paragraph with detailed explanation. ...
a2232e6226f76df6760eef59aab0f31edf7a75ec
3,650,160
def macd_cross_func_pd(data): """ 神一样的指标:MACD """ if (ST.VERBOSE in data.columns): print('Phase macd_cross_func', QA_util_timestamp_to_str()) MACD = QA.QA_indicator_MACD(data) MACD_CROSS = pd.DataFrame(columns=[ST.MACD_CROSS, FLD.MACD_CROSS_JX...
d7c970efc931a3f1f2c25e51cf8e55e630eb37ad
3,650,161
import json def jsonp_response(data, callback="f", status=200, serializer=None): """ Returns an HttpResponse object containing JSON serialized data, wrapped in a JSONP callback. The mime-type is set to application/x-javascript, and the charset to UTF-8. """ val = json.dumps(data, default=seri...
3ac71358043184b84b2f1f610a852b0b587d158d
3,650,162
import collections def enhance_bonds(bond_dataframe, structure_dict): """Enhance the bonds dataframe by including derived information. Args: bond_dataframe: Pandas dataframe read from train.csv or test.csv. structure_dict: Output of :func:`make_structure_dict`, after running :func:`enhance_st...
46836576b6bec8e1ca9f5685185d0f379b9e63f6
3,650,163
import numbers def _tofloat(value): """Convert a parameter to float or float array""" if isiterable(value): try: value = np.asanyarray(value, dtype=np.float) except (TypeError, ValueError): # catch arrays with strings or user errors like different # types o...
796b03699cb3b1e201436b6eb61df0636318de14
3,650,164
import time import functools def sp2mgc(sp, order=20, alpha=0.35, gamma=-0.41, miniter=2, maxiter=30, criteria=0.001, otype=0, verbose=False): """ Accepts 1D or 2D one-sided spectrum (complex or real valued). If 2D, assumes time is axis 0. Returns mel generalized cepstral coefficients. ...
01e380ddf10c56c3c4b9d09726ac98aef58715ca
3,650,165
def has_prefix(sub_s): """ :param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid :return: (bool) If there is any words with prefix stored in sub_s """ for key, val in word_dic.items(): if key.startswith(sub_s): return True else: pass return False
b52937578d62d464df3131374a5dc0bdca735807
3,650,166
def _package_data(vec_f_image, vec_f_imageBscan3d, downscale_size, downscale_size_bscan, crop_size, num_octa, str_angiography, str_structure, str_bscan, vec_str_layer, vec_str_layer_bscan3d, str_bscan_layer, dict_layer_order, dict_layer_order_bscan3d): """ Organizes the angio...
dfe9ed58bd25715948cfb09f069c76d2f844df3c
3,650,167
def apply_padding_by_last(list_of_lists): """ The same as applying pad_into_lists followed by carry_previous_over_none but takes a list of lists instead of events Args: lists_of_lists: list of lists with possibly different lengths Returns: lists of lists padded to the same length by ...
83316fedb46230665fc543d4a3961cb72692023b
3,650,168
def combine_patterns( *patterns: str, seperator: Expression = None, combine_all=False ) -> str: """ Intelligently combine following input patterns. Parameters ---------- patterns : The patterns to combine. seperator : The seperator to use. If None, the default seperator :dat...
1bcd703a183b72d88a8bfa7f1680754e0e3ee35e
3,650,169
from datetime import datetime async def utc_timediff(t1, t2): """ Calculate the absolute difference between two UTC time strings Parameters ---------- t1, t2 : str """ time1 = datetime.datetime.strptime(t1, timefmt) time2 = datetime.datetime.strptime(t2, timefmt) timedelt = time1...
ba0b406048467029f6d05d72898b534dd6309e45
3,650,170
def function(): """ >>> function() 'decorated function' """ return 'function'
46b892fb70b5672909d87efcf76ffd3f96f9cf7f
3,650,171
def load_stopwords(file_path): """ :param file_path: Stop word file path :return: Stop word list """ stopwords = [line.strip() for line in open(file_path, 'r', encoding='utf-8').readlines()] return stopwords
9cb6578b5cbc608bc72da7c4f363b4f84d0adbb7
3,650,172
def hello(): """Return a friendly HTTP greeting.""" return 'abc'
9acda65833bec5976c3e2f0ffa77df8a2a7537bf
3,650,173
def show_ip_ospf_route( enode, _shell='vtysh', _shell_args={ 'matches': None, 'newline': True, 'timeout': None, 'connection': None } ): """ Show ospf detail. This function runs the following vtysh command: :: # show ip ospf route :param dic...
0f80ef7a46211002141ea489459df6be78aeeb28
3,650,174
from typing import get_origin def attrs_classes( verb, typ, ctx, pre_hook="__json_pre_decode__", post_hook="__json_post_encode__", check="__json_check__", ): """ Handle an ``@attr.s`` or ``@dataclass`` decorated class. This rule also implements several hooks to handle complex case...
9db1f0a9ddefe1fb32d52331e158e8e2565b2697
3,650,175
import torch def delta(pricer, *, create_graph: bool = False, **kwargs) -> torch.Tensor: """Computes and returns the delta of a derivative. Args: pricer (callable): Pricing formula of a derivative. create_graph (bool): If True, graph of the derivative will be constructed, allowing...
88216117ba58afd68c88515210ad927a581eaf54
3,650,176
def formula_search(min_texts, max_texts, min_entries, max_entries): """Filter search results""" result = Cf.query.filter( Cf.n_entries >= (min_entries or MIN), Cf.n_entries <= (max_entries or MAX), Cf.unique_text >= (min_texts or MIN), Cf.unique_text <= (max_texts or MAX) )....
938cc7ea25c2fe1bcd240ad4b60e517295eebe7b
3,650,177
from datetime import datetime import uuid def versioneer(): """ Function used to generate a new version string when saving a new Service bundle. User can also override this function to get a customized version format """ date_string = datetime.now().strftime("%Y%m%d") random_hash = uuid.uuid4(...
7c5123d28e3bee45f2c9f7d519e830cf80e9fea8
3,650,178
import http def request_url(method, url): """Request the specific url and return data""" try: r = http.request(method, url) if r.status == 200: return r.data.decode('utf-8') else: raise Exception("Fail to {} data from {}".format(method, url)) except Exceptio...
9d25df49c9996364a9cb0195b90454378aefa5fd
3,650,179
def _ifail(repo, mynode, orig, fcd, fco, fca, toolconf, labels=None): """ Rather than attempting to merge files that were modified on both branches, it marks them as unresolved. The resolve command must be used to resolve these conflicts.""" # for change/delete conflicts write out the changed versio...
4d90ff7296fa9042392c7ffe28034fbbf804614f
3,650,180
from typing import Callable def __noise_with_pdf(im_arr: np.ndarray, pdf: Callable, **kwargs) -> np.ndarray: """Apply noise to given image array using pdf function that generates random values.""" util.check_input(im_arr) im_arr = im_arr/255.0 noise = pdf(**kwargs, size=im_arr.shape) out_im = im_a...
d1b9f612f4490ac526c2a952c54ee03cbedc2139
3,650,181
import subprocess def get_git_revision_hash(): """Returns the git version of this project""" return subprocess.check_output( ["git", "describe", "--always"], universal_newlines=True )
51c76a0e814cd8336d488c6d66a17ba3422c5c66
3,650,182
def train_test_split(df, frac): """ Create a Train/Test split function for a dataframe and return both the Training and Testing sets. Frac refers to the percent of data you would like to set aside for training. """ frac = round(len(df)*frac) train = df[:frac] test = df[frac:] r...
8e233e017a261141f57f7b2bff9a527e275d2ed9
3,650,183
def load_special_config(config_filename, special_type, image_type='extent'): """Loads the google earth ("google"), science on a sphere ("sos"), or any other special type of image config. """ cfg = load_config(config_filename) # Promote the image type's keys cfg = _merge_keys(cfg, cfg[image_typ...
b3a38d4ea9e39e42685604b4f01c7dcfa8ee2cdd
3,650,184
def softmax_strategy_cim(attrs, inputs, out_type, target): """softmax cim strategy""" strategy = _op.OpStrategy() strategy.add_implementation( wrap_compute_softmax(topi.nn.softmax), wrap_topi_schedule(topi.cim.schedule_softmax), name="softmax.cim", ) return strategy
11c5e581d9ad2814068558bc9faf24f57f5acba3
3,650,185
def get_statements_by_hash(hash_list, ev_limit=100, best_first=True, tries=2): """Get fully formed statements from a list of hashes. Parameters ---------- hash_list : list[int or str] A list of statement hashes. ev_limit : int or None Limit the amount of evidence returned per Statem...
26924f7d05b35b6655eb69989a32677edf1eedbf
3,650,186
def _is_in(val_set): """Check if a value is included in a set of values""" def inner(val, val_set): if val not in val_set: if isinstance(val_set, xrange): acceptable = "[%d-%d]" % (val_set[0], val_set[-1]) else: acceptable = "{%s}" % ", ".join(val_...
462afc33c73ae78bd62fa446f652a30492150643
3,650,187
import json def commit_config(config): """ :param config: :return: """ try: json_response = apply_config(config, False) # Checks for config validation with Write Param set to False if "message" in json_response: # If config is valid write the config return json_respon...
636b15704175373c18c2eb7229af2337058a076a
3,650,188
def onebyone(transform, loglikelihood, parameter_names, prior, start = 0.5, ftol=0.1, disp=0, nsteps=40000, parallel=False, find_uncertainties=False, **args): """ **Convex optimization based on Brent's method** A strict assumption of one optimum between the parameter limits is used. The bounds are narrowed until...
86a12d7d7b738cc8ab7d8e65e3765e6b81f825b4
3,650,189
import os def load_ucs_manager_config(): """ loads the test configuration into the UCS Manger """ logs.info_1('Loading UCSPE emulator from {0}'.format(fit_common.fitcfg()['ucsm_config_file'])) try: handle = ucshandle.UcsHandle(UCSM_IP, UCSM_USER, UCSM_PASS) ...
23d087132550967804533cdf45b81a4762b8aaa4
3,650,190
def test_data(): """Test data object for the main PlantCV module.""" return TestData()
f8b2dc49d460ddadcd74c89da1159274660ecdfb
3,650,191
import os def file_with_reftrack(request, tmpdir, parent_reftrack): """Return a filename to a scene with the reftracks from parent_reftrack fixture.""" fn = tmpdir.join("test1.mb") f = cmds.file(rename=fn.dirname) cmds.file(save=True, type='mayaBinary') def fin(): os.remove(f) reques...
8c760113e8143d1e842ca50b07f05eb9dcb9834a
3,650,192
def make_cmap(infile): """Call correct cmap function depending on file.""" cornames = ["coherence-cog.tif", "phsig.cor.geo.vrt", "topophase.cor.geo.vrt"] phsnames = ["unwrapped-phase-cog.tif", "filt_topophase.unw.geo.vrt"] if infile in cornames: cpt = make_coherence_cmap() elif infile in ph...
cd6408e1f8718b7073d1c5baa4e5a20ab8553720
3,650,193
def tail_correction(r, V, r_switch): """Apply a tail correction to a potential making it go to zero smoothly. Parameters ---------- r : np.ndarray, shape=(n_points,), dtype=float The radius values at which the potential is given. V : np.ndarray, shape=r.shape, dtype=float The potent...
50934031776cfd4d92ef7a05ca2e63c215518352
3,650,194
def process_input(input_string): """ >>> for i in range (0, 5): ... parent_node = Node(None) ... parent_node.random_tree(4) ... new_node = process_input(parent_node.get_test_string()) ... parent_node.compute_meta_value() - new_node.compute_meta_value() 0 0 0 0 ...
3cea94806034ebd3d95fdc7b5c8844d79698a684
3,650,195
import os def _get_version_info(blade_root_dir, svn_roots): """Gets svn root dir info. """ svn_info_map = {} if os.path.exists("%s/.git" % blade_root_dir): cmd = "git log -n 1" dirname = os.path.dirname(blade_root_dir) version_info = _exec_get_version_info(cmd, None) if ver...
533b7d7e19c3dec60450fb62af05f11e320a3940
3,650,196
def equiv_alpha(x,y): """check if two closed terms are equivalent module alpha conversion. for now, we assume the terms are closed """ if x == y: return True if il.is_lambda(x) and il.is_lambda(y): return x.body == il.substitute(y.body,zip(x.variables,y.variables)) return False ...
27cd246e217403320bd16580029eb1d7c0122e33
3,650,197
def delete(isamAppliance, file_id, check_mode=False, force=False): """ Clearing a common log file """ ret_obj = {'warnings': ''} try: ret_obj = get(isamAppliance, file_id, start=1, size=1) delete_required = True # Exception thrown if the file is empty # Check for Docker ...
7f27555eb33e489a59e1d9d1a7127713afd25d2f
3,650,198
def filter_imgs(df, properties = [], values = []): """Filters pandas dataframe according to properties and a range of values Input: df - Pandas dataframe properties - Array of column names to be filtered values - Array of tuples containing bounds for each filter Output: df - Filter...
cdc5c8bfef10fae60f48cee743df049581a0df04
3,650,199