content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from pesummary.core.plots.bounded_1d_kde import bounded_1d_kde def _setup_triangle_plot(parameters, kwargs): """Modify a dictionary of kwargs for bounded KDEs Parameters ---------- parameters: list list of parameters being plotted kwargs: dict kwargs to be passed to pesummary.gw.p...
b3be4c1d402a1defafb779274970d7a4983d396d
40,200
def _run_pipelines(pipelines): """Run the pipelines to load data. Args: pipelines (list): List of pipelines to be run. Returns: list: a list of booleans whether each pipeline completed successfully or not. """ # TODO: Define these status codes programmatically. run_...
8bee81b94dd9ee6a74e7b5188ff275a536401cfb
40,201
import collections import math import os from shutil import copyfile def reorg_train_valid(data_dir, labels, valid_ratio): """将验证集从原始的训练集中拆分出来""" # 训练数据集中样本最少的类别中的样本数 n = collections.Counter(labels.values()).most_common()[-1][1] # 验证集中每个类别的样本数 n_valid_per_label = max(1, math.floor(n * valid_ratio)...
b61e2aa6ac01dc8147288975f0af9d9c71738202
40,202
def pack(*v): """Packs value to fit into a word""" w = 0 for i, x in enumerate(v): w += INST_SZ**(len(v) - i - 1) * x return w
e9dcbab2655033077d14060da33656734a580d3c
40,203
def get_logging_connection(): """ Get main connection for logging :return: """ # todo if your db have authorize or other settings # todo please attach your code here return pymongo.MongoClient(host=DOCKER_HOST_IP, port=27017, maxPoolSize=1000)
a2a52e633b4a8fa3626163948d9c65355f3d5660
40,204
def print_card(card): """ Makes a card string from a card object :param card: The card object :return: The card string """ if card.layout() == 'normal': return make_card_string(card) elif card.layout() == 'split': return make_split_card_string(card) elif card.layout() == ...
e866afa374bc7d3664387262a5d9bf201087cc7f
40,205
def component_declaration1(): # type: ignore """ component_declaration1 = declaration comment """ return syntax.declaration, syntax.comment
48125c163fd8a6c12159f8d68d7786caf6acf42f
40,206
def BackupConfiguration(sql_messages, instance=None, backup_enabled=None, backup_location=None, backup_start_time=None, enable_bin_log=None, enable_point_in_time_recovery=None,...
18750b852fda215252c1211d41cf5f1ad1f6e887
40,207
def artifact_patch_request(user_id, req_op, req_path, req_value=None, req_from=None): """Modifies an attribute of the artifact Parameters ---------- user_id : str The id of the user performing the patch operation req_op : str The operation to perform on th...
96d69c1c5a12a53238565ca032c49861d2f73c17
40,208
def topo_2_property(topology, property): """ Returns properties of a topology for a given topology name. Properties: 'stk_func' - gives the stk topology function for building cages 'stoich' - gives the stoichiometries of both building blocks assuming that the first building bloc...
984e87ece3ad0fadf78a380807288995da873398
40,209
def get_full_names(pdb_dict): """Creates a mapping of het names to full English names. :param pdb_dict: the .pdb dict to read. :rtype: ``dict``""" full_names = {} for line in pdb_dict.get("HETNAM", []): try: full_names[line[11:14].strip()] += line[15:].strip() except: f...
be31bb2c8e59e7b2ef4b51aba45f3cbafcb23a63
40,210
import urllib import json def create_package(base_url, data=None, api_key=None): """Post a data dict to one of the actions of the CKAN action API. See the documentation of the action API, including each of the available actions and the data dicts they accept, here: http://docs.ckan.org/en/ckan-1.8/api...
24e58d050c7c7cc26d03f659e789143da722c77c
40,211
def getDiffError(a, b): """ (Deprecated)Calculate the distance square between a and b. Parameters ---------- a, b : ndarray of float, in the same shape The two matrices to be compared Returns ------- float The sum of element-wise distance square between a and b. ...
f31a785907c949b4f4230fc7e35a2b396dc40cdc
40,212
from scipy import linalg import warnings def _fit_corrs(x_xt, x_y, n_ch_x, reg_type, alpha, n_ch_in): """Fit the model using correlation matrices.""" known_types = ('ridge', 'laplacian') if isinstance(reg_type, string_types): reg_type = (reg_type,) * 2 if len(reg_type) != 2: raise Valu...
9033ab134f89183afb7e850f7d61b6793103b42d
40,213
def symbol(a=None): """ Return a variable from the symbolic ring with the given name. If an expression is given, it is returned unchanged. """ if isinstance(a, Expression): return a return SR.symbol(a)
48728d7775fa8013499e8070f557efe4bda63218
40,214
import glob def get_files(base_dir, ref_dir): """ get_files: get all the asdf files in base_dir. """ allfiles = sorted(glob(join(base_dir, "*h5"))) # we should use the head of ref_dir and the base of the globbed files result = [] for each_file in allfiles: result.append(join(ref_di...
5244e313193c9d77829f07e5400287953b89749e
40,215
def load_image(filename): """Loads a PNG image file.""" string = tf.read_file(filename) image = tf.image.decode_image(string, channels=3) image = tf.cast(image, tf.float32) image /= 255 return image
414ead568ecbbe61b90a155c50cdf83ee7783ec9
40,216
import abc def _actor_in_relationship(actor, relationship): """Test whether the given actor is present in the given attribute""" if actor == relationship: return True if isinstance(relationship, (AppenderMixin, Query, abc.Container)): return actor in relationship return False
7c9ab9c17552e4156dd0341a8244f9ef13e8aaa9
40,217
import math def gamma_correct(cs, c): """ Transform linear RGB values to nonlinear RGB values. Rec. 709 is ITU-R Recommendation BT. 709 (1990) ``Basic Parameter Values for the HDTV Standard for the Studio and for International Programme Exchange'', formerly CCIR Rec. 709. For details see ...
ebdc970f9e2e82e372bb4f83c162c9d9c2df0f44
40,218
def get_flat_pos_array(img_arr): """Converts grayscale image numpy array into flat array with cube positions for blender. """ WIDTH = 160 HEIGHT = 120 THRESH = 127 res_arr = np.zeros(WIDTH*HEIGHT*3) white_indexes = np.argwhere(img_arr > THRESH) for row in white_indexes: y, x...
7053be7d2cdfee76ca1e347a0982fa08589e99d5
40,219
import re def extract_last_reg_status_change(strValue): """处理show onu last-reg-status-change命令得到的数据。其中,时间若为0000-00-00 00:00:00,将会转换为None。 Args: strValue (str): show onu last-reg-status-change命令得到的数据 Returns: list: 字典列表。 """ # SLOT PON ONU LAST_OFF_TIME LAST_ON_TIME # 4 ...
8661b1b01cc0a8d9c01cad892c2b9560fcbc5406
40,220
def slurp(filename): """Return the contents of a file as a single string.""" fh = open(filename, 'r') try: contents = fh.read() finally: fh.close() return contents
f3e4a943dfe64dbc02e887a2f5f18e39597c8094
40,221
def refsoot_imag(wavelengths, enhancement_param=1): """imaginary part ot the refractive index for soot :param wavelengths: wavelength(s) in meter. :param enhancement_param: This parameter enhances the mass absoprtion efficiency of BC. It makes it possible to scale BC absorption. Values of this param...
bbd7a9ad7f14088739c8eeaef926dbc63f5a2385
40,222
def calculate_all_metrics(obs: DataArray, sim: DataArray) -> dict: """Calculate all metrics with default values.""" results = { "NSE": nse(obs, sim), "MSE": mse(obs, sim), "RMSE": rmse(obs, sim), "KGE": kge(obs, sim), "Alpha-NSE": alpha_nse(obs, sim), "Beta-NSE": ...
6649642ad06152646a82f6c8c68a09599d89cb36
40,223
import os def _file_path_check(filepath=None, format="png", interactive=False, is_plotly=False): """Helper function to check the filepath being passed. Args: filepath (str or Path, optional): Location to save file. format (str): Extension for figure to be saved as. Defaults to 'png'. ...
27d47df198331ee3dd3f6d4d0d1490520f09fd4b
40,224
from typing import Pattern def transform(pattern: Pattern) -> "Either": """Expand pattern into an (almost) equivalent one, but with single Either. Example: ((-a | -b) (-c | -d)) => (-a -c | -a -d | -b -c | -b -d) Quirks: [-a] => (-a), (-a...) => (-a -a) """ result = [] groups = [[pattern]] ...
d2ed8b04de376f6994d123cf8942eb8efb78068a
40,225
def create_placeholders(n_x, n_y): """ Creates the placeholders for the tensorflow session. Arguments: n_x -- scalar, size of an image vector (num_px * num_px = 64 * 64 * 3 = 12288) n_y -- scalar, number of classes (from 0 to 5, so -> 6) Returns: X -- placeholder for the data input, of sha...
e0140f18fd71fec61228f55384588faa0e9bf23e
40,226
import requests import html from datetime import datetime import time def checkIfUpdateAvailable(updateDateFileAddress): """Checks the Jyväskylä open data website for wheter there is an update for the linkkidata-package Returns true if there is, false if there is not""" try: lastUpdatedDate ...
6d7ce02adf4a2bb8e6944abfcc15dac791fa178b
40,227
import torch def nmse(outputs, targets): """ Normalized mean square error :param outputs: Module's output :param targets: Target signal to be learned :return: Normalized mean square deviation """ # Flatten tensors outputs = outputs.view(outputs.nelement()) targets = targets.view(ta...
97d801fa520e4eda214300bf2915d43dc2ec948d
40,228
async def get_schema_template( db: AsyncSession, tenant_id: UUID, wallet_id: UUID, schema_template_id: UUID, deleted: bool | None = False, ) -> SchemaTemplateItem: """Get Schema Template. Find and return a Traction Schema Template by ID. Args: db: database session tenant_i...
ae5da1b26eb74ba206c6b343ad7de95d3ea9081a
40,229
from typing import Callable def get_random_box(shape: AxesLike, box_shape: AxesLike, axes: AxesLike = None, distribution: Callable = uniform): """Get a random box of shape ``box_shape`` that fits in the ``shape`` along the given ``axes``.""" start = distribution(shape_after_full_convolution(shape, box_shape, ...
f75e86c96905cd98853dc83f1832481daa0fc7ea
40,230
def _optimize_font_size(font, text, max_font_size, min_font_size, max_text_len): """Calculate the optimal font size to fit text in a given size.""" # Check size when using smallest single line font size fontobj = ImageFont.truetype(font, min_font_size) text_size = fontobj.getsiz...
e19784e78e484ab6effe9d57ed6e2be89799bc2f
40,231
from redis import StrictRedis as Redis, RedisError def redis_exists(): """ Test that redis-py is installed and redis-server is running locally. """ try: except ImportError: return False try: Redis(db=15).ping() return True except RedisError: return False
181836efd149c4657a384628a0fe842d771d344a
40,232
def get_table_type(filename): """ Accepted filenames: device-<device_id>.csv, user.csv, session-<time_iso>.csv, trials-<time_iso>-Block_<n>.csv :param filename: name of uploaded file. :type filename: str :return: Name of table type. :rtype: str|None """ basename, ext = f...
bc4f39e4c9138168cec44c492b5d1965de711a7e
40,233
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up the IPX800v5.""" hass.data.setdefault(DOMAIN, {}) config = entry.data | entry.options session = async_get_clientsession(hass, False) ipx = IPX800( host=config[CONF_HOST], port=config[CONF_PORT]...
b3f8532338984a0e05a581588336d0311948abdf
40,234
def get_paradigm(dataset_name): """ Return the paradigm of a dataset ('domain_generalization' or 'subpopulation_shift') Args: dataset_name (str): Name of the dataset to get the paradigm of. (Must be part of the DATASETS list) Return: str: The paradigm of the dataset """ ...
c2f28b6b8d4ac4fdacbc26d04862406bc15ff240
40,235
def fix_cropBox_rot(img, bbox, input_size, rot): """Crop bbox from image by Affinetransform. Parameters ---------- img: torch.Tensor A tensor with shape: `(3, H, W)`. bbox: list or tuple [xmin, ymin, xmax, ymax]. input_size: tuple Resulting image size, as (height, width)....
a181821bf6f58e1356116b06d33c6fca58a24003
40,236
def find_locations(text): """ Find normalized location mentions in text, with natasha library """ locations = [] try: doc = Doc(text) doc.segment(segmenter) doc.tag_morph(morph_tagger) doc.parse_syntax(syntax_parser) doc.tag_ner(ner_tagger) for token i...
121478937e469687d482bce2454fc0fff8946a4e
40,237
def length_of_longest_substring(s: str) -> int: """ The most obvious way to do this would be to go through all possible substrings of the string which would result in an algorithm with an overall O(n^2) complexity. But we can solve this problem using a more subtle method that does it with one linear tr...
3844c6fd1c62025b704284e76da25f7c63aa0fc9
40,238
def loads(s): """Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a NeXTSTEP property list document) to a Python object. If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name must be specified....
6d6a36091b8278865370fa35cae5c3aa5c57cbb2
40,239
def make_download_filename(genome, args, response_format): """ Make filename that will explain to the user what the predictions are for :param genome: str: which version of the genome we are pulling data from :param args: SearchArgs: argument used for search :param response_format: str file extensio...
4645e3175de0db81e940d0e64740e937bce7afc3
40,240
def ranges_means(data): """ Return ranges, means of cycles counted using Downing's method 1. """ turns = data_rearranged_for_rainflow_counting(data) values = [] # of the current turns being processed ranges = [] means = [] for turn in turns: values.append(turn) while ...
6d5510709596773570ba5074cb561c66299f86f7
40,241
import os def graphics_from_directories(directories): """ Calls the tools.load_all_graphics() function for all directories passed. """ base_path = os.path.join("static", "images") GFX = {} for directory in directories: path = os.path.join(base_path, directory) GFX[directory] = ...
53970a2982f5539827d37588777f94808e27d211
40,242
def window_to_bounds(window, affine): """Convert pixels to coordinates in a window""" minx = ((window[1][0], window[1][1]) * affine)[0] maxx = ((window[1][1], window[0][0]) * affine)[0] miny = ((window[1][1], window[0][1]) * affine)[1] maxy = ((window[1][1], window[0][0]) * affine)[1] return min...
6377d792271a86175349daa277b8eb937dd740f5
40,243
def matches_version_constraint(constraint, target, version): """ See http://wiki.opscode.com/display/chef/Version+Constraints Do not pad the target to 3 (it would change the meaning of ~>) """ version = pad_to_3(version) # just in case if constraint == '~>': high = pad_to_3(target[:-2] + [(...
38acd10494032c8fd9a6764b308ab6388363bd40
40,244
def get_management_unit_from_pt(request): """This function accepts post requests that contains a geojson representation of a point. The view returns a dictionary contianing the id, label, mu_type, centroid and bounds (extent) of the management_unit containing the point, or an empty dictionary if the da...
542a198a66321456e537f84120ad964a12b20769
40,245
def forge_buy(oc_user,params): """购买打造的装备 """ data = {} user_forge_obj = UserForge.get_instance(oc_user.uid) user_property_obj = UserProperty.get(oc_user.uid) cost_smelting = user_forge_obj.cost_smelting user_smelting = user_property_obj.property_info.get("smelting",0) if cost_smelting >...
35312b9a82754c2854f9cb58266d97ebdd4d0bbe
40,246
from typing import Optional from typing import List def tm_path(name: str) -> str: """Returns the path of the settings file for name ('9o', 'doc', 'go', 'gohtml') Note: This is used to locate syntax files, and appears to break when GoSublime is not located in the ST Package directory. """ pkg...
6d711dd5eac524617e77bddbea5e8fde71ef7168
40,247
import json def get_javascript_value(value): """ Get javascript value for python value. >>> get_javascript_value(True) true >>> get_javascript_value(10) 10 """ if isinstance(value, bool): if value: return 'true' else: return 'false' else: ...
d8a20ebf1ad17e6e25d676f30cb57278b6b22589
40,248
import torch def sort_by_seq_lens(args, batch, sequences_lengths, descending=True): """ Sort a batch of padded variable length sequences by their length. Args: batch: A batch of padded variable length sequences. The batch should have the dimensions (batch_size x max_sequence_length x ...
224af4c3c687f95444aa661eb45d37bb46983a30
40,249
import os import uuid def docker_compose_package_project_name(): """Generate a project name using the current process PID and a random uid. Override this fixture in your tests if you need a particular project name. This is a package scoped fixture. The project name will contain the scope""" return "p...
7e7960a5e34e93618338765b95f5a4c8eb874a3f
40,250
import collections def neighbors(vertices, triangles, depth=1, direct_neighbor=False): """ Build mesh vertices neighbors. This is the base function to build Direct Neighbors (DiNe) kernels. See Also -------- neighbors_rec Examples -------- >>> from surfify.utils import icosahedron, ...
659eda93903526d2fbfe62075c8165ee18fb87d9
40,251
def Bootstrap(data1, data2, M = 1e4, paired = False, direction = None, verbose = False): """ Bootstrap difference in means between two groups. M = float64 # Number of iterations paired = {True, False} direction = {"greater", "lesser", None} if verbose = True, returns distribution and p_value, shows...
9c5773786600c073b40fd394f0f3a3636e576f23
40,252
def read_station_coordinates(file, group=None, var_x='Xs', var_y='Ys'): """ Read the x and y coordinates from an NetCDF file. :param file: Input NetCDF file :param group: The group of the NetCDF file to read. See xarray.open_mfdataset for details. :param var_x: Variable name for x coordinates ...
11cf18e18c01958a6365a137682dd4bc283d6e5c
40,253
def is_ctrl_z(e: InputEvent, keyboard: InputDevice) -> bool: """ Check whether event invokes ^z or not. """ return e.code == ecodes.KEY_Z and ecodes.KEY_LEFTCTRL in keyboard.active_keys()
97fb9da93b30be1b84aabaa0ee6a389d397d65df
40,254
import importlib def import_module_from_path(filepath): """ Import a module from given path. https://stackoverflow.com/a/67692/5159551 """ spec = importlib.util.spec_from_file_location('person', filepath) person_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(person_...
4bc6d2dfeaef811ceb234931e114781ecdae0e57
40,255
import numpy import random def time_mask(spec, T=40, n_mask=2, replace_with_zero=True, inplace=False): """freq mask for spec agument :param numpy.ndarray spec: (time, freq) :param int n_mask: the number of masks :param bool inplace: overwrite :param bool replace_with_zero: pad zero on mask if tru...
f69364510c78f2fc3e96fb4f028737c6c415d5df
40,256
def change(csq): """ >>> change("missense|TMEM240|ENST00000378733|protein_coding|-|170P>170L|1470752G>A") ('170P', '170L', True) >>> change('synonymous|AGRN|ENST00000379370|protein_coding|+|268A|976629C>T') ('268A', '268A', False) """ parts = csq.split("|") if len(parts) < 7: ret...
da43c6bd45e641b885469d07c2e6befff334d8a3
40,257
from pathlib import Path from typing import Optional import os def process( in_dir: Path = typer.Argument( ..., help="The directory containing the input form files" ), out_dir: Optional[Path] = typer.Option( None, "--out_dir", help="The directory where the output flat files...
2005e3a38bfb3091c40b9b383983f0b58da84c52
40,258
from typing import Dict from typing import List from typing import Tuple def update_params( workload: spec.Workload, current_param_container: spec.ParameterContainer, current_params_types: spec.ParameterTypeTree, model_state: spec.ModelAuxiliaryState, hyperparameters: spec.Hyperparameters, bat...
464aef19fd9e8eeb894f972daad57ced56701bb8
40,259
from typing import OrderedDict import sys import json def info(config, stdout=True): """ Info cmdline wrapper """ state = _get_state(config.base_dir, config.baseline, config.target, config.cursor, schema=config...
bb95ab4ea56dd99b61494208607e36ebdba88435
40,260
def with_coordinates(pw_in_path, positions_type, atom_symbols, atom_positions): """Return a string giving a new input file, which is the same as the one at `pw_in_path` except that the ATOMIC_POSITIONS block is replaced by the one specified by the other parameters of this function. `positions_type`, `a...
11dc207a4f17a6521a1aa6299d455f0548c50566
40,261
import sys import glob def list_serial_ports(): """ Lists serial port names https://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on t...
45a859a362cfb24bb3f08e8364bc54629dbe4319
40,262
def find_nearest(array, value): """ Returns the index of "array" whose data best matches "value". https://tinyurl.com/yc7twjx8 """ array = np.asarray(array) idxs = np.argsort(np.abs(array - value))[0] return idxs
7d8b0cba75d6077a6a35b351754546bb345d8090
40,263
def TDVGGNetV1(output_units, input_shape, num_conv_blocks=5, num_block_layers=2*[2]+3*[3], num_fc_layers=3, conv_filters=64, conv_filters_factor=2, max_conv_filters=512, dilation_rate=1, dilation_rate_factor=0, hidden_fc_units=4096, kernel_size=...
a410fe1dce21075f658d340f75f667f9902bf544
40,264
def countby(seq, key): """ Description ---------- Create a dictionary with keys composed of the return value of the funcion/key\n applied to each item in the sequence. The value for each key is the number of times\n each key was returned. Parameters ---------- seq : (list or tuple o...
45ce59f9fd5c837eefbb04ac31d662a10974598d
40,265
import re def datefmt_to_regex(datefmt): """ Convert a strftime format string to a regex. :param datefmt: strftime format string :type datefmt: ``str`` :returns: Equivalent regex :rtype: ``re.compite`` """ new_string = datefmt for pat, reg in PATTERN_MATCHNG: new_string =...
9daeeada904bdd1ca4b71a6e389e9f1ae1ac6ead
40,266
def hsv_decomposition(image, channel='H'): """Decomposes the image into HSV and only returns the channel specified. Args: image: numpy array of shape(image_height, image_width, 3). channel: str specifying the channel. Can be either "H", "S" or "V". Returns: out: numpy array of shap...
c7a853d8c3c4dac4748db262b992235786e91382
40,267
def resize_images(X, y): """ This method resizes the images to height=66, widht=200 No. of Output Images = No. of Input Images """ images = [] steering_angles = [] for i in range(len(X)): resized = cv2.resize(X[i], (200, 66)) images.append(resized) steering_angles.app...
c5356e2f3e6504f99901c6308a901b3e03047919
40,268
def spline_area(s_tuple, N=None): """Compute area of spline s discretized in N segments.""" # to get a good approx. take 3 x the number of knots if N is None: N = 3 * len(s_tuple[0]) c = splev(np.linspace(0, 1, N, endpoint=False), s_tuple) cprm = splev(np.linspace(0, 1, N, endpoint=False),...
0379ad15d86e5715ce142fdae5c038f4e01e5e72
40,269
def kgtk_date_hour(x): """Return the hour component of a KGTK date literal as an int. """ if isinstance(x, str): m = KgtkValue.lax_date_and_times_re.match(x) if m: return int(m.group('hour'))
50cd9029ce956f719b5618b2f7523ec876f6f2ce
40,270
def conv3d_blk(x, shape, stride, phase): """conv3d block with ReLu""" W = tf.get_variable("W", shape=shape, initializer=tf.contrib.layers.xavier_initializer()) b = tf.get_variable("b", shape=shape[4], initializer=tf.constant_initializer(0.1)) return conv3d(tf.nn.relu(tf.contrib.layers.batch_norm(x, is_t...
aec3a1f5de5db5f519499cf0ed32ae553f53d6b1
40,271
def check_bias(bias: TensorParams): """This function checks whether the bias values fit in 40 bits""" if bias and bias.dtype == np.dtype("int64"): valid = all(len(bin(bias_value)[2:]) <= 40 for bias_value in bias.values) return valid return True
666fa565611fc5496a2adb4d6319bd72c4e9ecb4
40,272
import argparse def build_parser(): """Build the cli args parser.""" parser = argparse.ArgumentParser( description=f"""Kubesplit v{__version__} Split a set of Kubernetes descriptors to a set of files. The yaml format of the generated files can be tuned using the same\ ...
3690bd7d7de9036828c9c02b021e832c9f762fb3
40,273
def l2normalize(v, eps=1e-12): """l2 normalize the input vector. Args: v: tensor to be normalized eps: epsilon (Default value = 1e-12) Returns: A normalized tensor """ return v / (tf.reduce_sum(v ** 2) ** 0.5 + eps)
9e3ecce736672a74e5239a3855b696dba8d0ec7c
40,274
def check_password_by_hash(pw, hashed_pw): """Check a password against a salted hash""" expected_hash = hashed_pw.encode('utf8') return bcrypt.checkpw(pw.encode('utf8'), expected_hash)
3aeb5699c708c28305e446c87e9d3a985dea3c33
40,275
def empty_ang(): """Return an empty angle tensor representing 1 residue-level pad character.""" dihe_padding = np.zeros(NUM_ANGLES) dihe_padding[:] = GLOBAL_PAD_CHAR return dihe_padding
0770020f1c61b5c6105a907229b74d67c2e128da
40,276
def _retrieve_gb_sent_state(status: FritzStatus, last_value: str) -> float: """Return upload total data.""" return round(status.bytes_sent * 8 / 1024 / 1024 / 1024, 1)
6a90fac0cbfee7ebd85506b53892ae809eb9bd51
40,277
def create_index(strings, method='fb-trie'): """Create a searchable index for a list of strings. Parameters ---------- strings : iterable of str Strings to index method : {'fb-trie', 'trie'} Index method to use. This affects memory usage and query run time. 'fb-trie...
839434a2489f99560ae5aa3a7a4d9bfdf875cfb7
40,278
def calculate_factor_initial_size(n, key): """ Calculate different initial embedding sizes by a chosen factor. :param n: Number of nodes in the graph :param key: The factor- for example if key==10, the sizes will be n/10, n/100, n/100, .... the minimum is 100 nodes in the initial embedding :retu...
35fdef82e55647b20f9d86ec926e77c1d5244e2e
40,279
def addAxes(pos, NixTopMargin=False, NixBottomMargin=False): """Add axes according the pos list, and return the axes handle. # margin indices 0,1,2,3 for each panel (left, right, bottom, top) """ rect = pos[0]+margins[0], pos[1]+margins[2], pos[2]-margins[0]-margins[1], pos[3]-margins[2]-margins[3] ...
cb0b5bb671cfe2a5b774914c31c99f678716847b
40,280
def main(reference_rmouth_outflows_filename, data_rmouth_outflows_filename, grid_type='HD',param_set='default',flip_data_field=False, rotate_data_field=False,flip_ref_field=False,rotate_ref_field=False,**grid_kwargs): """Top level river mouth matching routine. Deals with file handling""" refer...
0d7f73c41fa2881ae520c42488411eb84ea89dc7
40,281
from re import T def cast(x, dtype, same_kind=True): """ Parameters ---------- x: scalar, array or Theano variable The variable to cast dtype: str The type to which cast the variable. One of - 'int8' - 'int16' - 'int32' - 'int64' - 'uint8' ...
538708aa20f4f1e839eb1b633d39395c92aa631e
40,282
def verify_routing_routes(device, addr_list, protocol, contains, max_time=60, check_interval=10): """Verifies address list agianst 'show route protocol {protocol}' Args: add...
b2da7600f4862c0e3defe321bab64cd8ddaad997
40,283
def group(db): """Create group for the tests.""" group = GroupFactory() db.session.commit() return group
34ab9dc9a9d4766feb9c6e50823efe238ae17fb1
40,284
def is_iterable(value): """ Verifies the value is an is_iterable :param value: value to identify if iterable or not. """ try: iterable_obj = iter(value) return True except TypeError as te: return False
13728b7c28506086a3eb9b8faefcdc6276eba00e
40,285
def remove_stop_words(tokenized_headline_list): """ Takes list of lists of tokens as input and removes all stop words. """ filtered_tokens = [] for token_list in tokenized_headline_list: filtered_tokens.append([token for token in token_list if token not in set(stopwords.words('english'))]) return filtered_toke...
ddaa84becd4294881a3a7b5dc7582d0d289dd045
40,286
def set_agent_config(sampling_interval_seconds=1, cpu_limit_percentage=DEFAULT_CPU_LIMIT_PERCENTAGE): """ Reporting interval needs to have a minimum value and cpu_limit_percentage is used later in tests; the other values can be None as we are not using them here. """ return AgentConfiguration.set( ...
8b273996fd48ebcb82de739290e486da5956941a
40,287
def rw_normalize(A): """ Random walk normalization: computes D^⁼1 * A. Parameters ---------- A: torch.Tensor The matrix to normalize. Returns ------- A_norm: torch.FloatTensor The normalized adjacency matrix. """ degs = A.sum(dim=1) degs[degs == 0] = 1 r...
2a9f90d1f2bf02545e9719b0f373e6eb215fa0cd
40,288
def get_all_stock_fundamentals(): """ Returns a dict mapping instrument id to stock fundamentals """ db = get_db() fundamentals_by_instrument_id = dict() all_fundamentals = list(db["fundamentals"].find()) for f in all_fundamentals: fundamentals_by_instrument_id[f["instrument_id"]] ...
2933ee111b4754609a7172ac93648bccff6439fc
40,289
import os def get_assets_zip_provider(): """Opens stock TensorBoard web assets collection. Returns: Returns function that returns a newly opened file handle to zip file containing static assets for stock TensorBoard, or None if webfiles.zip could not be found. The value the callback returns must be cl...
562f20b276ebe75ccfbedf8ab05080e322cc6865
40,290
def _binary_operator_expression(expression, expression_right): """Builds the IR for a chain of equal-precedence left-associative operations. _binary_operator_expression transforms a right-recursive list of expression tails into a left-associative Expression tree. For example, given the arguments: 6, (T...
3064a7b0989f38245d8b1816a3d5d3414eb5979f
40,291
import re def extract_diacritics(join=True): """ Extracts unique diacritics from a pasted column of IPA transcriptions. Args: join : specifies joining of diacritics in the same transcription. Default True. Requires: regex module as re reDiac() ...
2ba59f3bd5463f03aecc7679fec88f02847921cc
40,292
def announce_work(work_on_population): """Handle the worker counter.""" def wrapper( analysis_id: str, t: int, redis: StrictRedis, kill_handler: KillHandler, **kwargs): # notify sign up as worker n_worker = redis.incr(idfy(N_WORKER, analysis_id, t)) logger.info( ...
ca27bd7dfe71dc36f6e9e7743bdcfd4c73f4f803
40,293
def round(arg: ir.NumericValue, digits: int | None = None) -> ir.NumericValue: """Round values to an indicated number of decimal places. Returns ------- rounded : type depending on digits argument digits None or 0 decimal types: decimal other numeric types: bigint digits non...
ceb4022f5397d76d0d55904d8c9d04536bafb490
40,294
from simtk import unit from typing import List from typing import Tuple import pickle def load_data_sets( atom_features: List[AtomFeature], bond_features: List[BondFeature] ) -> Tuple[MoleculeGraphDataLoader, MoleculeGraphDataLoader, int]: """Loads in the train and test molecules and generates labelled, featu...
a3e65f6f4a5ff392662ffb7da88a355af165a22e
40,295
def login(): """View function to login. Uses the login form. If the @login_required decorator is used on a view function then the user will be redirected to this function.""" if current_user.is_authenticated: return redirect(url_for('index')) form = LoginForm() if form.validate_on...
202880c166dfaa9c29557caf9bd2b738e8c391c4
40,296
def to_isbn13(number): """Convert the number to ISBN-13 format.""" number = number.strip() min_number = compact(number, convert=False) if len(min_number) == 13: return number # nothing to do, already ISBN-13 # put new check digit in place number = number[:-1] + ean.calc_check_digit('978...
acdccd1dffc576322b6ac3af9e1c2d64131bfebc
40,297
import itertools def refine_flare_ranges(lc, sigma=3., makeplot=True, flare_ranges=None): """ Identify the start and stop indexes of a flare event after refining the INFF by masking out the initial flare detection indexes. """ if not flare_ranges: flare_ranges, _ = find_flare_ranges(lc, sigma=sigm...
f73b8d46ac70bf10134749c0446382aee5d8cdb9
40,298
from typing import OrderedDict def get_partial_lm_state_dict(model_state_dict, modules): """Create compatible ASR state_dict from model_state_dict (LM). The keys for specified modules are modified to match ASR decoder modules keys. Args: model_state_dict (odict): trained model state_dict ...
bed8b06ba372ab0c8020d3f58fec07cdd4bdd9dd
40,299