content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def conv_variance_scaling_initializer(in_channel, out_channel, kernel_size): """conv init""" fan_in = in_channel * kernel_size * kernel_size scale = 1.0 scale /= max(1., fan_in) stddev = (scale ** 0.5) / .87962566103423978 mu, sigma = 0, stddev weight = truncnorm(-2, 2, loc=mu, scale=sigma)....
925339a12e4f2e04c403ad8148145df0497da0da
449
def vgg8(**kwargs): """VGG 8-layer model (configuration "S") Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = VGG(cfg['S'], **kwargs) return model
61d9f2e98c68691c1ed26631220f447eef28ba11
450
def get_char_from_ascii(key_num): """Function that converts a character to an ascii code Parameters ---------- ascii_code : int Ascii code of character Returns ------- char : character character converted from ascii """ return chr(key_num)
79f6a5627805909a005d5921f4e9fe738fb09936
451
def start(): """ view for data entry for optimisation """ form = LocationForm() if form.validate_on_submit(): return optimise(form.data) return flask.render_template("start.html", title="Start", form=form)
caba5a4d20d544ed480bda4d4e4d4377880bbd40
453
def c_flag(opt, test_not=False): """ convert a test parameter into t if true for the Fortran build system """ if test_not: if opt: return "FALSE" else: return "TRUE" else: if opt: return "TRUE" else: return "FALSE"
cf78668ae19287822fba9946fa472187848e0084
455
def false_function(): """Sample function to test unit testing.""" return False
7823ac0f533c97544a8f73f73715bebb8e5b45cc
456
def broker_task_send(task_uuid, request, broker_point, reply_to=None): """Command to publish `primitives.Request` to customer Args: task_uuid(str): task identification request: Serialized request broker_point(gromozeka.BrokerPoint): reply_to(gromozeka.BrokerPoint): Returns:...
52b389982676f65547f10a2cd45ac225e6486673
457
import numpy def process_axis_labels(datadesc, blobs, offset=0): """Convert the raw axis label descriptions. Similar to LiveDataPanel._process_axis_labels, but is flexible in datadesc. """ CLASSIC = {'define': 'classic'} labels = {} titles = {} for size, axis in zip(reversed(datadesc['shap...
d0f880c69160b2a620affe7b1cfe8c7dda12d807
458
def _to_ranks_by_group(dat, group, formula, exclude_cols=[]): """ Covert predictors to ranks separately for each group for use in rank Lmer. Any columns not in the model formula or in exclude_cols will not be converted to ranks. Used by models.Lmer Args: dat (pd.DataFrame): dataframe of data ...
6cff465b0a1877d6594953dda75913dfb36a67ad
459
def list_scans(): """ :return: A JSON containing a list of: - Scan resource URL (eg. /scans/1) - Scan target - Scan status """ data = [] for scan_id, scan_info in SCANS.iteritems(): if scan_info is None: continue target_urls = scan_info.target_u...
60d5eb5c33c09ac6e35ffae2c10b6aca566c6027
461
def factor_list(f, *gens, **args): """ Compute a list of irreducible factors of ``f``. **Examples** >>> from sympy import factor_list >>> from sympy.abc import x, y >>> factor_list(2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y) (2, [(x + y, 1), (1 + x**2, 2)]) """ return _gen...
c13e503a631d3bfc5ead05dc8de8cc5243614241
462
import pickle import torch def all_gather(data): """ Run all_gather on arbitrary picklable data (not necessarily tensors) Args: data: any picklable object Returns: list[data]: list of data gathered from each rank """ world_size = dist.get_world_size() if world_size == 1: ...
9e89ed2f299f5de8dec55d5529478177d45c21fa
463
import torch def init_net(net, init_type='normal', init_gain=0.02, gpu_ids=()): """Initialize a network: 1. register CPU/GPU device (with multi-GPU support); 2. initialize the network weights Parameters: net (network) -- the network to be initialized init_type (str) -- the name of an i...
2ddeda15b84bca0b83a7b5b516c83f991cec44c7
464
def remove_from_group(group_name, nodes=None, nodes_by_col='SUID', edges=None, edges_by_col='SUID', network=None, base_url=DEFAULT_BASE_URL): """Remove the specified nodes and edges from the specified group. Args: group_name (str): Specifies the name used to identify the group ...
0f7ae3b161aa1b189be14973ddaa7a7a4fef4bbf
465
def filter_bank_2high(t, Nj, Nj_1, ac=2.0, bc=2.0): """ computes the filter bank for control points N_j, Nj_1 given the variable t :param t: data points on the real line R arranged in numpy array :param Nj: control point, Nj > Nj_1, integer :param Nj_1: control point, Nj > Nj_1, integer :param ...
a197cbd99ea4d2ce6fcf9c277cff3e634b539049
466
def as_public(): """Return requests session without authentication""" return BaseUrlSession()
d55cc3616c6910e88d99083cf4e530987c1d8d6c
468
def transform_real_2_sim(real_position): """ Transforms a position from the 'real' coordinate system to the 'sim' coordinate system. :param real_position: dictionary with 'x', 'y' and 'z' keys to floating point values :return: position in sim space as dictionary with 'x', 'y' and 'z' keys to floating po...
29b83be1f6f4e49f777e085db651e4f31d47c2e0
469
import torch def generate_tgt_mask(sz): """Generate a square mask for the sequence. The masked positions are filled with float('-inf'). Unmasked positions are filled with float(0.0). This function is a slight modification of the version in the PyTorch repository. Parameters ---------- ...
3fce5eb1cb852ca162fda58407c2cf81c1bdc849
470
def SceneAddPipeline(builder, pipeline): """This method is deprecated. Please switch to AddPipeline.""" return AddPipeline(builder, pipeline)
f220a53ad13923b1f00d208f59e575926e5b7fa2
471
def SynthesizeUserId(email): """Return a synthetic user ID from an email address. Note that this is not the same user ID found in the production system. Args: email: An email address. Returns: A string userid derived from the email address. """ user_id_digest = _MD5_FUNC(email.lower()).digest() ...
fb3f81e37decaa941857ac575a5fd034f92a2324
472
import torch def compute_jacobian(fn, x0: torch.Tensor, bs: int): """ Computes the Jacobian matrix of the given function at x0, using vector-Jacobian products """ input_shape = x0.shape assert len(input_shape) == 3 dim = x0.numel() eye = torch.eye(dim, dtype=x0.dtype, device=x0.device) ...
c184fd03abea440e27bdd27bb1105778e7bde4b6
474
import math def pixel_distance(A, B): """ In 9th grade I sat in geometry class wondering "when then hell am I ever going to use this?"...today is that day. Return the distance between two pixels """ (col_A, row_A) = A (col_B, row_B) = B return math.sqrt(math.pow(col_B - col_A, 2) + m...
64853c44400428c8040ae47d1cc2cca17aed0a5f
475
def word_ngrams(s, n=3, token_fn=tokens.on_whitespace): """ Word-level n-grams in a string By default, whitespace is assumed to be a word boundary. >>> ng.word_ngrams('This is not a test!') [('This', 'is', 'not'), ('is', 'not', 'a'), ('not', 'a', 'test!')] If the sequence'...
8be360785e38b8f427c509d63f5ecba3b6b2c020
476
def phosites_detail(text): """ create detail view output of phosphosites by accession. :param text: string of phos group ID :return: template """ results = browse_queries.browse_detail(text,'Phosphosite') table = browse_queries.phos_kin_query(text) # pass tables, results and style indic...
5f1b67fadda3eb1dfe86e7e996e65197ff1eca3a
477
def convert_to_np_arrays(X): """ Converts the input arrays to dense numpy arrays to allow the methods to work properly """ try: X = X.todense() except: pass X = np.array(X) if len(X.shape) > 2: X = reduce_shape(X) return X
68fdf6fd87df160e96acec5abb8af310886fccc2
478
def reduce_arr(arr): """ Return which elements on which axis are unique Args: arr (np.ndarray) : input array which to reduce to unique value Returns: reduced array(np.ndarray) : array with reduced data. data_axis (list) : the axises that have changing data. """ ndim = l...
d207876b820c7d7b30f8af6c302181620b00bf25
480
import torch def nll_lorentzian(preds, target, gamma): """ Isotropic lorentzian loss function :param preds: prediction values from NN of size [batch, particles, timesteps, (x,y,v_x,v_y)] :param target: target data of size [batch, particles, timesteps, (x,y,v_x,v_y)] :param gamma: The tensor for t...
24d6ea2c4b40bc0f8c27eebf0e402261d865836e
481
from pathlib import Path def get_archive(): """Ensure that the archive file exists and return its path. This is a function so the path can be made configurable in the future. Returns: :obj:`str`: The full local path to the archive file. """ filename = '/config/archive.txt' archfile =...
78abc493d7f256ebf53ec2cfeb9ab4f1d42b5c02
482
from typing import Sequence from typing import Callable from typing import List def _filter_unique_configs( configs: Sequence[ProblemConfig], filter_fn: Callable[[ProblemConfig], bool] = lambda _: True, ) -> List[ProblemConfig]: # pytype: disable=annotation-type-mismatch """Filters a list of problem_config...
98481fa9991726f3ba4253fb132f7f7e3cb2a420
483
def convert_units(str): """ Convert some string with binary prefix to int bytes""" unit = ''.join(ele for ele in str if not ele.isdigit()).strip().lower() return int(''.join(ele for ele in str if ele.isdigit()))*{ "b": 1, "B": 1, "k": 2**10, "kb": 2**10, "m": 2**20, ...
a9de044090bfd4311a27dbbf373361e7d88a1e06
484
def match_piecewise(candidates: set, symbol: str, sep: str='::') -> set: """ Match the requested symbol reverse piecewise (split on ``::``) against the candidates. This allows you to under-specify the base namespace so that ``"MyClass"`` can match ``my_namespace::MyClass`` Args: candidates: set...
1c6d7240365ef22f753aa4195cfb5e879fc453e0
485
def is_kube_version_supported(kube_version, min_version=None, max_version=None): """Check if the k8s version is supported by the application. :param kube_version: the running or target k8s version :param min_version (optional): minimum k8s version supported by the app :param max_version (optional): max...
f08a5e5eb9ac9928e2e08ddddd6d30db90e8c868
486
def chebi(name=None, identifier=None): """Build a ChEBI abundance node. :rtype: Abundance """ return Abundance(namespace='CHEBI', name=name, identifier=identifier)
bbe8cf217a545f2818d7957b01d7bbaf0a2cc6d2
487
def get_group(request): """returns all the groups in database """ group_id = request.matchdict.get('id', -1) group = Group.query.filter_by(id=group_id).first() return [ { 'id': group.id, 'name': group.name, 'thumbnail_full_path': group.thumbna...
6d53d8969ecebb882c6626b128a72f24dafa6997
488
def create_histogram(path_to_image, target_path=''): """ creates a histogram of a given image and either shows or saves a plot Args: path_to_image: path to the image target_path: if given, saves a plot, otherwise (if empty) shows the plot Returns: the histogram plot """ ...
cb68b5f8bd55120d4f720020b092af02b727a6ba
489
def task_6_list_all_supplier_countries(cur) -> list: """ List all supplier countries Args: cur: psycopg cursor Returns: 29 records """ cur.execute("""SELECT country FROM suppliers""") return cur.fetchall()
a3d8af1eb2948ebc01e408265d20b0055f1a0504
490
def _energy_to_length_factor(e_unit, l_unit): """ Convert the units of Planck's constant and speed of light :param e_unit: :type e_unit: str :param l_unit: :type l_unit: str :return: c,h """ dest_h_u = ug.parse_units('%s s' % e_unit) dest_c_u = ug.parse_units('%s/s' % l_unit) ...
23e1dbfac7265ff1df4cf62e3609f91d5e327a35
491
def kev_to_wavelength(kev): """Calculate the wavelength from kev""" lamda = 12.3984 / kev #keV to Angstrom return lamda
cfb3126e56bc0890dd8cf2caa50a240b380dad56
492
def _convert_rde_to_1_0_format(rde_data: dict) -> dict: """Convert defined entity to RDE 1.0. :param DefEntity rde_data: Defined entity dictionary :return: converted defined entity :rtype: dict """ new_rde = common_models.DefEntity(**rde_data) new_native_entity: AbstractNativeEntity = rde_u...
931bc93c7326a4640892a3876885fcc19430bbe1
493
def additive_symbols(tokens, base_url): """``additive-symbols`` descriptor validation.""" results = [] for part in split_on_comma(tokens): result = pad(remove_whitespace(part), base_url) if result is None: return if results and results[-1][0] <= result[0]: ret...
346eae19c5d4d936d0ad7f2cdba2191943cc7bca
494
def _index_list(key_or_list, direction=None): """Helper to generate a list of (key, direction) pairs. Takes such a list, or a single key, or a single key and direction. """ if direction is not None: return [(key_or_list, direction)] else: if isinstance(key_or_list, string_type): ...
e32ddb70a10d52e1f2595cac9cb99c0381b9a3e4
496
def CalculateOSNames(os_name, os_variants): """Calculates all the names an OS can be called, according to its variants. @type os_name: string @param os_name: base name of the os @type os_variants: list or None @param os_variants: list of supported variants @rtype: list @return: list of valid names """...
5689ed7da55cec929045e95344c60e7a06af711d
498
def c4x(c: Circuit, c0: int, c1: int, c2: int, c3: int, t: int) -> Circuit: """A macro of 4-controlled X gate""" return c.h[t].c4z(c0, c1, c2, c3, t).h[t]
89b5d790a70448a1d46452554ab234e113e63c59
500
def pad(data, pad_id): """ Pad all lists in data to the same length. """ width = max(len(d) for d in data) return [d + [pad_id] * (width - len(d)) for d in data]
a0951f4332879600d25c061cf1c553126d6df8d2
501
from netharn import util def draw_boxes_on_image(img, boxes, color='blue', thickness=1, box_format=None): """ Example: >>> from netharn import util >>> img = np.zeros((10, 10, 3), dtype=np.uint8) >>> color = 'blue' >>> thickness = 1 >>> boxes = ...
3c4a3b547d39bac940ea9f6999a98f2db62f938b
502
def _select_random_features(feature_list, amount): """Selects a given amount of random features from the feature list""" set_size = len(feature_list) -1 random_features = [] for i in range(amount): while(True): random_feature = feature_list[randint(0, set_size)] if(random...
e281bfa75e153aa195119f84777f41db9d5e806c
503
def matrixop_inp_matr(): """ Функция возвращает матрицу, введённую пользователем с клавиатуры. Returns ------- a : [[float, float, ...], [float, float, ...], ...] Матрица, введенная пользователем """ while True: try: m = int(input('Сколько буде...
c373af0c7493ff32f919d903644b2031cc51162c
504
def dropannotation(annotation_list): """ Drop out the annotation contained in annotation_list """ target = "" for c in annotation_list: if not c == "#": target += c else: return target return target
9f4a695eaf80f79dce943f2f91926d9c823483b6
506
def do_associate_latest_edit(parser, token): """ AssociateLatestEdit """ try: tag, node = token.split_contents() except ValueError: raise template.TemplateSyntaxError, "%r tag requires one argument" % token.contents.split()[0] return AssociateLatestEdit(node)
75cf36f1cccd2191636f3cb603503c6655ae0c67
507
def open_monitoring_db(dbhost, dbuser, dbpass, database): """ Open MySQL monitoring DB """ try: conn = MySQLdb.connect(host=dbhost, user=dbuser, passwd=dbpass, db=database) except MySQLdb.Error, err: print "Error %d: %s" % (err.args[0], err.args[1]) ...
db33430d20c7c72c7428d85f161d1c186404dc05
508
def matdiff(matrix1,matrix2,figsize=None,cmap=None): """ display the difference between two real matrices, alongside this plot this difference on a log- colour scale (if diff!=0) """ if not figsize: figsize = defaults['figsize'] if not cmap: cmap = defaults['cmap'] _matdiff = matrix1-matrix2 f, (ax1, ax2)...
fb11354f7388e461ac49bcac942a9b6a2b5528d4
509
def _tokens_by_class_of(tokens): """Generates lookup table of tokens in each class.""" out = defaultdict(set) for token, token_classes in tokens.items(): for token_class in token_classes: out[token_class].add(token) return out
c335582785e4c8a5b82232849ccee579f5ab068f
510
def load_mnist_dataset(shape=(-1, 784), path='data'): """Load the original mnist. Automatically download MNIST dataset and return the training, validation and test set with 50000, 10000 and 10000 digit images respectively. Parameters ---------- shape : tuple The shape of digit images (the ...
856a758864ef85b4a5bea742dd90a49e997ad9b7
511
def EntryToSlaveName(entry): """Produces slave name from the slaves config dict.""" name = entry.get('slavename') or entry.get('hostname') if 'subdir' in entry: return '%s#%s' % (name, entry['subdir']) return name
258e68c683592c21ea8111f21ba3ab648ddb8c57
513
def is_symmetric_re(root: TreeNode) -> bool: """Check if a binary tree is a mirror of itself (symmetric around its center).""" if not root: return False def is_mirror(t1, t2): if not t1 and not t2: return True if not t1 or not t2: return False return...
b2d0450a881e0a1748575baa8d7c6ae1224fb3c0
515
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up paperless from a config entry.""" hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True
8793312f379c510e3420e785eba6ce4db3f098c7
516
def azimuthal_average(image, center=None, stddev=True, binsize=0.5, interpnan=False): """ Modified based on https://github.com/keflavich/image_tools/blob/master/image_tools/radialprofile.py Calculate the azimuthally averaged radial profile. Parameters: imgae (numpy ndarray): 2-D image ...
3ebadf5fa93cc93e6a5b14327392a2fdecb5d266
517
import re def find_assign(data, varname): """Finds a substring that looks like an assignment. :param data: Source to search in. :param varname: Name of the variable for which an assignment should be found. """ ASSIGN_RE = re.compile(BASE_ASSIGN_PATTERN.format(varname)) if...
99e1d1436307dd278fbef8b7e52c4d2eedd6d657
518
import requests def remove(token: str, server: str="http://localhost:8080/remove", params: dict=None) -> int: """ Removes the data associated with the token. :param token: the token to download the data for :type token: str :param server: the URL of the server to upload to :type server: str ...
a74f2c5f84ae064a909df717917f4589b59eacb5
519
import requests def get_pending_surveys_batch_number(batch_no): """ Gets batch number for the shared survey :param batch_no: Shared survey batch number :type batch_no: str :raises ApiError: Raised when party returns api error :return: list share surveys """ bound_logger = logger.bind(...
ee31c28c393e29b6cd628aefc38d2ca948c7cdaf
520
def make_sign_initializer(random_sign_init): """Random sign intitializer for HyperBatchEnsemble layers.""" if random_sign_init > 0: return ed.initializers.RandomSign(random_sign_init) else: return tf.keras.initializers.RandomNormal( mean=1.0, stddev=-random_sign_init)
e8ea2653ef9c7c5ba447921d7def990e29a7c9b2
522
def _parallel_predict_proba(ensemble, X, idx, results): """ Compute predictions of SCM estimators """ for k in idx: res = ensemble.estimators[k].predict(X[:, ensemble.estim_features[k]]) results = results + res return results
b0a2d5c59318506202c9331597ab2a11eacb7a32
523
def compute_FP_TP_Probs(Ycorr, Xcorr, Probs, is_tumor, evaluation_mask, Isolated_Tumor_Cells, level): """Generates true positive and false positive stats for the analyzed image Args: Probs: list of the Probabilities of the detected lesions Xcorr: list of X-coordinates of the lesions ...
434abefeba56201d20799b1f00783bc77dcbf2c0
524
def make_sentences(text, src): """ Builds a list of dictionaries, one for each sentence resulting from the sentence parser. The dictionary schema is {"src": src, "label": 0, "sentence": sent} Substitutions are made for the identified tokens. Args: text (str): text to process ...
5da57a55f76a3d4d29f1d0ed681b8597e958b9d0
525
def read_test_case(file_path): """ reads one test case from file. returns contents of test case Parameters ---------- file_path : str the path of the test case file to read. Returns ------- list a list of contents of the test case. """ file = open(file_path...
6a87ff979d0b1ccf838ebef56401a48760711541
526
import torch def accuracy4batch(model, testloader, criterion): """save a model checkpoint INPUT: model: pytorch nn model. testloader: DataLoader. test data set criterion: criterion. loss criterion device: torch.device. device on which model/data is based OUTPUT: accuracy: float in ...
2005984b94f17bf601034953bbea3dca6542143d
528
def pick_an_experiment(i): """ Input: { (repo_uoa) - experiment repository name (defaults to hackathon_local_repo, but can be overridden by '*') (extra_tags) - extra tags to filter } Output: { return - return code = ...
97671967ab153173280a142143fb4b07892c92fa
530
import uuid import pathlib def run(args, image: str) -> str: """ Run docker image and mount user-provided folder with C++ files. Parameters ---------- args : dict-like User provided arguments parsed by argparse.ArgumentParser instance. image : str Name of image from which cont...
eba0ab0e93543410ae4a2375ec80a9015168d303
531
def get_top_design_list(oProject): """ Returns a list of the names of the top-level designs. Parameters ---------- oProject : pywin32 COMObject The HFSS project in which the operation will be performed. designname : str Name of the design to insert. Returns ------- ...
6610cd68a90e20fd916a2ec13b54f37a75c31050
532
from typing import Union from typing import Dict from typing import Any def chi01(param_name: Union[str, None], yval: float, **kwargs) -> Dict[str, Any]: """Plot defaults for sweep_plotting.chi01""" kwargs["xlabel"] = kwargs.get("xlabel") or recast_name(param_name) kwargs["ylabel"] = kwargs.get("ylabel") ...
58e5d09152062a9307526bd953ff91832ef80321
533
def cstring(*args, **kwargs): """Return a colored string. Parameters ---------- args : iterable of str bold : bool color : str, {'HEADER', 'LIGHTBLUE', 'LIGHTGREEN', 'WARNING', 'FAIL', 'ENDC', 'BOLD', 'UNDERLINE' 'BLACK', 'RED', 'GREEN', 'YELLOW', 'BLUE', 'MA...
69bc81f0e9267743297bec25b2fccc8f2da2c89d
534
from . import routes # Import routes def create_app(): """Construct the core application.""" app = Flask(__name__, instance_relative_config=False) app.config.from_object('config.Config') db.init_app(app) admin.init_app(app) basic_auth.init_app(app) with app.app_context(): db.cre...
28bfb75626a5be05aef21404956f6ef7adf8f80a
535
def bytes_index(x: bytes, sub: bytes, start: int, end: int) -> int: """Where is the first location of a subsequence within a given slice of a bytes object? Compiling bytes.index compiles this function, when sub is a bytes object. This function is only intended to be executed in this compiled form. Arg...
3a78e029a96d27fdf5b5cdea397b21f57ca939d9
536
def uniform(minimum, maximum, shape=[]): """uniform(minimum, maximum, shape=[]) returns array of given shape of random reals in given range""" if shape == []: shape = None return mt.uniform(minimum, maximum, shape)
882cd915cb7dfec0e1b6857f99ecefe876ae21b1
538
def unquote_to_bytes(urlencoded_string): """Replace %xx escapes by their single-character equivalent, using the “iso-8859-1” encoding to decode all 8-bit values. """ return bytes( unquote(urlencoded_string, encoding='iso-8859-1'), encoding='iso-8859-1' )
60216d170381e356520c283f308add08754c987d
539
def qualifiedName(item): """Return the full name of an item, including any projects that it's in. If the item does not have a name, return ``None``. XXX: Doesn't include folders. """ names = [] # Note: assumes that the presence of a single null name in the parent tree # means that the item...
2a1cdc9e15897c104f63793041ed2d4fe91e383d
540
def assign_columns_of_sector_levels(df_load): """ Add additional column capturing the sector level in the two columns :param df_load: df with at least on sector column :param ambiguous_sector_assignment: if there are sectors that can be assigned to multiple sector lengths (e.g., for government or ho...
4dd60267702f21e103cab18293975a5f62c934d2
541
def add_matrices(matrix_a, matrix_b): """Add two n x n matrices """ return [[x + y for x, y in zip(matrix_a[i], matrix_b[i])] for i in range(len(matrix_a))]
a9f6a857892872fde584b6884e59a8b624220061
542
import scipy def no_pretrain_inner_speech(subject): """This function aims at training a model without pretraining by training only on the inner speech condition of a sigle subject :return: metric history for every of the n k-folds :rtype: list of dictonaries """ ###### DATA data, events =...
daa08a8ea88838b8e66c3fc23c2b6997bfdff490
543
from typing import Any def build_put_big_decimal_negative_decimal_request(**kwargs: Any) -> HttpRequest: """Put big decimal value -99999999.99. See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder into your code flow. :keyword json: The default value is -99...
e41800c8bee6a9c4874b3625ed374c9514c81fe7
544
def make_subplots( rows=1, cols=1, shared_xaxes=False, shared_yaxes=False, start_cell="top-left", print_grid=False, horizontal_spacing=None, vertical_spacing=None, subplot_titles=None, column_widths=None, row_heights=None, specs=None, insets=None, column_titles=No...
1119aba8e9b9f35b18959f765e4528e2d065a5b8
545
from re import T def op_table(name): """Get the symbol `name' as an int8_t[].""" return gdb.parse_and_eval("&'" + name + "'").cast(T('int8_t').pointer())
8266128cb1bf59b9d71d7dabb7d002ff22e41192
546
from typing import Dict from typing import Any def nf_masks_to_neurof_dict(binary_masks: np.ndarray, dataset_name: str) -> Dict[str, Any]: """ Take as input a tensor of binary mask and produces dict format for neurofinder Args: binary_masks: 3d ndarray (components x dimension 1 x dimension 2) ...
daee76afc56e6e0da0939530a49f4a77b4c1d5f6
547
def get_domain_machine_command(): """Retrieves a collection of Machines that have communicated to or from a given domain address. Returns: (str, dict, dict). Human readable, context, raw response """ headers = ['ID', 'ComputerDNSName', 'OSPlatform', 'LastIPAddress', 'LastExternalIPAddress', 'H...
0e614d15abd3e99408d4a3d7a93ecc49dba694ad
548
import copy from functools import reduce def flatten_dict(source_dict, name_delimiter='_', inner_name=False): """ flatten nest dict Parameters ---------- source_dict : nest dict name_delimiter : flatten name delimiter(non-use when inner_name is True) inner_name : False, use innermost name...
fbba7666c25f5eafd47642b8308a486e25cdc6f9
549
def matrix_multiply(A, B): """ Multiply two matrices A and B. :param A: the right matrix :param B: the left matrix :return: A * B """ # define m and n for the matrix as well as l, the connecting dimension between A and B m, l, n = len(A), len(A[0]), len(B[0]) # initialize an all zeros ...
3cd551ea87d9f925654a4153106c2fe87e33fa8c
550
def hard_light(image1, image2): """ Superimposes two videos on top of each other using the Hard Light algorithm :rtype: :py:class:`~PIL.Image.Image` """ image1.load() image2.load() return image1._new(image1.im.chop_hard_light(image2.im))
dcfd25a83f142c2d42c38a787569001af6f6bfc9
551
def show(*actors, **options): """ Create on the fly an instance of class ``Plotter`` and show the object(s) provided. Allowed input objects types are: ``str``, ``Mesh``, ``Volume``, ``Picture``, ``Assembly`` ``vtkPolyData``, ``vtkActor``, ``vtkActor2D``, ``vtkImageActor``, ``vtkAssembly`` or ``...
e95c9bbd325e8e6da6ee4f33ca861496c3048bd3
552
from typing import List def get_followup_question_list(intent: str) -> List[str]: """ Get all imported followup questions for this intent as a list * `intent`: name-parameter of the yml-section with which the followup questions were imported **Returns:** None if no followup questions are known for ...
00581a497d4e09670edaa0d44870a2a0d7589ada
554
from typing import Tuple def event_train_test_split( evs: np.ndarray, n_evs: int, train_split: float, random_seed: int=1 ) -> Tuple[np.ndarray, np.ndarray]: """[summary] Args: n_evs (int): [description] train_split (float): [description] random_seed (int, optional): [descripti...
69deb28d199fc8636ed45a90630a69753f4c1066
555
def get_cd(wcs, n=1): """ Get the value of the change in world coordinate per pixel across a linear axis. Defaults to wcs.wcs.cd if present. Does not support rotated headers (e.g., with nonzero CDm_n where m!=n) """ if hasattr(wcs.wcs,'cd'): if wcs.wcs.cd[n-1,n-1] != 0: re...
9b31c81a1a5e87efeb201ffef7f8f65f846fe0b7
556
def mock_clear(): """Clear MOCK_DATA_HEAP""" MOCK_DATA_HEAP.clear() return ""
96212726db3f1e29ac4da54e62df70cb89ba1f2e
557
from datetime import datetime def cls_merge_type(classification): """ classification type이 2가지일 때 합쳐주는 함수 Parameters ---------- classification: cls classification 리스트 Returns ------- list of cls 변환된 classification 리스트 """ cls_type = {'instant' if cls.get('instant_...
e6a59f45adecdc21acb81f6890ac79cfaa93b4d6
558
def duplicate_detector(gate_orders: list[tuple[str]]) -> int: """Detects any schematics that have an identical combination of gates.""" difference = len(gate_orders) - len(list(set(gate_orders))) # List - list with no duplicates return difference
e439a106abc0ff21bfe9773b3185d35b5bf05aa0
559
def permutations(x): """Return all permutations of x""" def fn(i): if i == len(x): ans.append(x.copy()) for k in range(i, len(x)): x[i], x[k] = x[k], x[i] fn(i+1) x[i], x[k] = x[k], x[i] ans = [] fn(0) return ans
691c701e1ac17da5dabb0fc3fe607ff68ac8fcdc
560
def encode(model, text, out_file=None, topic_priors=None, prior_weight=1.0): """ Perform text-to-image encoding. Parameters ---------- model : :obj:`gclda.model.Model` Model object needed for decoding. text : :obj:`str` or :obj:`list` Text to encode into an image. out_file :...
941745be7b84c3af9d7f7e62cb2d93fabc3b22c1
562
def clean_string(s: str) -> str: """Cleans and returns an input string >>> clean_string(" xYz ") 'XYZ' """ return str(s).strip().upper()
c97281505492ded5b9167076312959c5eee41a6c
563
import collections def get_unique_region_cov_df(unique_region_dict, fuzzer_names): """Returns a DataFrame where the two columns are fuzzers and the number of unique regions covered.""" fuzzers = collections.defaultdict(int) for region in unique_region_dict: for fuzzer in unique_region_dict[reg...
923227fb804549252bf51cd94e65180c3f8564e8
564
def display_generation_hit_results(hit_info, hit_results): """Displays the results of a generation HIT Parameters ---------- hit_info : GenerationHITInfo HITInfo object storing information regarding the HIT hit_results : GenerationResults HIT results object storing the results ...
649cf05d0ee3a87032993fd05fc120162c7f8d2b
566
def XOR(v1, v2): """ XOR operation element by element from 2 lists :param v1: [1, 0, 1, 0, 0, 1] :param v2: [1, 1, 0, 0, 1, 1] :return: [0, 1, 1, 0, 1, 0] """ return [a ^ b for a, b in zip(v1, v2)]
e3b94b35ccf4e1dd99cc51f32c70f96c5fe99795
568