content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import argparse import sys def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='Test a Fast R-CNN network') parser.add_argument('--device', dest='device', help='device to use', default='gpu', type=str) parser.add_argument('--devi...
aa501774ef07fc2170cc12627ed2af48584602f4
3,623,100
def memcached(func): """Use memcached to cache the results of a function. Must have the memcached server running. """ def wrapper(key, *args, **kwargs): value = memcached_client().get(key) if value is None: value = func(key, *args, **kwargs) memcached_client().s...
2723d8dbd06ad0bd73ab6bb76f24fdad4f8b91d3
3,623,101
def __virtual__(): """ Only works on Windows systems with PyWin32 installed """ if not salt.utils.platform.is_windows(): return False, "Module win_service: module only works on Windows." if not HAS_WIN32_MODS: return False, "Module win_service: failed to load win32 modules" ret...
121b5124219eb6a604598e57c21f13d7e7f866ae
3,623,102
from bs4 import BeautifulSoup import re def parse_html(mail): """ Parser for HTML part of message """ link = "" soup = BeautifulSoup(mail, "lxml") # print(soup.prettify()) for item in soup.find_all('a'): link = re.findall(match_regex, str(item.get('href'))) if len(link) != ...
d8f7a2731b33650c17b48c153b540ede9c39b451
3,623,103
def clamp(input, min, max): """ Return an attribute that represents the given input clamped in the range [min, max]. All inputs can be either attributes or values. """ return _createUtilityAndReturnOutput('clamp', input=input, min=min, max=max)
6f143529c336fdcbfa75e98dd97ccf391b5ec776
3,623,104
import platform import sys import warnings import urllib import tokenize import io import os def _url_handler(url, content_type="text/html"): """The pydoc url handler for use with the pydoc server. If the content_type is 'text/css', the _pydoc.css style sheet is read and returned if it exits. If the...
3786e0b61c07306969038eeeacf87c8becae0371
3,623,105
import collections import random def train_pmi(dataset, initial_cutoff=0.5, alpha=0.75, margin=1.0, max_iter=15, batch_size=256): """ Train a dict mapping pairs of ASJP sounds/chars to their PMI scores on word pairs using the EM algorithm with the specified parameters. The first arg should be a Datas...
33f38aec39732e7d94458d4d9cc3ebebd2791a28
3,623,106
def to_category(category_reference, fuzzy=True): """ Coerces a category, category name or category id to a BuiltInCategory. >>> from rpw.utils.coerce import to_category >>> to_category('OST_Walls') BuiltInCategory.OST_Walls >>> to_category('Walls') BuiltInCategory.OST_Walls >>> to_category(...
ae70bf78eb883cf44948c7f1af7b84291a098790
3,623,107
def get_class_mapping(super_mode: str): """ Mapping mode into integer :param super_mode: before, after & both :return: """ class_mapping = ['none', 'replace'] if super_mode == 'both': class_mapping.extend(['before', 'after']) else: class_mapping.append(super_mode) ret...
33e1f40c600f68b6ea760ec9340d04555ecae463
3,623,108
import sys def get_test_obs(cursor=None, testid=0): """Arguments: cursor: cursor of the database connection to be used for the query testid: test ID Return value: Dictionary with observer IDs, keys and node IDs 1 if there is an error in the arguments passed ...
67d52df8e477af223759a38edd7de613e38ffdc3
3,623,109
def permissions_required(permissions, login_url=None): """ Decorator that checks if a user has the given permissions. Accepts a list or tuple of lists of permissions (see check_permissions documentation). If the user is not logged in and the test fails, she is redirected to a login page. If the ...
179e8e34674b57b3c2278924c80cfa2c937afce2
3,623,110
def auth(opts, whitelist=None): """ Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader """ return LazyLoader( _module_dirs(opts, "auth"), opts, tag="auth", whitelist=whitelist, pack={"__salt__": minion_mods(opts)},...
b562ac7c6893e3accc18ceb8fe03870e21f4258f
3,623,111
def preprocess_data(dfs, target): """ For each df in dictionary the number of columns is reduced to number of features. Features get scaled using preprocessing.scale() Arguments: dfs(dict) - dictionary with monthly fixtures target(str) - market to predict, three markets get handled: "e...
b7d5c329f6678acb800ee89b4c591fd494224894
3,623,112
def mlp(inputs, mlp_hidden=[], mlp_nonlinearity=tf.nn.relu, regularizer=None, scope=None): """Define an MLP.""" with tf.variable_scope(scope or 'Linear'): mlp_layer = len(mlp_hidden) res = inputs for l in range(mlp_layer): res = mlp_nonlinearity(linear(res, mlp_hidden[l], scope='l'+str(l), regular...
88f51bbc54b4b5c12d2aeb702158f9aba25f13c4
3,623,113
import socket def get_banner(): """Get the ``banner`` that will be signed in :meth:`adb_shell.adb_device.AdbDevice.connect` / :meth:`adb_shell.adb_device_async.AdbDeviceAsync.connect`. Returns ------- bytearray The hostname, or "unknown" if it could not be determined """ try: ...
9babf7db8d4177b427f46c0785b899c79ba2691c
3,623,114
def tweets_for_search(*args): """ Tweets for a search query. """ return tweets_for(QUERY_TYPE_SEARCH, args)
9b2a7a828da3fca036433b4c150bd52bcaa33915
3,623,115
def get_vois(dwi_array, image_coordinate_system, phantom_definition, debug=False, name=None): """ Find the VOIs for this phantom and ADC/T1. Args: dwi_array: 4d numpy array of dicom pixel data indexed by slice, then original dicom pixel_data x/y, then flip angle or b value; e.g. dwi[sl...
2a82334522ad22a0dc77fda1d16b339ec9139a83
3,623,116
def rol(value, count): """A rotate-left instruction in Python""" for y in range(count): value *= 2 if (value > 0xFFFFFFFFFFFFFFFF): value -= 0x10000000000000000 value += 1 return value
ac6f4efee5d806201a04f83921bca47ac6e42ee8
3,623,117
def power(**kwargs): """ Powers on/off key fob. Optional arguments: - value (bool): Power on or off. """ return client.send_sync(_msg_pack(_handler="power", **kwargs))
7b7e956ebe2b7c44b4cb9cd83524090befbcc036
3,623,118
import time import decimal def collatz(num): """ :type num: int; :param num: start number, any positive integer; :return [start number, [following_numbers], steps, time]; """ num_original = num following_nums = [] step = 0 start = time.time() while num != 1: # print(str...
82427afa292d9f7581a0964482d08e454b9012e5
3,623,119
def bubble_sort(vals): """Sort the given array using bubble sort.""" for i in range(len(vals) - 1): for j in range(len(vals) - i - 1): if vals[j] > vals[j + 1]: vals[j], vals[j + 1] = vals[j + 1], vals[j] return vals
ee0286dd53da0fbfc508fa1c26dbf913ba8f92ce
3,623,120
def create_labels(features_end, prediction_start, prediction_end, conn, output = False): """ Generate a list of labels and return the table as a dataframe. Parameters ---------- features_end prediction_start prediction_end conn: obj Returns ------- df_labels: Da...
ccf218f686664051dce572a8b45e7d32feff1246
3,623,121
def latex_print(expr): """Prints a tensor expression in Latex.""" # my_strs = copy(defaults) # my_strs["dot"] = "%s %s" # my_strs["inverse"] = "{%s}^{-1}" # my_strs["name_attr"] = "latex" # my_strs["transpose"] = "{%s}^t" # my_strs["pow"] = "{%s}^{%s}" # my_strs["div_under_one"] = "{%s}^{-1}" #...
88f5705362f14abc0136be10ff6fe95d1589690e
3,623,122
import numpy def clean(grid, distances): """ Given a list of boxes and the distances between each pair, returns a new list of boxes and distances, by removing the boxes that are not on land, as well as the -empty- distances referring to these boxes. Args: grid: A m*n list of boxes dis...
41e88d68a69b23a3fb90fb43deb8b44564df781e
3,623,123
from typing import List import os def get_all_labware_definitions() -> List[str]: """ Return a list of standard and custom labware definitions with load_name + name_space + version existing on the robot """ labware_list = ModifiedList() def _check_for_subdirectories(path): with os...
cf8ae27402b4100ccdedfba7f3b59e470bfc8d91
3,623,124
def public_byte_prefix(is_test): """Address prefix. Returns b'\0' for main network and b'\x6f' for testnet""" return b'\x6f' if is_test else b'\0'
3ecc4fe0cbbd8dee1a91f90e0112d9be3184fc73
3,623,125
from typing import Dict import gzip import tqdm def map_refseq_to_uniprot() -> Dict[str, str]: """ Reads the RefSeq_UniProt_collab file and maps RefSeq IDs to UniProt IDs. :return: dictionary of refseq: uniprot """ ref_up_mapping = {} with gzip.open(osp.join(DATA, 'gene_refseq_uniprotkb_collab...
decc8bd6e5ce9cb44770cde75a505e9d4f541e65
3,623,126
async def character_search(bot, context): """Searches for characters with the given list of tags.""" tags = [_clean_text_wrapper(it) for it in context.arguments] cursor = data.db_select( bot, from_arg='characters', where_arg='tags @> %s', input_args=[tags], additional='ORDER BY clean_name AS...
56c32cc21ec2e0e5aa5142d3e03c4599f498f2dc
3,623,127
def global_synchronization_enabled(): """Checks if we should synchronize objects via hooks. We shouldn't run these hooks if integration to IssueTracker turned off or it was called by import request. We can detect that it was called by import via trying to get request. Import calls doesn't have requests. "...
080d8137c584dad2ae98b29a7b1c1c4834bc9627
3,623,128
from typing import Any import dataclasses def is_template_like(obj: Any) -> bool: """Check whether the given object is template-like. Currently this includes templates and dataclasses. """ return is_template(obj) or dataclasses.is_dataclass(obj)
584e645c3991985ca827b880ffd19824871c2ec7
3,623,129
def get_resource_ignore_params(params): """Helper method to determine which parameters to ignore for actions :returns: A list of the parameter names that does not need to be included in a resource's method call for documentation purposes. """ ignore_params = [] for param in params: ...
02d805f9bc62e8aa47830e459adc044c8f70858a
3,623,130
from functools import reduce def Rotation3DMatrix(Xangle=0,Yangle=0,Zangle=0): """ unit: degree [0,360] """ Xangle = np.pi*Xangle/180 Yangle = np.pi*Yangle/180 Zangle = np.pi*Zangle/180 Rx = np.array([[1,0,0], [0,np.cos(Xangle),-np.sin(Xangle)], ...
df61864b8318e8d7982e1e97b0956d6fbacbb6b1
3,623,131
from typing import Callable def sum(x: Callable[[AbstractRow], R | None]) -> AggregateSpecification: """Compute the sum of `x`, with an empty column summing to NULL. Parameters ---------- x A column getter. """ return AggregateSpecification(Sum, x)
48d18d0c5617acccc43a357a27a9c7fb2de416c3
3,623,132
def camera_to_world_frame(x, R, T): """ Args x: Nx3 points in camera coordinates R: 3x3 Camera rotation matrix T: 3x1 Camera translation parameters Returns xcam: Nx3 points in world coordinates """ xcam = R.T.dot(x.T) + T # rotate and translate return xcam.T
15a340becccd5679b2aac63ee133468deec6cb1e
3,623,133
def left_multiplied_unitary_solution(C, R, c, verify=False): """ Find portfolio in a rather indirect way ... useful for checking min w^t R C w subject to w^t c == 1 """ C_prime, H, c_prime = left_multiplied_unitary_problem(C=C, R=R) u = scaled_unitary_problem_solution(C=C_prime, c=c_prime) ...
aed065dc5946ca693d9a50ffdef1f136e553c509
3,623,134
def find_job(schedd=None, attr_list=None, **constraints): """Query the condor queue for a single job matching the constraints Parameters ---------- schedd : `htcondor.Schedd`, optional open scheduler connection attr_list : `list` of `str` list of attributes to return for each job, ...
e527f0de3a26a693f32fdcbc1ac3559e0f61d9d9
3,623,135
import json def _json_read(filename): """Read a json into a dict.""" with open(filename) as file: return json.load(file)
84187d2a2281d2725adb8dae903253bdcd41e2b9
3,623,136
def get_flagged_cells(gameboard): """This is another example that is written through the use of a cell class.""" flagged_cells = [] for cell in gameboard: if cell.is_flagged(): flagged_cells.append(cell) return flagged_cells # consider def copy_string(a1, a2) # vs def copy_string(source, destination) ...
362cd976f92584274bd94420485c7ecaabc371ce
3,623,137
def addLists(list1, list2): """Add lists together by value. i.e. addLists([1,1], [2,2]) == [3,3].""" # Find big list and small list blist, slist = list(list2), list(list1) if len(list1) > len(list2): blist, slist = slist, blist # Overlay small list onto big list for i, b in enumerate(sl...
f5469dab8fd2c62d2d3ffed253803c1a3d343281
3,623,138
def qrGetGuidesColorFromGuidesNode( guidesNode ): """ This method sets the color from the guides node. It returns the color of the root of all the guides. """ return cmds.getAttr( '%s.overrideColorRGB' % guidesNode )[ 0 ]
fbd909e0bbd1dcc12dd5f6c8f74b500d497a4dba
3,623,139
def dbconn_mysql(host=None, user=None, password=None, database=None, port=3306, from_file=False, filename=None): """ Return MySQL database connection and cursor objects. Prompt for missing credentials. DESIGN: Function designed to create a connection to a MySQL database using ...
3d2cbe7a775e03446f5912606aca7ce4cb4f9ba2
3,623,140
def apply_coefficients_for_band(numpyarray, band, regression_coefficients): """ Apply regression coefficients in the form: ETM = c0 + OLI*c1 As per table 2 in http://www.mdpi.com/2072-4292/6/9/7952/htm :param numpyarray: array of measurements to apply coefficients to :param band: name of the coeffic...
679c18885fed81de5ea2fe76f03bcf37b017e437
3,623,141
def append_to_csv(file_name, nda_str, set_id_group): """ Output all doc in set_id to a csv file. Parameters: file_name (Path): filename to store exported csv nda_str (String): ex "12345-23456" set_id_group (String): ex: "7b5489a1-e30f-450f-bd2b-00d05fd52915" """ _logger.info...
37cdf883e74d100a9d71be5743aeabf883474b04
3,623,142
from typing import Callable def _sumprod( func: Callable, values: np.ndarray, mask: np.ndarray, *, skipna: bool = True, min_count: int = 0, ): """ Sum or product for 1D masked array. Parameters ---------- func : np.sum or np.prod values : np.ndarray Numpy array...
0a47863f256cb6a60cb6adad27c036e879a188ff
3,623,143
import tarfile def files_from_archive(tar_archive: tarfile.TarFile): """ Extracts only the actual files from the given tarfile :param tar_archive: the tar archive from which to extract the files :return: List of file object extracted from the tar archive """ file_members = [] # Find the ...
09ead0b2b955afdc5bf96a8e0a8717989c155406
3,623,144
def regular_wl_axis(axis, xlims=None): """ Converts a wavenumber axis ([cm-1]) into a regular (==equally spaced) wavelength axis ([Angstroms]) Parameters ---------- axis : 1D :class:`~numpy:numpy.ndarray` Input axis in cm-1 xlims : tuple of floats (Optional) limits in cm-1 to re...
62952e855aaba730be77c56e0ada6712ea1b62d9
3,623,145
def load_stack_plane(image,c,z,x,y,w,h): """ Load ROI of a Z plane from every time point in OMERO image Inputs: image: OMERO ImageWrapper c: int, channel z: int, plane x: float, x corner of ROI y: float, y corner of ROI width: int, width of ROI height:...
41b65078b83360776757d4a6ea001557482849a9
3,623,146
from typing import Optional def read_file(href: HREF, stac_io: Optional[StacIO] = None) -> STACObject: """Reads a STAC object from a file. This method will return either a Catalog, a Collection, or an Item based on what the file contains. This is a convenience method for :meth:`StacIO.read_stac_obje...
75132349e139af5dc52c2be424b4cdd5d1ae062a
3,623,147
def gcn_encoder(features, hparams, embed_scope, embed_token_fn=common_embed.embed_tokens, adjcency_feature="obj_dom_dist", discretize=True): """Encodes a screen using Graph Convolution Networks. Args: features: the feature dict. hparams: the hyperparameter. ...
5732c937c8f46d74b9ba29fe848b1cbc1d88fa8c
3,623,148
def help(term, arabic_column, english_column): """ show all details of word""" exclude_keys = [arabic_column, english_column] details = {k: term[k] for k in set(list(term.keys())) - set(exclude_keys)} return details
c1118fd1240802a4ba1f7976d21806eb7302276c
3,623,149
def nodify(n): """ Modifies string to contain node#mod_ :param n: string :return: string """ return 'node#mod_{}'.format(n)
b0d09ded891e369d463f44404501d82e5f266941
3,623,150
def calculate_rescue_time_pulse(very_distracting, distracting, neutral, productive, very_productive): """ Per RescueTime API :param very_distracting: integer - number of seconds spent :param distracting: integer - number of seconds spent :param neutral: integer - number of seconds spent :param ...
28144b5e1c7820b12971a0f5a88d56971c798dc7
3,623,151
def load_linux_so(): """ Load the shared object for Linux platforms. The shared object must be in the same folder as this python script. """ shared_name = get_project_root() / "build/libastyle.so" shared = str(pl.Path(shared_name).absolute()) # file_ = {f for f in pl.Path().iterdir() if f.n...
7fda7c73995bb99d86ac82f43e06c4d2c2f75a66
3,623,152
import torch def load_embeddings_from_imgs(det_df, dataset_params, seq_info_dict, cnn_model, return_imgs = False, use_cuda=True): """ Computes embeddings for each detection in det_df with a CNN. Args: det_df: pd.DataFrame with detection coordinates seq_info_dict: dict with sequence meta in...
1d5dbffb904f98cb8e33247ab5619ba2ff74c0bf
3,623,153
import base64 import requests def send_notification(subject, recipients, html, mailtype=''): """ Generic email sending method, handly only HTML emails currently """ if not EMAIL_USER or not EMAIL_API_ENDPOINT: logger.warning( 'Cannot send notifications.\n' 'No username and/or A...
29c938aab306116ef9e1de403ba91502e571f194
3,623,154
def serial_to_usb_widget(serial_into_USBhub_port_displayed): """Function used to create Jupyter widget. It takes the parameter chosen from the widget and returns it such that it can be used as a variable. Args: serial_into_USBhub_port (str) : the port number of the USB Hub that the Serial Adaptor i...
4bbf68ca2ab90da5a1f6ba3cc0a1b6f140b39484
3,623,155
def build_discriminator(input_shape=(256, 256, 3)): """Returns the discriminator network of the GAN. Args: input_shape (tuple, optional): shape of the input image. Defaults to (256, 256, 3). Returns: 'Model' object: GAN discriminator. """ x0 = layers.Input(input_shape) ...
c0d541a6e613f78aabb81e0cb73027961acc7d48
3,623,156
import json def user_list(_request): """ This will return a list of all users in the database """ # We'd really like to do .distinct, but sqlite+django does not support this; # hence the hack with sorted(set(...)) users = sorted( user_id[0] for user_id in set(XBlockState.object...
d9456f0d7348382d4ed8e9ef17443f641cd8d39d
3,623,157
from datetime import datetime def price_dataframe(symbols='sp5002012', start=datetime.datetime(2008, 1, 1), end=datetime.datetime(2009, 12, 31), price_type='actual_close', cleaner=clean_dataframe, ): """Retrieve the prices of a list of equities as a DataFrame (columns = symbols) Argumen...
d6c7cdb8d14d097a3f5eddb46c3a38dde58bb416
3,623,158
def split_nth(string, count): """ Splits string to equally-sized chunks """ return [string[i:i+count] for i in range(0, len(string), count)]
38833ef711ce04f5563b343f477e7792035ec669
3,623,159
def market_EWindex(market: simuldata.Market, name: str="Market EW Index") -> pd.DataFrame: """ Sums all assets to make an index, corresponds to the Equally-Weighed (EW) index. The formula for the weights here is: w_i = c / N for all i and we choose c = N so that \sum_i w_i = N. Thus we...
f6713e7cc5a7dd70c0057de8e7bb252b386f6e70
3,623,160
import six def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'): """ Similar to smart_text, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ # Handle the comm...
cf5fdb32b67bb280e6830a9039056793d896354d
3,623,161
def column_hash_values(column0, *other_columns, initial_hash_values=None): """Hash all values in the given columns. Returns a new NumericalColumn[int32] """ columns = [column0] + list(other_columns) buf = Buffer(rmm.device_array(len(column0), dtype=np.int32)) result = NumericalColumn(data=buf, d...
dc8d94e87b16e51979d6b88b6203ae1d09592eff
3,623,162
from typing import Optional def get_service_from_request( request, raise_exception: bool = True ) -> Optional[Service]: """Return the service for the request. Unauthenticated calls will identify the service using ServiceAPIKey. Authenticated calls will check the azp claim of the auth token to see...
ffe03089902dc73ae6459d5f5f02b40ee049509d
3,623,163
from typing import Any def resnet50( sensor: str, bands: str, pretrained: bool = False, progress: bool = True, **kwargs: Any, ) -> ResNet: """ResNet-50 model. If you use this model in your research, please cite the following paper: * https://arxiv.org/pdf/1512.03385.pdf Args: ...
30200f110e4a3ddab4b8f1ca48bf031531b6024a
3,623,164
from labmanager.views import get_json import json import traceback import cgi def requests(): """SCORM packages will perform requests to this method, which will interact with the permitted laboratories""" db_lt = db.session.query(LearningTool).filter_by(name = g.lt).first() if request.method == '...
4bbc162ec8460028ae45d6170d165c4c84cdd6ef
3,623,165
def divide_graph(graph, distance): """ divide graph with connected components by links whose distance is less than the second argument. """ group = [-1] * NUM_NODE current_group_id = 0 division = [] for i in range(NUM_NODE): current_group = set() if(group[i] != -1): ...
372e88a16a0b3cdbdc5ebebc05a37c0767e360b8
3,623,166
def deduplicate(elements): """Remove duplicate entries in a list of dataset annotations. Parameters ---------- elements: list(vizier.datastore.annotation.base.DatasetAnnotation) List of dataset annotations Returns ------- list(vizier.datastore.annotation.base.DatasetAnnotation) ...
99de9667b46ab9da619d28748d3d74bbec54892a
3,623,167
import select def get_keywords(): """ The get_keywords function retrieves keywords from the database if they are set to active.""" return select(k for k in Keyword if k.active)
bee91f16ec635e41c9576410db8ed55f3f20607d
3,623,168
def parse_spectrum_list2dict(spectrum_list): """ Parse the spectrum list [start, stop, num] to a list """ if spectrum_list[0].unit.physical_type != 'length' and \ spectrum_list[1].unit.physical_type != 'length': raise ValueError('start and end of spectrum need to be a length...
73db559fe9f617d5e0240f444d3fc30d8aed68eb
3,623,169
from matplotlib.lines import Line2D def _connection_line(x, fig, sourceax, targetax, y=1., y_source_transform="transAxes"): """Connect source and target plots with a line. Connect source and target plots with a line, such as time series (source) and topolots (target). Primarily used ...
4dfafce86b02d8c670f3a4a681d886231697ce53
3,623,170
import io def RDKit_Mol_from_ProDy(prody_instance, removeHs=True): """ Creates an RDKit Mol object from a ProDy AtomGroup instance :return: """ residue_io = io.StringIO() prody.writePDBStream(residue_io, prody_instance) return Chem.MolFromPDBBlock(residue_io.getvalue(), removeHs=removeHs)
dba8495f0e69847d678dfad14c62960ec3794701
3,623,171
def get_cut_rect_x(rect, axis): """ cuts one rect about an x axis """ rects = [rect] llx, lly, urx, ury = rect if llx < axis and urx > axis: rects = [(llx, lly, axis, ury), (axis, lly, urx, ury)] return rects
98ec23d892b974238d0a064c5e9de044598bb788
3,623,172
import inspect def get_class_name(obj, fully_qualified=True, truncate_builtins=True): """Get class name for object. If object is a type, returns name of the type. If object is a bound method or a class method, returns its ``self`` object's class name. If object is an instance of class, returns instan...
41e0233593e76cc81c0afddbce6db644b26c349c
3,623,173
def windShear(u, v, z, top, bottom, unit=None): """ calculate the wind shear between discrete layers <div class=jython> shear = sqrt((u(top)-u(bottom))^2 + (v(top)-v(bottom))^2)/zdiff</pre> </div> """ udiff = layerDiff(u, top, bottom, unit) vdiff = layerDiff(v, top, bottom, unit) zdiff = layerDi...
7164b46c04d114562c0ba3194fabeb3d1a70594d
3,623,174
import requests def check_all_links(links): """ Check that the provided links are valid. Links are considered valid if a HEAD request to the server returns a 200 status code. """ broken_links = [] for link in links: head = requests.head(link) if head.status_code != 200: ...
b6e784da72b4f81af3e393804ef3f776c2f3fc85
3,623,175
def process_currency(curr): """Gets a formatted list of cryptocurrency to show in home.html""" assets = [] for c in curr: assets.append(c['CGname']) data = new_lookup(assets, "usd") final_list = [] i = 1 for name, price in data.items(): final_list.append({"id": i, "name": n...
fdf66c99b3452cd2abafde6c9079589b39c669d4
3,623,176
async def validation_middleware(request: web.Request, handler) -> web.Response: """ Validation middleware for aiohttp web app Usage: .. code-block:: python app.middlewares.append(validation_middleware) """ orig_handler = request.match_info.handler if not hasattr(orig_handler, "_...
5f529e005fc9de9e5c7ce43d8cab628e960cec18
3,623,177
import inspect def register_ranged_hparams(name=None): """Register a RangedHParams set. name defaults to fn name snake-cased.""" def decorator(rhp_fn, registration_name=None): """Registers & returns hp_fn with registration_name or default name.""" rhp_name = registration_name or default_name(rhp_fn) ...
fb0ee544a31bbda610e599f44a6dce4a2cfc0621
3,623,178
import json def get_monitoring_data(): """ 1. Get required arguments 2. Call the worker method 3. Render the response """ # 1. Get required arguments args = Eg001Controller.get_args() try: # 2. Call the worker method to get your monitor data results = Eg001Controll...
63034190afdf72bf0fa4e03416a814aa9ac6c1d8
3,623,179
def calculate_histogram(magnitudes, angles, bin_count=9, is_signed=False): """Calculate the localized histogram of each cell. :param magnitudes: The maginitude of each cell :type: np.ndarray :param angles: The angle of each cell :type: ...
82b7ddccd571031fedceee43f51292cf4e21cc19
3,623,180
def dot_product_mpnn_attention(q, k, v, adjacency_matrix, num_edge_types, ignore_zero=True, name=None): """Dot product attention with edge vectors. Args: q: [batch, length, key_depth] tensor k: [batch, num_edge_types, length, key_depth] v: [batch, num_edge_types, length, ...
5e545f714c72a4136352b531d3980fc56931a7a9
3,623,181
def selective_representer(dumper, data): """Process yml to correctly handle \n.""" return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|' if '\n' in data else None)
4a748fb6b2eb997aee76239f875b5097648f4d88
3,623,182
def optimize_trajectory(target, start, parameters): """ 牛顿迭代法,梯度下降法 :param target: :param start: :param parameters: :return: """ for i in range(max_iter): end_state = generate_last_state(start, parameters) end_state_error = np.array(calc_diff(target, end_state)).reshape(...
1b64c7eaf0f5601bf99ed2531677c86b6aab6a5c
3,623,183
def get_session_monitor(target): """Px means the session is parallel run coordinator.""" return render_page()
0bb186cbec3c72d1bbe9c40bfdd01bf68e57ab86
3,623,184
def _evaluate_embedding_cpu(r, d, r_neighbor, metric="dihedral", epsilon=1e-4): """ Evaluate the final embedding by calculating the stress and correlation Args: r (ndarray): n-dimensional dataset (rows: frame; columns: angle/intramolecular distance) d (ndarray): the final projected embe...
91e7f9c127190e2785775cf388c071a5dea179cf
3,623,185
def encode_type2_user_id(user_id): """Append a type-2 error detection code to the user_id.""" return f"{user_id:04d}-{Type2Code.calculate(user_id):02d}"
0d4b1e3ff919fcbd9bb26d0d5d25ae0e0a1fa5e5
3,623,186
import logging def pipeline(computational_stages, pipeline_depth, repeat_count=1, inputs=None, infeed_queue=None, outfeed_queue=None, optimizer_function=None, device_mapping=None, pipeline_schedule=None, ...
3ed309513147e78ba34709c34dea9ce5a68b40c4
3,623,187
def twitter(request, account_inactive_template='socialregistration/account_inactive.html', extra_context=dict(), client_class=None): """ Actually setup/login an account relating to a twitter user after the oauth process is finished successfully """ client = client_class( request, setting...
f86d054fb976884d7b6b94efed8319970fafcafb
3,623,188
def delete_activator_cd(activatorId, dbsession): """ Args: activatorId ([int]): [The Activator id] list_of_cd ([list]): [A list of CD ids] 1. Logically delete all active CD ids for this activator """ # Inactivates the active activator-cd for this activator (activatorId) cd_l...
78d06cd824d2f67d7bb3459b929d03b39d84dad2
3,623,189
def makeVariables_npv(image): """ Make variables for NPV regression model """ year = ee.Image(image.date().difference(ee.Date('1970-01-01'), 'year')) season = year.multiply(2 * np.pi) return image.select().addBands(ee.Image(1)).addBands( season.sin().rename(['sin'])).addBands( season.cos().rename(['cos...
20e8a988e033371296fcd52e86f6e0654657f9f7
3,623,190
import re def mrg_labeled(tr): """return labeled constituency string.""" if isinstance(tr, nltk.Tree): if tr.label() in WORD_TAGS: return tr.leaves()[0] + ' ' else: s = '(%s ' % (re.split(r'[-=]', tr.label())[0]) for subtr in tr: s += mrg_labeled(subtr) s += ') ' retu...
95540cfcb3d5a2da7b14dcdcdcfb196c8923d3ff
3,623,191
import subprocess def fast_genotypes(chrom, pos: int, samples): """Efficiently look up genotypes for a variant Parameters ---------- chrom: str or int chromosome of the variant pos : int position of the variant samples iterable or comma-delimited string of samples to l...
c72abe0f7271c6dbcae456d8e86697c629381b8a
3,623,192
def compute_seen_words(inscription_list): """Computes the set of all words seen in phrases in the game""" return {word for inscription in inscription_list for phrase in inscription['phrases'] for word in phrase.split()}
496fc64ee37a6a6b0b3df0c3e9230d7b7ef46d0f
3,623,193
def replace_previous(user, code, is_alt): """function replace_previous This function changes the previous lesson code Args: user: user model using tutor code: code that user submitted in last lesson is_alt: boolean for if alternate lesson Returns: code: ? string of code ...
22c8ecb38611c9d184d588be8ca29bcd8430bd17
3,623,194
import argparse def get_args(batch_size=8, image_size=256, max_iter=100000): """ Get command line arguments. Arguments set the default values of command line arguments. """ description = "Example of Lightweight GAN." parser = argparse.ArgumentParser(description) parser.add_argument("-d"...
b9f5a7acc6e95eb112cb33827f65b7acc02d08eb
3,623,195
def page_rank_dense_lstsq(datafile, d, datasize, n=None): """ Solve the page rank problem, given the data in 'datafile', the dampening factor 'd', the size 'datasize' of the dataset, and the number 'n' of nodes to include. Have 'n' default to None. Use the method involving least squares.""" data...
2a392f769e3f1ccc0c4a8b999ccaec80ad8c98a1
3,623,196
def resume(request): """ Resume the container """ if request.method != "POST": messages.error(request, "Invalid request method.") return redirect('containers') if 'id' not in request.POST or not request.POST.get('id').isdigit(): messages.error(request, "Invalid POST request."...
6c1a880b2c927d51cdcf146bb9bae952287c7c9d
3,623,197
def TextNodeEnd(builder): """This method is deprecated. Please switch to End.""" return End(builder)
78dd2492d43531cad4e53d6f7fa0f79bd244cf70
3,623,198
def set_item_checked(service, context): """ Fixture for factory function to set whether an item is checked. """ def _set_item_checked(shopping_list, item, checked): request = shopping_list_pb2.SetItemCheckedRequest( shopping_list_id=shopping_list.id, item_id=item.id, ...
6d4619489ef5c8c1648a076f98e9f8ef3cd56d91
3,623,199