content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def phrase_replacement(structured_phrases, short_phrases): """replaces phrases in structred_phrases with phrases from short_phrases if the short phrase is contained in the longer phrase""" short_set = set(short_phrases) return [_rewrite_doc(doc, short_set) for doc in structured_phrases]
6971ab9044ee43da9172dcf15845a8e52890bd64
3,615,319
from copy import copy def struct(typename, field_names, verbose=False): """Returns a new class with named fields. >>> Point = struct('Point', 'x y') >>> Point.__doc__ # docstring for the new class 'Point(x, y)' >>> p = Point(11, y=22) # instantiate with positional ar...
74dcfd6e0a0c83a6679691e49f09a528eb8e6a4a
3,615,320
def zip_tasks_verbose_output(table, stdstreams): """Zip a list of strings (table) with a list of lists (stdstreams) :param table: a formatted list of tasks :param stdstreams: for each task, a list of lines from stdout/stderr tail """ if len(table) != len(stdstreams): raise ValueError('Can on...
33d74cd274ec39330cbc127a3088a430b80d234a
3,615,321
def stable_softmax(x, axis=2): """ Numerically stable softmax: softmax(x) = e^x /(sum(e^x)) = e^x / (e^max(x) * sum(e^x/e^max(x))) Args: x: An N-dimensional array of floats axis: The axis for normalizing over. Returns: output: softmax(x) along the specifi...
144e65a287591901316b29932ddbb1b989a1c199
3,615,322
from typing import Union def is_chinese(x: Union[int, str]) -> bool: """Recognizes whether the server/uid is chinese :param x: A server or a genshin uid """ return str(x).startswith(("cn", "1", "2", "5"))
e63d7e98a3dcdaeb9f9853715dcd8f466d9a293b
3,615,323
def add_edit_button(user_id): """Determines if home page requires an edit button Args: user_id: user_id being used to request home page Returns: list list of dictionaries containing buttons """ button_list = [ { "textButton": { "text": "START ...
0bcc8a9e81af2b809ef6e2cbab0bba9c7d188258
3,615,324
def not_found(error): """ error handler """ return make_response(jsonify({'error': 'Not found'}), 404)
b09e9c47df42a40c3c241d5b6631726b7bebb580
3,615,325
import resource def port(port_data): """Represents a view for a port object""" keys = ('id', 'network_id', 'mac_address', 'fixed_ips', 'device_id', 'admin_state_up', 'tenant_id', 'status') return resource(port_data, keys)
fc4d987aa75c7548f8f9a2edfb00e5ccbf3849ad
3,615,326
def get_bridge(ip): """The name to be used for the bridge interface connecting the VMs and the host.""" return "spirebr%s" % ip.packed.hex().upper()
898347580052cce492bb12d60668fc7661a7f811
3,615,328
def test1(): """test case 1 Returns: matrix: np.array vector b: np.array vector c: np.array vector j: np.array """ A = np.array([ [-2, -1, -4, 1, 0], [-2, -2, -2, 0, 1] ]) b = np.array([-1, -1.5]) c = np.array([-4, -3, -7, 0, 0]) J = np.ar...
ca1836d985fef266aeb67d7b74ddfbfa2f20f053
3,615,329
import pickle def try_deserialize_handler(serialized_handler): """Reverse function of try_serialize_handler. Args: serialized_handler: serialized handler str or None. Returns: handler instance or None. """ if serialized_handler: return pickle.loads(serialized_handler)
bc91e26c65add4e74affd148b8ed550fe923c925
3,615,331
from typing import Optional async def load_from_server( component_builder: Optional[ComponentBuilder] = None, project: Optional[Text] = None, project_dir: Optional[Text] = None, remote_storage: Optional[Text] = None, model_server: Optional[EndpointConfig] = None, wait_time_between_pulls: Optio...
94e2e8a477af31761756c1ed1d887c75b0177a9a
3,615,332
def unravel_index(ind, tensor_shape): """no official tensorflow implementation for this yet; this is based on one proposed in https://github.com/tensorflow/tensorflow/issues/2075 """ ind = tf.expand_dims(tf.cast(ind, tf.int64), 0) tensor_shape = tf.expand_dims(tf.cast(tensor_shape, tf.int64), 1) ...
64070c8a832843884436bbc1107ea5be946dd7be
3,615,333
def write_tfrecord_from_tensorrec_dataset(tfrecord_path, dataset): """ Writes the contents of a TensorRec Dataset to a TFRecord file. :param tfrecord_path: str :param dataset: tf.data.Dataset :return: str The tfrecord path """ session = get_session() iterator = create_tensorrec_itera...
6108e384cdb1ecefa3b87ee1d11f78c3dbc56b26
3,615,334
def _convert_universal_format(format): """Converts Universal Date Time Format to Python strftime format string""" i = 0 token_string = format python_format = format token_map = sorted(_DATETIME_FORMAT_MAP, key=lambda t: t[0], reverse=True) calculated_tokens = {} for f in token_map: i...
d9b747c044e37317352ab402da080845ef39b2df
3,615,335
from typing import Tuple def get_loader(dataset: str, batch_size: int) -> Tuple: """ :param dataset: The name of the dataset we want to use. Either JSB_Chorales, MuseData, Nottingham, or Piano_midi. :param batch_size: how many sequences to train on at once. :return: DataLoaders for training, testing, ...
bc900e42f7d1523dbc1a629d27f4668caa6e0a10
3,615,336
def hardwareVersionToString (hwversion): """ Converts a raw integer value into a human readable string a.b.c.d. :param int hwversion: raw value as received from the generator :return str: a human readable string 'a.b.c.d'. """ if ((hwversion >> 30) & 1) != 0: # new format 30-22 + 21-16 # mask here with 0xFF ...
1f1fab23706e05fa593ef4cf56f3ec4e1a6f4c6f
3,615,337
def pareto_mtl_search(ref_vecs,i,t_iter = 100, n_dim = 20, step_size = 1): """ Pareto MTL """ # randomly generate one solution x = np.random.uniform(-0.5,0.5,n_dim) # find the initial solution for t in range(int(t_iter * 0.2)): f, f_dx = concave_fun_eval(x) weights...
245a9358ea64db0c667025f18599a6f1fd996229
3,615,338
def get_region_stats_np(im: np.ndarray, region: Box) -> Stat: """Get array region stats using Numpy. Parameters ---------- im : np.ndarray Input image to analyze region : Box Coordinates for region Returns ------- Stat Stat object containing various statistics o...
bc7fcad29c8638123d7b2d0bb7a0408e794d6dec
3,615,339
def _create_pipeline( pipeline_root: str, csv_input_location: str, taxi_module_file: tfx.dsl.experimental.RuntimeParameter, push_destination: tfx.dsl.experimental.RuntimeParameter, enable_cache: bool ): """Creates a simple Kubeflow-based Chicago Taxi TFX pipeline. Args: pipeline_root: The r...
c483ba700d2c4b0a2386cad997424ac4b10c6ee1
3,615,340
import numpy def gz(tesseroid, lons, lats, radii, nodes, weights): """ Integrate gz using the Gauss-Legendre Quadrature """ order = len(nodes) lonc, latc, rc, scale = _scale_nodes(tesseroid, nodes) # Pre-compute sines, cossines and powers sinlatc = numpy.sin(latc) coslatc = numpy.cos(l...
0e3878fa24fb00f810be03502f19c712b59044f9
3,615,341
def polynomial_coefficients_fast(r,s,alpha,beta,_=None): """ Return the coefficients of the Farey polynomial of slope r/s. The method used is the recursion algorithm. Arguments: r,s -- coprime integers representing the slope of the desired polynomial alpha, beta -- parameters o...
82ad772a4ae192b84b7cd2b2052315038d7dde9d
3,615,342
def get_light_threshold(response): """Get light from response.""" light_threshold = response.get("highlight") return light_threshold
602d3b11fbabfa6c8b0d284a21b4b1ebb816d327
3,615,343
def variant_ids( locus: hl.expr.LocusExpression, alleles: hl.expr.ArrayExpression, max_length: int = None ) -> hl.expr.ArrayExpression: """ Return a list of variant ids - one for each alt allele in the variant """ def compute_variant_id(alt): return hl.rbind( hl.min_rep(locus, [...
0ecf119ddf9d4a97e99987afc69444a2179cc1dd
3,615,344
def normalize_img_to_rgb(img_1_, img_h_, img_w_): """ Normalize the given image """ rgb_img_1 = cv2.imread(img_1_, 1)[:, :, ::-1] rgb_img_1 = cv2.resize(rgb_img_1, (img_h_, img_w_)) rgb_img_1 = np.float32(rgb_img_1) / 255. return rgb_img_1
b3b385fd30e956f47b2648ed8dc71f5ecb552839
3,615,345
def getonts(): """get the list of ont terms""" return Ontterms.objects.all().filter(to_remove__isnull=True).order_by('title')
b69e6e59774d323113b2d21a3f75be5c8cedc347
3,615,346
def load_frame_building_sample_data(): """ Sample data for the BuildingFrame object """ number_of_storeys = 6 interstorey_height = 3.4 # m masses = 40.0e3 # kg n_bays = 3 fb = models.FrameBuilding(number_of_storeys, n_bays) fb.interstorey_heights = interstorey_height * np.ones(num...
3d87d3e8a949fb1344ea13780cb529be427e1409
3,615,347
def analyze_group(group, verbosity, error_level): """analyze AD group object group -- group object to be analyzed verbosity - NAGIOS verbosity level - ignored error_level - ignored Returns the Nagios error code (always 0) and error message (group defn) """ return 0, '{name:%s, description:%...
868746cedd1815df1b9188b02671c3d5431bf83b
3,615,348
from typing import Sequence import signal def discount_rewards(x: Sequence, gamma: float) -> np.ndarray: """ Given vector x, computes a vector y such that y[i] = x[i] + gamma * x[i+1] + gamma^2 x[i+2] + ... """ return signal.lfilter([1], [1, -gamma], x[::-1], axis=0)[::-1]
7b5f3cf4f40f5b1dc127aa6c850456dbd7bccaa1
3,615,349
def type_for_objcclass(objcclass): """Look up the :class:`ObjCInstance` subclass used to represent instances of the given Objective-C class in Python. If the exact Objective-C class is not registered, each superclass is also checked, defaulting to :class:`ObjCInstance` if none of the classes in the supercl...
9dff18d82efdb780749dc57c0a6e0e0d587977c4
3,615,350
def command(name=None, descr=None, long_descr=None, examples=None, free_form=False, kind='command'): """Define a model command. :param name: An optional name of the command. Defaults to the name of the function. :param descr: A short description of the command :param long_descr: A long de...
9df0a43cbcefa3ba722f5fb7faa4a11e574eb39b
3,615,351
def bilinearUpsample2Don3D(input_tensor): """ Using tf.image.resize for bilinear interpolation """ """ ATTENTION: bilinear seems only works on 2D image """ ##### NOTE: this bilinaer upsampling works on axies [1,2] in [0,1,2,3,4] ##### input_shape = input_tensor.shape switch_axes = [0,3,1,2,4] re...
f9df49c2cbfc0d19896aa7bb1edff1c8ff067bbc
3,615,352
def fromhaeberlen(diso, delta, eta): """ Converts from the haeberlen convention to the PAS CSA tensor. Parameters ---------- diso : float diso == 1/3(d11 + d22 + d33) delta : flaot dzz - diso eta : float (dyy - dxx)/delta (0 <= eta <= 1) Returns ---------- ...
9d01a784384ca7f0aaebbb59eebc5cab68ffe994
3,615,353
def gst00b(uta, utb): """ Greenwich apparent sidereal time, consistent with IAU 2000 resolutions, using truncated nutation model IAU 2000B. :param uta, utb: UT1 as a two-part Julian date. :type uta, utb: float :returns: Greenwich apparent sidereal time in radians (float). .. seealso:: |MANUAL...
532b5967dd64e416ab16a0777cb26a9406788e2d
3,615,354
import re def search_bad_symbols_and_username(username): """Поиск зарезервированных слов и запрещенных символов""" search_bad_symbols_result = 'No' bad_username = ['root', 'admin', 'moderator', 'support', 'supports', 'helpdesk'] bad_symbols = ['&', ' ', '=', '+', '<', '>', ',', '.', '\"', '\'', '?', ...
79beccff28ce3c319698e47e05353e1c8354522c
3,615,355
import fnmatch def FilterMatchesTest(filter_string, test_string): """Does something close enough to base/strings/pattern.h's MatchPattern() for our purposes here.""" return fnmatch.fnmatch(test_string, filter_string)
9f4cca026e60fe1b3fb0c2858477090fdf03c44e
3,615,357
def make_path(components): """Build a path from a list of components.""" return '/{}'.format( '/'.join([quote(str(c), '') for c in components if c]))
fc7cbf848e3c3ad8fd2a30ee1c01992c77d3be35
3,615,358
def price_task(request): """ Lista de nomes, datas e VALORES das tarefas""" context = {} cliente = request.user try: cliente = Cliente.objects.get(usuario=cliente) # filter mostra como está a saida em __str__ # do models da classe # cronograma = Cronograma.objects.filter(...
3c2021770ff6a7396880321a69470398e580fcb4
3,615,359
def quotation_detail(request, quotation_id): """ View to show all record detail for a particular quotation """ try: quotation = get_object_or_404(Quotation, pk=quotation_id) except Exception as e: messages.error(request, f'ERROR: {e}') return redirect(reverse('quotations')) co...
2fe9bf09a6a21d7e6e80c7dcd57fa5f1d163561d
3,615,360
def li(content, value: str="", accesskey:str ="", class_: str ="", contenteditable: str ="", data_key: str="", data_value: str="", dir_: str="", draggable: str="", hidden: str="", id_: str="", lang: str="", spellcheck: str="", style: str="", tabindex: str="", title: st...
732af5f05c942d1f60d3a575b64922140c2748bf
3,615,361
from typing import List from typing import Dict def get_relations() -> List[Dict[str, str]]: """ Get the relations used for annotation for this app. """ return configuration.relations
4f55f1ad9545305ccb20e329b2ad573d8f97aeea
3,615,362
from typing import Dict def sort_by_color(e: Dict) -> float: """Sorting function, using a globally-declared color variable.""" return e[color]
9748e621798ff8cd9a41a57b657bac78b3105536
3,615,364
def get_texts_from_url_and_selector(url: str, selector: str) -> t.List[str]: """Get the texts of the elements found at the url and selector""" elements = get_elements_from_url_and_selector(url=url, selector=selector) texts = [element.text for element in elements] return texts
898b6d461db94b143edfb4a73e0747635033ab76
3,615,365
import random def flat_monte_carlo(func, z_min, z_max, epsilon): """ Operate Monte Carlo integration on specified function. Random numbers are generated with a flat distribution function. ---------- Input: func: the function of integrand z_min: lower limit of the integration z_...
9f4fdb0a3f75ee9e0af2b6d3d0e6f439720d1fe9
3,615,367
def hbp_fn(): """Create a 2d convolution layer with HBP functionality.""" set_seeds(0) return HBPConv2d( in_channels, out_channels, kernel_size, stride=stride, padding=padding, dilation=dilation, bias=bias, )
ccfae6f3b41a508cbe9e8124587b65f90356603e
3,615,368
from typing import List import ctypes def GetMonitorsRect() -> List[Rect]: """Return monitors rect""" SM_CMONITORS = 80 monitorsCount = ctypes.windll.user32.GetSystemMetrics(SM_CMONITORS) arrayType = ctypes.c_int * (monitorsCount * 4) values = arrayType() monitorsCount = _DllClient.instance()....
5780f1af36c323fb9447619e30eb068870fa994d
3,615,369
import code def main(_): """Run an interactive console.""" code.interact() return 0
e85a21c0197a599378c3f25022ec99cb557d6017
3,615,371
import mkl import numpy import scipy def fit_r_mdv_scipy(configure, experiments, numbers, vectors, matrixinv, func, flux, method = "SLSQP"): """Low level function for model fitting using scipy.optimize.minimize Args: configures (dict): "model.configures" including various configulatoins of the model...
5e4ffe4ec7fff423409ad019333585b0c3c04712
3,615,372
import heapq def heapmerge(*inputs): """Like heapq.merge(), merges multiple sorted inputs (any iterables) into a single sorted output, but provides more convenient API: each input is a pair of (iterable, label) and each yielded result is a pair of (item, label of the input) - so that it's known what input a g...
580ec9f2f0793f8907390f5c7f8eebf4ac539b59
3,615,373
def histograma(img): """Calcula y representa el histograma de una imagen RGB. Args: img (Numpy array 3d): Un imagen RGB Returns: List: Devuelve una lista con el array del histograma de cada canal RGB. Cada canal contendra un array de dos dimensiones, la primera contendra la...
782f69002220ad744efab496f7d71e0bff811957
3,615,374
from datetime import datetime def get_all_data(start=datetime.date(1970, 1, 1), end=datetime.date(2099, 12, 31)) -> pd.DataFrame: """得到一段日期内的全部信息""" return _calendar.get_all_data(str(start), str(end))
714bb182bbc4dbe3dc2a07378f7ce0c140d03a6b
3,615,375
def tb_extent(table, db='main'): """Get the extent of the table""" data = [] try: conn = psycopg2.connect(conn_str(db)) cur = conn.cursor() sql = f""" SELECT ST_AsText(ST_SetSRID(ST_Extent(st_transform(wkb_geometry, 4326)), 4326)) As bextent FROM {table};"...
c096fb8924379494e6c6a1475fdac47207f61eb0
3,615,376
from typing import Iterable def _avro_pfb_schema(azul_avro_schema: Iterable[JSON]) -> JSON: """ The boilerplate Avro schema that comprises a PFB's schema is returned in this JSON literal below. This schema was copied from https://github.com/uc-cdis/pypfb/blob/1497bf50e5c85201f6bad9ca69616138b17b8c77/s...
3019f3ae3005f625953eb8cdf0e9539d58ab5dd0
3,615,377
def _extend_job_info(connection, info): """Extends job info with connection/API related data.""" info['path'] = '/jobs/%s/%s' % (connection.id, info['uid']) info['agent'] = { 'platform': connection.handshake_data[pagent.identity.KEY_PLATFORM], 'properties': connection.handshake_data[pagent.i...
6865f76e5c0ea23e7c6910ca723c7d5c08f391bd
3,615,378
def get_timeseries_data_as_df(quantum:object, entity:object, attribute:str=None): """ :param quantum: An instance of quantumleap where the timeseries data should be obtained from :param entity: The entity of which the data should be obtained :param attribute: The attribute of which the data should be ...
505e2f2ea58c0e3681dd4eed3ed0437f81c9b5f3
3,615,379
async def login_for_access_token( form_data: OAuth2PasswordRequestForm = Depends(), db: AsyncSession = Depends(get_db_session), ): """Generate and return a token""" user = await crud.backend_user.authenticate(db=db, user_name=form_data.username, password=form_data.password) # check if OK if us...
636db7af85f0fb2e951bc6dfb1c3fb53b0213a89
3,615,380
from datetime import datetime import pytz def utc_float_to_pretty(utc_float=None, fmt=None, timezone=None): """Return the formatted version of utc_float - fmt: a strftime format - timezone: a timezone If no utc_float is provided, a utc_float for "right now" will be used. If no fmt is provided an...
a419d41818e2fbd5682f0dfc8b453f85da2b85a4
3,615,381
def find_teacher(req: str): """ Find teacher :param req: Request :return: Search result as string """ if len(req) < 3: return r_teacher_find_symbols req_f = f"%{req.lower()}%" res = cur.execute("SELECT * FROM teachers WHERE teacherClassSearchable LIKE ? LIMIT 5", (req_f,)).fetch...
0158f1cccf816d03b6cc4bc107096384ccbf38a7
3,615,382
def pause_synchronization(): """ Pauses synchronization of files from Artella server """ client = get_artella_client() return client.pause_downloads()
9eff1128e4e80809ca0a96b86f64835489519cff
3,615,383
def shortest_common_super_sequence(a, b): """ get the shortest common string for a and b This cannot solve complex case like the one in the test case, when same char repeats before the next common substring letter. """ def separate_by_char(letter, seq): idx_seq = seq.find(letter) ...
3a989f342269b1319c4fc3af48f894ef1bcb53fb
3,615,384
def contains_carriage_return(text): """Check if carriage return is present.""" return "↵" in clean_string(text)
13f470e652a231b43cfd890e5a9f444f466b3215
3,615,385
from datetime import datetime def timestamp_to_datetime( timestamp: float, tzinfo: timezone = timezone.utc, ) -> datetime: """ Convert a given UNIX timestamp to a Python datetime object. Args: timestamp: A UNIX timestamp (as a float). tzinfo: A timezone object. Usually, everything...
041b43383d68565086eb817379ba341dd2ce6883
3,615,386
def handle_get(key): """Return a tuple containing True if the key exists and the message to send back to the client.""" try: return_value = DATABASE_DICT[key] operation_status = True except KeyError: operation_status = False return_value = None return (operation_statu...
8da98332545f97996294fdaea05684da6dfbe4f0
3,615,388
def preprocess_document(text): """Wrapper of the above.""" return create_tokens(lowercase_text(text))
bae1e0d5789caaac3a9254037aa604f43b49dee3
3,615,389
def analizar_propuesta(propuesta, codigo): """Determina aciertos y coincidencias""" aciertos = 0 coincidencias = 0 for i in range(DIGITOS): if propuesta[i] == codigo[i]: aciertos += 1 elif propuesta[i] in codigo: coincidencias += 1 return aciertos,coincidencias
dd86380a1afb044ff922f8de64c4892976f17c6c
3,615,390
def conditions_gen(conditions, safe=True): """ Generate comma separated conditions. Args: conditions: An iterator that yields ConditionClause tuples. Returns: The string of the query. """ conditions_str = '' connector = None for index, condition in e...
6a00557004ce4a3080df3d6d477df2014c681c7b
3,615,391
def as_type(val, types): """Try converting `val`to each of `types` in turn, returning the first one that succeeds.""" errs = [] for type in make_seq(types): try: return type(val) except Exception as e: errs.append(e) pass raise TypeError('Could not con...
da30769367f6f295fde983ad637610ace14f2b6a
3,615,392
import json def cjson_parser(cjsonfile, trajfile=None): """Parse CJSON files Parameters ---------- cjsonfile : str Path to the CJSON file. trajfile : str, optional Name of trajectory file to be saved, by default None. Returns ------- atoms A list of Atoms obje...
caf4b21b8a887408dc59c80672d39f5787a04bfa
3,615,393
def tableHeaders(): """ tableHeaders table model headers Returns: list: header definitions """ data = [ [ "jobID", { "Type": "int", "CastFunction": int, "Label": " " + _(Text.txt0131) + " ", "A...
2b10d139efc5d3965cf8a636b9ad80c7cfbecaf3
3,615,395
import unicodedata import re def slugify(value, allow_unicode=False): """ Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens. Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip leading and trailing whitespace. From Django 2....
c36a9c383f537ace0d7113994d36eae79f631073
3,615,396
import yaml def cfg_to_algorithm(config_file): """ Return instance of classification algorithm helper from config file Args: config_file (str): location of configuration file for algorithm Returns: tuple: scikit-learn estimator (object) and configuration file (dict) Raises: ...
f8dde9cbb47e59e994e5ae688b7f432b89c46d3b
3,615,397
def get_pdf_form(): """ 1. Call the envelope get method """ # import pdb; pdb.set_trace() args = { "account_id": session["ds_account_id"], "document_id": 1, "envelope_id": session["envelope_id"], "envelope_documents": session["envelope_documents"], "base_path"...
ddbcaff85e4424a8c7509c47a69f25428f942c94
3,615,399
def read_parameters_start(config): """ Read info on starting parameter values. The distributions can be 'gauss', 'uniform', or 'log-uniform'. """ section = 'EMCEE starting' parameters_to_fit = [var for var in config[section]] starting = {} for param in parameters_to_fit: words = ...
4dc2c3660f0de3b96eeadb4b792c2ff40fab6822
3,615,400
from typing import Dict from typing import Any def list_third_party_asi_vulnerable_components_command(client_obj: Client, args: Dict[str, Any]) -> CommandResults: """ Retrieves the attack surface vulnerable component information of the given third-party account. :param client_obj: client object which is ...
fa5676b5570614ea05109cd63f8e53b5ce901491
3,615,401
def get_lon(da, errors="raise"): """Get the longitude coordinate Parameters ---------- da: xarray.DataArray {errors} Return ------ xarray.DataArray or None See also -------- get_lat get_depth get_altitude get_level get_vertical get_time xoa.cf.CFSpe...
f83dde7507b5cc14784466e932969fa47317dc2d
3,615,402
import mimetypes def bundle_media_description(key, filename): """Bundle the media description necessary for uploading. :param key: form-data key name :param filename: Local file name or path. :return: tuple of ('key name', ('file name', 'file object', 'MIME content-type') :rtype: tuple """ ...
8c160a9c767d86a1c1867d22f018d6342239e68d
3,615,403
def _getColor(*color): """Analyzes the color arguments and returns a proper 4-float tuple or None""" if len(color) == 1 and type(color[0]) == tuple: # a tuple, i.e., a value of type color, was passed rather than in-line values: # no transformation takes place assert (len(color[0]) =...
0e8b9c9c0ef1dc60ae30c4e5499888f28b22c845
3,615,404
def format_write_request(address, value): """ Format a write request based on an address and the value to write to the FPGA. :param address: address at which to write date. :param value: data to write to the address. :return: formatted request. """ if address >= 2**(4 * 8): raise Va...
8425b7ff3422162cb0127c64069dbf68a414becf
3,615,406
def get_prob(board, policy_val): """Return the probabilities of selecting the children of a node given the policy and removing illegal moves""" x = (board[:, :, 0] == board[:, :, 1]).reshape(225,) * policy_val return x / np.sum(x)
a275188ebda5397c6a3b2cda80652d52501c0460
3,615,407
import hashlib import ray def get_actor_method_function_id(attr): """Get the function ID corresponding to an actor method. Args: attr (str): The attribute name of the method. Returns: Function ID corresponding to the method. """ function_id_hash = hashlib.sha1() function_id_hash.update(attr.enco...
1627d2635e2dfcce088d1848d5832c113f0b9960
3,615,408
def tangent_basis_transposed(v): """ """ return v[:,:-1,...] - v[:,-1:,...]
e2cd1c0c398ba58e76541aa9976bae64cdecf339
3,615,409
import warnings def headloss_manifold(FlowRate, Diam, Length, KMinor, Nu, Roughness=None, NumOutlets=None, *, PipeRough=None): """Return the total head loss through the manifold. :param FlowRate: flow rate through manifold :type FlowRate: u.m**3/u.s :param Diam: diameter of manifold :type Diam: u...
332b1fca8f54dfa2adc699727afc911f6c03ba55
3,615,411
import logging def get_pending_jobs_info(max_slots_filter=None, skip_if_state=None, log_pending_jobs=True): """ Retrieve the list of pending jobs. :param max_slots_filter: discard jobs that require a number of slots bigger than the given value :param skip_if_state: discard jobs that are in the given ...
d534d6a2cc901687344e2f68af59193c09b8eb01
3,615,412
def reduce_squeeze(m): """Reduce model by removing length=one dimensions.""" out = m.copy() print('input model has shape:{}'.format(m.param_shape())) keep = np.array(m.param_shape()) != 1 for k,p in zip(keep,m.parameters): if not k: del out.param_values[p] out.parameters =...
9ef37448207756ca490401da80cfe032b4fe4538
3,615,413
def recreate_phage(phage_row): """ Input: the list of prophages for a particular timepoint (i.e phage[-1], where phages is read in above) Output: the same line formatted as a list of lists of integers """ phage_list = [] phages_string = phage_row.decode("utf-8").split('[')[2:] for phage...
8dc38ee643e4c8b59a4ea985aedf7def54b8c64d
3,615,414
def get_chan_nbrs(geom, nbr_dist=70, n_nbrs=7, keep_less_nbrs=False, chans_exclude=None): """Get the channels with n_nbrs neightbors within nbr_dist radius on the electrode array. Returns an array of such channels and a mapping of each channel to its neighbors. Have the option to keep chennels with less ...
49bc361d188d416fdd0a71e24dcf9067eef2ef96
3,615,415
def getHashes(): """ Returns an element with the given itemid :param str i: ItemID of the element :return: the returned object from Monogo less the mongo object ID :rtype: dict or None """ collection = asdb["hashes"] e = collection.find({}, {"_id": False, "hash": True}) return list(e)
12f7172e1aa8761b297eb78c5076ba23a1b0e5c1
3,615,416
def generate_default_function(node, base_name, func_counter): """Generate a default function from the given node """ ft = onnx_optype_to_nnabla_function_type.get(node.op_type) if ft is None: raise ValueError( "op_type {} is currently not supported for NNP conversion".format(node.op_t...
a59826061f21c6ad8f65947face0f35502e6b45d
3,615,417
def unicycle_to_single_integrator(dxu, poses, projection_distance=0.05): """A function for converting from unicycle to single-integrator dynamics. Utilizes a virtual point placed in front of the unicycle. dxu: 2xN numpy array of unicycle control inputs poses: 3xN numpy array of unicycle poses proje...
6872e73ecfbf5e2181f18bb748c656ae68968490
3,615,418
def lloyd_fix(T, Rref, E0): """ Lloyd & Taylor (1994) Arrhenius type with T0=-46.02 degC and Tref=10 degC T Temperature [k] Rref Respiration at Tref=10 degC [umol(C) m-2 s-1] E0 Activation energy [K] """ Tref = 283.15 # 10 [degC] T0 = 227.13 # -46.02 [degC] ...
6e654c119bf882a3db9dd7c7a4c4b4b9bb5493f4
3,615,419
def merge(left, right): """ Merges two linked list, sorting by data in nodes Returns a new, merged list Runs in linear time """ #Create new linked list that contains node from #merging left and right merged = LinkedList() #Add fake head discarded later merged.add(0...
cd3a03770a07276fa604a9653159d0567c5bd51d
3,615,420
def safe_interval_insert(M_new, interval): """ Deal with interval overlaps when adding a new one to the list """ for i, (a, b) in enumerate(M_new): # overlap found, construct the larger interval if (b >= interval.lower_bound) and (a <= interval.upper_bound): lb = min(a, int...
5f0ba60e6ae8c486dca3e22fd69e6f6002b0ef17
3,615,421
def nms(bboxes, iou_threshold, sigma=0.3, method='nms'): """ :param bboxes: (xmin, ymin, xmax, ymax, score, class) Note: soft-nms, https://arxiv.org/pdf/1704.04503.pdf https://github.com/bharatsingh430/soft-nms """ classes_in_img = list(set(bboxes[:, 5])) best_bboxes = [] for cls...
469e5a4c27bb43dbeb9ce9ee619ac2a81f6f1781
3,615,422
from datetime import datetime def create_envelope(payload: dict) -> dict: """ Creates a dictionary with event label, timestamp and message field :param payload: The payload dict :return: An event message dictionary """ payload['timestamp'] = datetime.utcnow().timestamp() if 'event' not in...
593a2b60a667dece41f10031d13ad98018d9f881
3,615,423
def ConsValue(t,ma,st,ra,ds,m,sol,par,idx,ad=0,ad_min=0): """ interpolate consumption and value (ad and ad_min are only so the couple model can look up in this function) """ # a. unpack solution ad_idx = ad+ad_min D = transitions.d_plus(t+ad-1,ds,par) # t-1 so we get choice set today ra_look ...
bda95a033115d50e7fd3f424f465c29d37edc8c8
3,615,424
def decipher(ciphered_name: str, key: int) -> str: """Decipher the room name.""" return "".join(shift(char, key) for char in ciphered_name)
bf46a62ce88941a00407027a681d72fe03367865
3,615,425
def tensor_to_local(tensor): """ to local """ tensor = tensor.to_consistent(sbp=flow.sbp.broadcast).to_local() return tensor
59a8859e301fa1179f0a19ae54c32a8857425b58
3,615,428
def proceed(request): """ This is a fake "Terms" view that we overlay the login. We link here from the Developer Hub landing page. """ if request.user.is_authenticated(): return submit(request) agreement_form = forms.DevAgreementForm({'read_dev_agreement': True}, ...
36faa7fbcbd758ef23828dcee0ff32cce3f9d50a
3,615,429
def angle(v1, v2): """Angular separation between two vectors.""" dot = vdot(hat(v1), hat(v2)) if np.ndim(dot) == 0 and dot > 1: return 0 if np.ndim(dot) > 0: dot[dot > 1] = 1 return np.degrees(np.arccos(dot))
81132ac90f5bbcf612f565ce2a26028b2a579801
3,615,430
def flex_convolution(features, position, neighborhood, theta, bias, name=None): """Flex-Convolution computation. Computes a convolution over arbitrary neighborhoods with elements of arbitrary positions: ...
a8cc9ec48a9b945e2e6ab7d0c0304bfb33747f8d
3,615,431