content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import re import argparse def soundtone_type(value): """ Parse tone sounds parameters from args. value: 'square:90hz,10s,100%' returns: {'waveform': 'square', 'frequency': '90', 'amplitude': '100'}' """ abbr_map = {"hz": "frequency", "%": "amplitude", "s": "duration"} tone_form, generator...
cdbf98939ac99210c2722653427cd8a7b2e847e2
3,000
def rouge_l_sentence_level(evaluated_sentences, reference_sentences): """Computes ROUGE-L (sentence level) of two text collections of sentences. http://research.microsoft.com/en-us/um/people/cyl/download/papers/ rouge- working-note-v1.3.1.pdf. Calculated according to: R_lcs = LCS(X,Y)/m P_lcs = LCS(X,Y)/n ...
168b3202baa5e8d185d5d181b3b468b810cf92fd
3,001
import numpy as np from scipy.signal import medfilt, medfilt2d def median(array, width=None, axis=None, even=False): """Replicate the IDL ``MEDIAN()`` function. Parameters ---------- array : array-like Compute the median of this array. width : :class:`int`, optional Size of the ne...
829d3c00055c57a5368d366dac04731353ace5e6
3,002
def stitch_frame(frames, _): """ Stitching for single frame. Simply returns the frame of the first index in the frames list. """ return frames[0]
833ceb66f9df61e042d1c936c68b8a77566545c4
3,003
def project_add(): """ Desc: 新增项目接口 """ form_data = eval(request.get_data(as_text=True)) pro_name, remark = form_data['projectName'], form_data['remark'] user_id = get_jwt_identity() response = ProjectM().add_project(user_id, pro_name, remark) return response
b03a07e129f5c52b70a6db3c687318225090318b
3,004
def end_of_next_month(dt): """ Return the end of the next month """ month = dt.month + 2 year = dt.year if month > 12: next_month = month - 12 year+=1 else: next_month = month return ( dt.replace( year=year, month=next_month, day=1 ) - ...
0ee3ac845275cc0a101f2cd1603d2de268ef9108
3,005
import os import subprocess def get_version(): """ Reads version from git status or PKG-INFO https://gist.github.com/pwithnall/7bc5f320b3bdf418265a """ # noinspection PyUnresolvedReferences git_dir = os.path.join(base_dir, '.git') if os.path.isdir(git_dir): # Get the version using...
8aa95e3c9206d4fe93d33b16d4889d014d354f68
3,006
import argparse def parse_args(): """Parse the arguments.""" parser = argparse.ArgumentParser( "dashboard", description="Data Visualization for the simulation outcome" ) parser.add_argument( "--datadir", type=str, required=True, help="The path to the simulation ...
747d8a06dc5e519f185eb06634383b73e0aeb3f2
3,007
def test_build_dynamic__with_location_mobility_data(monkeypatch): """ Ensure dynamic mixing matrix can use location-based mobility data set by the user + Google. """ def get_fake_mobility_data(*args, **kwargs): vals = {"work": [1, 1.5, 1.3, 1.1]} days = [0, 1, 2, 3] return vals,...
a85722c24f57918f16e35ee2ae57cefdd23824fb
3,008
def margin_to_brightness(margin, max_lead=30, pct_pts_base=0): """"Tweak max_lead and pct_pts_base to get the desired brightness range""" return int((abs(margin) / max_lead) * 100) + pct_pts_base
d6f101c52ddee9f520e36e31fac7042e0aba3992
3,009
def RotateFullImage2D(src, dst, angle, scale=1.0, interp=InterpolationType.linear): """\ Rotate an image resizing the output to fit all the pixels. Rotates an image clockwise by a given angle (in degrees). The values of unknown pixels in the output image are set to 0. The output I...
faedd430ae87f32e56c13ad50125051daa5994f3
3,010
def render_practice_text_field_validation1(request): """テキストフィールドのバリデーションの練習""" template = loader.get_template( 'webapp1/practice/vuetify-text-field-validation1.html') # ----------------------------------- # 1 # 1. host1/webapp1/templates/webapp1/prac...
714093e2b606cab0bbfb094025b5608d781f8aab
3,011
import os def cpsf_critical(request): """ cpsf_critical page, deals with file upload and allows the user to spawn off the update task """ if 'project' not in request.session: return HttpResponseRedirect(reverse('index')) transcription_location = os.path.join(settings.ESTORIA_BASE_LOCATION...
77282754af35bfecc1bc9ae3d444024453fe4ddb
3,012
def hlc3(high, low, close, offset=None, **kwargs): """Indicator: HLC3""" # Validate Arguments high = verify_series(high) low = verify_series(low) close = verify_series(close) offset = get_offset(offset) # Calculate Result hlc3 = (high + low + close) / 3.0 # Offset if offset != ...
16bb3e49f5017f13c84046dce880dd3f022eb15e
3,013
async def findID(context: Context, dueDateID: str = ""): """Find Due date !ass find subject_name """ if not dueDateID: return await notEnoughArgs(context) try: dueDates = DueDateData().findById(context, dueDateID) if len(dueDates) == 0: return await context.send(...
a6aab2219fcb29e073ccb5d73e440dd7a42163b9
3,014
def front_page() -> HTML: """ Renders the front page """ return render_template("frontPage.html")
2ec04c4c24b1aade9f7389b29bd91985b657fc67
3,015
async def async_setup_entry(hass, entry): """Set up the Samsung TV platform.""" # Initialize bridge data = entry.data.copy() bridge = _async_get_device_bridge(data) if bridge.port is None and bridge.default_port is not None: # For backward compat, set default port for websocket tv d...
a5e411560c8f3f1e609d6675061a72000984e0ce
3,016
def bring_contact_bonus_list(pb_client, obj_pb_ids, arm_pb_id, table_pb_id): """ For some bring goals, may be useful to also satisfy an object touching table and not touching arm condition. """ correct_contacts = [] for o in obj_pb_ids: o2ee_contact = len(pb_client.getContactPoints(o, arm_pb_id)...
6c0033b0bfb1d3f4d08c8ca114855e089fe852f7
3,017
def topic(**kwargs): """ :param to: Topic ID :return: """ return api_request('topic', kwargs)
2d2af8f74db1ffde7732ecff529911b7058154bf
3,018
def load_data(filename: str) -> pd.DataFrame: """ Load city daily temperature dataset and preprocess data. Parameters ---------- filename: str Path to house prices dataset Returns ------- Design matrix and response vector (Temp) """ daily_temp_df = pd.read_csv(filename, ...
381eac22a1c3c0c9ad85d0c416fb1c182429153e
3,019
def group_intents(input_file, intent_file, slot_file): """ Groups the dataset based on the intents and returns it. Args: input_file : The path to the input file intent_file : The path to the intent file slot_file : The path to the slot file Returns: A dict mapping intents to a list of tuples. ...
8db186fc91ddc3adfbc163ef63e66cc408f3b47d
3,020
def _get_path(string): # gets file path from variable name """ Gets path that a variable holds, convert it to start from root (.), esolves any symbolic link and returns the converted path. """ varname = string.replace("(long)", "") try: path = c.VAR_STACK[varname] except KeyError: ...
794660ed9571dded27f5907c4ac1d9cdc99f41b6
3,021
def create_service_endpoint(service_endpoint_type, authorization_scheme, name, github_access_token=None, github_url=None, azure_rm_tenant_id=None, azure_rm_service_principal_id=None, azure_rm_service_prinicipal_key=None, azure_rm_subscr...
75ad8fdb237d4dac9105bc33b96273f67482375f
3,022
import math def voronoi_diagram_interpolation(interpolationcellid, id0, id1, voronoiDataset0, voronoiDataset1, centerlines, step, clippingPoints): """Given two Voronoi datasets interpolate the data sets along the centerline. Args: in...
13c719b89f737bac625cf76c7d64a5c34a856fdd
3,023
def plot_kde_matrix(df, w, limits=None, colorbar=True, refval=None): """ Plot a KDE matrix. Parameters ---------- df: Pandas Dataframe The rows are the observations, the columns the variables. w: np.narray The corresponding weights. colorbar: bool Whether to plot th...
a0272a0f819fc5bca6144c9a8293f29f415327b8
3,024
from typing import Optional import os def get_root(user_id: Optional[int]) -> str: """ Return the absolute path to the current authenticated user's data storage root directory :param user_id: current user ID (None if user auth is disabled) :return: user's data storage path """ root = app...
ce8dad4ea50534bba61948e064e47d8a22ed874f
3,025
import requests import os def download_model(model_id, file_format="json", save=True, path="."): """ Download models from BiGG. You can chose to save the file or to return the JSON data. Parameters ---------- model_id : str A valid id for a model in BiGG. file_format : str If ...
b95c8b1231ef0907044649856045aeef7c0b70eb
3,026
import os def open_expand(file_path, *args, **kwargs): """ Allows to use '~' in file_path. """ return open(os.path.expanduser(file_path), *args, **kwargs)
6ad3d6ae98bdb2295e66f4d52a8282dfd3162a3d
3,027
import os def get_app(): """load API modules and return the WSGI application""" global get_app, _app, login_manager _app = Flask(__name__, instance_relative_config=True, instance_path=os.environ.get('UKNOW_CONFIG')) _app.config.from_object(DefaultConfig()) _app.s...
9f9715e928b6b4829d5fc2cb53b72298858282a5
3,028
import logging def _submit_to_all_logs(log_list, certs_chain): """Submits the chain to all logs in log_list and validates SCTs.""" log_id_to_verifier = _map_log_id_to_verifier(log_list) chain_der = [c.to_der() for c in certs_chain] raw_scts_for_cert = [] for log_url in log_list.keys(): re...
16081a2ddbc924c0490af5f7c3ffc625300486cd
3,029
def update(oid, landingZoneProgressItemDetails): """ This function updates an existing landingZoneProgressItem in the landingZoneProgressItem list :param id: id of the landingZoneProgressItem to update in the landingZoneProgressItem list :param landingZoneProgressItem: landingZoneProgressItem to upda...
af9d09aab0c5dfb3defea4db428265a71c60ed76
3,030
import sqlite3 def create_connection(db_file: str): """Create database file.""" conn = None try: conn = sqlite3.connect(db_file) print(sqlite3.version) except Error as e: print(e) return conn
a50dff80de36e391aeea7f6867cc85334f4bc690
3,031
def _simplex_gradient(op, grad_wrt_weight): """Register gradient for SimplexInterpolationOp.""" grad_wrt_input = simplex_gradient( input=op.inputs[0], weight=op.outputs[0], grad_wrt_weight=grad_wrt_weight, lattice_sizes=op.get_attr('lattice_sizes')) return [grad_wrt_input]
58447f073cdf4feb6e1f115b039c8573ab1048ca
3,032
def generate_experiment(): """ Generate elastic scattering experiments which are reasonable but random """ exp_dict = {} exp_keys = ['qmin', 'qmax', 'qbin', 'rmin', 'rmax', 'rstep'] exp_ranges = [(0, 1.5), (19., 25.), (.8, .12), (0., 2.5), (30., 50.), (.005, .015)] for n, k...
f913cbfc6f871fa290dd6cdb3e5da874b06243b4
3,033
def connectDB(): """function to start the database connection using MongoClient from pymongo and the connection link from .env file path. Using certifi to provide certificate in order to enable the connection Returns: Cursor: database white-shark """ try: client = MongoClient(f"{MONGO_U...
6d04fbc03ed45d5ec2b868dd52270f7dd1d7339d
3,034
import gzip def load_dicom(filename): """Loads in a given dicom file using a pydicom library :param filename: a path to the .dcm.gz or .dcm file :type filename: Union[str, os.path] :return: pydicom.dataset.FileDataset or pydicom.dicomdir.DicomDir :raises TypeError: raised if the file extension do...
898b2003049dd91d53f57e28208ad82b5449632e
3,035
import torch def load_pytorch_policy(fpath, itr, deterministic=False): """ Load a pytorch policy saved with Spinning Up Logger.""" fname = osp.join(fpath, 'pyt_save', 'model'+itr+'.pt') print('\n\nLoading from %s.\n\n'%fname) model = torch.load(fname) # make function for producing an action giv...
d368f9b120c78c00e446ab6a4b2b63e893507de7
3,036
def make_server(dashboard): """ Creates the server by mounting various API endpoints and static file content for the dashboard Parameters ---------- dashboard : plsexplain.Dashboard The dashboard instance to server Returns ------- FastAPI The application instance that h...
a7e7e599ba8166d4a27818dcc21da25bb66a4171
3,037
def bash_complete_line(line, return_line=True, **kwargs): """Provides the completion from the end of the line. Parameters ---------- line : str Line to complete return_line : bool, optional If true (default), will return the entire line, with the completion added. If false, ...
571e0822cd7a4d44e19c969072d624123640d1f1
3,038
def use_board(name): """ Use Board. """ _init_pins() return r_eval("pins::use_board(\"" + name + "\")")
5f08450f48fca6ca827383f4a57f006ee6e50836
3,039
def add_parameter(name, initial_value=1.0, **kwargs): """Adds a new global parameter to the model. :param name: the name for the new global parameter :type name: str :param initial_value: optional the initial value of the parameter (defaults to 1) :type initial_value: float ...
8fa0839f1a38fa78add8ab35b2eb03f0c3d4bbd8
3,040
from samplesheets.models import GenericMaterial def get_sample_libraries(samples, study_tables): """ Return libraries for samples. :param samples: Sample object or a list of Sample objects within a study :param study_tables: Rendered study tables :return: GenericMaterial queryset """ if ...
284d08b313d982a4b6d6fe9d780f1a668f036455
3,041
def parse_next_frame(data): """ Parse the next packet from this MQTT data stream. """ if not data: return None, b'' if len(data) < 2: # Not enough data yet return None, data packet_type, flag1, flag2, flag3, flag4 = bitstruct.unpack('u4b1b1b1b1', data[0:1]) length =...
ce725ce871fdbd45fbf5d7367049171e7001469b
3,042
import random def pick_glance_api_server(): """Return which Glance API server to use for the request This method provides a very primitive form of load-balancing suitable for testing and sandbox environments. In production, it would be better to use one IP and route that to a real load-balancer. ...
e32e75b675f0b3e07c71ae172423b6393f213a4d
3,043
def remove_punctuation(transcriptions): """ :param: transcriptions is the dictionary containing text file that has been converted into an array. :return: cleaned string of words This function removes punctuations from the story """ parsed_string = dumps(transcriptions) punctuations = '''[],!...
5800a97a2a232f41161c9c8357cd826212d8302e
3,044
def snakify(str_: str) -> str: """Convert a string to snake case Args: str_: The string to convert """ return str_.replace(" ", "_").lower()
c40d972fc99f2cb99f3c2b4a83296e793018c32b
3,045
def search_images( project, image_name_prefix=None, annotation_status=None, return_metadata=False ): """Search images by name_prefix (case-insensitive) and annotation status :param project: project name or folder path (e.g., "project1/folder1") :type project: str :param image_name_prefi...
dc5733e0c22419f850592ee2f8dd3b13e177c99b
3,046
def bibtexNoteszotero(bibtex_names): """ params: bibtex_names, {} response, {} return: notes_dict, {} """ # notes_dict = {} notes_dict["itemType"] = "note" notes_dict["relations"] = {} notes_dict["tags"] = [] notes_dict["note"] = bibtex_names["notes"].strip() # r...
97e30f746f59ee5e1cfed8581a2dc272fc4b477f
3,047
def iliev_test_5(N=10000, Ns=10, L=15. | units.kpc, dt=None): """ prepare iliev test and return SPH and simplex interfaces """ gas, sources = iliev_test_5_ic(N, Ns, L) conv = nbody_system.nbody_to_si(1.0e9 | units.MSun, 1.0 | units.kpc) sph = ...
f4675e8c7f51c18cb31644295a1d5945e453de5b
3,048
def run(model, model_params, T, method, method_params, num_iter, tmp_path="/tmp/consistency_check.txt", seed=None, verbose=False, simplified_interface=True): """ Wrapper around the full consistency check pipeline. Parameters ---------- model : str Name ...
152eb33e3e6c68306c3f965f734bc8d7ddeb4010
3,049
def clean_street(address: str) -> str: """ Function to clean street strings. """ address = address.lower() address = _standardize_street(address) address = _abb_replace(address) address = _ordinal_rep(address) if address in SPECIAL_CASES.keys(): # Special cases address = SPECIAL_...
af166bd9ebd51e1a157135587c4efdb6469181ea
3,050
def unroll_policy_for_eval( sess, env, inputs_feed, prev_state_feed, policy_outputs, number_of_steps, output_folder, ): """unrolls the policy for testing. Args: sess: tf.Session env: The environment. inputs_feed: dictionary of placeholder for the input modalities. prev_s...
59979b74f7ff7dcdaf7c875ce93d3333f467cd0d
3,051
import time import os def get_result_filename(params, commit=''): """ 获取时间 :return: """ save_result_dir = params['test_save_dir'] batch_size = params['batch_size'] epochs = params['epochs'] max_length_inp = ['max_dec_len'] embedding_dim = ['embed_size'] now_time = time.strftime...
51b79d6a5850b50fcb41847ba16acfc12d7c323a
3,052
def is_iterable(o: any) -> bool: """ Checks if `o` is iterable Parameters ---------- o : any The value to be checked. Examples -------- >>> is_iterable(list(range(5))) True >>> is_iterable(5) False >>> is_iterable('hello world') True >>> is_iterable(N...
f3124d5ead76977c45899c589e0c6873abafd773
3,053
def fit(init_file, semipar=False): """ """ check_presence_init(init_file) dict_ = read(init_file) # Perform some consistency checks given the user's request check_presence_estimation_dataset(dict_) check_initialization_dict(dict_) # Semiparametric Model if semipar is True: qua...
05d484c0aae6e739881714eb7ec81c982503cf15
3,054
def date2gpswd(date): """Convert date to GPS week and day of week, return int tuple (week, day). Example: >>> from datetime import date >>> date2gpswd(date(2017, 5, 17)) (1949, 3) >>> date2gpswd(date(1917, 5, 17)) Traceback (most recent call last): ... ValueError: Invalid date: 191...
29000e900ffb743b29d41fa752fc4da5f470e1b8
3,055
import html def __make_sliders(no, f): """Create dynamic sliders for a specific field""" style = {'width':'20%', 'display': 'none'} return html.Div(id={'index': f'Slider_{no}', 'type':'slider'}, children=[__make_slider(no, i) for i in range(1,f+1)], style=style)
b4fb97042e22d06e903f77a13381f9323acacacf
3,056
def kurtosis(iterable, sample=False): """ Returns the degree of peakedness of the given list of values: > 0.0 => sharper peak around mean(list) = more infrequent, extreme values, < 0.0 => wider peak around mean(list), = 0.0 => normal distribution, = -3 => flat """ a = iterab...
ba53f2425de5ffbf6cff0724e7128953554c829b
3,057
def gen_data(shape, dtype, epsilon): """Generate data for testing the op.""" var = random_gaussian(shape, miu=1, sigma=0.3).astype(dtype) m = random_gaussian(shape, miu=1, sigma=0.3).astype(dtype) v = random_gaussian(shape, miu=1, sigma=0.3).astype(dtype) grad = random_gaussian(shape, miu=1, sigma=0...
75f790eda84ab2e718d504d26a303a6639775829
3,058
def factor_tmom_T1_RTN_60(df: pd.DataFrame): """ factor example """ factor = df['return'].rolling(60).sum() return factor
53b5700902bf409015f4e1c2063f741cea3736ee
3,059
def get_dataset_info(dataset_name='mnist'): """Method to return dataset information for a specific dataset_name. Args: dataset_name: a string representing the dataset to be loaded using tfds Returns: A dictionary of relevant information for the loaded dataset. """ ds_info = tfds.builder(dataset_nam...
b4e36c966a34a3eacd327484e8d88d54303c0ea8
3,060
def full_model(mode, hparams): """Make a clause search model including input pipeline. Args: mode: Either 'train' or 'eval'. hparams: Hyperparameters. See default_hparams for details. Returns: logits, labels Raises: ValueError: If the model returns badly shaped tensors. """ if hparams.us...
3ab3a089628f9460b9f1ae9800ec9003fdae5d17
3,061
def aggregatePredictions(df_pred, threshold=0.8): """ Aggregates probabilistic predictions, choosing the state with the largest probability, if it exceeds the threshold. :param pd.DataFrame df_pred: columns: state rows: instance values: float :param float threshold: :return pd.Series: ...
a5d8efbe24d45279e80ff461e900dd3ac4921659
3,062
import os def GetLocalInstanceConfig(local_instance_id): """Get the path of instance config. Args: local_instance_id: Integer of instance id. Return: String, path of cf runtime config. """ cfg_path = os.path.join(GetLocalInstanceRuntimeDir(local_instance_id), ...
4f550234a1defe41995af8fc4bea5e73c001e157
3,063
from typing import Any def is_input_element(obj: Any) -> bool: """ Returns True, if the given object is an :class:`.InputElement`, or a subclass of InputElement. """ return isinstance(obj, InputElement)
c3fbaea9588d40e2fa370aab32688c7e926bd265
3,064
def line_intersects_grid((x0,y0), (x1,y1), grid, grid_cell_size=1): """ Performs a line/grid intersection, finding the "super cover" of a line and seeing if any of the grid cells are occupied. The line runs between (x0,y0) and (x1,y1), and (0,0) is the top-left corner of the top-left grid ce...
f9710a61bcb101202295e50efb86800e855f00d5
3,065
def SimuGumbel(n, m, theta): """ # Gumbel copula Requires: n = number of variables to generate m = sample size theta = Gumbel copula parameter """ v = [np.random.uniform(0,1,m) for i in range(0,n)] X = levy_stable.rvs(alpha=1/theta, beta=1,scale=(np.cos(np.pi/(2*theta)))...
55eba3c327b99b0bd6157b61dff9d161feda0519
3,066
import math def Norm(x, y): """求一个二维向量模长""" return math.pow(math.pow(x, 2) + math.pow(y, 2), 0.5)
4c161ada3c446d996f6e33be602a9475948f5bf8
3,067
from typing import Optional from typing import Union from typing import Callable from typing import List def make_roi(ms_experiment: ms_experiment_type, tolerance: float, max_missing: int, min_length: int, min_intensity: float, multiple_match: str, targeted_mz: Optional[np.ndarray] = None, ...
f8b3edbe24091082d1d20af6fdd7875449716a43
3,068
def get_all_zcs_containers(session, start=None, limit=None, return_type=None, **kwargs): """ Retrieves details for all Zadara Container Services (ZCS) containers configured on the VPSA. :type session: zadarapy.session.Session :param session: A valid zadarapy.session.Sessi...
6d2d6ba7037323174d93d2191aef93c072bd0030
3,069
def jordan_wigner(n): """ Generates the Jordan-Wigner representation of the fermionic creation, annihilation, and Majorana operators for an n-mode system. The convention for the Majorana operators is as follows: c_j=aj^{dag}+aj c_{n+j}=i(aj^{dag}-aj) """ s = ket(2, 0) @ dag(k...
193a2b91f84e2789b46a8767900938bcac8f83f9
3,070
import logging def make_update(label: str, update_time: str, repeat: str, data: str, news: str) -> list[dict]: """Schedules an update with name 'label' to happen in 'interval' seconds. Updates saved covid data, news and repeats the update depending on the content of the respective parameters. Adds to glob...
d284d51695229005650eed58de10297ad200c8e4
3,071
def performTest(name, test): #{{{ """ Given a series of writes in `test', generate a format string and pass it to the vulnerable program. If the writes were successful without destroying any other memory locations, return True. Terminates after 2 seconds to handle infinite loops in libformatstr. ...
829e19dbb45cfcc1788365f1c3a5459209c42e5e
3,072
def readsignal_VEC(name , fa): """ Reads the time signal stored in the file var.txt and written in a single column format. Returns the signal into the single vector signal. fa is an instrumental amplification factor """ path = '../data/' channel = np.loadtxt(path + name + '.txt') ...
2365988aa8baf717f332a021e24c1a7ca6d24243
3,073
import os def extract_slide_texture_features(index, output_segment, slide_path, halo_roi_path, method_data): """Extract slide texture features Args: index (string): main index string output_segment (string): path to write result parquet slide_path (string): path to the whole slide ima...
25ed7ea09178217ffb5f082e38c58ee1441e68e3
3,074
import socket def connect(host="localhost", port=27450): """Connect to server.""" client = socket(AF_INET, SOCK_DGRAM) client.connect((host, port)) return client
c60bd35b75ee9b3b5aee898b0ee58b95562627c1
3,075
def is_coroutine_generator(obj): """ Returns whether the given `obj` is a coroutine generator created by an `async def` function, and can be used inside of an `async for` loop. Returns ------- is_coroutine_generator : `bool` """ if isinstance(obj, AsyncGeneratorType): code =...
fea1d344f32a0fffe7fe0bb344299e5fd54a6baa
3,076
def get_scheme(scheme_id): """ Retrieve the scheme dict identified by the supplied scheme ID Returns: An scheme dict """ for node in sd["nodes"]: if scheme_id == node["id"]: return node
41c4b30496656201c58563fd5cc3ab3abe7ecf95
3,077
def Axicon(phi, n1, x_shift, y_shift, Fin): """ Fout = Axicon(phi, n1, x_shift, y_shift, Fin) :ref:`Propagates the field through an axicon. <Axicon>` Args:: phi: top angle of the axicon in radians n1: refractive index of the axicon material x_shift, y_shift: shift from ...
a333d29c94e79bdee1ef17ceb3993b28f2e9bd5d
3,078
import urllib import types def addrAndNameToURI(addr, sname): """addrAndNameToURI(addr, sname) -> URI Create a valid corbaname URI from an address string and a stringified name""" # *** Note that this function does not properly check the address # string. It should raise InvalidAddress if the address lo...
fd54c23b4e3396b224341fa54c106e4523b55314
3,079
def blkdev_uname_to_taptype(uname): """Take a blkdev uname and return the blktap type.""" return parse_uname(uname)[1]
e7165a9bd987d4820ed5486a06a1ceceec9c5564
3,080
def detection_layer(inputs, n_classes, anchors, img_size, data_format): """Creates Yolo final detection layer. Detects boxes with respect to anchors. Args: inputs: Tensor input. n_classes: Number of labels. anchors: A list of anchor sizes. img_size: The input size of the mo...
85ada39e57c80eced3dbdc145759a1caa609607d
3,081
from operator import pos def create_position_tear_sheet(returns, positions, show_and_plot_top_pos=2, hide_positions=False, sector_mappings=None, transactions=None, estimate_intraday='infer', return_fig=False): """ Gen...
87338d6acb2852f9d45fa21cb4005c602cbfc909
3,082
import csv def statement_view(request, statement_id=None): """Send a CSV version of the statement with the given ``statement_id`` to the user's browser. """ statement = get_object_or_404( Statement, pk=statement_id, account__user=request.user) response = HttpResponse(mimetype='text/csv...
c5a475086ee4a75fa76efae9cdf7bd185c8aa78a
3,083
def get_proton_gamma(energy): """Returns relativistic gamma for protons.""" return energy / PROTON_MASS
049e92cf85824561a50f559ef54045865da2a69b
3,084
def demandNameItem(listDb,phrase2,mot): """ put database name of all items in string to insert in database listDb: list with datbase name of all items phrase2: string with database name of all items mot: database name of an item return a string with database name of all items separated with ',' ...
67af8c68f0ba7cd401067e07c5de1cd25de9e66c
3,085
def escape_yaml(data: str) -> str: """ Jinja2 фильтр для экранирования строк в yaml экранирует `$` """ return data.replace("$", "$$")
d1142af7447ad372e6b0df5848beb28e0dd84e68
3,086
def stokes_linear(theta): """Stokes vector for light polarized at angle theta from the horizontal plane.""" if np.isscalar(theta): return np.array([1, np.cos(2*theta), np.sin(2*theta), 0]) theta = np.asarray(theta) return np.array([np.ones_like(theta), np.cos(2*theta), ...
a35f342ee32cdf54e432ee52e1faefbfb3b24382
3,087
import re from datetime import datetime def validate_item_field(attr_value, attr_form): """ :param attr_value: item的属性 :param attr_form: item category的属性规则 :return: """ if not isinstance(attr_form, dict): return -1, {"error": "attr_form is not a dict."} required = attr_form.get('re...
ac4687b576bb29707f55a2cb4627dc67ff07b2fa
3,088
def display_instances(image, boxes, masks, ids, names, scores): """ take the image and results and apply the mask, box, and Label """ n_instances = boxes.shape[0] colors = random_colors(n_instances) if not n_instances: print('NO INSTANCES TO DISPLAY') else: assert boxes....
4268d08a7e413a0558e2b0386cbd184ffaba05ba
3,089
import json def read_squad_examples(input_file, is_training): """Read a SQuAD json file into a list of SquadExample.""" with tf.io.gfile.GFile(input_file, "r") as reader: input_data = json.load(reader)["data"] examples = [] for entry in input_data: for paragraph in entry["paragraphs"]: paragrap...
1c893c8f443bca9c707498650142ecd5262d619d
3,090
import os def load_gamma_telescope(): """https://archive.ics.uci.edu/ml/datasets/MAGIC+Gamma+Telescope""" url='https://archive.ics.uci.edu/ml/machine-learning-databases/magic/magic04.data' filepath = os.path.join(get_data_dir(), "magic04.data") maybe_download(filepath, url) data = pd.read_csv(file...
575636be935fb8a44a13b4fc418504315a90a83c
3,091
def qarange(start, end, step): """ Convert the cyclic measurement and control data into the required array :param start: :param end: :param step: :return: np.array """ if Decimal(str(end)) - Decimal(str(start)) < Decimal(str(step)) or step == 0: return [start] start_decimal =...
6e0331160f6501b4106c9e6379762f9c4bf87f1b
3,092
def get_default_render_layer(): """Returns the default render layer :return: """ return pm.ls(type='renderLayer')[0].defaultRenderLayer()
b134b52bf35a46c10460ab612b14fcea44895a45
3,093
def translation(shift): """Translation Matrix for 2D""" return np.asarray(planar.Affine.translation(shift)).reshape(3, 3)
2b77265545194cabfc44728dbc7c5c95d808da38
3,094
def pad(adjacency_matrices, size): """Pads adjacency matricies to the desired size This will pad the adjacency matricies to the specified size, appending zeros as required. The output adjacency matricies will all be of size 'size' x 'size'. Args: adjacency_matrices: The input list of adjac...
dc015eb4dd41dcf3f88ef6317dab2e3f57709453
3,095
def mapping_activities_from_log(log, name_of_activity): """ Returns mapping activities of activities. :param name_of_activity: :param log: :return: mapping """ mapping_activities = dict() unique_activities = unique_activities_from_log(log, name_of_activity) for index, activity in e...
82fc23f08e9ae3629c654a5c04bcfcecb76a8cb3
3,096
def pad(x, paddings, axes=None): """ Pads a tensor with zeroes along each of its dimensions. TODO: clean up slice / unslice used here Arguments: x: the tensor to be padded paddings: the length of the padding along each dimension. should be an array with the same length as x.axes. ...
484676f81ec2f394dbe5f58831b708b1794c4424
3,097
def labels_to_1hotmatrix(labels, dtype=int): """ Maps restricted growth string to a one-hot flag matrix. The input and the output are equivalent representations of a partition of a set of n elelements. labels: restricted growth string: n-vector with entries in {0,...,n-1}. The fi...
eef80548e340477bf6881d0d14e434e0ee2f44da
3,098
import select def recall(logits, target, topk=[1,5,10], typeN=8): """Compute top K recalls of a batch. Args: logits (B x max_entities, B x max_entities x max_rois): target (B x max_entities, B x max_entities x max_rois): topk: top k recalls to compute Returns: N: numb...
ea3ec996808e25566e5bd3dd33f1a56232e5ba7a
3,099