content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def pseudo_rev(t, kf, kb, prod, major, minor, backend=None): """Analytic product transient of a reversible pseudo first order reaction. Product concentration vs time from pseudo-first order reversible kinetics. Parameters ---------- t : float, Symbol or array_like Time. kf : number or ...
2e1b7091fcec3fc0517445ababe0f60cbe1c7677
3,599,700
def to_acc_pubkey(data: ValPubKey) -> AccPubKey: """Converts a validator pubkey into an account pubkey. Args: data (ValPubKey): validator pubkey Raises: ValueError: if provided string is not Bech32 Returns: AccPubKey: account pubkey """ vals = bech32_decode(data) i...
f991c7e02b38c08bb71f32ebebe9d61be8e5831b
3,599,701
import argparse import sys import os def parse_args(): """Parse and check args.""" app = argparse.ArgumentParser() app.add_argument("input", type=str, help="Input image.") app.add_argument("output", type=str, help="Output file.") app.add_argument("--size", type=int, default=1000, help="Long dimens...
8bbb8f8dd24623546dc3384a5fd9a71208065fa0
3,599,702
import subprocess import sys def shell_cmd(cmd, alert_on_failure=True): """Execute shell command and return (ret-code, stdout, stderr).""" print('SHELL > {}'.format(cmd)) proc = subprocess.Popen(cmd, shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) ...
31299cd69991254ecbca2ecb314c55eb2d9b0544
3,599,703
import base64 import binascii def get_basic_authorization(headers: dict) -> tuple[str, str]: """ Extracts the authentication credentials from a Basic authentication scheme. :param headers: Dictionary of the headers. :type headers: dict :return: Authentication credentials. :rtype: tuple[str, ...
f83b4799d18dc545264d447b338f37c4f1c21dbe
3,599,704
def is_in_system(system: Orbiter, target_name: str) -> bool: """Return true if there is a space object with the target name anywhere in the parm system.""" # We found the target name in the system! if system.name == target_name: return True # If the names don't match, and no orbiters, then the...
d0f166de19067338f3654d10fedd7c2cf3174a30
3,599,705
def get_successful_move_actions(actions: DataFrame[SPADLSchema]) -> DataFrame[SPADLSchema]: """Get all successful ball-progressing actions. These include successful passes, dribbles and crosses. Parameters ---------- actions : pd.DataFrame Actions, in SPADL format. Returns -------...
692f550967202e56ebaf2075e40bbec8188a8273
3,599,706
def obtener_cantidad_turistas_y_ciudades_origen_en_ciudad_en_rango_anios(PaisDestino, AnioInicio, AnioFin): #OK """ Dado un pais y un rango de años obtiene la cantidad total de personas que llegan a esa ciudad separando por años, paises y ciudades de origen Dado un pais, una ciudad, un mes y un rango de año...
0e08bec08437a0b9c0862aa620547bc59071f35e
3,599,707
import logging def evaluate(*, p_eval_step, params, eval_ds: tf.data.Dataset, num_eval_steps: int): """Evaluate the params an return a dictionary with the metrics.""" logging.info("Gathering evaluation metrics.") eval_metrics = [] eval_iter = iter(eval_ds) # pytype: disable=wrong-arg-types for...
1da62df7af3c8c44408d78a1d7de05a6b8e046c8
3,599,708
import glob def dse_build_design_space(max_partition_num): # type: (int) -> int """ Build and partition the design space Return the partition number """ if SINGLE_PARTITION: max_partition_num = 1 builder_py = must_use_pyc('{0}/optimizers/'.format(MERLIN_COMPILER_HOME) + ...
9424695e8c298f9ab515fb0e765e9803b7c7db7b
3,599,709
def fastprint(text, show_prefix=False, end="", flush=True): """ Print ``text`` immediately, without any prefix or line ending. This function is simply an alias of `~fabric.utils.puts` with different default argument values, such that the ``text`` is printed without any embellishment and immediately...
4d28eb647651fc1b936726c15b7356e370e32561
3,599,710
def find_strongest_common_ancestor(els): """ Return the deepest common ancestor of all elements, provided that at least 2/3 of the elements have this ancestor. >>> import lxml.html >>> doc = lxml.html.fromstring('<table><tbody><tr><td>A</td><td>B</td></tr></tbody></table>') >>> find_strongest_c...
6fe8d88d3989b8494fefb3881ad6e3ab74f05119
3,599,711
def make_shell_context(): """ Creates a python REPL with several default imports in the context of the app """ return dict(app=app)
2d1b22b2447846694236ddc8ac41363377a25e3c
3,599,712
def glyph2vertices(glyph, n_segments=5): """ Sample glyph outline vertices checking points on the curve and control points for conic and cubic bezier arcs as described in: https://www.freetype.org/freetype2/docs/glyphs/glyphs-6.html Vertex coordinates are scaled such that the vertical advance is 1 unit...
660998f75b1fffcb11ba158407af321aa7aaf452
3,599,713
def calc_prefix_color(*args): """ calc_prefix_color(ea) -> color_t Get prefix color for line at 'ea' @param ea (C++: ea_t) @return: Line prefix colors """ return _ida_lines.calc_prefix_color(*args)
1ec3bd3ed96c2b8b1e46090cfb3c6786595b53d1
3,599,714
import torch def get_col_mins_efficient(X, Y, b): """ Computes the l2 distance to the closest x or each y. :param X: (n1, d) tensor :param Y: (n2, d) tensor Returns n1 long array of L2 distances """ mins = torch.zeros(Y.shape[0], dtype=X.dtype, device=X.device) n_batches = len(X) // ...
af3382009edb39ec00cd75ce67cbc6395d5eb861
3,599,715
def open_create_obj_modal(obj_type): """Opens create object modal for selected type.""" selenium_utils.open_url(url.dashboard()) obj_modal = dashboard.Dashboard().open_create_obj_modal(obj_type=obj_type) return obj_modal
7a9a345b3068f994d4082b5db38fa8f6f4b8bed2
3,599,716
import argparse def __add_filtering_arguments(parser, defaults=None, diff_mode=False): """ Add some common filtering arguments to the given parser. """ def init_default(dest): return defaults[dest] if defaults and dest in defaults \ else argparse.SUPPRESS f_group = parser.add...
04ae5e9279885288b1ac67b02514df4e745ce195
3,599,717
def time_to_sec(time_str: str) -> int: """Convert time in string format to seconds. Skipping seconds since sometimes the last column is truncated for entries where >10 days. """ total_sec = 0 if '-' in time_str: # parse out days days, time_str = time_str.split('-') total...
e08667cc35a3d85dc30ea3eb63e5d91f2ba99252
3,599,718
def get_coordinates(label): """ given a label returns the coordinates associated with that label/region. The coordinates are precomputed from training points. The coordinate of a label equals to the median latitude and longitude of all training points in that region. Args: label (int): label or region id associ...
80fc0e45b8096d7c48e70cf32ef6dcc3eb33d0da
3,599,719
import functools def mobilized(normal_fn): """ Replace a view function with a normal and mobile view. For example:: def view(): ... @mobilized(view) def view(): ... The second function is the mobile version of view. The original function is over...
c7e23f233e10ddeabaca083367a99bd6d5bfc7bf
3,599,720
def init_layers_mf(Y, Z, kernels, num_outputs=None, Layer=SVGP_Layer): """ Creates layer objects from initial data :param Y: Numpy array of training targets :param Z: List of numpy arrays of inducing point locations for each layer :param kernels: List of kernels for each layer :param num_output...
c2936de4b9517912aa8a6afb2b0b4aec8f09cfaa
3,599,721
def procrustes(X, Y, scaling=True, reflection='best'): """ This function is taken from here: https://stackoverflow.com/a/18927641. It aligns a shape defined by Y to a shape defined by X. # Y_transformed = b * YT + c Procrustes analysis determines a linear transformation (translation, refle...
3324bf9487c747cfffa004d1b95bd7a9ec4cdb90
3,599,722
def perform_cva(ds, base_times=None, comp_times=None, reduce_comp=False, vege_var='tcg', soil_var='tcb', tmf=2): """ Takes a xarray dataset/array of tasselled cap greeness and brightness values, as well as a a tuple of base years (e.g. 1990, 2010) that are averaged together to form a ba...
c6cb565f25c26d72ff1a0fd6f13838e93540246c
3,599,723
from typing import Optional def get_event_invoke_config(id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetEventInvokeConfigResult: """ Resource Type definition for AWS::Lambda::EventInvokeConfig """ __args__ = dict() __args__['id'] = ...
df7e0ed209aa8991eabfbdd63dfe3fd85dc2e2b8
3,599,724
def deco1(func): """docstring for deco1""" @wraps(func) def wrapper(): return func() return wrapper
33fa3c8354f64a9d9430e82623bdb5b8c3f84fde
3,599,725
def keras_mxnet_symbol(func): """Decorator function used with all Keras API implementation. This decorator helps to establish the symbolic graph for the result MXNet symbol generated in the operator function. # Arguments func: Decorated function reference. """ @wraps(func) def func...
19bbbce3e620daa713d1946a0375f9488a185658
3,599,726
import contextlib def variables_on_gpu(): """Prevent variables from accidentally being placed on the CPU. This dodges an obscure bug in tf.train.init_from_checkpoint. """ if _our_gpu() is None: return contextlib.suppress() def device(op): return '/gpu:0' if op.type == 'VarHandleOp...
8a4755a3dc9754b189a5c33f818ba98c474b7ad4
3,599,727
def extract_names(filename): """ Given a file name for baby.html, returns a list starting with the year string followed by the name-rank strings in alphabetical order. ['2006', 'Aaliyah 91', Aaron 57', 'Abagail 895', ' ...] """ # +++your code here+++ with open(filename, "r") as f: fi...
8a00e099b7da57f409f04a9f2f723dca0002818b
3,599,728
import urllib import requests def gas(bot, trigger): """Fetches gas prices for provided query/location.""" query = trigger.group(2) if not query: return bot.reply("You need to give me a location!") quoted_query = urllib.parse.quote_plus(query) try: url = SEARCH_ENDPOINT.format(q...
97cc8d29af99ff88f561eea594bc8bda052e6f6b
3,599,729
def hhmm_to_seconds(hhmm: str) -> int: """ Converts hours and minutes into seconds. Arguments: hhmm: The time in hh:mm format. Returns: If the argument is a valid format it returns the time in seconds. """ if len(hhmm.split(':')) != 2: print('Incorrect format. Argument must be ...
656b21241ce9c79ebb75fc9c20f09d781f70cd0f
3,599,730
def get_string_value(value_format, vo): """Return a string from a value or object dictionary based on the value format.""" if "value" in vo: return vo["value"] elif value_format == "label": # Label or CURIE (when no label) return vo.get("label") or vo["id"] elif value_format == "...
0efaa0850a63076dd0334bc54f2c96e4f352d6ae
3,599,731
def create_msearch_payload(host, st, mx=1): """ Create an M-SEARCH packet using the given parameters. Returns a bytes object containing a valid M-SEARCH request. :param host: The address (IP + port) that the M-SEARCH will be sent to. This is usually a multicast address. :type host: str :param ...
cb0da629716e992dd35a5b211f26cae3ad949dcb
3,599,732
def ustrip(text): """Strip Unicode extended whitespace from a string.""" return text.strip(unicode_extended_whitespace)
4af1f734e9d73523f304d56630fc26ac8c5649e7
3,599,733
from pathlib import Path def valid_folder(path_): """ Returns True if path_.match any of the conditions. False otherwise. conditions assigned: - "_*" """ # ignores dunders, __pycache__ conditions = ( "_*", ) p = Path(path_) return not(any(p.m...
a0ddff2667eea34d7b00e3aac8623e65140894f9
3,599,734
def _balance(target, weight): """Assume `cross_entropy(ignore_index=-100)`. Args: target (Tensor[H, W]): input tensor. weight (Tensor[H, W]): probability of BG. """ negative_mask = target.eq(0) limit = 3 + 3 * target.gt(0).sum().item() if negative_mask.sum().item() > limit: ...
fd59351331319d10b89f70ef816fb9f922e61046
3,599,735
def newgpg(ui, **opts): """create a new gpg instance""" gpgpath = ui.config("gpg", "cmd") gpgkey = opts.get(r'key') if not gpgkey: gpgkey = ui.config("gpg", "key") return gpg(gpgpath, gpgkey)
43f5d58f994d6de635f47817dc7212c541952af5
3,599,736
import requests from bs4 import BeautifulSoup def get_google_image_link(word): """ Function returns a url for the movie image in google search resoults Returns second image as first is a search_url :param word: search word :return: url """ url = 'https://www.google.com/search?q=' + word + ...
54b7e4626d0825dee6baaecc6a41ddb14c384797
3,599,737
def get_values_from_line(line): """Get values of an observation as a list from string, splitted by semicolons. Note 1: Ignore ';' inside \"...\". E.g. consider \"xxx;yyy\" as one value. Note 2: Null string '' for NA values. """ raw_list = line.strip().split(';') i = 0 values = [] whi...
585c6c9484f6ad145f7265613dc189351cc2d556
3,599,738
import httpx import json async def download_github_issue( client: httpx.AsyncClient, owner: str, repo: str, issue_number: int, ) -> Maybe[GithubIssueRaw]: """ Download a single file from its identifier. - Returns `SimpleError` if the issue was not found - Returns a `GithubIssueRaw` ot...
1fc0984b551392db17b4f7f666603e5b4d6fc03b
3,599,739
import inspect def burst(nbursts=2): """Wait `nbursts` calls before calling the wrapped function with a list of accumulated arguments. Note: the return value of the wrapped function will be None when it's not actually called, i.e. in between bursts. Can be applied to a function and a method. ...
f78a037afe97f987fab463506141424ef6509e19
3,599,740
def load_model(detector_path, classifier_path, gpu, num_classes): """Load model.""" detector = Res18UnetCenterNet() chainer.serializers.load_npz( detector_path, detector ) classifier = MobileNetV3(out_ch=num_classes) chainer.serializers.load_npz( classifier_path, ...
b8d7630a6fbd78d1ebf8999405811df0ee434037
3,599,741
import os def find_basic_file(dir, adventure_name): """ Try to figure out which basic file belongs to this adventure. Args: dir: The directory where the adventure's EDX data files live, e.g., "C:/EDX/C/EAMONDX/E001" adventure_name: The name of the adventure, e.g., "The Beginner's Cave" ...
26761043299826286fab4dacd6092287f674866b
3,599,742
def ask_string(question, default=''): """Ask the user to enter something. Example: >>> ask_string("What's your name?", default='No Bo Dy') # doctest: +SKIP :: What's your name? (Default: No Bo Dy) > Odysseus You chose: Odysseus 'Odysseus' """ ...
1c93db4fbc19320933323c51870e621084920e7b
3,599,743
def np_mat_to_rot6d(np_mat): """ Get 6D rotation representation for rotation matrix. Implementation base on https://arxiv.org/abs/1812.07035 [Inputs] flattened rotation matrix (last dimension is 9) [Returns] 6D rotation representation (last dimension is 6)...
a7b7b00667803096242d41af6971f1fce2ff27b5
3,599,744
def oauth_callback(): """Callback for OAuth1a authorization.""" # Get verifier from GET arguments oauth_verifier = request.args.get('oauth_verifier', None) if oauth_verifier is None: abort(400, 'oauth_verifier arguments are missing.') # Request access token and token secret args = [OAU...
561d6c9e7950c97b98378bcb8a6ccc8bad5c2791
3,599,745
def grib_get(gribid,key, ktype=None): """ @brief Get the value of a key in a grib message. The type of value returned depends on the native type of the requested key. The type of value returned can be forced by using the type argument of the function. The type argument can be int, float or str. ...
4acd8bfaab72e51942b85c2e8feb0500c17ce43d
3,599,746
from summit_core import voc_dir as rundir from summit_core import core_dir, Plot, Config from summit_core import connect_to_db, TempDir, create_daily_ticks, add_or_ignore_plot from summit_voc import Base, GcRun, summit_voc_plot, get_dates_peak_info from datetime import datetime import datetime as dt from summit_voc imp...
264aad030ff630f4d2c0e737497b0b1723f4622c
3,599,747
import os def get_checkpoint_name(checkpoints_path, iteration, release=False): """A unified checkpoint name.""" if release: directory = 'release' else: directory = 'iter_{:07d}'.format(iteration) # Use both the tensor and pipeline MP rank. if mpu.get_pipelin...
4476d567e4625cb86965adc1df668646be7e7233
3,599,748
def comparehits_bin_min(image_bin,featureimage_bin,max_sum=10,startx = 0 ,endx = 0,move_px = 1): """ 查找特征图像出现的位置 要求传入二值化图像 返回 出现位置的起始位置 和 差异 """ find_list = [] h, w = image_bin.shape[:2] h_f, w_f = featureimage_bin.shape[:2] bc_min = max_sum start_px = -1 if endx==0 : endx...
53233fc1d8bc36f6e9b121b9bc29d11380cbff57
3,599,749
import torch def map2central(cell, coordinates, pbc): """Map atoms outside the unit cell into the cell using PBC. Arguments: cell (:class:`torch.Tensor`): tensor of shape (3, 3) of the three vectors defining unit cell: .. code-block:: python tensor([[x1, y1, ...
5ab75804efa182516ec4e99ec6707e65f205b842
3,599,750
def _vae_step( time, sequence_length, min_sequence_length, max_sequence_length, zero_output, zero_zt, zero_pt, zero_logits1, zero_logits2, state, call_cell, skip_conditionals=False): """Calculate one step of a dynamic RNN minibatch. Returns an (output, state) pair conditioned on `sequence_length...
c2b8d4310d3bd8f5c3089f5aa5c230d2778eb2ba
3,599,751
def get_left_strip(chonk): """ Compute the left vertical strip of a 2D list. """ return [chonk[_i][0] for _i in range(len(chonk))]
dfc57a0776e5ab97a808a75170634fa6a072d9d3
3,599,752
def capture(sync_fn, *args, **kwargs): """Run ``sync_fn(*args, **kwargs)`` and capture the result. Returns: Either a :class:`Value` or :class:`Error` as appropriate. """ try: return Value(sync_fn(*args, **kwargs)) except BaseException as exc: return Error(exc)
cf8432521f19bcea5c1d51191c020cbdc3abc0c2
3,599,753
def filter_waveforms(stream,f1,f2): """ Bandpass filter waveforms INPUTS stream - list of obspy streams, one for each station/channel combo, each 60 s long f1 - lower bandpass limit in Hz f2 - upper bandpass limit in Hz OUTPUTS stream - same list of streams, but filtered ""...
6a563a987e50d668a164c7020449dd2ce5cf28a8
3,599,754
def is_lambda_decorator(tree, fname=None): """Test tree whether it decorates a lambda with ``fname``. A node is detected as a lambda decorator if it is a ``Call`` that supplies exactly one positional argument, and its ``.func`` is the decorator ``fname`` (``is_decorator(tree.func, fname)`` returns ``Tr...
1e5f8bf07fc7f6b935db0bdb73244277e80580ac
3,599,755
def enter_outfit_details(): """Generate a random outfit.""" activities = ["urban hike", "dinner", "brunch", "workout", "concert", "girls night out", "hiking", "casual date", "stay at home", "beach", "picnic", "date night", "pool"] select_string = "<select name='activity'><option value='...
8cfdf1bbeea2480fda2ed66192eb5eebb4a2d261
3,599,756
def project_world_to_camera(P,X): """ P: projection matrix X: 3D-world points as 3D vectors (not homegeneous) output: 2D camera/image points """ X_w = np.concatenate((X,np.ones((1,X.shape[1]))),axis=0) # homogeneous coords X_c = np.dot(P, X_w) X_c /= X_c[2,:] # divided by the third row...
622cd26aa05693aa4ce0791cb2ea6565a4370774
3,599,757
import logging def load_regmap(fp): """ Returns a panda DataFrame with the register and bitfield definition """ if exists(fp): df = pd.read_csv(fp, encoding="utf-8") else: log_msg = f"regmap path {fp} does not exist" logging.error(log_msg) raise Exception(log_msg) df[R...
bf1761e76ca07e6f38bf02f8922f86ab3d52b9fb
3,599,758
def gradient_table_from_bvals_bvecs(bvals, bvecs, b0_threshold=0, atol=1e-2, **kwargs): """Creates a GradientTable from a bvals array and a bvecs array Parameters ---------- bvals : array_like (N,) The b-value, or magnitude, of each gradient direction. bvec...
616e61691212a8c0fc88f3031dd94468287b7386
3,599,759
def _shift_num_right_by(num: int, digits: int) -> int: """Shift a number to the right by discarding some digits We actually use string conversion here since division can provide wrong results due to precision errors for very big numbers. e.g.: 6150000000000000000000000000000000000000000000000 // 1e27 ...
ba459cb419ef19ac2884d8299d4f1a9213832fa3
3,599,760
import json def js2str(js, sort_keys=True, indent=4): """Encode js to nicely formatted human readable string. (utf-8 encoding) Usage:: >>> from weatherlab.lib.dataIO.js import js2str >>> s = js2str({"a": 1, "b": 2}) >>> print(s) { "a": 1, "b": 2 ...
17fac42012b5abae77a00083e183d851baaab5b3
3,599,761
import torch def accuracy(output, target, topk=(1,)): """ Computes the accuracy over the k top predictions for the specified values of k Args output: logits or probs (num of batch, num of classes) target: (num of batch, 1) or (num of batch, ) topk: list of returned k ...
4d9e9d5452feb8a35eb3f409b3d74a981222514d
3,599,762
def load(path, has_ids=True, has_header=True, has_labels=True, delimiter=","): """ Loads a data set from a delimited text file. Args: path: the path to the file containing the data set. has_ids: boolean set to False if the first column in the loaded dataset should not be ...
79f336359bcc7d87f5faecedb27dd314b33a2db9
3,599,763
import re def natural_key(some_string): """See http://www.codinghorror.com/blog/archives/001018.html""" return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', some_string)]
147d36719a899fbf07471af2fe9fd6b1a2440a27
3,599,764
def add_account_receive(account_receive_data): """ 添加信息 :param account_receive_data: :return: None/Value of user.id :except: """ return db_instance.add(AccountReceive, account_receive_data)
e029e00b0cc429e42e15be8badf2a5f69be70f2f
3,599,765
from sys import path def file_del(file_path: str): """ 删除文件 :param file_path: :return: """ if path.exists(file_path): remove(file_path) return 0 else: return 1
273de87bd416c8831de233b33794a52e9515e0c4
3,599,766
from pathlib import Path import torch def quantize(model_path : Path, precision : Precision , device : Device = Device.cpu, input_shape : str = typer.Option(default=None, help="Comma seperated input tensor shape e.g 64,3,7,7")) -> torch.nn.Module: # TODO: define model output path # TODO: Support multiple inp...
6ab038aa7f15339200001989230b09de37c59ec7
3,599,767
def handle_extends(tail, line_index): """Handles an extends line in a snippet.""" if tail: return 'extends', ([p.strip() for p in tail.split(',')],) else: return 'error', ("'extends' without file types", line_index)
3b20cc5719d123e36db954c5ffc4537df64f268a
3,599,768
def bin_phase_curve(phase, data, statistic="median", bins=20): """ Bin phase curve. """ bin_medians, bin_edges, _ = binned_statistic( phase, data, statistic=statistic, bins=bins ) bin_width = bin_edges[1] - bin_edges[0] bin_centers = bin_edges[1:] - bin_width / 2 return bin_cent...
7719fee2f5ab716e542a297e462424f660d865cc
3,599,769
def get_frames_from_sequence(event_list, num_events_per_frame, data_format, frame_gen_method, is_x_first, is_x_flipped, is_y_flipped, maxpool_subsampling, do_clip_three_sigma, chip_size, target_shape=None...
7ce5d741bc1374e953bf4423f4618562a73c0861
3,599,770
def pad(img: np.ndarray, target_height: int, target_width: int) -> np.ndarray: """Pads the image to have the target size for the network input.""" return np.pad(img, [(0, max(0, target_height-img.shape[0])), (0, max(0, target_width-img.shape[1]))], constant_values=0)
7cb9fd8c9d82b669b340162bfa231f481448acbd
3,599,771
import os import codecs def get_lines_of_cha_files(path): """ Gets the lines in the cha files in the given path :param path: The path that is looked at, this includes the subfolders :return: a list of cha files with the lines """ results = [] for file in os.listdir(path): with cod...
6c9fdb90d5f59d5cdd4aa47d7c43b707839ce998
3,599,772
def entryID(entry): """Try to make an unique ID for entry.""" id = None if entry.get('guidislink', None): id = entry.get('id', None) if id is None: id = entry.get('link', None) if id is None: raise Exception return id
f1ca161d60db7197e8b51f40585d74690a00c004
3,599,773
import torch def repackage_hidden(h): """Wraps hidden states in new Tensors, to detach them from their history.""" if isinstance(h, torch.Tensor): return h.detach() else: return tuple(repackage_hidden(v) for v in h)
b435d7537e4418d3877db55077285d35a24e46b3
3,599,774
import os import yaml def save(c, prefix, relative_paths=True): """ Save data from a Chipseq object. Parameters ---------- c : Chipseq object Chipseq object, most likely after calling the `diffed_array` method prefix : str Prefix, including any leading directory paths, to sa...
2b30cb74f958b7a0a50023914a03acaecbcb5888
3,599,775
def cityblock(u, v): """ d = cityblock(u, v) Computes the Manhattan distance between two n-vectors u and v, \sum {u_i-v_i}. """ u = np.asarray(u) v = np.asarray(v) return abs(u-v).sum()
07553804b20a0269b959ecccead4206fc372cdf2
3,599,776
def determineThresholdCrossing(latencies, baselineLatencies, alpha=0.001): """ Determines when the latencies cross the significance level designated by alpha. Confidence intervales of the baseline latency distribution are determined by applying the Dvoretzky-Kiefer-Wolfowitz inequality. Inputs: ...
18b5eacf5458fdf15bea7f92836afe02409e783a
3,599,777
def minus(evaluator, ast, state): """Evaluates "-expr".""" return -evaluator.eval_ast(ast["expr"], state)
bf945c368e84d3badd7a90bfce74cb3c89b6890a
3,599,778
from typing import List def _validate(vector: np.ndarray, sizes: List[int], name: str): """Validate vector has one of the expected sizes.""" sizes = [sizes] if type(sizes) == int else sizes if vector.shape[0] in sizes: return np.copy(vector) else: sizes_str = ', '.join(["(%d,1), (%d)" ...
c1cb8be31076291b2fe5ef134e34230dffccd6ac
3,599,779
import torch def query_ball_point(radius, nsample, xyz, new_xyz, itself_indices=None): """ Grouping layer in PointNet++. Inputs: radius: local region radius nsample: max sample number in local region xyz: all points, (B, N, C) new_xyz: query points, (B, S, C) itself_in...
c304988065bd71a458f6b62fd322a75319b97a87
3,599,780
def angle_M(M_r: float, n: float, t_r: float, t: float) -> float: """ M = Mr + n * (t - tr) :param M_r: mean anomaly at tr :type M_r: float :param n: mean movement :type n: float :param t_r: reference time :type t_r: float :param t: time :type t: float :return: mean anomaly ...
c99e5dacffea44fa7fadfaebaf6ce734eea81e16
3,599,781
from typing import Union from typing import Dict import torch def convert_double_to_float(data: Union[Dict, torch.Tensor]): """ Utility function to convert double tensors to float tensors in nested dictionary with Tensors """ if type(data) is torch.Tensor and data.dtype == torch.float64: retur...
737edbb9625b6cc1dbce425f7e8df8e06cb80410
3,599,782
import re def is_transaction_expired_exception(e): """ Checks if exception occurred for an expired transaction :type e: :py:class:`botocore.exceptions.ClientError` :param e: The ClientError caught. :rtype: bool :return: True if the exception denote that a transaction has expired. False other...
c836521a7137b61ad8443157824ca5da59de65e3
3,599,783
def otsu_triangles(img, KERNEL_SIZE = 5): """ Transforms the image using otsu binarizarion method, similar to the "otsu" function on this module. The only difference, however, is that this version draws a small triangle (5 percent of img's width) on each of the four corners, and applies floodFill to all of ...
ee57256a1a8574340c0a4e316618c796a74e97d7
3,599,784
def adjust_ws_gs_comp(ws, bms, gs): """Adjusts the compatibility of widths and groups.""" ws_bot = [int(w * b) for w, b in zip(ws, bms)] gs = [min(g, w_bot) for g, w_bot in zip(gs, ws_bot)] ws_bot = [quantize_float(w_bot, g) for w_bot, g in zip(ws_bot, gs)] ws = [int(w_bot / b) for w_bot, b in zip(ws_bot, bms...
2790fb708162b369d9c016c0f2acbbc90a4f7d91
3,599,785
def convert_base64_exams_to_PIL(exams: list[str]): """ Convers a list of base64 images or pdfs into PIL Image objects """ exames_pil = [] for exam in exams: if get_base64_datatype(exam) == "pdf": exam = convert_base64_pdf_to_base_64_img(exam) exames_pil.append(base_64_to...
fbf52936ab8be90a7fa01da38eb3e54401d3c367
3,599,786
def get_reverb_send(header: bytes) -> int: """Return reverb send value (0-100).""" assert isinstance(value := _unpack(header, "REVERB_SEND"), int), type(value) assert 0 <= value <= 100, value return value
733634443f8b9c7c8ae575bd5523b2af1cdee153
3,599,787
def stations_within_radius(stations, centre, r): """Function to return a list of all stations (type MonitoringStation) within radius r of geographic coordinate x""" stationlist = [] for i in stations: # Find distance from centre to station, if it is < r, add to list dist = haversine(i.coord ...
320a8d6a240023af9d2dae30a7ecde4dc2e54c84
3,599,788
from typing import List from typing import Literal from typing import Tuple def parity_network(n: int, S: List[List[Literal[0,1]]]) -> List[CNOT]: """Implements the parity network algorithm of https://arxiv.org/pdf/1712.01859.pdf. Specifically, it follows the pseudo-code of page 14.""" c = [] # List of cn...
78b0e0197b0fccd14173c3f7162cb2021747eeb6
3,599,789
def _convert_room_label(room_name): """ Convert room label from str to index, using the mapping defined by FloorNet""" room_name = room_name.split('-')[0] original_room_label_map = getRoomLabelMap() room_name = room_name.replace(' ', '_').lower() try: room_label = original_room_label_map[ro...
2ad86678e40465520bfc25d0b592c50704075a3b
3,599,790
import re def get_all_local_funcs(vba): """Get the names of all locally defined functions. Also get the names of all defined constants. The constant names are saved in core.strip_lines.defined_constants. @params vba (VBA_Parser object) The olevba VBA_Parser object for reading the Office file bein...
600b0f1860b9026ec9179cd8586add231dea21f0
3,599,791
import argparse def parse_args(): """Parse input arguments.""" parser = argparse.ArgumentParser(description='Experimenting Trackers with SORT') parser.add_argument('--NoDisplay', dest='display', help='Disables online display of tracker output (slow)',action='store_false') parser.add_argument('--dlib',...
3ff5d05f2a800a5338c2ac386d0ae78610b285d3
3,599,792
def get_legal_moves_lshift(size, mask, player, blank, shift_size): """ 左シフトで石が置ける場所を取得 """ tmp = mask & (player << shift_size) for _ in range(size-3): tmp |= mask & (tmp << shift_size) return blank & (tmp << shift_size)
42a259f21b2ae1c0c57007f939e5e7e935761b88
3,599,793
def _make_stacked_ensemble_pipeline(input_pipelines, problem_type, n_jobs=-1, random_seed=0): """ Creates a pipeline with a stacked ensemble estimator. Arguments: input_pipelines (list(PipelineBase or subclass obj)): List of pipeline instances to use as the base estimators for the stacked ensemble....
58fc0fbcd39a0896ae3a4721ce841b8ea2ad22ee
3,599,794
def TokenEndBlockquote(depth=1): """ `TokenEndBlockquote` is used to denote that we are ending a blockquote. This token will not render anything. """ return { "type": "SpaceCharacters", "data": "", "_md_type": mdTokenTypes["TokenEndBlockquote"], "_md_depth": depth, ...
e19142a780aa44f951980ce184dae068f6949629
3,599,795
import warnings def _compute_angles_list(view_index_list, num_acquired_scans, total_angles, rotation_direction="positive"): """Return angles list from indexes list. Args: view_index_list (list[int]): Final index list after subsampling and time point selection. num_acquired_scans (int): Total ...
2c942044072a455b21b7d95ffc1f6b73f6331eb4
3,599,796
import sys def pbsvp_main(argv=None): """pbsvp Main function, entry for command line tool `pbsvp`""" argv_ = sys.argv if argv is None else argv parser = pbsvp_get_parser() return main_runner(argv_[1:], parser, args_executer, setup_log, log)
9953775d0a5e15e24dfc2a0712bfb39f7c89f56e
3,599,797
import yaml import os def parse(filename): """Parse a yaml config file. Will parse a yaml configuration file for configuration directives. Some configuration directives can be overriden by passing arguments in the environment. In this case, there are certain rules: - If overriding the DATABA...
2f5c80a22cbdb677e5c42b30952cc0e33aeabbdd
3,599,798
def discriminator_patch(input_image, leaky_relu_alpha: float = 0.2, reuse: bool = None, scope: str = None, dim: int = 64, ks: int = 4): """ Discriminator (Patch GAN) Input 256 x 256 x 3 image...
7ef1869f7404a2164660256cd7ac7d76ae8c9df9
3,599,799