content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def GetTevType(tev): """ Return the type of the specified event (TEV_... constants) @param tev: event number """ return idaapi.get_tev_type(tev)
bad1e7696297629563eed7c64b76ce6789248d0a
3,600,400
def create_hparams(hparams=None): """Create model hyperparameters. Parse nondefault from given string.""" hparams = Hparams() return hparams
ee6c3132a9554ea94da41d4d4fb9b95e6b97999c
3,600,401
def extract_categorical_cols_hot(df, cols): """Create HOT encoded feature columns for the dataframe, based on the defined categorical columns.""" all_col_features = [] for col in cols: print(f"Now extracting features from column: '{col}'.") col_features = pd.get_dummies(df[col], prefix=col, ...
b541bd5a80a4fae2fb976280cfb990f01fc3a251
3,600,402
import functools def expand_args(function): """Expand arguments passed inside the CallContext object. Converts internal method signature 'method(ctx)' to whatever is appropriate to the client code. Args: function: Async function expecting CallContext as a last argument. Returns: A...
72e7de46684b2c02d958fad7f9ded71e653bb811
3,600,403
from app import create_app import logging def export(context, output_format='json', quiet=False): """ Export swagger.json content """ # set logging level to ERROR to avoid [INFO] messages in result logging.getLogger().setLevel(logging.ERROR) app = create_app(flask_config_name='testing') ...
7ee8683ea17895213d38345815adda5b568c700e
3,600,404
def derivative_of_binary_cross_entropy_loss_function(y_predicted, y_true): """ Use the derivative of the binary cross entropy (BCE) loss function. Parameters ---------- y_predicted : ndarray The predicted output of the model. y_true : ndarray The actual output value. Return...
7803c852f794ab9eae165c639bfb7a04cd0c1028
3,600,405
def AUC(answers, scores): """ Compute the `AUC <https://en.wikipedia.org/wiki/Area_under_the_curve_(pharmacokinetics)>`_. @param answers expected answers 0 (false), 1 (true) @param scores score obtained for class 1 @return number """ ab = list(zip(answers,...
477cdf2a7b51352dd728465c883dae9cb4ab6e9a
3,600,406
def search_geojson_gui(m=None): """Generates a tool GUI template using ipywidgets. Args: m (leafmap.Map, optional): The leaflet Map object. Defaults to None. Returns: ipywidgets: The tool GUI widget. """ widget_width = "250px" padding = "0px 0px 0px 5px" # upper, right, bottom...
366db5020f55ad51d2803a61991343e30d781d86
3,600,407
def plot_gradient_descent_path(perceptron, X, y): """Plot the gradient descent path of a trained perceptron. Args: perceptron ([class]): trained perceptron. Expects instance of perceptron.Perceptron. X ([ndarray]): the data (instaces x features) y ([array]): labels for ...
4a2deb99e4475d33b785b81b9894dbc88f8e4798
3,600,408
import six import types import functools def skip(reason): """ Defines a decorator to unconditionally skip a test. Called by conditional skip wrappers to skip tests that require optional dependencies. This is needed because nose doesn't respect unittest skip_if decorators. Based on: https://stack...
5862e8122cdad2566ba2f925f37b64c7593cab82
3,600,409
def factorial(number: int) -> int: """ Calculating factorial of a number using prime decomposition method """ prime: list = [True] * (number + 1) result: int = 1 for i in range (2, number + 1): if prime[i]: j: int = 2 * i while j <= number: p...
2d6a85daa1b324fe419c3e5aecfbfc8373cffdcf
3,600,410
def analytical_sol(x): """ function to draw analytical solution """ return -1 / 300 * np.exp(-x)
4a3daab1cd15b769d4556a1482e50746bb5ac659
3,600,411
from typing import Optional from typing import Dict from typing import Any from typing import List def process_args( *, dataset: Optional[Dataset] = None, sibling: Optional[str] = None, url: Optional[str] = None, endpoint: Optional[str] = None, ) -> Dict[str, Any]: """Process common arguments,...
cedd78169920f06a3dce0bd801eec0ff9604a0ed
3,600,412
from typing import Any def read_search_terms( db: Session = Depends(deps.get_db), skip: int = 0, limit: int = 100 ) -> Any: """ Retrieve search terms. """ search_terms = crud.search_term.get_multi(db=db, skip=skip, limit=limit) return search_terms
aba424374f19d48722a168770dc616b3dceb1d65
3,600,413
def create_da_bry_std(filename, eta_rho=10, xi_rho=10, s_rho=1, bry=4, reftime=default_epoch, clobber=False, cdl=None, title="My BRY STD"): """ Create a boundaries standard deviation file Parameters ---------- filename : string name and path of fi...
b884e2eb4a5ec35b8c1a57fa10c086fdf9fb8127
3,600,414
def cluster_jaxpr_by_cost(jaxpr: Jaxpr, layer_num: int, eps: float, costs, cost_criteria): """Clusters the jaxpr by cost.""" layer_num = int(layer_num) length = len(jaxpr.eqns) non_trivial, input_sizes, compute_costs = costs compute_costs_avg = compute_costs.sum() / layer_n...
6104ddd251e34b0e9ad847292e9b6d597994c082
3,600,415
def MPI_ApplicationsTeam(mintime = 5, maxtime = 20, cap = 60): """ Returns a costOfLaborValue object suitable to attach to a sim or other event Time is in hours """ timeDist = LogNormalValue(maxtime, mintime, cap) costDist = LogNormalValue(240, 115, 390) team = costOfLaborValue("Applications...
2a1bcf41a9f91a5d42eb69ab5e60cc2061a137b9
3,600,416
import os def filestructure_snapshot(path): """ Create a filestructure snapshot by returning the paths of all files inside a path. """ paths = [] for dirpath, _dirnames, filenames in os.walk(path): paths.append(dirpath) for filename in filenames: paths.append(os.path.jo...
36a0e5ee6f05c74e75bdeca7609702735127411e
3,600,417
def KK_RC59(w, Rs, R_values, t_values): """ Kramers-Kronig Function: -RC- Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) """ return ( Rs + (R_values[0] / (1 + w * 1j * t_values[0])) + (R_values[1] / (1 + w * 1j * t_values[1])) + (R_values[2] / (...
45e91818fa256f127af237cb9374c4fa8d5ad03c
3,600,418
def flirtMatrixToSform(flirtMat, srcImage, refImage): """Converts the given ``FLIRT`` transformation matrix into a transformation from the source image voxel coordinate system to the reference image world coordinate system. To construct a transformation from source image voxel coordinates into refe...
d6cc963154dff8e334d67102bbcd3594776054db
3,600,419
import torch def device_count(): """Returns the number of GPUs available.""" if is_available(): return torch._C._cuda_getDeviceCount() else: return 0
8aab80cb1da63f4726fc23cea685a82a0f7652af
3,600,420
def api_failed(response, endpoint, exit_on_error=True): """ Check if api request failed Can raise exception """ if 200 <= response.status_code < 300: return False if exit_on_error: raise Exception("Status code {0} calling {1}".format( response.status_code, endpoint...
6a9d803444c4be09806eb6c5b588e1e04062c431
3,600,421
def select_field(X, cols=None, single_dimension=False): """ Select columns from a pandas DataFrame Args: X (pandas DataFrame): input data cols (array-like): list of columns to select single_dimension (bool): reduce data to one dimension if only one column i...
4f80af3621af5e0c622f2c880e88d95a6e93034e
3,600,422
from pathlib import Path from typing import Optional from typing import Iterable from typing import Callable def import_images( *, input_directory: Path, origin: Optional[RawImageUploadSession] = None, builders: Optional[Iterable[Callable]] = None, recurse_subdirectories: bool = True, ) -> Importe...
eaa270f1cf479fd7b60628d8b50c2057d1dd6b8e
3,600,423
from pydantic import BaseModel # noqa: E0611 def get_model_reference( model_name: str ) -> BaseModel: """Return a reference to the class of a chosen model. Note that this is different from get_model(), which returns an instance of a model. The reference, returned by this function, is a class before ...
6505952b32f55af087cdb98784fa14ab244720e8
3,600,424
from typing import Optional def get_subnet(subnet_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetSubnetResult: """ This data source provides details about a specific Subnet resource in Oracle Cloud Infrastructure Core service. Gets the specified subne...
b23a29f521a03f25bc423edc92b8ebdd0778a9bf
3,600,425
import time async def html(request): """Return HTML content and a custom header.""" content = "<b>HTML OK</b>" headers = {'x-time': f"{time.time()}"} return HttpResponse(content, headers=headers)
fd7cc43333db94dd25d2d9cefeac74b2cbe86db6
3,600,426
def KaimingUniformInitializer(out_dim=-1, in_dim=-2, param=0.): """Returns an initializer for random uniform Kaiming-scaled coefficients.""" return ScaledInitializer( out_dim, in_dim, 2.0 / jnp.sqrt(1 + param**2), 'fan_in', 'uniform')
d991d0300caec11684df44a2ccb3aec160138c80
3,600,427
def reactions_block(rxn_param_dct, comments=None): """ Writes the reaction block of the mechanism file :param rxn_param_dct: dct containing the reaction parameters :type rxn_param_dct: dct {rxn:params} :return total_rxn_str: str containing the reaction block :rtype: str """ ...
d7a3a4cc7d5857a063712e69fc0fe17e62aa7e30
3,600,428
def run_fdr_ranking_labeled( scores: pd.Series, target: pd.Series, decoy_ratio: float, rule_of_succession: bool, monotonic: bool, ): """Runs an FDR ranking for a list of scores with a separate target/decoy flag. Returns calculated FDRs for both targets and decoys.""" fdr_map = score_to_f...
638c57337615048725d27173985926a9738b018c
3,600,429
import logging def compute_mean_average_precision(logits, labels, suffix='', suffix_separator='_', return_per_class_ap=False): """Computes mean average precision for multi-label classification. Args: logits: Numpy array of shape [num_examp...
637be28b7042dcae8f2a65b5afc00e92136c649c
3,600,430
import json def transfer_json_string_to_dict(json_str): """把可能是json的字符串转为json字典""" try: if isinstance(json_str, bytes): # bytes转str json_str = json_str.decode('utf-8') # str转dict return json.loads(json_str) elif isinstance(json_str, str): ...
fde4335ff321592bd3141bd9f6017296a14c449d
3,600,431
def create_item(item_name: str = None, item_quantity: int = None, item_unit: str = None, item_date_added=None, item_category=None): """ :param item_name: :param item_quantity: :param item_unit: :param item_date_added: :param item_category :return: """ #TODO: Create bett...
7c8585202c3772eb01f2fd4523c7d797b303c660
3,600,432
def count_non_variant(genotypes): """Count variants with no non-reference alleles. Parameters ---------- genotypes : array_like An array of shape (n_variants, n_samples, ploidy) where each element of the array is an integer corresponding to an allele index (-1 = missing, 0 = re...
2f6c2ea4b570f7219c6d6d1778d12ac68c520724
3,600,433
import json def set_timeline_item_pype_tag(timeline_item, data=None): """ Set openpype track item tag to input timeline_item. Attributes: trackItem (resolve.TimelineItem): resolve api object Returns: dict: json loaded data """ data = data or dict() # get available openpy...
d014da05f7b0082f99f2ac8c2a92b8c75aad02b5
3,600,434
import json def GetRecentCompletedBuilds(master_name, builder_name, http_client): """Returns a sorted list of recent completed builds for the given builder. Sorted by completed time, newer builds at beginning of the returned list. """ data = { 'name': master_name } response_json = DownloadJsonData(_M...
6479eb57c8d3f0ad5e95eee2f572c273c62cf091
3,600,435
def gce(cred): """ :returns: list [{'region': str, 'timestamp': int, 'nodes': list}] """ result = list() project_id = cryptotool.decrypt_scalr(app.crypto_key, cred['project_id']) key = _gce_key(cred) conn, http = _gce_conn(cred, key=key) request = conn.zones().list(project=proje...
67355a9d79c1a41f8a62df0a494aae8e2dc022e9
3,600,436
from re import A def findElemArray2D(x, arr2d): """ :param x: a scalar :param arr2d: a 2-dimensional numpy ndarray or matrix Returns a tuple of arrays (rVec, cVec), where the corresponding elements in each are the rows and cols where arr2d[r,c] == x. Returns [] if x not in arr2d. \n Exam...
991abbf4ecd511878dd85a6d9318922468d74426
3,600,437
def calculate_unc_in_ext_coeff(Nsamples): """Calculates the uncertainty in each extinction coefficient given the uncertainty in x parameter (Section 5.3 of Schlafly et al. 2016)""" arr = np.zeros((Nsamples, 13)) for i, x in enumerate(0.02*np.random.randn(Nsamples)): arr[i, :] = calculate_ext_coeffs(...
f8154c3ba0bdffc93e233bf54863eab568ad8bce
3,600,438
def get_pathless_file_size(data_file): """ Takes an open file-like object, gets its end location (in bytes), and returns it as a measure of the file size. Traditionally, one would use a systems-call to get the size of a file (using the `os` module). But `TemporaryFileWrapper`s do not feature a ...
df1edfa6cb7b97c6abbdb2252b7dd8d505931768
3,600,439
import requests import time def youtube(string): """Download new videos from a YouTube playlist""" db = utils.db()['db'] query = utils.db()['query'] operations = utils.db()['operations'] apikey = utils.config('api_key') playlistid = utils.config('playlist_id') # https://developers.google.com/youtube/v3/docs/p...
822c67ef56b864200fc0c7f3215e6cdf877b7009
3,600,440
def find_xss_script(url, **kwargs): """ parse the URL for the given XSS payload """ data = urlparse.urlparse(url) payload_parser = {"path": 2, "query": 4, "fragment": 5} if data[payload_parser["fragment"]] is not "" or None: retval = "{}{}".format( data[payload_parser["query"...
fd8a54a7f6ba6cd3a0e35caec481cfc12e512026
3,600,441
import collections def _make_repolist(c, path): """turn the repo log into a history input: pathname to the repository output: dictionary containing the history """ ## logging.info('processing {}'.format(item)) with c.cd(path): result = c.run('hg log -v', hide=True) data = resu...
5c3d27bcfd52f8b0656d5bf770ce83b0fcbdf5d0
3,600,442
def EspDB(): """Return an instance of `SNPDB` configured to search the Exome Sequencing Project's(ESP) database""" return SNPDB('ESP')
3691240f2dc8cdc16fa31e70c501d354c05c2198
3,600,443
import os import random def init_program(args, _for="logreg"): """ Initialize the program either for feature extraction or for evaluation. Also checks if all the args are valid. """ assert _for in ["ft-extract", "logreg", "results"] # load the config file cfg = get_default_cfg(args.model,...
daeb7a574aa6b611198fd2afb1d1e128731dfd67
3,600,444
def svn_proplist_invoke_receiver2(*args): """svn_proplist_invoke_receiver2(svn_proplist_receiver2_t _obj, void * baton, char const * path, apr_hash_t prop_hash, apr_array_header_t inherited_props, apr_pool_t scratch_pool) -> svn_error_t""" return _client.svn_proplist_invoke_receiver2(*args)
98aca1a3d47be403c36da410387bcd2b9f9668b3
3,600,445
def fizz_buzz_one( start, end ): """ Note: This method returns a long string not a list. """ fizzbuzz = '' # range is NOT inclusive of the 2nd number, so add 1 to include it. # range(1,4) > 1,2,3. range(1, 4 + 1) > 1,2,3,4. for i in range(start,end+1): if i%3 == 0: fizzbuzz += "f...
9000ed93629bff15a74171565f562eee29814dd0
3,600,446
import torch def test_CenteredParameter_fit(): """Tests fitting a model with probflow.parameters.CenteredParameter""" class MyModel(Model): def __init__(self, di, do): self.w = CenteredParameter([di, do], center_by="column") def __call__(self, x): return Bernoulli(tor...
5ac9be9dc00e3ffce5743308431fa041a3dfaeaa
3,600,447
def max_coupling(v1_probs, v2_probs): """max_coupling as described in Jacob's chapter 3 notes. """ ncolors = len(v1_probs) # compute overlap pmf overlap = np.min([v1_probs, v2_probs], axis=0) overlap_size = np.sum(overlap) overlap_size = np.min([1.0, overlap_size]) # protect from roundi...
e2a40ca74602dc80e342613794de309d82b4aaed
3,600,448
async def revision_logs(request: Request): """Retrieve the revision log as a JSONL stream. It contains the revision timestamp and content, and the associated Tatoeba sentence ids. """ current_user = request.session.get('id', 1) if current_user == 1: return JSONResponse( dict...
725d72b0e46a8c2d5c788d35342c972d9eaab0bf
3,600,449
import logging import pprint def apply_change_list(exploration_id, change_list): """Applies a changelist to a pristine exploration and returns the result. Each entry in change_list is a dict that represents an ExplorationChange object. Returns: the resulting exploration domain object. """ ...
8fd43550ac0f50111ff467bc079c279027db055e
3,600,450
from functools import reduce import operator def factorial(n): """Calculate n factorial""" return reduce(operator.mul, range(2, n+1), 1)
a58e0aad4e3a8baf06bbd1a6929a3aab2ab4e66e
3,600,451
from shapely.wkt import loads from shapely.geometry import LineString def plot(n, margin=None, ax=None, geomap=True, projection=None, bus_colors='cadetblue', bus_alpha=1, bus_sizes=2e-2, bus_cmap=None, line_colors='rosybrown', link_colors='darkseagreen', transformer_colors='orange', ...
ccc9590b21978c257a2a9ba0b076604de5052454
3,600,452
def logo_2bridged(fusion1, fusion2, positivities, half12_positive, half21_positive): """Create a Type 2, MISA, or negative Type 2 logo: yellow connector cycle interconnected with red and blue.""" styles = [('solid' if positive else 'dashed') for positive in positivities] tips = [('normal' if positive else '...
e8e91397392315b578f61a00ac6165cb5129d29c
3,600,453
import random def make_colors(num, seed=1, ctype=1): """Return `num` number of unique colors in a list, where colors are [r,g,b] lists.""" rand = random.Random(seed) colors = [] while len(colors) < num: colors.append(list(hex_to_rgb(random_unique_color(colors, ...
0f4ff3e4ff5deb8ee3a83700eaca6d0ea4206914
3,600,454
def fromstring(html, base_url=None, parser=None, **kw): """ Parse the html, returning a single element/document. This tries to minimally parse the chunk of text, without knowing if it is a fragment or a document. base_url will set the document's base_url attribute (and the tree's docinfo.URL) ...
72a1f63772240954353ed467009533201b949c22
3,600,455
import os def favicon(): """ Return the favorite icon """ return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico', mimetype='image/vnd.microsoft.icon')
b5359f6538fba35ef7d41568717d961fd772ad60
3,600,456
def freq_saturation(truth,output): """ #provides saturation value - how many total notes did our model predict #requires notes array be of value 0-32 ~~~~ ARGUMENTS ~~~~ - truth : np.array - should be values 0-32 notes array - true note values - output : np.array - shoul...
d8a684cf51163041837289be87ce5edd0b32ac84
3,600,457
import argparse import time def parse_input(): """ Sets up the required input arguments and parses them """ parser = argparse.ArgumentParser() parser.add_argument('log_file', help='CSV file of log data') parser.add_argument('-e, --n_epochs', dest='n_epochs', help='number of tr...
3d701c6a91312ee597d8d25149ffdf2f6a0ea8cc
3,600,458
def _get_best_checkpoint(checkpoint_dir, latest_filename=None): """Find the filename of the best checkpoint file. Args: checkpoint_dir: Directory where the variables were saved. latest_filename: Optional name for the checkpoint state file that contains the best checkpoint filenames....
0f6302f227e4ad99a9491de9792f335d3c3a9737
3,600,459
def packagePath(): """Returns the root directory of the simulator package""" return rospkg.RosPack().get_path(PACKAGE_NAME)
5e718d5aa7c6ae75cf86daf4a896bb0a99cc375e
3,600,460
from typing import Optional from typing import Tuple from typing import Match import re def is_conversion_err(error: Exception) -> Optional[Tuple[str, int]]: """Check if error is caused by generic conversion error. Return a tuple of the converter type and parameter name if True, otherwise return None. ...
2e53420bb8a5715c75ee30a549453f40202d4ff7
3,600,461
import random def preenche_posicao_aleatoria(t): """list -> list Esta funcao recebe uma lista do tipo tabuleiro e preenche uma posicao livre (escolhida aleatoriamente) com um dos numeros 2 e 4, de acordo com as probabilidades ja indicadas""" x=tabuleiro_posicoes_vazias(t) v=x[int(random()*(len(x)-1))]...
362367b7a3e66a44d6aeece5e9242bedf688b196
3,600,462
def txt_file_to_list(genomes_txt): """ Read ids from a one column file to a list Args: genomes_txt:str: Path to file with the ids. """ with open(genomes_txt, 'r') as fin: genomes_list = [line.strip() for line in fin] return genomes_list
f79874dfbcb6a2a71be87b180e80513d480fcc8e
3,600,463
import typing def group(**kwargs) -> typing.Callable[[typing.Any], commands.Group]: """ Decorates a coroutine to make it into a command group name: str The name of the command. callback: coroutine The coroutine that is executed when the command is called. help: str The lon...
75154cc603b863c8039d923167fe4de125266036
3,600,464
def cubic_lattice( a, b, c, spacing ): """ Generate a cubic lattice. Args: a (Int): Number of lattice repeat units along x. b (Int): Number of lattice repeat units along y. c (Int): Number of lattice repeat units along z. spacing (Float): Distance bet...
d2fd739a5f5c8ff4bc792146da385bbdecb12cee
3,600,465
def decode(ciphertext, key1, key2): """ Decode the ciphertext with the 2 keys """ plaintext = '' for b in bytes_from_hex(ciphertext): plaintext += chr(b ^ key1) key1 = (key1 + key2) % 256 return plaintext
7f5311e8f794342e187490eb8281290e0cfeee96
3,600,466
def test_maxsize_none(): """Unlimited Caching.""" ac = AnyCache(maxsize=None) @ac.anycache() def myfunc(posarg, kwarg=3): # count the number of calls myfunc.callcount += 1 return posarg + kwarg myfunc.callcount = 0 eq_(myfunc(4, 2), 6) size1 = ac.size n = 5 ...
8ad07fe9af411b78b132bee73182fcb32a4b0ec7
3,600,467
def get_next_or_last_broadcast(tmp_date): """Возвращает дату следующего эфира, если он есть. Если нет, то дату последнего эфира :param: tmp_date - исходная дата :return: ближайшая дата """ select_min = db.func.min(Broadcast.date) # Выбор минимального where_next = Broadcast.date >= tmp_date # ...
172853d085e9f2b8c63c0673aa5d25384e9c3a85
3,600,468
def config1(): """Example config file""" config = r''' ! the following is a config file for 3 pulses and some custom ! data pulse: type = gauss, t_FWHM = 1.8, E_0 = 1.0, w_L = 0.2, & & oct_shape = flattop, ftrt = 0.2, oct_lambda_a = 100, & & oct_increase_factor = 10 * id = 1, t_0 = 0, oc...
703475289e053a061857cb5b72dda304c5f70ce6
3,600,469
def get_auth_backend(): """Returns the sole authentication backend.""" backends = auth.get_backends() if len(backends) != 1: raise ImproperlyConfigured("Expected exactly 1 backend (found {})".format(len(backends))) return backends[0]
248cd45ed6e90e7037c7e4640a5df47ce5258d94
3,600,470
import lark from typing import Callable def compile_func_call(func, compile_arg, ops, tree): """ Returns lambda that call func from results of compiled functions of tree.children """ sig = signature(func) #TODO: 2 types of leafs (Token) handling: # 1-st - find it in ops and return functio...
be34b0f9af0385378d5d0fb6eed8fb4bc98c9093
3,600,471
def cvSetImageIOFunctions(*args): """ cvSetImageIOFunctions(CvLoadImageFunc _load_image, CvLoadImageMFunc _load_image_m, CvSaveImageFunc _save_image, CvShowImageFunc _show_image) -> int """ return _cv.cvSetImageIOFunctions(*args)
7d2e97348af035f827109e01246f1a5b70e1f2f4
3,600,472
def make_gene_dictionary( celltype_df, bulk_df, disp_min=0.5, bulk_min=1e-5, bulk_max=0.01, remove_mito=True, ): """ Finds highly variable genes across cell types and checks for expression thresholds within each bulk separately, returns a dictionary of...
ff71476fec80799f42abccd4c558c4e1d40b7f94
3,600,473
def oxfordcomma(listed, condition): """Format a list into a sentance""" listed = [f"'{str(entry)}'" for entry in listed] if len(listed) == 0: return "" if len(listed) == 1: return listed[0] if len(listed) == 2: return f"{listed[0]} {condition} {listed[1]}" return f"{', '....
c64ec05df35ccb6169363bf276fb874e61525c85
3,600,474
from typing import Dict from typing import Set from typing import Optional def _get_out_of_sample_arms( model: ModelBridge, generator_runs_dict: Dict[str, GeneratorRun], metric_names: Set[str], fixed_features: Optional[ObservationFeatures] = None, ) -> Dict[str, Dict[str, PlotOutOfSampleArm]]: """...
d7467ac51d691eb2060953454018b3542e6f84d7
3,600,475
def get_all_user_attributes(client): """ This command gets all users, chooses the first then, run a second get command that returns all the users attributes """ user_id = "" attributes = [] all_users = client.get_all_users() users_list = all_users.get("searchRecords") if isinstance(...
d92ccab35a61bec96e34d3ca4a4035d7688001a0
3,600,476
import logging def make_jump(slope_angle, start_pos, approach_len, takeoff_angle, fall_height, plot=False): """Returns a set of surfaces and output values that define the equivalent fall height jump design and the skier's flight trajectory. Parameters ========== slope_angle : float ...
eef01dad24400532b625f61db495ca9d87b512be
3,600,477
def get_backlog_msg(self, chan, msg): """get message from backlog""" if len(msg) < 1: msg = "1" try: back = int(msg) + 0 except: back = 1 if chan in self.backlog and len(self.backlog[chan]) >= back: return self.backlog[chan][0 - back] else: raise Backlog...
1040827e0a3eab8696f27feaae54b2bb73c1532a
3,600,478
def filter_red_pen(rgb, output_type="bool"): """ Create a mask to filter out red pen marks from a slide. Args: rgb: RGB image as a NumPy array. output_type: Type of array to return (bool, float, or uint8). Returns: NumPy array representing the mask. """ t = Time() result ...
0dd656841d4b23007de55199ba801bdfb423df72
3,600,479
def kmeans_plus_plus(X: np.ndarray, k: int, random_state: int = 42) -> np.ndarray: """ Create cluster centroids using the k-means++ algorithm. Args: X: The dataset to be used for centroid initialization. k: The desired number of clusters for which centroids are requi...
4766b6d2dfa17593c6d05e8e7342c9bf389caab3
3,600,480
import requests def logout(): """revoke current user's access_token and reset login session""" access_token = login_session.get('access_token', None) for key in [ 'access_token', 'gplus_id', 'username', 'email', 'picture' ]: if key in login_session: del login_session[k...
bb44650e27d0a68d8113323c313728af9f5836a2
3,600,481
def setup_loading(): """Establish how recordings are loaded.""" # Indicates if all information on a recording is loaded in bulk, or as needed load_all = True # If load_all is True, indicates what is loaded in bulk # Should be a subset of ["signals", "spatial", "units"] to_load = ["signals"] ...
8855e02ba57a79c72861796de3d0c3178232c2a8
3,600,482
from exploits import add_exploit, connect_exploits def process_exploits(filename=None): """ Process Nexpose exploits.xml file into the database """ log("Processing Nexpose exploits file: %s ..." % filename) try: exploits = etree.parse(filename) except etree.ParseError, e: rai...
07242bd7308e28659d53285c39405bc6dd3159f0
3,600,483
def retrieve_single_movie(imdb): """Return a specific movie based on IMDB id.""" if request.method == 'GET': movie = movie_collection.read(imdb) if movie: return jsonify(movie) elif request.method == 'PUT': movie = movie_collection.update(request.json) if movie...
378b8e249d44dfd1ecaa80e8f65753f5ae2f5eb4
3,600,484
import six import binascii def _read_ssh_ed25519_pubkey(keydata): """ Parse a Ed25519 SSH public key from a string into a raw public key. :param keydata: The public Ed25519 SSH key to parse. :type keydata: unicode :returns: The raw public keys (32 bytes). :rtype: binary """ if type(k...
ddeaa76388fce9b5700fd71d5f19130dfebb51fe
3,600,485
def migration(transactional_db): """ This fixture returns a helper object to test Django data migrations. The fixture returns an object with two methods; - `before` to initialize db to the state before the migration under test - `after` to execute the migration and bring db to the state after the ...
49df867892dbbd3fb89a49d8ddaac24190beb7d9
3,600,486
def read_memory(library, session, space, offset, width, extended=False): """Reads in an 8-bit, 16-bit, 32-bit, or 64-bit value from the specified memory space and offset. Corresponds to viIn* functions of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logi...
6b1926375a3d14276c2e9f266b10bdd683fca2bf
3,600,487
def dense_rank(x, na_option = "keep"): """Return the dense rank. This method of ranking returns values ranging from 1 to the number of unique entries. Ties are all given the same ranking. Example: >>> dense_rank(pd.Series([1,3,3,5])) 0 1.0 1 2.0 2 2.0 ...
53bd64e112741f20c0e62f44ba7f5bcf8cdb2f83
3,600,488
def rsqrt_decay(step, warmup_steps): """Decay based on the reciprocal of the step square root.""" return 1.0 / sqrt(max(step, warmup_steps))
3d4849e62d9dc789d907501fa8776645e9d554d7
3,600,489
import json import requests def delete_bulk_by_externalIds(tibody=None): """ Makes a POST request to delete multiple TI indicators by external IDs. Currently support 'Azure Sentinel' targetProduct only. :param tibody: Body of the POST request. :returns: json response. :raises ValueError: raises a...
cdce121d9bf8b04f1177e56f52ccc92547c0cf99
3,600,490
def contact_parent(): """ Contact parent. """ # Create an empty error. error = None # Create a form object. contact_form = ContactForm() # Select all the staff and tutors. contact_form.user.choices = [ (parent.parent_id, parent.get_full_name()) for parent in select_parents(...
50826ee8d73465bc98074adcead97ecc8718fe7e
3,600,491
def erbb2_context(): """Create test fixture for ERBB2 Gene Context.""" return { "id": "normalize.gene:ERBB2", "type": "GeneDescriptor", "label": "ERBB2", "gene": { "gene_id": "hgnc:3430", "type": "Gene" }, "xrefs": [ "ncbigene:2...
0a4ef3bf47d8ac622d6c2778bd33199f5da2a747
3,600,492
def get_repository(): """Return the shared instance of the package repository. Returns: PackageRepository: The package repository. """ global _repository if not _repository: _repository = PackageRepository() return _repository
ace15568a0b3876fc7eb3fda28ce465346696051
3,600,493
import time def delete_cluster(redshift_client): """ Deleting the redshift cluster :param redshift_client: a redshift client instance :return: True if cluster deleted successfully. """ cluster_identifier = config.get('DWH', 'DWH_CLUSTER_IDENTIFIER') if(len(redshift_client.describe_cluste...
8cd5b7181a92de0ddc37953ad14cebe45ddc1b7c
3,600,494
import _winreg as wreg import sys import os def get_home_dir(require_writable=False): """Return the 'home' directory, as a unicode string. * First, check for frozen env in case of py2exe * Otherwise, defer to os.path.expanduser('~') See stdlib docs for how this is determined. $HOME is first ...
eab2d7dee103eec722c518c82a84eeb13ea38acb
3,600,495
def create_nested_multiple(N,masses,semimajor_axes,eccentricities,inclinations,arguments_of_pericentre,longitudes_of_ascending_node): """ N is number of bodies masses should be N-sized array the other arguments should be (N-1)-sized arrays """ N_bodies = N N_binaries = N-1 particles = ...
21bf038744a77913115596880ff80ff613f0fde2
3,600,496
import codecs def decode_rot13(cipher: str): """Used to decode rot13""" return codecs.decode(cipher, 'rot_13')
3c20989614c6691c74294a93268745bbaccecf42
3,600,497
def parse_rec(filename,imgpath): """ Parse a PASCAL VOC xml file """ objects = [] # 还需要同时打开图像,读入图像大小 img = cv2.imread(imgpath) height, width, channels = img.shape with open(filename, "r", encoding='utf-8') as f1: dataread = f1.readlines() for annotation in dataread: o...
6dcf1af2728fcf8759b16d60dd53abadbefdb982
3,600,498
def _urlencode(params): """ A version of Python's urllib.urlencode() function that can operate on unicode strings. The parameters are first case to UTF-8 encoded strings and then encoded as per normal. """ return url_encode([i for i in _generate_smart_str(params)])
6aa5cfbfd3106cadcdb7db52489e9bd470bb288e
3,600,499