content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from sentry.plugins import plugins def should_process(data): """Quick check if processing is needed at all.""" for plugin in plugins.all(version=2): processors = safe_execute( plugin.get_event_preprocessors, data=data, _with_transaction=False ) if processors: r...
8e6f013d54ac1e3a0b77f8969a3700c45efdc673
23,428
from typing import Tuple from typing import List import gzip def load_fasta_file(input_file: str) -> Tuple[str, List]: """ Load a fasta file into a list of SeqRecords. :param input_file: The path to the input fasta file. :returns: A tuple of the sequence type ('protein' or 'dna'), and the list of Seq...
8e62e7d7002d74da7a43315785f5ce663b5ba366
23,429
from typing import get_args def train_valid_test_datasets_provider(train_val_test_num_samples): """Build train, valid, and test datasets.""" args = get_args() print_rank_0('> building train, validation, and test datasets ' 'for GPT3 ...') train_ds, valid_ds, test_ds = build_train_val...
06f9532c6d60a3c3858dc08a43070b8aa4d19691
23,430
import requests def get(username, start): """ Second level function to pull up to 50 reviews. start - review number to start from """ r = requests.get( '{}/user/beers/?start={}&&ba={}&order=dateD&view=R'.format( BASE_URL, start, username ) ) beers = [] pq = ...
7aaccda46954b629bad37e0a77f834e5b3f40c27
23,431
def isInContinent(country_name: str, continent: str): """Permet de vérifier si le pays est dans un continent Paramètres ---------- country_name : str Le nom du pays continent : str Le code du continent (alpha2) Retours ------- is_in_continent : int entier binair...
5a78e181ace8574baa00eeadd21e7ecea8529f6c
23,432
def encoder_decoder_archi(inputs, is_train): """ Input is assumed to be a 4-D Tensor, with [batch_size, phrase_len, 1, features] """ encoder_layers = [] encoded = inputs encoder_layers.append(encoded) for i in range(config.encoder_layers): encoded = encoder_conv_block(encoded, i,...
6b75ce8a31375173e01ccd7d33078c76aff6d2b8
23,433
def build_dict_conforming_to_schema(schema, **kwargs): """ Given a schema object (for example, TIMESTAMP_SCHEMA from this module) and a set of keyword arguments, create a dictionary that conforms to the given schema, using the keyword arguments to define the elements of the new dict. Checks the result to mak...
8971b7c6e1df8fd16a1b0e0946c9f21a3c601512
23,434
def drop_non_channels(overlaps_df, filename): """ Return the overlap dataframe with all channels dropped and index reset. Save the df as a csv with the filename passed this function. """ df = overlaps_df channels_df_dict = {} for column in df.columns: # For eac...
0cfa7f1ec86328179612c46c6b5f4b787984a7fa
23,435
def _REOM(y,t,pot,l2): """ NAME: _REOM PURPOSE: implements the EOM, i.e., the right-hand side of the differential equation INPUT: y - current phase-space position t - current time pot - (list of) Potential instance(s) l2 - angular momentum squared OU...
427393c1eeb89214603dc8363a9b39084e9030d4
23,437
def optimize_inst(module, inst): """Simplify one instruction""" for operand in inst.operands: if isinstance(operand, ir.Id): if operand.inst.op_name not in ir.CONSTANT_INSTRUCTIONS: return inst if inst.op_name == 'OpCompositeConstruct': inst = optimize_OpComposit...
1de61b914bdac4076be4ffb27823ad9384504814
23,438
def table_3_3(M, lambd_nos, lambd_cil): """ Функция для вывода Су для оживальной ГЧ arguments: число Маха, относительное удлинение носка и цилиндрической части return: Значение Су ГЧ """ cy1iz_alf_0 = [0.0350, 0.0350, 0.0350, 0.0350, 0.0362, 0.0375, 0.0380, 0.0378, 0.0374...
d0d4b2e1fa65f3e8ad2cd39bee1d0d4878293090
23,439
def ms_to_timestamp(ms): """Convert ms to 'HH:MM:SS,mmm'""" # XXX throw on overflow/underflow? if ms < 0: ms = 0 if ms > MAX_REPRESENTABLE_TIME: ms = MAX_REPRESENTABLE_TIME h, m, s, ms = ms_to_times(ms) return "%02d:%02d:%02d,%03d" % (h, m, s, ms)
514773d94f4e3b78594bed4f232f34bcd2956f4d
23,440
import torch def _lovasz_softmax_flat(y_pred, y_true, classes="present"): """ Multi-class Lovasz-Softmax loss y_pred: [P, C] Variable, class probabilities at each prediction (between 0 and 1) y_true: [P] Tensor, ground truth y_true (between 0 and C - 1) classes: 'all' for all, 'present' for ...
9cdbab2873e198750079e560a559b1f4eb8f256c
23,441
def quantum_state_encoding_circuit(bits): """根据`bits`构建并返回量子态编码线路.""" circuit = cirq.Circuit() circuit.append(cirq.H.on_each(bits)) return circuit
75734a349187af7ac32683d5faf6aec331f25713
23,442
from datetime import datetime def parse_mov_date(date_str): """converts string to date""" try: return datetime.datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S%z") except (TypeError, ValueError): pass return None
6d4f1ad566f3e3914eeed7f9c29d914f1ced96df
23,443
def get_settable_attr(attr): """ If attr is not settable, navigate upp in the connection hierarchy until we find the settable attribute. For example, in RigSqueeze, the ikFk state attribute will be redirected to the root ctrl. Note that in some case the attribute might have been piped in an utility node...
aca71e6e7f9e1312beaf1c4dcba897073ae3b3ea
23,444
def adds(repo, subset, x): """Changesets that add a file matching pattern. The pattern without explicit kind like ``glob:`` is expected to be relative to the current directory and match against a file or a directory. """ # i18n: "adds" is a keyword pat = getstring(x, _(b"adds requires a pat...
6d9d1879c77f64bb68d43483cc2d3095328fd26f
23,445
def data_context_topology_context_topologyuuid_linklink_uuid_available_capacity_bandwidth_profile_committed_information_rate_get(uuid, link_uuid): # noqa: E501 """data_context_topology_context_topologyuuid_linklink_uuid_available_capacity_bandwidth_profile_committed_information_rate_get returns tapi.common.Ca...
b44e48aa0fff6b01da22576fc73352deba812636
23,446
from typing import List from typing import Dict from operator import and_ def update_mlwh_with_cog_uk_ids(samples: List[Dict[str, str]]) -> None: """Update the MLWH to write the COG UK barcode for each sample. Arguments: samples {List[Dict[str, str]]} -- list of samples to be updated """ if l...
b4d6dfaec4bb40a59cbdfef619f7f4542e55e2a9
23,450
def make_09f9(): """倉庫インベントリーフッタ""" return ""
91d21aeb58fc004865db91846d73f978f48f9be4
23,451
def get_last_successful_hour_or_start_hour(): """Get the last hour that ran successfully or the start hour.""" last_hour = crash_stats.get_last_successful_hour() if last_hour: return last_hour return get_start_hour()
86518100bafe3296d63a8ac3612de1fa2c2ed8d4
23,452
import copy from datetime import datetime def encode_jwt(payload, secret): """ Return ``payload`` as a JWT encoded with ``secret``. Return a JWT whose payload is ``payload`` and that is signed using ``secret``. :arg payload: the payload to encode :type payload: dict :arg secret: the secr...
497d5180e8956a737ad6edbd1113d73aeb915e80
23,453
def make_model(): """ Loads pretrained torchvision model and redefines fc layer for car classification """ # uses about 1 GiB of GPU memory model = models.vgg19(pretrained = True) #model = models.resnet50(pretrained = True) in_feat_num = model.classifier[3].in_features mid_feat_num = int...
cd189f4b4d4dcadf6dd686aad08e2e494e0c2200
23,454
def empty_call_false(*args, **kwargs) -> bool: """ Do nothing and return False """ return False
3b3964c859a47698f0000e1b26963953980fad51
23,455
def cookie_is_encoded(data): """ Tests whether or not a cookie is encoded / HMAC signed -> #bool True if encoded .. from vital.security import cookie_is_encoded cookie_is_encoded( "!YuOoKwDp8GhrwwojdjTxSCj1c2Z+7yz7r6cC7E3hBWo=?IkhlbGxvLCB3b3JsZC4i") ...
baf2a05b516a23cacca4985944974112019abfda
23,456
import torch def l2_normalize(x: torch.Tensor, eps: float = 1e-12) -> torch.Tensor: """Normalizes the input tensor using L2-norm. Args: x: Tensor to be normalized. eps: Small value to avoid division by zero. Returns: Normalized tensor. """ return x / (torch.norm(x, p=2, ...
22273bbbda7bece511d31d517790bfa14427d76f
23,457
from re import S def ssq_cwt(x, wavelet='gmw', scales='log-piecewise', nv=None, fs=None, t=None, ssq_freqs=None, padtype='reflect', squeezing='sum', maprange='peak', difftype='trig', difforder=None, gamma=None, vectorized=True, preserve_transform=None, astensor=True, order=0, patie...
2776e85dde171b1c47fdce028bf9c845298b3a93
23,458
import torch def predict_image_classification(model: nn.Module, input_: torch.Tensor): """ Predict using an image classification model. Args: model (`nn.Module`): Pytorch model. input_ (`Tensor`): Input image tensor. Returns: (`tuple`) Predic...
2343d4db9b93910337e0e55b9935783714710330
23,459
def _id_to_box(id_, dim): """Convert id to box ID""" row = id_ // (dim ** 3) col = (id_ % (dim ** 2)) // dim return row * dim + col
8e6c4779872fff5cdc5a6ca6b4143a1519d8aaf2
23,460
import string def _load_hex(instream): """Load font from a .hex file.""" global_comment = [] glyphs = [] comment = [] for line in instream: line = line.rstrip('\r\n') if ':' in line: # parse code line key, value = line.rsplit(':', 1) value = valu...
6e5980e53ee598d813f10bdbcb775e8d47102fa8
23,461
def make_small_graph(graph_description, create_using=None): """ Return the small graph described by graph_description. graph_description is a list of the form [ltype,name,n,xlist] Here ltype is one of "adjacencylist" or "edgelist", name is the name of the graph and n the number of nodes. This ...
deb1cf0d08bba91a538c7d2c47c1d89e2c2a28da
23,462
def get_masksize(mask, labelnum = None): """ Compute mask size in surface space Parameters: ---------- mask: label image (mask) labelnum: mask's label number, use for group analysis Return: -------- masksize: mask size of each roi Example: -------- >>> masksize = g...
c8ccd82d9887f923e3d2581f97dd2a8f016cc182
23,463
def _context_py2rpmversion(context): """get a python PEP0440 compatible version and translate it to an RPM version""" # the context needs a variable set via {% set upstream_version = 'ver' %} _context_check_variable(context, CONTEXT_VAR_UPSTREAM_VERSION, 'py2rpmversion') ...
3f9110dff377a6c819e6b87ab5fd9c81a7532694
23,464
def check_and_format_address(address): """ check address """ try: formatted_address = to_checksum_address(address) return formatted_address except Exception as e: raise ArgumentsError("invalid address {}, reason: {}" .format(address, e))
1b0c88aede34386d1ccd5facd1bdbd4724538ab7
23,465
from typing import Optional def get_cache_name(cache_type: str, tag: Optional[str] = None) -> str: """ Get the canonical cache name (e.g., "tmp.cache.mem.tag") for a type of cache. :param cache_type: type of a cache :param tag: optional unique tag of the cache, empty by default :return: name ...
ff933829314dd1794406ca4282eaf4efdf860b39
23,466
def _aves2_cfg(): """ Read aipctl config """ config = ConfigObj() # The result is a merge of all the files as they appear in the list f_list = cfg_files() if not f_list: print("error: configuration file not found") exit(1) for f in cfg_files(): _cfg = ConfigObj(f, e...
527f1e94d5ec2c5cd13aa1a886d4c56914828f4d
23,467
def estimate_responsivity(mis_MU, norm_MU): """from the estimated base intensities, we return onlu users which have zero base intensity for misinformation and greater than zero base intensity for normal content. """ no_bad_intentions_ids = [] for id in range(len(mis_MU)): if mis_MU[id] == 0 and...
4d944478694f1be1474eea963fad284079d5fe57
23,469
from typing import Union from typing import Any from datetime import datetime def parse_field_constraint( x: Union[str, int, float, bool, list], constraint: str, type: str = "string", **field: Any, ) -> Union[str, int, float, bool, list, datetime.datetime, ConstraintTypeError]: """ Parse field...
531e33a1bc79e8a232032ebe9d340f829a3f513c
23,470
def compute_ab_cycles(c_cycles, linear_combinations, g, tretkoff_graph): """ Returns the a- and b-cycles of the Riemann surface given the intermediate 'c-cycles' and linear combinations matrix. Input: - c_cycles - linear_combinations: output of the Frobenius transform of the """ linco...
645d569ee06cb87161b12158603b1b6dcfb92077
23,471
import pickle import pathlib def pmlb_multiclass_classification_dataset_names(): """Returns list of multiclass classification datasets in PMLB.""" try: name = pickle.load(open(".pmlb/mcdn.pkl", "rb")) except FileNotFoundError: pathlib.Path(".pmlb").mkdir(parents=True, exist_ok=True) ...
d3030441c119de0c96c9d83df026b7f922fe21e6
23,472
from losses.loss_functions import BalancedCrossEntropyLoss from losses.loss_functions import SoftMaxwithLoss from losses.loss_functions import NormalsLoss from losses.loss_functions import BalancedCrossEntropyLoss from losses.loss_functions import DepthLoss def get_loss(p, task=None): """ Return loss function for...
6284d2e40fc8aa220c153307fc7199a47549d15d
23,473
def compute_embeddings(image): """A mock function for a call to a deep learning model or a web service.""" del image # this is just a mock and doesn't do anything with the input return 42
31536d4a2371140e962aadb63b8645685328b3df
23,474
def text_to_string(filename): """Read a text file and return a string.""" with open(filename) as infile: return infile.read()
dbd79e78c84c3374c0252544086885b909ae9bd9
23,476
def lgsvlToScenicElevation(pos): """Convert LGSVL positions to Scenic elevations.""" return pos.y
d90f7509285b08c791eac56c1a119f91120cf556
23,477
import jinja2 def render_to_string(backend, filename, context): # type: (str, str, Dict) -> str """ Render a template using the specified context :param backend: The backend for which the template is rendered :param filename: The template name :param context: The data to use when rendering the...
c645a9867acdb50236a5604144a104cb38e841f9
23,478
def customfield_by_name(self, name): """ Get the value of a customfield by name """ # Get all fields from Jira. This is expensive, so only do it once if not hasattr(self, '_fields'): response = self._session.get( self._base_url.format( server=self._options['server...
35f7ee1e88029201086fc75bbc280beb386cca44
23,479
from pathlib import Path def download_images(imgs): """Save any images on page to local directory""" had_download_issue = False for img in imgs: image_url = 'https://projecteuler.net/{}'.format(img.get('src')) logger.info(f'downloading image {image_url}') image_name = Path(image_ur...
7d39dff40797a698215a589f9ff65f3df4a85e9f
23,480
def admin_order_pdf(request, order_id): """ 1. Get data (and templates for displaying data) 2. Set type (cuz you'll need to download it, right?) 3. Using the module (configuring stuff, e.g. the CSS :P) """ order = get_object_or_404(Order, id=order_id) html = render_to_string...
c4cf5a38743f573ef8dfa704cfe2d12bb47a679c
23,481
import traceback def delete_container(request, container): """ Deletes a container """ storage_url = request.session.get('storage_url', '') #meta_storage_url = request.session.get('meta_storage_url', '') auth_token = request.session.get('auth_token', '') #meta_auth_token = request.session.get('me...
ce205d6112239905707064f0357b6c19fe3bd688
23,482
def dense_encoder(X, params): """Dense model encoder subgraph that produces latent matrix. Given data matrix tensor X and dictionary of parameters, process through dense model encoder subgraph and return encoder latent vector for each example in batch. Args: X: tf.float64 matrix tensor of input data. ...
1dfe2b876cb32b5d8b89e70e451a732730762a14
23,483
def __asset_inventory_espanol(asset): """ Renombra los encabezados del inventario de bases de datos de Datos \ Abiertos Colombia a términos en español. :param asset: (pandas.DataFrame) - Tabla de inventario del portal de datos\ abiertos Colombia (https://www.datos.gov.co). :return: base de ...
dfb508cec458ecb63c371849d84cb3b3d79335ba
23,484
def end_of_sign_found(token: str, preceding_token: str): """ This function receives a token and its preceding token and returns whether that token ends an Akkadian sign. """ if not preceding_token: return False if '-' in token or '.' in token: return True if not preceding_token.e...
30024ddad31c3149d1d2363842b085d2923c1387
23,485
from typing import Optional from typing import Dict import datasets def get_loaders( dataset: str, batch_size: int, num_workers: Optional[int] ) -> Dict[str, DataLoader]: """Init loaders based on parsed parametrs. Args: dataset: dataset for the experiment batch_size: batch size for loader...
2340d05f69057bcb034a8ec4ad5515055d0bde71
23,488
def pipeline(): """ Creates a pipeline configured to use a given model with a specified configuration. Notes ----- Pipeline can be executed only if its config contains the following parameters: model_class : TFModel Architecture of model. List of available models is defined at 'AVAILABLE_M...
f8fbbe3898b58b1b1621d742e4acdf80f17ba11c
23,489
import copy def get_screen_point_array(width: float, height: float): """Get screen points(corners) in pixels from normalized points_in_square :param width: screen width :param height: screen height :return: """ points = copy.deepcopy(points_in_square) for i in range(len(points_in_square))...
34d88ddb1a24e4e3ebc81f0c7e99530548ed8a8b
23,490
def get_spacing_matrix(size, spacing, offset): """Returns a sparse matrix LinOp that spaces out an expression. Parameters ---------- size : tuple (rows in matrix, columns in matrix) spacing : int The number of rows between each non-zero. offset : int The number of zero r...
5871385bcdcb9ce538fe1e4525c947c2cfa582c9
23,491
def next_power2(x): """ :param x: an integer number :return: the power of 2 which is the larger than x but the smallest possible >>> result = next_power2(5) >>> np.testing.assert_equal(result, 8) """ return 2 ** np.ceil(np.log2(x)).astype(int)
379c2170d0dbd25ee01a47eb0765f4dfd143efbb
23,492
def category_induced_page(): """Form to compute the Category induced.""" return render_template('category-induced.html')
176af8bbbb67afce78c11483f66b3d5ac15f6d76
23,493
import array from operator import concat def zext(value, n): """Extend `value` by `n` zeros""" assert (isinstance(value, (UInt, SInt, Bits)) or (isinstance(value, Array) and issubclass(value.T, Digital))) if not is_int(n) or n < 0: raise TypeError(f"Expected non-negative integer, got '...
dfd666446f1b93ebdeeb94b932d8de7b243f6a4e
23,494
import math def _distance(point0, point1, point2, seg_len): """Compute distance between point0 and segment [point1, point2]. Based on Mark McClure's PolylineEncoder.js.""" if (point1[0] == point2[0]) and (point1[1] == point2[1]): out = _dist(point0, point2) else: uuu = ((point0[0] - po...
1927a5fe46dcb0245031b395aade67ec01270930
23,495
def delete_node( graph: xpb2.GraphProto, node_name: str = "", **kwargs): """ Add node appends a node to graph g and returns the extended graph Prints a message and returns False if fails. Args: graph: A graph, onnx.onnx_ml_pb2.GraphProto. node_name: Name of the node...
620e325a0ea9da7cd83e897fee49fb6ef9183da4
23,496
from PIL import Image def image_to_term256(pil_image): """Convert image to a string that resembles it when printed on a terminal Needs a PIL image as input and a 256-color xterm for output. """ result = [] im = pil_image.convert('RGBA') try: except ImportError: im.thumbnail((80, 8...
482f6c868adf5f302d88898abeff426d9ed000e7
23,497
def false_discovery(alpha,beta,rho): """The false discovery rate. The false discovery rate is the probability that an observed edge is incorrectly identified, namely that is doesn't exist in the 'true' network. This is one measure of how reliable the results are. Parameters ---------- ...
849c236157070c5d1becfec3e4e5f46a63d232d2
23,498
def add_default_legend(axes, subplots, traces): """ Add legend to the axes of the plot. This is needed to be done using matplotlib shapes rather than the build in matplotlib legend because otherwise the animation will add a legend at each time step rather than just once. Parameters ---------- ...
d352c1d90dac882f687be426d63dea35dca4ba46
23,499
def split_data(n_samps, percent_test): """ :param n_samps: number of data samples :param percent_test: percent of data to hold out :return: two sets of indices corresponding to training and validation data """ # generate and randomly shuffle idx = np.arange(n_samps) np.random.shuffle(id...
68d63d28b2aaab2697f2aab70fc7341a9a31811d
23,501
def compute_totals(songs, limit_n, save_file=None): """ Return array of shape (4, 3, 35) representing counts for each group of each context type of each label """ totals = np.zeros((4, 3, 35), dtype='int32') i = 0 for song_path, beatmap_ids in songs: print('song {}'.format(i)) ...
d8e845912d6e1b5e0fab864e8a19cdc08500b4c5
23,502
def _initialize_arrays(initial_values, num_steps): """Construct a structure of `TraceArray`s from initial values.""" trace_arrays = tf.nest.map_structure( lambda t: tf.TensorArray( # pylint: disable=g-long-lambda dtype=t.dtype, size=num_steps, # Initial size. ...
f63e13f35aade7979b4090964c593c2d222e94bd
23,503
def blend(image1, image2, factor): """Blend image1 and image2 using 'factor'. Factor can be above 0.0. A value of 0.0 means only image1 is used. A value of 1.0 means only image2 is used. A value between 0.0 and 1.0 means we linearly interpolate the pixel values between the two images. A value greater than...
5012d34ab9974e88bfc7dae4683521313fd37cd0
23,504
def start_of_next_clk_period(time: float, clk_period: float): """ :return: start time of next clk period """ return (start_clk(time, clk_period) + 1) * clk_period
d59dafc3a8fdec9d199dcf379eefce52267ea4c1
23,506
import re def eval_formula(formula, assignment): """ Evaluates a formula represented as a string. **Attention**: Be extremely careful about what to pass to this function. All parameters are plugged into the formula and evaluated using `eval()` which executes arbitrary python code. Parameters ...
c1f344fc0049e20e86feb2428a46d51f9eee5898
23,507
def soil_temperature(jth: int, states: States, weather: Weather): # j = 1,2,..,5 """ Equation 2.4 / 8.4 cap_soil_j * soil_j_t = sensible_heat_flux_soil_j_minus_soil_j - sensible_heat_flux_soil_j_soil_j_plus 0 is Floor, 6 is SoOut """ h_soil_j_minus = Coefficients.Floor.floor_thickness if jth =...
ddd3e50b30dc1240d5f6c6200aea710beba6b498
23,508
def clean_user_data(model_fields): """ Transforms the user data loaded from LDAP into a form suitable for creating a user. """ # Create an unusable password for the user. model_fields["password"] = make_password(None) return model_fields
9b9f968c4a775527dac36597ecadee476549dc7d
23,509
import json def case_structure_generator(path): """Create test cases from reference data files.""" with open(str(path), 'r') as in_f: case_data = json.load(in_f) system_dict = case_data['namelists']['SYSTEM'] ibrav = system_dict['ibrav'] ins = {'ibrav': ibrav, 'cell': case_data['cell']} ...
1c7249c207032ed623bbfe274ed117283cd6ef4d
23,510
from typing import Optional from typing import Type from typing import Dict from typing import List from typing import Any def load_ascii(file: 'BinaryFile', # pylint: disable=unused-argument,keyword-arg-before-vararg parser: 'Optional[Type[ASCIIParser]]' = None, type_hook: 'Optional[Di...
fa7f0ba4a98dc295fb23651373a6489dad5c205e
23,511
def differences_dict(input_dict): """Create a dictionary of combinations of readers to create bar graphs""" # Getting the combinations of the formats for each_case in input_dict.keys(): comb = combinations(input_dict[each_case].keys(), 2) x = list(comb) comp_values = {} comp_...
a15ef7bab8a9abaf556e1ce97a4c695b50d5b460
23,512
import psutil def available_memory(): """ Returns total system wide available memory in bytes """ return psutil.virtual_memory().available
5071312f64aa37e1d777c8f20009fa38137381a4
23,513
from typing import List from typing import Set import numpy def get_hypergraph_incidence_matrix(node_list: List[Node], hyperedge_list: List[Set[Node]] ) -> numpy.array: """Get the incidence matrix of a hypergraph""" node_to_index = {node:...
706bdd53a1fefec3ee3f77fa79248361ffff0351
23,515
from re import X def fformat(last_data, last_records): """ @param last_data: dictionary(node_name => node's data segment) @param last_records: dictionary(node_name => timestamp, node when last transmitted) @return: html """ nodelist = last_data...
28da148b43c616652872cabc7815cba51dafd16c
23,516
import math def ceil(base): """Get the ceil of a number""" return math.ceil(float(base))
ebe78a5eb8fa47e6cfba48327ebb1bdc469b970d
23,517
def train( dir, input_s3_dir, output_s3_dir, hyperparams_file, ec2_type, volume_size, time_out, docker_tag, aws_role, external_id, base_job_name, job_name, use_spot_instances=False, metric_names=None, ...
7cd92363bcde8dc86989a8932236cd4b2961b0e3
23,519
def wikitext_page(d, e, title, fmt='wikitext'): """Create infobox with stats about a single page from a category. Create infobox with stats about a single page from a category. Currently only supports formatting as wikitext. Only returns the string of the text, does not save any files or modify other data ...
1288a1fea5bc54ef6243089eea0578cc43ec311e
23,520
from typing import Tuple def _quadratic( self: qp.utils.Minimize[Vector], direction: Vector, step_size_test: float, state: qp.utils.MinimizeState[Vector], ) -> Tuple[float, float, bool]: """Take a quadratic step calculated from an energy-only test step. Adjusts step size to back off if energy ...
49b2e75d0ae39e968e7288690dea7d42c423a2df
23,521
def create_image(ds: "Dataset", data_element: "DataElement") -> "gdcm.Image": """Return a ``gdcm.Image``. Parameters ---------- ds : dataset.Dataset The :class:`~pydicom.dataset.Dataset` containing the Image Pixel module. data_element : gdcm.DataElement The ``gdcm.DataElemen...
95f96b0f666903529811fbf3aaeb71305dfcb1bc
23,522
def linear_interpolate_by_datetime(datetime_axis, y_axis, datetime_new_axis, enable_warning=True): """A datetime-version that takes datetime object list as x_axis """ numeric_datetime_axis = [ totimestamp(a_datetime) for a_datetime in datetime_axis ] numer...
515eb1e389b711ff3add707abe91bf577b38192d
23,523
def calculate_index( target_ts: pd.Timestamp, timestamps: pd.DatetimeIndex ) -> pd.Timestamp: """ Return the first index value after the target timestamp if the exact timestamp is not available """ # noinspection PyUnresolvedReferences target_beyond_available = (target_ts > timestamps).all() ...
db1ad3130b3763115cb88e8798618d9632996bd7
23,524
from typing import OrderedDict import pydoc def walk_through_package(package): """ Get the documentation for each of the modules in the package: Args: package: An imported python package. Returns: output: A dictionary with documentation strings for each module. """ output = ...
9ad0e9d935a812608fb42af788c1ae6746b78684
23,525
import gzip def extract_images_2(f): """Extract the images into a 4D uint8 numpy array [index, y, x, depth]. Args: f: A file object that can be passed into a gzip reader. Returns: data: A 4D unit8 numpy array [index, y, x, depth]. Raises: ValueError: If the bytestream does not start with 2051. "...
eb3b44051c6cc3721a82641346c233d9d4bfe1da
23,526
from datetime import datetime def slope_finder(station): """ This function computes the slope of a least-squares fit of polynomial of degree p to water level data and return that is it positive or negative""" try: dt = 2 dates, levels = fetch_measure_levels(station.measure_id, dt=datetime....
035a78a4e54b94945837e97c6dce53bc36770956
23,527
def get_attr_counts(datas, attr): """ 不同属性值的数量. :param datas: :type datas: list[BaseDataSample] :param attr: :type attr: str :return: """ results = {} for data in datas: value = data.get_value(attr) if isinstance(value, list): for v in value: ...
bea8e6e1c99efe1ad18894831006f0e218517c74
23,528
def split(string: str, separator: str = " ") -> list: """ Will split the string up into all the values separated by the separator (defaults to spaces) >>> split("apple#banana#cherry#orange",separator='#') ['apple', 'banana', 'cherry', 'orange'] >>> split("Hello there") ['Hello', 'there...
73e01d7ff9111d949f31f37b36c3b0656d06e340
23,529
import ast def _find_class(name: str, target: ast.Module) -> t.Tuple[int, ast.ClassDef]: """Returns tuple containing index of classdef in the module and the ast.ClassDef object""" for idx, definition in enumerate(target.body): if isinstance(definition, ast.ClassDef) and definition.name == name: ...
ad67d36772ef9541edb72a9d56f3553dc9eaffd2
23,530
def tidy_osx_command_line_tools_command(client: TidyClient, **kwargs) -> DemistoResult: """ Install OSX command line tools Args: client: Tidy client object. **kwargs: command kwargs. Returns: DemistoResults: Demisto structured response. """ runner: Runner = client.osx_comma...
0045848f0cef054dfab24a7698e4b3432843f747
23,532
def nav_entries(context): """ Renders dynamic nav bar entries from nav_registry for the provided user. """ context['nav_registry'] = nav_registry return context
8af1917c04a9cbd17895c0fab0239d6fd7c009d2
23,533
from typing import Any def get_largest_component(graph: ig.Graph, **kwds: Any) -> ig.Graph: """Get largest component of a graph. ``**kwds`` are passed to :py:meth:`igraph.Graph.components`. """ vids = None for component in graph.components(**kwds): if vids is None or len(component) > len(...
24f04905c767f02a03b5a6fbf4ae0ba0b1f49269
23,534
def hiring_contests(): """Gets all the hiring challenges from all the availbale platforms""" contests_data = get_contests_data() active_contests = contests_data["active"] upcoming_contests = contests_data["pending"] get_challenge_name = lambda x : x.lower().split() hiring_challenges = [contest for contest i...
91566f0117fc5bc38db7bc930d5e4c7bd1bd2992
23,535
import torch def _find_quantized_op_num(model, white_list, op_count=0): """This is a helper function for `_fallback_quantizable_ops_recursively` Args: model (object): input model white_list (list): list of quantizable op types in pytorch op_count (int, optional): count the quantizable...
c51b06e476ff4804d5bdfca5a187717536a0418f
23,536
from unittest.mock import patch def test_process_bulk_queue_errors(app, queue): """Test error handling during indexing.""" with app.app_context(): # Create a test record r1 = Record.create({ 'title': 'invalid', 'reffail': {'$ref': '#/invalid'}}) r2 = Record.create({ ...
83c4609eb62d65fb7d53117906a0d6f128fe7b30
23,539
def list_to_string(the_list): """Converts list into one string.""" strings_of_list_items = [str(i) + ", " for i in the_list] the_string = "".join(strings_of_list_items) return the_string
f580dd8646526e64bb50297608e8ad8e338d9197
23,540
from typing import Optional def get_rate_plan(apiproduct_id: Optional[str] = None, organization_id: Optional[str] = None, rateplan_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetRatePlanResult: """ Gets the details of...
c439d2b991174b2fa4137d0b88f04af0ba4a22b9
23,542
def detail_blotter(backtest, positions, holdings, mode='simplified'): """ 分品种获取详细交易状况,合并市场数据、交易情况和账户变动 参数: backtest, positions, holdings为回测引擎返回的变量 mode: 'simplified'则市场行情数据只保留'close'列 (DataFrame的字典) 返回: 字典,键为symbol,值为DataFrame格式 示例: blotter = detail_blotter(backtest, positions, ...
9a2d8168cfc9ee979be847c6dac783a70503503c
23,543