content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import json def check_downsample_queue(args): """ Check queue for downsample jobs. Also marks downsample as in progress if message found. Args: (dict): { 'queue_url': <URL of SQS queue>, 'sfn_arn': <arn of the downsample step fcn> } Returns: (dict): { 'start_downsamp...
adce4257b14f5dda17df9ccc29929a6a1c34b863
36,072
def pindajya(k: int): """ Return the kth pindajya computed by the nilakantha recurrence Inputs: k (int) : index from 0 to 23 Outputs: int : kth pindajya """ assert ((k>=0) & (k<24)), f"Input must be between 0 and 23 inclusive, got {k}" return float(_b[k])
63ddf7ab855b9fc8056a66264e6748f7c53240bf
36,073
from typing import Iterable from typing import Tuple from typing import Sequence def g2xys(m: Basemap, coords: Iterable[Tuple[float, float]]) \ -> Tuple[Sequence[float], Sequence[float]]: """ Convert an iterable with geographical coordinates into two sequences with x- and y-coordinates in the pl...
e6e1d761351c28bc23061ae0c4ed323ac33d17ae
36,074
def create_linear_transform(linear_transform, features): """Function for creating linear transforms. Parameters ---------- linear_transform : {'permutation', 'lu', 'svd'} Linear transform to use. featres : int Number of features. """ if linear_transform.lower() == 'permutati...
96cac529cc6e20e7d2976fcad9b22e9e4f05c60a
36,075
def cross_entropy(y_pred,y): """ Cross entropy loss for classification purposes""" epsilon = 0.001 # To prevent overflow and ensure numerical stability return sum(-y*np.log(y_pred+epsilon))
96eddb997a706dc0c1b92fa2f423bb00b5f216c1
36,076
def create(name, root, *args, **kwargs): """ Create a dataset instance. Parameters ---------- name : str The dataset name. Can be one of 'pitts', 'tokyo'. root : str The path to the dataset directory. """ if name not in __factory: raise KeyError("Unknown dataset:...
0a36c94451aad03edc819bfa97007166efdd5ba3
36,077
from typing import cast def get_time_stamp_from_lidar_pc(lidar_pc: LidarPc) -> int: """ Extracts the time stamp from a LidarPc. :param lidar_pc: Input lidar pc. :return: Timestamp in micro seconds. """ return cast(int, lidar_pc.ego_pose.timestamp)
245111bafebe9b2e9ec701d9c4a7f0912bb655da
36,078
import torch def infer_mask(seq, eos_ix, batch_first=True, include_eos=True, dtype=torch.float): """ compute length given output indices and eos code :param seq: tf matrix [time,batch] if batch_first else [batch,time] :param eos_ix: integer index of end-of-sentence token :param include_eos: if Tru...
6038291eecc96898491e685c63f69187dca7e8fc
36,079
def print_alignment(match,test_instance,gold_instance,flip=False): """ print the alignment based on a match Args: match: current match, denoted by a list test_instance: instances of AMR 1 gold_instance: instances of AMR 2 filp: filp the test/gold or not""" result=[] for i...
27e17e2ecdcf08325667d753bed7301fbb15c111
36,080
def beta_labelling(LLR,ln_beta): """ apply a filter to the LLR array : if the LLR is above log_beta : return 1 else : return 0 """ beta_func = np.vectorize(lambda a,b: 1 if a>b else 0) return beta_func(LLR,ln_beta)
c424ae565ca3b43a9fe696eaebe3e01838a87725
36,081
def tr_sqrt(A, rank=None): """Return the trace of the sqrt of a positive semidefinite operator. """ if rank is None: el = eigvalsh(A, sort=False) else: el = eigvalsh(A, k=rank, which='LM', backend='AUTO') return np.sum(np.sqrt(el[el > 0.0]))
2b86a07f51efaa3d0e89e84bffb5425ee67c4bdc
36,082
def myBasicTreeXMLLines(tree): """ Takes: - tree (ete3.TreeNode) Returns: (list): list of xml lines """ lines = ["<phylogeny>"] indentChar = " " tmp = myBasicTreeXMLLinesAux(tree) for l in tmp: lines.append( indentChar + l ) lines.append("</phylogeny>") ...
ffdb4ec91d9f70dc2d320ba19c4b7207f87b30d5
36,083
from typing import Iterator def parse(tokens, parse_until=None, start_from=0): """ :param tokens: Tokens to parse :type tokens: list[Token] :param parse_until: :param start_from: :return: AstTree """ tree = AstTree() it = Iterator(tokens, start_from=start_from) wh...
9e712ab053fe66aeca3ebdeada5dd03bfd654102
36,084
import torch import json def silero_lang_detector_116(**kwargs): """Silero Language Classifier (116 languages) Returns a model with a set of utils Please see https://github.com/snakers4/silero-vad for usage examples """ hub_dir = torch.hub.get_dir() model = init_jit_model(model_path=f'{hub_di...
fb3c5ce00f145c6f9b37184b65059d6a44bb3317
36,085
def isPrime(n): """Returns True if n is prime.""" if n == 2: return True if n == 3: return True if n % 2 == 0: return False if n % 3 == 0: return False i = 5 w = 2 while i * i <= n: if n % i == 0: return False i += w ...
a11dc193b69d3f16b67a32c39ac24c90ed9b096c
36,086
def is_saved(response: Response, name: str, port: int) -> bool: """Wait for the response showing that saving has taken place.""" expected_url = f"http://localhost:{port}/api/contents/{name}" method = response.request.method try: t = response.json().get("type") except AttributeError: ...
46939fed0eee343b48ead3ccdb21959ac20ed7f4
36,087
def filter_polygons(state, header): """ Removes any non-polygon sources from the state file. We are only interested in parsing parcel data, which is marked as Polygon in the state file. """ filtered_state = [] for source in state: if 'Polygon' in source[header.index('geometry type'...
d100e6a4e87dccdc42c7217dc1e793e4353237e2
36,088
def conv_out_init(obj: MyArray, results: ArgTuple[BaseArray], outputs: OutTuple[BaseArray], conv: _ty.Sequence[bool] = ()) -> ArgTuple[MyArray]: """Process outputs in an __array_ufunc__ method using a constructor. Creates an instance of ``type(obj)`` with `...
9a54fbb82be9ff70cce2cd3f1de20071a1d3a503
36,089
def detect_blobs(im,im_out,params): """ :param im: input image to track :param im_out: image to display bounding boxes :param params: Blob detector params :return: blob, im_disp, bbox """ detector = cv2.SimpleBlobDetector_create(params) blob_im = im blob = detector.detect(blob_i...
4ee4c48be0f1df07f43336b0c33ca68083c015b3
36,090
import copy def get_thermal_instance(wildcards): """ Returns a formatted template Arguments: rest_base - Base URL of the RESTful interface ident - Identifier of the chassis """ c = copy.deepcopy(_TEMPLATE) c['@odata.context'] = c['@odata.context'].format(**wildcards) ...
06997ea9468c034a276a852e096a8d1e0f55a263
36,091
def getWorldSimState(world): """Returns a dict containing a copy of all variables that are simulated in the world. Can be used with setWorldSimState to save/ restore state. NOTE: this does not perfectly save the state of a Simulator! To do that, you must use the Simulator().getState()/saveState()...
f9198abab6e78dee9b0407d6a64adc062a505a13
36,092
import unicodedata def unicode_normalize(text): """Return the given text normalized to Unicode NFKC.""" normalized_text = unicodedata.normalize('NFKC', text) return normalized_text
1b6defacd09665412a1b31dd48f5291c4984d044
36,093
import importlib def import_obj(clsname, default_module=None): """ Import the object given by clsname. If default_module is specified, import from this module. """ if default_module is not None: if not clsname.startswith(default_module + '.'): clsname = '{0}.{1}'.format(default...
8cb064348b7b38e1e3f659240f4bc9677237d3fd
36,094
def _SelectUploadCompressionStrategy(object_name, is_component=False, gzip_exts=False, gzip_encoded=False): """Selects how an upload should be compressed. This is a helper function for _UploadFileToObject...
1ddb0d8640a05aa12ce8ee7ba76a84c03f99e7ec
36,095
def polynomial_features(X, degree): """ Make polynomial feature. Parameters: ----------- X: ndarray of shape (n_samples, n_features) The input samples degree: int The highest of the degrees of the polynomial's monomials (individual terms) with non-zero coefficients Returns: -...
914715295ffa5469dbc1342ba6c78720de81b271
36,096
def flesch_reading_ease_score(sentences: int, words: int, syllables: int, *, is_russian: bool = False) -> float: """ Calculate the Flesch-Kincaid score. """ if not sentences or not words: return 0.0 # Flesch-Kincaid score constants: x_grade: float = FRES_RU.X_GRADE if is_russian else FR...
9ab6abd5ddf874de4a14e02a580502aa103086eb
36,097
import select def add_publication_to_group(project, publication_id): """ Add a publication to a publication_group POST data MUST be in JSON format POST data MUST contain the following: group_id: numerical ID for the publication_group """ request_data = request.get_json() if not reque...
966984eb8994c38259795500dfbad7fd9e4f1044
36,098
def is_compatible(feature: Feature, other: Feature): """Determines if two features are compatible with one another.""" return feature.api == other.api and not ( other.version.major > feature.version.major or ( other.version.major == feature.version.major and other.version...
5cb4f94a9fb8b8faf666aa018bbec7cd33abedc9
36,099
def get_tworay_path_loss(range_m, freq_hz, tx_ht_m, rx_ht_m, include_atm_loss=True, atmosphere=None): """ Computes the two-ray path loss according to L = 10*log10(R^4/(h_t^2*h_r^2)) This model is generally deemed appropriate for low altitude transmitters and receivers, with a flat Earth model....
343d3b3e2df86f209d2b175e06f36ff695178818
36,100
def check_bots_database(): """Check for elements in bot's database. Returns: int: Size of list if there is any elements None: If table is empty """ db_status = database.get_data("confDB", False, "SELECT bot_name FROM tokens") return None if not db_s...
7f7302d9f6edb4bfd42cc053f81875de728d11f6
36,101
from datetime import datetime def get_features_for_commit_people(git_commit): """Retrieves the people associated with a git commit Arg: git_commit(dict): a commit message parsed into a dictionary Return: (tuple): relevant people and type extracted from the commit """ curr_time = datetime.datetime....
2f1ba38bb1f190ead2c1f4974f023feaeb55bca2
36,102
from bs4 import BeautifulSoup def get_url_source(url_name): """ If you already know the url_name or if you have run through the get_noaa_forecast_url(), then you can send in the url here. Get the source information for the url and place the information into a BeautifulSoup object, so that we can do an...
f7ab186d2d9f68020286317f28a169ad296d39fd
36,103
import torch def norm(x): """ Normalize (z-norm) from [0,1] range to [-1,1] """ out = (x - 0.5) * 2.0 if isinstance(x, torch.Tensor): return out.clamp(-1, 1) elif isinstance(x, np.ndarray): return np.clip(out, -1, 1) else: raise TypeError( "Got unexpected objec...
43dba4ec5c7e44daccef4231db5667319d73cc88
36,104
def gen_gp_loss(gp): """Generate an internal objective, `dlik_dh * H`, for a given GP layer. """ def loss(_, H): dlik_dh_times_H = H * K.gather(gp.dlik_dh, gp.batch_ids[:gp.batch_sz]) return K.sum(dlik_dh_times_H, axis=1, keepdims=True) return loss
e3fe0f3634c1309acce9cc65978e028da2fa05ff
36,105
from typing import Tuple from typing import Optional def set_market(asset_form: NewAssetForm) -> Tuple[Optional[Market], Optional[str]]: """Set a market for the to-be-created asset. Return the market (if available) and an error message.""" market = None market_error = None if int(asset_form.marke...
9d597acc1b12cbc95fea929939292a0f7641f550
36,106
def _evaluateMockedResponse(table, cmd_dict, success=True, is_save=True): """ Evaluates if the response from a mock is as expected. :param Table table: :param dict cmd_dict: :param bool success: value of success :param bool is_save: value of is_save """ response, returned_is_save = \ table.p...
20b5a3ff800e012cffc65fd0876656ced9e45f89
36,107
def plot_resource_utilization(filename, subplt, ylim=None, pattern=None): """ :param filename: resource_log file :param subplt: pyplot axes object :param ylim: y-axes range, defaults to [0,1.05] :param pattern: only plot resources whose name matches the pattern (in regular expression), ...
e82b902fccc77d3d7850ade72adcbdd9fb9910df
36,108
import collections def _get_synthetic_digits_data(): """Returns a dictionary suitable for `tf.data.Dataset.from_tensor_slices`. Returns: A dictionary that matches the structure of the data produced by `tff.simulation.datasets.emnist.load_data`, with keys (in lexicographic order) `label` and `pixels`....
c770d08c9a92c7aa958037a45baf2fde306c2bc2
36,110
def all_subclasses(cls): """Returns recursively-generated list of all children classes inheriting from given `cls`.""" return set(cls.__subclasses__()).union([s for c in cls.__subclasses__() for s in all_subclasses(c)])
fa9c08bd37d9bee504a404d20f5e94e8e3b2bab1
36,111
from typing import Tuple def get_sample_input01() -> Tuple[int, np.ndarray]: """ A single input vector sample of the "Necessary" category. """ label = 0 feature_vector = np.array([[0., 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ...
2bab4949027b015d645a5a965867227453d29448
36,112
def cap_rating(flight_phase, short_period_cap, short_period_damping): """ Give a rating of the short period mode flight quality level: Level1 Level2 or Level3 and 4 according to MIL-STD-1797A Args: flight_phase (string) : 'A', 'B' or 'C' short_period_cap (float): Control Anticipation ...
2ecebb417f32320213a916ca1366f36dd473fc62
36,114
def set_immd(*args): """ set_immd(ea) -> bool Set 'has immediate operand' flag. Returns true if the 'FF_IMMD' bit was not set and now is set @param ea (C++: ea_t) """ return _ida_bytes.set_immd(*args)
9521a509cfed727a0e48b6ac72704bbbc5218087
36,115
from slycot import sb01bd def place_varga(A, B, p, dtime=False, alpha=None): """Place closed loop eigenvalues K = place_varga(A, B, p, dtime=False, alpha=None) Required Parameters ---------- A : 2D array_like Dynamics matrix B : 2D array_like Input matrix p : 1D array_like...
fcfcbca4e7320e39143deb6462fd98c335566b26
36,116
def kToc(k, nu = 5.0, xF = 0.2, xS = 0.8, xG = 0.0 ): """ kToc will convert a k-eigenvalue to a c-eigenvalue given the cross sections for the problem. """ xA = xG + xF xT = xA + xS return (nu*xF/k + xS)/xT
a3e310884f3a260b0bc5069f3799784d81b2c93f
36,117
def analysis(sliceno, prepare_res, params): """ reading complete file, writing to this slice only""" separator, filename, _, labels, dw = prepare_res if options.hashlabel: hash_ix = labels.index(options.hashlabel) else: hash_ix = -1 copied_lines = 0 n_labels = len(labels) res_num = ffi.new('uint64_t [2]'...
e14d3440a24404f8487d9ecf7ac50a7aa5291f3c
36,119
def construct_generic_B(n_states, n_control): """ Generates a fully controllable transition likelihood array, where each action (control state) corresponds to a move to the n-th state from any other state, for each control factor """ num_factors = len(n_states) if num_factors == 1: ...
e09b6abd0b72637b914e0c94b57b04aed42c3554
36,120
from typing import Union from typing import TextIO from typing import Optional import click def parse( in_data: Union[str, PathLike, TextIO], input_linesep: Optional[str] = None, max_size: int = _MAX_SIZE, ) -> dict: """Parse a VEP plain text statistics file into a dictionary. :param in_data: Inp...
171914b54aadd2cddef672951351c4a987110a9e
36,121
def analysis_to_subword_dicts(ana): """ Returns a list of list of dicts. Each list element is an analysis. For each analysis, there is a list of subwords. Each dict contains an Omorfi analysis """ return map(pairs_to_dict, chunk_subwords(analysis_to_pairs(ana)))
933a73c0c4787bf63cecefbedfd230a3d99906f9
36,122
from datetime import datetime def create_directory_content_output(share_name: str, raw_response: dict, directory_path: str = "") -> dict: """ Create XSOAR context output for list directory command. Args: share_name (str): Share name. raw_response (dict): Request raw response. direc...
a23b3ce74f4274c2ee59823a3f9a976943b94a5a
36,123
def circle_area(r): """Calculates the area of a trapezium using the formula: area = \u03C0(radius squared) Parameters ---------- r: int or float The radius in the equation. Returns ------- Float \u03C0 * (r**2) Raises ------ ValueError If r:: ...
e8d3c8fd556a90851757a4edf6091d44452f59cc
36,124
import json def build_response(status, message): # type: (DownloadStatus, str) -> str """ function to build a response as json string """ return json.dumps({'status': status, 'message': message})
078db81165a43e2bf68ddde13b4ca566507ef3ab
36,127
import json def loads_json(fid, **kwargs): """ Loads a JSON file and returns it as a dict. :param path: String or another object that is accepted by json.loads :param kwargs: See ``json.dump()``. :return: Content of the JSON file. """ assert isinstance(fid, str), fid return json.loads(fi...
ccdb62568982f6a0862dd5c8167b2e1d177137ea
36,128
def get_rad_list(H_MR, H_OR): """ไธปใŸใ‚‹ๅฑ…ๅฎคใ€ใใฎไป–ใฎๅฑ…ๅฎคใจใ„ใ†ๅ˜ไฝใง่จญๅฎšใ•ใ‚ŒใŸๆ”พ็†ฑๆฉŸๅ™จใ‚’ๆš–ๆˆฟๅŒบ็”ปใ”ใจใฎ้…ๅˆ—ใซๅค‰ๆ› Args: H_MR(dict): ๆš–ๆˆฟๆฉŸๅ™จใฎไป•ๆง˜ H_OR(dict): ๆš–ๆˆฟๆฉŸๅ™จใฎไป•ๆง˜ Returns: list: ๆ”พ็†ฑๆฉŸๅ™จใฎๆš–ๆˆฟๅŒบ็”ปใ”ใจใฎ้…ๅˆ— """ # ๆš–ๆˆฟๅŒบ็”ปi=1-5ใซๅฏพๅฟœใ—ใŸๆ”พ็†ฑๅ™จใฎใƒชใ‚นใƒˆใ‚’ไฝœๆˆ rad_list = [None, None, None, None, None] # ๆ”พ็†ฑ็ณปใฎ็จฎ้กž rad_types = get_rad_type_list() ...
0645c6f5af6cbbd2568e664272cea3a0576fa3bf
36,130
def GetArrayElement(tag, array_id, idx): """ Get value of array element. @param tag: Tag of array, specifies one of two array types: AR_LONG, AR_STR @param array_id: The array ID. @param idx: Index of an element. @return: Value of the specified array element. Note that this functi...
5d2c957a0f2c64d25325db55d748b0f041d34eaa
36,131
def init_lars_optimizer(current_epoch, params): """Initialize the LARS Optimizer.""" learning_rate = poly_rate_schedule(current_epoch, params) optimizer = tf.contrib.opt.LARSOptimizer( learning_rate, momentum=params['momentum'], weight_decay=params['weight_decay'], skip_list=['batch_norma...
6eba9c650c1a14b3df9a1e46d52014cb62898124
36,133
import time import random def suffix(): """Generate a random string of length 4""" alph = "abcdefghijklmnopqrstuvwxyz" return "-".join([time.strftime("%Y-%m-%d-%H%M%S"), "".join(random.sample(alph, 4))])
f0e6c053ffb38e09d5ed4516f07fb1533b5dd80d
36,134
def augment_data(spectrogram: np.ndarray) -> list: """ Augment the given data. :param spectrogram: Data to augment :return: Augmented data """ result = [ mask_spectrogram(spectrogram, n_freq_masks=1, n_time_masks=0), # mask_spectrogram(spectrogram, n_freq_masks=3, n_time_masks=0)...
a56bd5e7baaa45f6ccb53b27b73e50baecf6e3ee
36,135
import datasets import torch def load_train(root_path, dir, batch_size, phase): """ Load data for train set """ transform_dict = { 'src': transforms.Compose( [transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), ...
372571a5cf75c878782fa96c73860bfe04631972
36,136
def reduceModel(model, atoms, select): """Return reduced NMA model. Reduces a :class:`.NMA` model to a subset of *atoms* matching *select*. This function behaves differently depending on the type of the *model* argument. For :class:`.ANM` and :class:`.GNM` or other :class:`.NMA` models, force constan...
6bb5ed82638f50e311879ec623fbe027a6297258
36,137
def executable(s): """Attempts to use the "ex" entry in LS_COLORS, falling back to green""" return __ls_color(s, 'ex', term.green)
0a6ae7f999a7fa23391db68eddfc4cd67f89df2c
36,138
def _skew_circulant_multiply(c, x, f_method='std'): """Multiply a skew-circulant matrix by a vector. Runs in O(n log n) time. See algorithm S7 in Sukhoy & Stoytchev 2019 (full reference in README). Args: c (np.ndarray): first column of skew-circulant matrix G x (np.ndarray...
de20516ce427385d7462cd031cfb2001f0f3b640
36,140
def _apply_temp_conv(var, var_unit, dest_unit): """Return the variable converted to different units using a temperature conversion algorithm. Args: var (:class:`xarray.DataArray` or :class:`numpy.ndarray`): A variable. var_unit (:obj:`str`): The variable's current units. ...
6df9d02b1d74cd8554d4ad8b135986636f3e2c95
36,141
import requests def epidemic_history() -> pd.DataFrame: """ ่ฏฅๆŽฅๅฃๆœ€ๅฅฝ็”จไปฃ็†้€Ÿๅบฆๆฏ”่พƒๅฟซ https://github.com/canghailan/Wuhan-2019-nCoV 2019-12-01ๅผ€ๅง‹ :return: :rtype: pandas.DataFrame """ url = "https://raw.githubusercontent.com/canghailan/Wuhan-2019-nCoV/master/Wuhan-2019-nCoV.json" r = requests.g...
c16e375c0e3e288667afebcbc8fa3f54dc486dcc
36,143
def main(*, data, d): """entrypoint function for this component Usage example: >>> main( ... data = pd.Series( ... [1.2, 7.2, 2.8, 4.8, 10.8], ... index = [2, 3, 5, 6, 9] ... ), ... d = 2 ... )["interpolation"] 2 1.2 4 5.0 6 4.8 8...
e026badb020177538c34689300cb9df7783df0aa
36,144
def derivative ( fun , x , h = 0 , I = 2 , err = False , args = () , kwargs = {} ) : """Calculate the first derivative for the function # @code # >>> fun = lambda x : x*x # >>> print derivative ( fun , x = 1 ) - see R. De Levie, ``An improved numerical approximation for the first derivative'...
f6dc64f483e9512775b078e8cd602dc9dc66cc53
36,145
def get_statevector(result) -> np.ndarray: """ Creates a statevector out of a simulation result. Used when the simulator does not give a statevector. Parameters ---------- result: the result from the simulation. Returns ------- ndarray: the statevector correspondin...
6dab1bb772e54f084dcf0b9ce141f8dea08812e0
36,146
def weighting(distance): """Weighting function for pyresample.""" weight = 1 / distance**2 return weight
2af699d6daef7a3d375fe80ee79f7414047921c8
36,147
import math def weighted(*values): """ Calculates the uncertainty weighted average of the provided values, where each value is a ValueUncertainty instance. For mathematical formulation of the weighted average see "An Introduction to Error Analysis, 2nd Edition" by John R. Taylor, Chapter 7.2. ...
b51158e5f34d010902bbdcb6a98e94971c549c15
36,149
def average_precision_at_k(targets, ranked_predictions, k=None): """Computes AP@k given targets and ranked predictions.""" if k: ranked_predictions = ranked_predictions[:k] score = 0.0 hits = 0.0 for i, pred in enumerate(ranked_predictions): if pred in targets and pred not in ranked_...
57e21a1ca8b8f7fccc0b5c59dbfc799d8618fc93
36,150
def on_intent(intent_request, session): """ Called when the user specifies an intent for this skill. Main logic point to determine what action to take based on users request. """ print("on_intent requestId=" + intent_request['requestId'] + ", sessionId=" + session['sessionId']) #...
23ed09f7c6f26a155e9a550b31fe538a33075107
36,151
import time def check_index_by_doc(es_alias, db, doc_id, interval=10): """ Given a doc, update it in couch (meaningless save that updates rev) and check to make sure that ES will eventually see it after some arbitrary delay """ target_rev = None try: couch_doc = db.open_doc(doc_id if d...
3df71f7795859f8ca30f79858c659ce692cf7523
36,152
def formatEpisodeNumbers(episodenumbers): """Format episode number(s) into string, using configured values """ if len(episodenumbers) == 1: epno = Config['episode_single'] % episodenumbers[0] else: epno = Config['episode_separator'].join( Config['episode_single'] % x for x in...
d33da0c2da5213dfc7214f4c11d18b5c3bdd814c
36,153
def _PureShape(shape): """Make sure shape does not contain int tensors by calling int().""" return [int(x) for x in shape]
1cebacd516cbf223833342ecffb6f8d9fe22ff2d
36,154
from typing import cast def sum(pda: pdarray) -> np.float64: """ Return the sum of all elements in the array. Parameters ---------- pda : pdarray Values for which to calculate the sum Returns ------- np.float64 The sum of all elements in the array Raises ----...
9a28da173746280b6fd28ad0a6c942ee5e7a7463
36,155
import textwrap def add_ui_containerized_action(sub_parser: ArgumentParser) -> ArgumentParser: """Populates the sub parser with the container launch kernel arguments.""" sub_parser.add_argument( '-d', '--directory', dest='notebooks_directory', default='.', help=textwrap.dedent(...
ba21b9a990bf290db86a330faed7433a0bd4da4b
36,156
from typing import Sequence def _tf_cleanup_all( triples_groups: Sequence[MappedTriples], *, random_state: TorchRandomHint = None, ) -> Sequence[MappedTriples]: """Cleanup a list of triples array with respect to the first array.""" reference, *others = triples_groups rv = [] for other in o...
7b76533b8860d17f072b54645fc11f02d1bc3ffd
36,157
import copy def apply_pdbfixer(input_file_path, output_file_path, directives): """ Apply PDBFixer to make changes to the specified molecule. Single mutants are supported in the form "T315I" Double mutants are supported in the form "L858R/T790M" The string "WT" still pushes the molecule through P...
3ef9a13e9d9842e8837651f197fb20b86bf86ceb
36,158
def char_to_number(value: str, required_type: str) -> str: """Converts the string representation of a number (int or float) to a number Args: value (str): String representation of a number required_type (str): Output type desired (bigint or double) Raises: Exception: The conversion...
cb58f24100f961d4f260473cee4fa82621eb5887
36,159
def get_PHM08Data(save=False): """ Function is to load PHM 2008 challenge dataset """ if save == False: return np.load("./PHM08/processed_data/phm_training_data.npy"), np.load("./PHM08/processed_data/phm_testing_data.npy"), np.load( "./PHM08/processed_data/phm_original_testing_data...
0f963eb988ac8e9d8ead2b47f9ff13dd82449389
36,160
def _validate_index_string(index_string: str) -> bool: """ Handle validation of index string from the argument. a string should be in format 't{%d}' or 'r{%d}' or 'd{%d}' Parameters: index_string: the string we want to validate Returns: a boolean indicating whether the index st...
aa6d7d0aba2a0378d2e1c836b78b0ec943cc1bdb
36,161
def get_r_GU(r_HPU): """1ๆ™‚้–“ๅนณๅ‡ใฎใ‚ฌใ‚นใƒฆใƒ‹ใƒƒใƒˆใฎๆš–ๆˆฟๅ‡บๅŠ›ๅˆ†ๆ‹…็އ (15) Args: r_HPU(ndarray): 1ๆ™‚้–“ๅนณๅ‡ใฎใƒ’ใƒผใƒˆใƒใƒณใƒ—ใƒฆใƒ‹ใƒƒใƒˆๆš–ๆˆฟๅ‡บๅŠ›ๅˆ†ๆ‹…็އ (-) Returns: ndarray: 1ๆ™‚้–“ๅนณๅ‡ใฎใ‚ฌใ‚นใƒฆใƒ‹ใƒƒใƒˆใฎๆš–ๆˆฟๅ‡บๅŠ›ๅˆ†ๆ‹…็އ """ return 1 - r_HPU
dc4c7a913ff7402a10d9aad08bab4f3646cff904
36,163
def onset_by_rain(date, df, window=5, rain_threshold=5): """ Finds true storm onset by finding the first date around the landfall that rain exceeds a threshold Args: date: the date to look around df: df with a date and rain column window: number of days around date to find max (tota...
87e4d1f35114974a004c5b923aea05ed835cf9a7
36,164
def get_most_read(key): """ Gets the most read news from a given page (national or international) :param key: the key of the source page (e.g: g1, localDF, WP, etc.) :return: a list with the most read news from the page """ # Check if the News Source is national or internacional if key in n...
89998185adaeb4e129440ab5dd90b89f823dab6b
36,165
def counter(iterable): """ Return a dict of counts for items in iterable. """ counts = defaultdict(int) for item in iterable: counts[item] += 1 return counts
ace03795b5204fdad77860d99965889c1dec4435
36,170
def meets_criteria(num): """boolean test for meeting the password criteria. + Two adjacent digits are the same (like 22 in 122345). + Going from left to right, the digits never decrease; they only ever increase or stay the same (like 111123 or 135679) Arg: num: number to be tested ...
9001f2012cb3572c52967307924bdf4f0e37e614
36,171
def return_loop( onset_loc, envelope, function_time_thresh, hist_threshold, hist_time_samples, nperseg=512, ): """ This function is used by the calculate_onsets method. This looks backwards in time from the attack time and attempts to find the exact onset point by identifying the p...
50c2a3afbc4b1b2a753a7f43ae30c7601ad49c1e
36,172
from numpy import matrix def hostAppMat2numpy(hostmat): """ This will return a matrice in a numpy.array format This function can also be used when theire is LeftHand / RightHand conflict. ie a numpy matrice is a regular 4x4 matrice (3x3rot+trans) @type hostmat: hostObject Matrice @p...
f28ff26826edbac6f41e1882d6aa250c639d613b
36,173
def integrate_entropy(data, scaling): """Integrates entropy data with scaling factor along last axis Args: data (np.ndarray): Entropy data scaling (float): scaling factor from dT, amplitude, dx Returns: np.ndarray: Integrated entropy units of Kb with same shape as original array ...
0a92f4c1da3966cc12a581f943c96bb79a1c8e4e
36,174
import urllib def removelink(inp, nick='', db=None): """.removelink <search terms> -- Remove a bad link from the database. e.g., .removelink shaq""" if nick in administrators: result = remove_link(db, urllib.quote_plus(inp)) if result is True: return "Removed " + inp + " successfu...
1b2581651373fb16f6f8c24daebd4e832dc87307
36,176
def embed(sagas): """ The data is embedded into numerical data (vectors to represent characters) that we can use to train our RNN. :param sagas: Training data :return: Tensor containing the input data in embeded form, array of unique character in the input. """ # All unique characters in our sa...
a85fa1bc5b3ff09640a832d8ba13cd03590cec92
36,177
def create_data(step: 'projects.ProjectStep') -> STEP_DATA: """ Creates the data object that stores the step information in the notebook results JavaScript file. :param step: Project step for which to create the data :return: Step data tuple containing scaffold data structure for th...
56a55bf01ce52b69973f1054eee9b32427aed826
36,178
def byte_string_dtypes(endianness="?", min_len=0, max_len=16): # type: (str, int, int) -> st.SearchStrategy[np.dtype] """Return a strategy for generating bytestring dtypes, of various lengths and byteorder.""" order_check("len", 0, min_len, max_len) return dtype_factory("S", list(range(min_len, max_...
4a8de45377b2c15671049762b5f1f4de10bc8692
36,179
def get_company(): """ Gets company for contact entered """ company = input("Please input a company\n") while True: if company == "": print("Please input a company please") else: break return company
324d49384ab80aad3c8c09a3707ad9fd01929166
36,180
def set(request): """Set new CTL value to a encoder/decoder""" def inner(func, obj, value): result_code = func(obj, request, value) if result_code is not opuslib.api.constants.OK: raise opuslib.exceptions.OpusError(result_code) return inner
695caab9b6ac1b63b1cd22c4ad534dd60e768c5d
36,181
def read_mapping(mapf, verbose=False): """ Read the mapping from metagenomes to nodes in the tree :param mapf: the mapping file :param verbose: more output :return: """ mapping = {} with open(mapf, 'r') as f: for l in f: p = l.strip().split("\t") if p[1] ...
d6852efb1a3514e1ef4bdf545624e5ee38b07a69
36,183
def tfr_gen(func, op_defs): """Parse a function and emit the TFR functions.""" mlir_code, _ = TfrGen(op_defs).transform(func, None) assert tfr.verify(mlir_code), 'mlir code not verified: {}'.format(mlir_code) return mlir_code
7bb43e936aa4f9dd4ed0527a7d2a533b4172b7b3
36,184
from typing import Tuple import torch def preprocess_image(image:'np.ndarray', input_shape:Tuple=(79,95,79), normalized=True) -> 'torch.Tensor': """Resize, normalize between 0-1 and convert to uint8 Args: image('np.ndarray'): input_shape(Tuple, optional): (Default value = (79,95,79)) norma...
c8d9f7c0d504f28fd45a1fa6fe6d43ff176f2d59
36,185
import inspect import textwrap def convert_to_static(dyfunc): """ Converts dygraph function into static function. """ # Get AST from dygraph function raw_code = inspect.getsource(dyfunc) code = textwrap.dedent(raw_code) root = gast.parse(code) # Transform AST dygraph_to_static = D...
00c2e2126832ab36a43d7537fa147cb2a91a6592
36,186
def poly_kernel(X, Y=None, gamma=1.0, coef0=0.0, degree=3): """ Compute the poly kernel between X and Y: K(x, y) = (scale*dot(x, y^T) + shift)**degree for each pair of rows x in X and y in Y. Parameters ---------- X : ndarray of shape (n_samples_X, n_features) Y : ndarray of shap...
c47ebba04bf50e474c0eff94b777110ead0a4f61
36,188
def filter_process(session, file, action, wkt, **kwargs): """Wrapper function for the filtering process. Arguments: session (dict): Dictionary with session information. file (str): The full path of the source file. action (str): The filtering operation. wkt (str): Well-Known Tex...
68a2e8be4df13996d9a45ee5138076faa2378539
36,189