content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import jinja2 def render_template(path, ctx): """Render a Jinja2 template""" with path.open() as f: content = f.read() tmpl = jinja2.Template(content) return html_minify(tmpl.render(**ctx))
0eb4b2a73a645283998260cdadbab37da32d6784
3,644,200
import os import subprocess def linux_compute_tile_singlecore(optimsoc_buildroot): """ Module-scoped fixture: build a Linux image for a single-core compute tile """ # Get the buildroot base directory from the optimsoc_buildroot() fixture. # Note that this directory is cached between pytest runs. ...
9eec134fb48c678eb18a25290d82427648c8ea31
3,644,201
def reverse( sequence ): """Return the reverse of any sequence """ return sequence[::-1]
f08ae428844347e52d8dbf1cd8ad07cfbf4ef597
3,644,202
def createOutputBuffer(file, encoding): """Create a libxml2 output buffer from a Python file """ ret = libxml2mod.xmlCreateOutputBuffer(file, encoding) if ret is None:raise treeError('xmlCreateOutputBuffer() failed') return outputBuffer(_obj=ret)
28ece9b710362d710ff6df25f426d91a0b318ebf
3,644,203
import os def get_table_name(yaml_path): """gives how the yaml file name should be in the sql query""" table_name = os.path.basename(yaml_path) table_name = os.path.splitext(table_name)[0] return table_name
5181e1e68a844bc529573da02a78f034092def46
3,644,204
def wait_for_proof(node, proofid_hex, timeout=60, expect_orphan=None): """ Wait for the proof to be known by the node. If expect_orphan is set, the proof should match the orphan state, otherwise it's a don't care parameter. """ def proof_found(): try: wait_for_proof.is_orphan = n...
f8f390424fe084bf8bf62bf1d16ac780d5c5df69
3,644,205
def check(verbose=1): """ Runs a couple of functions to check the module is working. :param verbose: 0 to hide the standout output :return: list of dictionaries, result of each test """ return []
4ecf144fc64a165b5b0f9766b76eb6b703eba130
3,644,206
def cylinder_sideways(): """ sideways cylinder for poster """ call_separator('cylinder sidweays') T1 = .1 #gs = gridspec.GridSpec(nrows=2,ncols=3,wspace=-.1,hspace=.5) fig = plt.figure(figsize=(5,4)) ax11 = fig.add_subplot(111,projection='3d') #ax12 = fig.add_subplot(...
98c0ed70c11ffe619d28623a5c5f4c4e2be40889
3,644,207
def get_generic_or_msg(intent, result): """ The master method. This method takes in the intent and the result dict structure and calls the proper interface method. """ return Msg_Fn_Dict[intent](result)
00853e2e74892a6d01ba1c6986e72f6436c88a92
3,644,208
def s3_example_tile(gtiff_s3): """Example tile for fixture.""" return (5, 15, 32)
a4b7e35fc6f7bf51a551ac8cb18003c23ff35a01
3,644,209
def execute_list_of_commands(command_list): """ INPUT: - ``command_list`` -- a list of strings or pairs OUTPUT: For each entry in command_list, we attempt to run the command. If it is a string, we call ``os.system()``. If it is a pair [f, v], we call f(v). If the environment variable...
79247f8dc15cc790b6f1811e3cb79de47c514bc4
3,644,210
import requests def get_transceiver_diagnostics(baseurl, cookie_header, transceiver): """ Get the diagnostics of a given transceivers in the switch :param baseurl: imported baseurl variable :param cookie_header: Parse cookie resulting from successful loginOS.login_os(baseurl) :param transceiver: d...
c2863b54b03ae3bdcf779fbd18a50e2bcdb2edd7
3,644,211
import os def plot_cross_sections(obj, paths, xs_label_size=12, xs_color='black', map_style='contour', scale='lin', n=101, x_labeling='distance', show_max=True, fp_max=True, fp_text=True, cmap='viridis_r', max_fig_width=12, max_fig_height=8, legend_padding=6, **kw): """Generate a map style...
1617695199087a79ed0388f6673204a37f5d0e0e
3,644,212
def mask_valid_boxes(boxes, return_mask=False): """ :param boxes: (cx, cy, w, h,*_) :return: mask """ w = boxes[:,2] h = boxes[:,3] ar = np.maximum(w / (h + 1e-16), h / (w + 1e-16)) mask = (w > 2) & (h > 2) & (ar < 30) if return_mask: return mask else: return...
3a3c00f934dabce78ee8a28f0ece2105d79f9f3f
3,644,213
import tokenize def import_buffer_to_hst(buf): """Import content from buf and return an Hy AST.""" return tokenize(buf + "\n")
4571bac8987911bf9b9a277590be6204be6120ab
3,644,214
import argparse def parse_args(): """ Parse command line arguments. """ parser = argparse.ArgumentParser(description="Deep SORT") parser.add_argument( "--sequence_dir", help="Path to MOTChallenge sequence directory", default=None, required=False) parser.add_argument( "--det...
318c5dd4d3c62c730f49c4a19fce9d782651499f
3,644,215
from typing import Mapping import os def load_lane_segments_from_xml(map_fpath: _PathLike) -> Mapping[int, LaneSegment]: """ Load lane segment object from xml file Args: map_fpath: path to xml file Returns: lane_objs: List of LaneSegment objects """ tree = ET.parse(os.fspath(ma...
57819b11e51dace02464e7c3e3436dc82d629564
3,644,216
def preprocess_input(x, **kwargs): """Preprocesses a numpy array encoding a batch of images. # Arguments x: a 4D numpy array consists of RGB values within [0, 255]. # Returns Preprocessed array. """ return imagenet_utils.preprocess_input(x, mode='tf', **kwargs)
ca81dff57f51184042899849dff6623d32e475c0
3,644,217
def build_gauss_kernel(sigma_x, sigma_y, angle): """ Build the rotated anisotropic gaussian filter kernel Parameters ---------- sigma_x : numpy.float64 sigma in x-direction sigma_y: numpy.float64 sigma in y-direction angle: int angle in degrees of the needle holder ...
14dd4143ad94bcdfa3298b4acf9b2d4c2bd0b7e6
3,644,218
def kwargs_to_flags(**kwargs): """Convert `kwargs` to flags to pass on to CLI.""" flag_strings = [] for (key, val) in kwargs.items(): if isinstance(val, bool): if val: flag_strings.append(f"--{key}") else: flag_strings.append(f"--{key}={val}") retu...
aa672fe26c81e7aaf8a6e7c38354d1649495b8df
3,644,219
def extractBananas(item): """ Parser for 'Bananas' """ badwords = [ 'iya na kao manga chapters', ] if any([bad in item['tags'] for bad in badwords]): return None vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): r...
f06167a0d379ec3b1921bb7ad8146b0bca9fd8aa
3,644,220
import os import fnmatch def BuildSymbolToFileAddressMapping(): """ Constructs a map of symbol-string -> [ (file_id, address), ... ] so that each symbol is associated with all the files and addresses where it occurs. """ result = defaultdict(list) # Iterate over all the extracted_symbols_*.txt files. fo...
386ce1c15af09295fb098286f87ceb020bbb3b3d
3,644,221
def get_template_parameters_s3(template_key, s3_resource): """ Checks for existance of parameters object in S3 against supported suffixes and returns parameters file key if found Args: template_key: S3 key for template file. omit bucket. s3_resource: a boto3 s3 resource Returns: filename of paramete...
3b68dc9c1fa8636bd0d066780aab43a6e55ecf2f
3,644,222
def cell_from_system(sdict): """ Function to obtain cell from namelist SYSTEM read from PW input. Args: sdict (dict): Dictinary generated from namelist SYSTEM of PW input. Returns: ndarray with shape (3,3): Cell is 3x3 matrix with entries:: [[a_x b_x c_x] ...
fbd6e034f738f42be45d7e5304892a9e69a8493b
3,644,223
def A12_6_3_2(FAxial, eta, Pp, Pu, Muey , Muez, Muay, Muaz, Ppls, Mby, Mbz, GammaRPa, GammaRPb): """ A.12.6.3.2 Interaction equation approach where : Pu is the applied axial force in a member due to factored actions, determined in an analysis that includes Pu effects (see A.12.4); ...
7a36ec489681100f99563f9c336df1306363851d
3,644,224
def gain_deploy_data(): """ @api {get} /v1/deploy/new_data 获取当前deploy_id 的信息 @apiName deployNew_data @apiGroup Deploy @apiDescription 获取当前deploy_id 的信息 @apiParam {int} project_id 项目id @apiParam {int} flow_id 流程id @apiParam {int} deploy_id 部署id @apiParamExample {json} Request-Example:...
9dc5e5faa53235ac6c5d8f0d37a2989b15ead477
3,644,225
def topk_mask(score, k): """Efficient implementation of topk_mask for TPUs. This is a more efficient implementation of the following snippet with support for higher rank tensors. It has the limitation that it only supports float32 as element type. The mask only contains k elements even if other elements have...
0a33dc6d5b9c621ab3fbd86c54c9ec90ac00f21f
3,644,226
def _generateGroundTruth(uids, COURSEDESCRIPTIONS): """Generate the ground truths from pre-stored bert model results given unique id lists :param uids: list of unique ids :type uids: list :param COURSEDESCRIPTIONS: dictionary of course Descriptions :type COURSEDESCRIPTIONS: dict :return: a...
623803815d3016989d26cf6841750e2cbd55bc83
3,644,227
import calendar def valueSearch(stat_type,op,value,**kwargs): """Quick function to designate a value, and the days or months where the attribute of interest exceeded, equalled, or was less than the passed value valueSearch("attribute","operator",value,**{sortmonth=False}) * "attribute" must ...
94b55a362d179f6acce705b002eb99f330a5427b
3,644,228
import requests def get_gnid(rec): """ Use geonames API (slow and quota limit for free accounts) """ if not any("http://www.geonames.org" in s for s in rec.get("sameAs")) and rec["geo"].get("latitude") and rec["geo"].get("longitude"): changed = False r = requests.get("http://api.geonam...
ab9d5e50e45217e3742f1d1ca7f58326ed3bf6f6
3,644,229
def handle_message(message): """Handles every message and creates the reply""" if re_vpncheck_short.search(message.body) or re_vpncheck_long.search(message.body): """Checks for VPN Connectivity""" servername = None protocol = None if re_vpncheck_short.search(message.body): ...
cc95a1f088edd8e815c533e43ad56205bf4747d6
3,644,230
def allowed_file(filename): """ Is file extension allowed for upload""" return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
3d0a3a15eecf8f6b0d76b52935a14628f1655328
3,644,231
import re def parse_tsv(filename, name_dict): """ """ output_matrix = [] with open(filename, 'rU') as handle: curr_protein = [] for line in handle: if line[0] == "#" or line[0] == "-" or len(line.strip('\n')) < 1: continue if re.match("Protein",...
12aa31ab3ff033ecc514518700c22ea467f01ef6
3,644,232
def get_orlist(site=DEFAULT_SITE, namespace="0|6|10|14|100|828", redirects="nonredirects"): """Get list of oldreviewed pages.""" request = Request(site=site, action="query", list="oldreviewedpages", ornamespace=namespace, or...
8253b2ac8ea72690086fa7864e5ca4ffcc33de50
3,644,233
def meshVolume(verts, norm, tri): """Compute the Volume of a mesh specified by vertices, their normals, and indices of triangular faces """ # TEST zeronorms = [] for i, n in enumerate(norm): #if n == [0., 0., 0.] or n == (0., 0., 0.): if n[0] == 0 and n[1] == 0 and n[2] == 0: #print "norma...
018818ab558b64b9699250bf6f45f0a1c47f92c8
3,644,234
def _groupby_clause(uuid=None, owner=None, human_name=None, processing_name=None): """ Build the groupby clause. Simply detect which fields are set, and group by those. Args: uuid: owner: human_name: processing_name: Returns: (str): "field, ..., field" """...
21546efa19e841661ed3a7ad8a84cf9a9a76d416
3,644,235
def _coeff_mod_wfe_drift(self, wfe_drift, key='wfe_drift'): """ Modify PSF polynomial coefficients as a function of WFE drift. """ # Modify PSF coefficients based on WFE drift if wfe_drift==0: cf_mod = 0 # Don't modify coefficients elif (self._psf_coeff_mod[key] is None): _log.w...
345d07a8850ec702d42f5c527fae0311f50a69b1
3,644,236
def get_transformed_webhook_payload(gh_payload, default_branch=None, lookup_user=None): """ Returns the GitHub webhook JSON payload transformed into our own payload format. If the gh_payload is not valid, returns None. """ try: validate(gh_payload, GITHUB_WEBHOOK_PAYLOAD_SCHEMA) except Exception as ex...
26e645219b816405521ddb6033a0a44c2ab7bba5
3,644,237
def get_retweeted_tweet(tweet): """ Get the retweeted Tweet and return it as a dictionary If the Tweet is not a Retweet, return None Args: tweet (Tweet or dict): A Tweet object or a dictionary Returns: dict: A dictionary representing the retweeted status or None if there is...
f852d45deadb1622687d097f2c724bdaef72ccc9
3,644,238
def listminus(c1, c2): """Return a list of all elements of C1 that are not in C2.""" s2 = {} for delta in c2: s2[delta] = 1 c = [] for delta in c1: if not s2.has_key(delta): c.append(delta) return c
829c347343d6a305fef2ad2f71539d7267b5a973
3,644,239
import random import torch def distribute_quantity_skew(batch_size, grouped_data, distributed_dataset, groupings, p=0.5, scalar=1.5): """ Adds quantity skew to the data distribution. If p=0. or scalar=1., no skew is applied and the data are divided evenly among the workers in each label group. :pa...
b4ebd1d6058550d2e32cedd62a56b50441d93b4c
3,644,240
import numpy as np import lightkurve as lk def xmkpy3_tpf_get_coordinates_v1(): """Unit test""" print(lk.__version__, "=lk.__version__") def msg(ok, tag_): # helper function print("***" + tag_ + ": ", end="") if ok: print("PASS***") else: print("FAIL***")...
c01e7440f4e48fb922bf683185d76ecc1eb349b6
3,644,241
import os import sys import imp def __loadModule(modulePath): # type: (str) -> module """ Load module Args: modulePath (str): Full path to the python module Return: mod (module object): command module None: if path doesn't exist """ # Create module names for import, ...
df043a8f5bb189aaa55060266bf6a0bb2a8b77f2
3,644,242
def get_dtype(names, array_dtype=DEFAULT_FLOAT_DTYPE): """ Get a list of tuples containing the dtypes for the structured array Parameters ---------- names : list of str Names of parameters array_dtype : optional dtype to use Returns ------- list of tuple Dty...
9f29dae78b3839429f13b8513293e9ce4c240e2f
3,644,243
import sys def print_progress_table(col_headers, col_widths = None, col_init_data = None, col_format_specs = None, skip_header=False): """ Live updates on progress with NUPACK and Multistrand computations. Note: This table has two rows. The Args: col_headers (list(str)): The header of the table. ...
605e916a67e5dfa68cbf25dd261fd7710416ae39
3,644,244
def if_analyser(string): """调用python的eval函数计算True false""" trans = sign_transform(string.strip().lower()) # print('if_analyser>>', trans) boool = eval(trans) boool = 1 if boool else 0 return boool
a27469a6c23a53f0131e8135600c6dc7d596cdbb
3,644,245
def zzX_trunc(f, p): """Reduce Z[X] polynomial modulo polynomial p. """ return zzX_strip([ zzX_rem(g, p) for g in f ])
9e80862a229b1a0689dea01fef865997ee87d1f9
3,644,246
from typing import List def _format_bin_intervals(bins_arr: np.ndarray) -> List[str]: """ Auxillary function to format bin intervals in a histogram Parameters ---------- bins_arr: np.ndarray Bin endpoints to format into intervals Returns ------- List of formatted bin inte...
96d3a89fc3427bf33abe5c44a04061694ae7b2b3
3,644,247
from typing import List from typing import Dict from typing import Callable def get_embedder_functions(corpus: List[str]) -> Dict[str, Callable[[List[str]], List[float]]]: """ Returns a list of the available embedders. #! If updated, update next function too """ embedders = { # 'Bag of Wo...
6e1d4ddd41725a26b940c7d108ea552366ab6c9b
3,644,248
import logging def test_stimeit(): """ Test the stimeit function """ dummy_function = lambda x: x + 2 @vtime.stimeit(logging.info) def stimeit_function(x): return dummy_function(x) assert dummy_function(42) == stimeit_function(42)
6d5cf6d261871cb466b71e93dbecfafff1731727
3,644,249
import yaml def parse_thermal_properties(f): """thermal_properties.yaml parser.""" thermal_properties = { "temperatures": [], "free_energy": [], "entropy": [], "heat_capacity": [], } data = yaml.load(f, Loader=Loader) for tp in data["thermal_properties"]: th...
4cc0020849e6ec1202fd2138f0bc86e5abfadf3b
3,644,250
def convert(ts, new_freq, include_partial=True, **kwargs): """ This function converts a timeseries to another frequency. Conversion only works from a higher frequency to a lower frequency, for example daily to monthly. NOTE: add a gatekeeper for invalid kwargs. """ new_ts = ts.clone() ...
a6b8daf6092052c0d7872d4b9a75edbe10bc15e5
3,644,251
def _get_image_info(name: str) -> versions.Image: """Retrieve an `Image` information by name from the versions listing.""" try: return versions.CONTAINER_IMAGES_MAP[name] except KeyError: raise ValueError( 'Missing version for container image "{}"'.format(name) )
4a328d6924adc3c826a6a01c46a27e6380d5d89a
3,644,252
def _mother_proc_cpp_stat( amplitude_distribution, t_stop, rate, t_start=0 * pq.ms): """ Generate the hidden ("mother") Poisson process for a Compound Poisson Process (CPP). Parameters ---------- amplitude_distribution : np.ndarray CPP's amplitude distribution :math:`A`. `A[j]`...
90ea9272c1a5541ea5c278960369ea301b31d01a
3,644,253
import telegram import urllib def get_service(hass, config): """Get the Telegram notification service.""" if not validate_config({DOMAIN: config}, {DOMAIN: [CONF_API_KEY, 'chat_id']}, _LOGGER): return None try: bot = telegram.Bot(toke...
474efeccaef641ba50042a036d5edf6d6e86f90c
3,644,254
def has_numbers(input_str: str): """ Check if a string has a number character """ return any(char.isdigit() for char in input_str)
5038cb737cdcfbad3a7bd6ac89f435559b67cebc
3,644,255
def _validate_LIMS_data(input, field_label, selectedTemplate, planObj): """ No validation but LIMS data with leading/trailing blanks in the input will be trimmed off """ errorMsg = None if input: data = input.strip() try: if planObj.get_planObj().metaData: ...
2ca3f271c546e4506e7e2490fb8b60fc0ef03f35
3,644,256
def get_report_permission(report: Report, user: User) -> Permission: """Get permission of given user for the report. :param report: The report :type report: Report :param user: The user whose permissions are to be checked :type user: User :return: The user's permissions for the report :rtyp...
bb09d744c133a4c9212ab6c6e2ba345bb9c8f78f
3,644,257
def peak_time_from_sxs( sxs_format_waveform, metadata, extrapolation_order='Extrapolated_N2'): """Returns the time when the sum of the squared amplitudes of an SXS-format waveform is largest. Note: this is not necessarily the time of the peak of the l=m=2 mode.""" extrap = extrap...
1ad4b593db3aa3d74170056f2c32d4108ec05a48
3,644,258
def create_trackhub_resource(project_dir, api_client, create_user_resource, create_genome_assembly_dump_resource): """ This fixture is used to create a temporary trackhub using POST API The created trackhub will be used to test GET API """ _, token = create_user_resource api_client.credentials(H...
a81db1e7c9c95355457d9f6c4ec4c6428e1a77a7
3,644,259
def create_node(x, y): """Create a node along the network. Parameters ---------- x : {float, int} The x coordinate of a point. y : {float, int} The y coordinate of a point. Returns ------- _node : shapely.geoemtry.Point Instantiated node. """ _node = P...
d8645b77a3d843bf3855522c63156916432ae899
3,644,260
from typing import Match def get_matchroom_name(match: Match) -> str: """Get a new unique channel name corresponding to the match. Parameters ---------- match: Match The match whose info determines the name. Returns ------- str The name of the channel. """...
404d21b6f88918204aa287c9227640c03f47b916
3,644,261
import re def unidecode_name(uname): """ unidecode() of cjk ideograms can produce strings which contain spaces. Strip leading and trailing spaces, and reduce double-spaces to single. For some other ranges, unidecode returns all-lowercase names; fix these up with capitalization. """ # Fix ...
16676453059b53b3e397f33630e00de66f3585b9
3,644,262
def scnet50(**kwargs): """ SCNet-50 model from 'Improving Convolutional Networks with Self-Calibrated Convolutions,' http://mftp.mmcheng.net/Papers/20cvprSCNet.pdf. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str,...
c900c5a0da1f4f0960ced2ba36fb9785a7340f4a
3,644,263
def xception_block(inputs, depth_list, prefix, skip_connect_type, stride, rate=1, depth_activation=False, return_skip=False): """用于构建xception,同样用到了残差结构,但是将卷积换成了 深度可分离卷积(depthwise + pointwise + conv 1x1)""" residual = inputs for i in range(3): # depthwise + pointwise + conv2d ...
3a8eaf7cb73216039411ec8fddd7bfb8c81604a6
3,644,264
def auth_test(): """ Test's the endpoint authenticiation works. :return: """ return "hello"
7c65897d83b0af41307aec28d7f2ce3d6852f8b7
3,644,265
def cnn_2x_lstm_siamese(voc_size, max_len, dropout=0.5): """Two siamese branches, each embedding a statement. Binary classifier on top. Args: voc_size: size of the vocabulary for the input statements. max_len: maximum length for the input statements. dropout: Fraction of units to drop. Returns: ...
d0eec28b8e91bed77fbc84bd085cae337da04c61
3,644,266
def roll_function(positions, I, angular_velocity): """ Due to how the simulations are generated where the first point of the simulation is at the smallest x value and the subsequent positions are in a clockwise (counterclockwise) direction when the vorticity is positive (negative), the first point...
79e9e3fbcdd2bfc1f2f9108f17aeeeb13fc6339d
3,644,267
import subprocess import tempfile import pipes def run_exkeys(hosts, capture=False): """ Runs gpssh-exkeys for the given list of hosts. If capture is True, the (returncode, stdout, stderr) from the gpssh-exkeys run is returned; otherwise an exception is thrown on failure and all stdout/err is untouche...
1ecb634e76b2ed68966457a0baac2122da00270f
3,644,268
def top10(): """Renders the top 10 page.""" top10_urls = ShortURL.query.order_by(ShortURL.hits.desc()).limit(10) return render_template("top10.html", urls=top10_urls)
781c7e65b94894e1292e626c163dfecb1d966678
3,644,269
def rename_group(str_group2=None): """ Rename OFF food group (pnns_group_2) to a standard name Args: str_group2 (str): OFF food group name Returns: conv_group (str): standard food group name """ #convert_group1 = {'Beverage':['Beverages'], # 'Cereals':['Cerea...
31b52f600fe3a087f8b230c880ae55f0dd63264e
3,644,270
from typing import Union import pathlib import io import os def save_png(fig: Figure, path: Union[None, str, pathlib.Path], width: Union[int, float] = None, height: Union[int, float] = None, unit: str = 'px', print_info: bool = False) -> Union[str, io.BytesIO]: """ Save PNG image of ...
113973e0633bdce6464d725f50ed7d04a47f6834
3,644,271
def parse_debug_node_name(node_name): """Parse the name of a debug node. Args: node_name: Name of the debug node. Returns: 1. Name of the watched node, as a str. 2. Output slot index of the watched tensor, as an int. 3. Index of the debug node, as an int. 4. Name of the debug op, as a str, e.g...
523f00841d9352725b3561f401ee827274aaa05b
3,644,272
def run_basic(): """Check that the windows all open ok (i.e. is GUI functioning?).""" _initialize() s = 'Simulation' p = 'Plots' menu_paths = [ (s,'Test Pattern'), (s,'Model Editor'), (p,'Activity'), (p,'Connection Fields'), ...
e90546b7312b9c7de5fd812784d91c5ef1c9f22f
3,644,273
def node_to_evenly_discretized(node): """ Parses the evenly discretized mfd node to an instance of the :class: openquake.hazardlib.mfd.evenly_discretized.EvenlyDiscretizedMFD, or to None if not all parameters are available """ if not all([node.attrib["minMag"], node.attrib["binWidth"], ...
168bf8efcacac4eaf5832bbab4b3708e8187d5dd
3,644,274
from typing import Collection def delete_comment(request, collection_id, comment_id): """Delete comment if the staff or comment owner want to delete.""" collection = get_object_or_404(Collection, id=collection_id) comment = get_object_or_404(Comment, id=comment_id, collection=collection) if not reques...
e8de0e5b8fb1ca8d6b6f27009f34ef0b8678c7cd
3,644,275
import numpy def layers_weights_as_vector(model, initial=True): """ Creates a list holding the weights of each layer (Conv and Dense) in the CNN as a vector. model: A reference to the instance from the cnn.Model class. initial: When True, the function returns the initial weights of the CNN. When Fal...
3a13d44868cb67c8ba757db3ceed8b6cf01bfbfb
3,644,276
def calculate_moist_adiabatic_lapse_rate(t, p): """calculate moist adiabatic lapse rate from pressure, temperature p: pressure in hPa t: temperature in Kelvin returns: moist adiabatic lapse rate in Kelvin/m """ es = 611.2*np.exp(17.67*(t-273.15)/(t-29.65)) # Bolton formula, es in Pa qs...
4a20b15bdee1ce72f10d85b74a68358fa7934093
3,644,277
def read_cat_file(genomeCatFile): """ Read in genome categories and create dictionary of category name and genomes in that category""" inFile = open(genomeCatFile, 'r') catDict = {} for line in inFile: line = line.strip() entries = line.split() genome = entries[0] ca...
23a30f29cb62d56a3e0763be34cad45717421815
3,644,278
import matplotlib.pyplot as plt def _check_axes(axes): """Check if "axes" is an instance of an axis object. If not, use `gca`.""" if axes is None: axes = plt.gca() elif not isinstance(axes, Axes): raise ValueError( "`axes` must be an instance of matplotlib.axes.Axes. " ...
c615b622dbf23b7f7f963256cab028c2d1a18706
3,644,279
import sys def gauss_method_mpc(filename, bodyname, obs_arr=None, r2_root_ind_vec=None, refiters=0, plot=True): """Gauss method high-level function for minor planets (asteroids, comets, etc.) orbit determination from MPC-formatted ra/dec tracking data. Roots of 8-th order Gauss polynomial are computed usi...
6450a4bb5b2fc66b89edf6ec6189f1a446bfc982
3,644,280
def removeCable(n, edges): """ @param n 道路 @param edges 连通情况 """ fa = initFa(n) totalW, nodes = 0, [] for x, y, w in edges: node = Node(x, y, w) nodes.append(node) totalW += w def getW(node): return node.w nodes.sort(key=getW) tmpW = 0 ...
4b43cc0ddd1ea89113a95a6771dea97d2b21a0fb
3,644,281
from read_file import read_selected, narrow def upload(): """POST route through which downloading sequence is triggered :param checked: which pins were selected by user :returns: log of arrays with pins, files downloaded counts, and notes """ DASHRlut = findSNs(compCrawl()) checked = request....
99a00d173574b789e8e6681a0373c2b805a42e39
3,644,282
def verify_credentials(): """Verify credentials to gdrive for the current user""" if 'credentials' not in flask.session: return flask.redirect(flask.url_for('authorize_app', _external=True)) credentials = client.OAuth2Credentials.from_json( flask.session['credentials']) if credentials.access_token_exp...
96ebe13a7e04f245fa432f0dcbfecdb490367ad9
3,644,283
def _gaussian_blur(heatmaps, kernel=11): """Modulate heatmap distribution with Gaussian. sigma = 0.3*((kernel_size-1)*0.5-1)+0.8 sigma~=3 if k=17 sigma=2 if k=11; sigma~=1.5 if k=7; sigma~=1 if k=3; Note: batch_size: N num_keypoints: K heatmap height: H ...
e49edc97eefc2f0de5200e4c8aee794642cb6a1f
3,644,284
def pose_vec2mat(vec): """Converts 6DoF parameters to transformation matrix Args: vec: 6DoF parameters in the order of tx, ty, tz, rx, ry, rz -- [B, 6] Returns: A transformation matrix -- [B, 4, 4] """ # batch_size, _ = vec.get_shape().as_list() batch_size = tf.shape(vec)[0] ...
1ecfb0461bc7ec19c1e730e4499510a890474b33
3,644,285
import collections def get_gradients_through_compute_gradients(optimizer, loss, activations): """Compute gradients to send to TPU embedding. Args: optimizer: a subclass of optimizer.Optimizer, usually CrossShardOptimizer. Used to call compute_gradients(). loss: a Tensor to call optimizer.compute_gr...
2a2ebca1e6024e11f541e3ccaf1fee4acd7ab745
3,644,286
def distance_to_mesh(mesh, pts, engine="auto", bvh=None): """ Compute the distance from a set of points to a mesh. Args: mesh (:class:`Mesh`): A input mesh. pts (:class:`numpy.ndarray`): A :math:`N \\times dim` array of query points. engine (``string``): BVH engine name. Val...
c44230d7e9cd18c2d992a85e2fba04a890b55ed8
3,644,287
from typing import Any from typing import Tuple from typing import Dict def parse_config(settings: Any) -> Tuple[Dict[str, Queue], Dict[str, dict]]: """ SAQ configuration parsing. Args: settings: The settings (can be pydantic.BaseSettings). Returns: Tuple[Dict[str, Queue], Dict[str, ...
d2711efedff319fb181d062593338f32271f39d1
3,644,288
def create_zeros_slot(primary, name, dtype=None, colocate_with_primary=True): """Create a slot initialized to 0 with same shape as the primary object. Args: primary: The primary `Variable` or `Output`. name: Name to use for the slot variable. dtype: Type of the slot variable. Defaults to the type of `...
ac940b8d92e4de025a2fc83695adb66a611935ea
3,644,289
def AdditionalMedicareTax(e00200, MARS, AMEDT_ec, sey, AMEDT_rt, FICA_mc_trt, FICA_ss_trt, ptax_amc, payrolltax): """ Computes Additional Medicare Tax (Form 8959) included in payroll taxes. Notes ----- Tax Law Parameters:...
de0e35fbe5c7c09de384e1302cba082149ea5930
3,644,290
import copy def append_step_list(step_list, step, value, go_next, mode, tag): """from step_list, append the number of times a step needs to be repeated if runmode or retry is present :Arguments: step_list = Ordered list of steps to be executed step = Current step value = attempts...
b8b5b3614fea0709b484df087ffa3ee2861532c4
3,644,291
def load_license(request, project_slug): """ Reload the license input queryset with the right options for the access form's current access policy choice. Called via ajax. """ user = request.user project = ActiveProject.objects.filter(slug=project_slug) if project: project = project.g...
59fb710cfccfaaf642283e6fb26631f56a39cc1e
3,644,292
def wt(): """Return default word tokenizer.""" return WordTokenizer()
d9e9a9c3cb99f1c3846ee54b38184d39d67051a7
3,644,293
import warnings def epochplot(epochs, *, ax=None, height=None, fc='0.5', ec='0.5', alpha=0.5, hatch='////', label=None, hc=None,**kwargs): """Docstring goes here. """ if ax is None: ax = plt.gca() ymin, ymax = ax.get_ylim() if height is None: height = ymax - y...
2e4f993ac48e6f054cd8781f4356b7afed41b369
3,644,294
def run_dag( dag_id, run_id=None, conf=None, replace_microseconds=True, execution_date=None, ): """Runs DAG specified by dag_id :param dag_id: DAG ID :param run_id: ID of the dag_run :param conf: configuration :param replace_microseconds: whether microseconds should be zeroed ...
124954d350a09d576b32e80fae4c56d1c0b2c141
3,644,295
from typing import Any import hashlib import glob import os import requests import html import re import uuid import io def open_url(url: str, cache_dir: str = None, num_attempts: int = 10, verbose: bool = True) -> Any: """Download the given URL and return a binary-mode file object to access the data.""" asse...
d2c478c7c9e64423c6d494016e0c46e9ca642984
3,644,296
def get_function_handle(method, var): """ Return a function handle to a given calculation method. Parameters ---------- method : str Identifier of the calculation method to return a handle to. var : dict Local variables needed in the mu update method. Returns ------- ...
e9f363908be5e628e2e17a781a3626737a3d3879
3,644,297
def build_receiver_model(params, ds_meta, utt_len: int, vocab_size: int, pre_conv=None) -> ReceiverModel: """ given the size of images from a dataset, and a desired vocab size and utterance length, creates a ReceiverModel, which will take in images, and utterances, and classify the images as being consi...
59904d83fa48d390f472b69b5324005d1a28e9c6
3,644,298
import math def fermi_fitness(strategy_pair, N, i, utilities, selection_intensity=1): """ Return the fermi fitness of a strategy pair in a population with N total individuals and i individuals of the first type. """ F, G = [math.exp(k) for k in fitness(strategy_pair, N, i, utilities)] return ...
fc2631d85ad0fa8ce879ff1fffd6976b1a1e1abf
3,644,299