content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import List def readOneLineFileWithCommas(filepath: str) -> List[str]: """ Reads a file that is one line long, separated by commas """ try: with open(filepath) as fp: s: str = fp.readline() return s.split(",") except: raise Exception(f"Failed to open {filepath}...
4c181523192fab0ea01ae5da0883c543565119c6
23,400
from operator import or_ def package_search(filters, context, limit=None, catalog=False): """Search packages with different filters Catalog param controls the base query creation. Catalog queries only search packages a user can deploy. Non-catalog queries searches packages a user can edit. ...
0d15d2936f713437e3d9dad794cd07faf1ca3090
23,401
def is_valid(listener_tuple): """ There are a few rules that aws has when creating listeners, this function ensures those rules are met before we try and create or update a listener. While these could be caught with boto exception handling, I would rather be nice and catch these early before we...
d95db075e302753a373ed4e0efd7a3667dc2ecf3
23,402
def _jitter_boxes(gt_boxes, jitter=0.05): """ """ jittered_boxes = gt_boxes.copy() ws = jittered_boxes[:, 2] - jittered_boxes[:, 0] + 1.0 hs = jittered_boxes[:, 3] - jittered_boxes[:, 1] + 1.0 width_offset = (np.random.rand(jittered_boxes.shape[0]) - 0.5) * jitter * ws height_offset = (np.ra...
570fa7a6bd2f898ce1d64dd9f6e666e50251fcf5
23,403
import os def last_model_path(exp_name): """ get path of the last model in the exp """ model_path = os.path.join(constants.ET_LOGS, exp_name, "latest.pth") assert os.path.islink(model_path) return model_path
8948eb304047540fc988a55a9682c841f356eb72
23,404
def lcm_gcd(a, b): """Finds the least common multiple of two integers Args: a, b: integers greater than or equal to 1 """ return a * b//greatest_common_divisor(a, b)
3b23d04164c8e69eee26e48ab2b1a60e8e99fd14
23,405
def test_ahocorasick_rs_overlapping(benchmark, test_data): """ahocorasick_rs overlapping matches.""" patterns, haystacks = test_data ac = ahocorasick_rs.AhoCorasick(patterns) def run(): for haystack in haystacks: x = ac.find_matches_as_strings(haystack, overlapping=True) ret...
3c53369e8006502a5071fb73a75ace4705421a84
23,406
import warnings def merge_frames(frames): """ Merge the multiple data files downloaded from the M2M system or the Gold Copy THREDDS server into a single xarray data set. Keep track of how many files fail to merge. :param frames: The data frames to concatenate/merge into a single data set :ret...
b8b083d8f0e9360df325fbeb812b64fffc8d1d0f
23,407
import re def sorted_nicely(l): """ This function sorts the given iterable in the way that is expected Obtained from: https://arcpy.wordpress.com/2012/05/11/sorting-alphanumeric-strings-in-python/ :param l: The iterable to be sorted :return: Sorted iterable """ convert =...
c2e398e7a654a1a1ec7cc113fcad500beefd876a
23,408
def run_board(effects: list, audio: np.array, sample_rate: float) -> np.array: """Run board on input audio data. Args: board (list): List of Pedalboard effects. audio (np.array): Input audio data. Returns: Output (effected) audio data """ board = Pedalboard(effects, sample_...
062f7d34aa7eadad5401e64df1e96857606cbcf6
23,409
def html_escape( s ): """ """ s = s.replace( '&', '&amp' ) s = s.replace( '<', '&lt' ) s = s.replace( '>', '&gt' ) return s
eb47ba4d4651763cb74f081095b78d53ee9bebc1
23,410
def model_query(context, model, *args, **kwargs): """Query helper. :param context: context to query under :param session: if present, the session to use """ session = kwargs.get('session') or object_sqla.get_session() query = session.query(model, *args) return filter_by_project(context, q...
c6e5fb09b7e9a4d85ab6c6abc1e03e227010591f
23,411
def bert_dropout_model(num_classes, bert_config, use_mc_dropout_mha=False, use_mc_dropout_att=False, use_mc_dropout_ffn=False, use_mc_dropout_output=False, channel_wise_dropout_mha=F...
6ee1d09b2070e54ba631bd6e1b8e3e453960073a
23,412
def calculate_monthly_sales(year: int, month: int, beer_style: str) -> int: """Calculates the sales of a particular type of beer in a given month. param: month -- an int ranges from 1 to 12, beer_style; return: total_sales """ total_sales = 0 for item in data: if item[2].year =...
fa448a8e9dfb7186652a6dc3000d3a8465320994
23,413
def check_canopy_height(region_info, regional_lookup): """ Check the regional canopy height. """ mean_canopy_height = region_info['mean_canopy_height'] if mean_canopy_height == 'no data': mean_canopy_height = 0 return mean_canopy_height
5f04ad71df7f0b1c9ef73e97bbe99bea1916ae5e
23,414
def annotated_var(prs): """ Parser for annotated variable in parentheses. Annotation is parsed with prs. Parser output is a var token annotation is stored in attribute 'annotation' of var token. Sample input to parser: (x : A) """ def trt(acc): v,ann = acc ...
42acdf6eb09952701d17fab73a2ee8fc20c7dc5e
23,415
def action_from_json(project, value): """return a action from the given json """ json_type = value.get('type') for class_ in sftoolbox.engine.action_classes_register: if json_type == class_.json_type: return class_.from_json(project, value) return DummyAction.from_json(project, ...
69658b53e839c7d112b7509e3ecdf57a82de817a
23,416
def get_springer_doi(node): """ :param node: :return: """ for elem in find_key(node, 'occurrence'): if isinstance(elem, list): for sub_elem in elem: if isinstance(sub_elem, dict): values = sub_elem.values() if len(values) =...
ca8773f10e6fed6b41064a5a5ad6717afd540bb5
23,417
def check_versions(versions=[]): """ Check if there are version to build the changelog. """ if len(versions) == 0: raise NotEnoughVersionsError() return True
f9c7f81c02f08a867f27f329554ed85eddc34243
23,418
def create_fnet(widths, nfeat, nfeato, orthoinit, llbias): """ Creates feature-generating network, a multi-layer perceptron. Parameters: widths: list of widths of hidden layers nfeat, nfeato: # input and output channels of the convolution orthoinit: whether to use orthogonal weight initialization ...
3bdfdd89d77b6ba172e2ac85df191b11e78ab049
23,419
def pytorch_array_setitem(op): """Implementation of array_setitem for pytorch.""" def _impl(array, begin, end, strides, value): idx = tuple(slice(b, e, s) for b, e, s in zip(begin, end, strides)) ret = array.clone() ret[idx] = value return (ret,) return _impl, op.inputs[1:]
b0c6504b2c0d1971ec16e5fdf198b20a911d4946
23,420
def time_series_seasonal_test(x: pd.Series, expected_lags: list): """ 通过自相关系数来获取不同lag的相关系数,通过相关系数来判断时序数据的周期值 PS:需要列出lag的值的列表 :param x: 时序数据x,type: Series :param expected_lags: 可供选择的的滞后值 :return: 返回滞后值值的自相关性排序序列 """ acf_scores = [] for lag in expected_lags: acf_score = acf(x.v...
5c0614b986eb8dfe576821245e80ef0244c70c69
23,421
def comment_like(): """ - 1.判断用户是否登陆 - 2.获取参数 - 3.校验参数,为空校验 - 4.操作类型校验 - 5.根据评论编号取出,评论对象 - 6.判断评论对象是否存在 - 7.根据操作类型,点赞,取消点赞 - 8.返回响应 :return: """ # - 1.判断用户是否登陆 if not g.user: return jsonify(errno=RET.NODATA, errmsg="用户未登录") # - 2.获取参数 comment_id = req...
09564653f3d843c7d82e16946507c8a081374ce6
23,422
import os def open_fits(subject, field, wavelength, size='2x2'): """Opens a FITS image of a subject. Can be used as a context handler. subject: RGZ subject dict, from the ATLAS survey. field: 'elais' or 'cdfs' wavelength: 'ir' or 'radio' size: Optional. '2x2' or '5x5'. -> FITS image file...
ae101ca51d4a6687cec21d57749faf610850bbb5
23,423
def create_relationships(model_cls, data): """ Create the relationship dict of the specified model class with the data :param model_cls: :param data: :return: """ relationships = model_cls.get_relationships() relationship_map = {} for key in relationships.keys(): relationship...
6ed811b180141190cde5eaa20d4fca817647c970
23,424
import requests def get_news_items_from_web(url): """ Calls the Athletics News RSS API, parses the resulting response and returns a list of parsed news_items to be stored in DynamoDB :param url: Url for the RSS API for UBCO Heat :return: Parsed news items in a JSON formatted list """ try:...
aff75310b155475d185f15c5bbaadeda9902aae3
23,425
def get_node_model(manager, handle_id=None, node=None): """ :param manager: Context manager to handle transactions :type manager: Neo4jDBSessionManager :param handle_id: Nodes handle id :type handle_id: str|unicode :param node: Node object :type node: neo4j.v1.types.Node :return: Node mo...
a8c42b8e72b6ae96e897bd5c7f5a06b5820b4b56
23,426
from functools import reduce def convert_hcp_plane(plane: list) -> np.ndarray: """ four index notion to three index notion for hcp and rhombohedral plane Args: plane (list): four index notion Returns: three index notion of plane """ u1 = plane[0] v1 = plane[1] w1 = p...
aa6d7527a55d8b14bd03b2f6660ed94c8cf760a8
23,427
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
import os def evaluate_all_flights(model, train_flights_dict, val_flights_dict, trial_folder, n_extreme_flights=10): """ Arguments model: trained tf model to make the predictions train_flights_dict: a dictionary whose key is flight name and value is a tuple of (features,labels) ...
eafbd5d7276ef503a2d609d3593e50751971af6e
23,436
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
import os def CreateMD5ChecksumFile(filename, mangled_filename=None): """Create and upload an MD5 checksum file for filename.""" if not mangled_filename: mangled_filename = os.path.basename(filename) checksum = CalculateMD5Checksum(filename) checksum_filename = '%s.md5sum' % filename with open(checksu...
8de75d2ab9e82ca663f29a6ca377bfe44576932d
23,447
import argparse def parse_arguments() -> argparse.Namespace: """Parse the arguments.""" parser = argparse.ArgumentParser( description="Panoptic segmentation evaluation." ) parser.add_argument( "--gt", "-g", required=True, help="path to panseg ground truth" ) parser.add_argument...
5d9b968015282340973fb0b631f0fe9539d08f50
23,448
from typing import Union import os import tqdm def get_similarity_graph( *, fullgraph: Union[str, BELGraph] = DEFAULT_FULLGRAPH_WITHOUT_CHEMSIM_PICKLE, rebuild: bool = False, mapping_file: str = DEFAULT_CHEMICALS_MAPPING_PATH, chemsim_graph_path=None, clustered: bool = True, weighted: bool...
768ffa099af70e6a0fc12416dded6776a048d3f2
23,449
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
import os def create_readme(top_dir,package_name,description="",docs=False): """ README requires the name of the package and the directory in which to write the file in. Optionally, give a description and whether or not to create a 'docs' directory. """ readme_str=""" # {package} ## Descript...
70f7221536078a5d5c13eb97b28c394b12621941
23,468
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
from pathlib import Path import os def dir(path: str) -> Path: """Get equivalent directory in cache""" _, filename = os.path.split(path) if filename: # TODO fix; this won't work as intended # If file return __get_cache_filepath(path).parent else: # If directory return _...
203ebec92b19e82fe92d0cc4043db3aad2278a2f
23,475
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
import sys def main(argv=None): """Execute the application from CLI.""" if argv is None: argv = sys.argv[1:] if not argv: argv = [curdir] args = _parse_args(argv) data = csft2data(args.path) if args.top: data = data.head(args.top) if args.with_raw: data['r...
c6a0200c26373ca6f7ea2544608b5a9382ea9d96
23,486
import os def get_base_path(node=None): """ get the base path for the system """ if node==None: node = get_system() ## ## Base path try: path = os.environ['sdss_catl_path'] assert(os.path.exists(path)) except: proj_dict = cookiecutter_paths(__file__) ## ...
35f321f93e1bfcbe32cb3dd0fd3497da19bfa264
23,487
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