content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os def get_config(args): """ Merge local configuration files with arguments addedd from commandline. Args: args (obj): Argparse argument object. Returns: obj: :class:`ConfigParser.SafeConfigParser` instance. """ config = ConfigParser.SafeConfigParser() config.read(...
0d7b672e734a26819f198a890c55574be0a88374
71,800
def plot_cluster_centroids(vpc, colorful_bars='blue', order=None, sortby=None, n_extra_ax=0, plot_counts=True, **kws): """class centroids pcolormesh""" # TODO: split massive func pn, extra = vpc.clus_centroids(order=order, sortby=sortby) order_out = ...
f6ee594df802bd1a034793ebfe40c40d5e43a773
71,801
def is_supported_django_language(language_code): """ Return whether a language code is supported. """ language_code2 = language_code.split("-")[0] # e.g. if fr-ca is not supported fallback to fr return language_code in LANGUAGES_DICT or language_code2 in LANGUAGES_DICT
a19a0c7c7198b01c3fca0fe41c4e540db0a02504
71,802
def share_snapshot_instance_delete(context, snapshot_instance_id): """Delete a share snapshot instance.""" return IMPL.share_snapshot_instance_delete(context, snapshot_instance_id)
af3342e9e4fe441413374eddfdf59e16e7b5c785
71,803
def distance_between_points(start, destination): """ This function finds the distance between the two points, start and destination using Pythagoras' Theorem. """ startX = start[0] startY = start[1] destinationX = destination[0] destinationY = destination[1] diffX = destinationX - st...
35896eb26395161837d198474971f8776b7b0e48
71,804
def get_layout_from_cli( layout: str, cols: int, ) -> QtWidgets.QLayout: """ Return a correct layout object based on user input. Parameters ---------- layout : str String representation of the layout. cols : int Number of columns to use for the grid layout. Returns ...
0296608b42d3166d478ff848a37d95d99b72bb78
71,805
def multiarray_sort(arr, srt=[0]): """ Sort rows of a two-dimensional array for a given hierarchy of rows. Parameters ---------- arr : ndarray A two-dimensional numpy array. srt : list List specifying in which order of rows to sort. Returns ------- ndarray ...
1b21206bffe07f836b4ab4d239ea68047f676752
71,806
import six def tar(target, sources, compression=None): """This adds or creates a tarball with the provided folder. If the tar exists it will append, otherwise it will create the tar. The folder specified will be added to the root of the tar. For example, if fs.tar('tar.tar', '/foo') is called, it ...
c63054211d5dda51f72be04b2ecd0c711460855a
71,807
def count_total_molecules(filename: str) -> int: """Counts number of molecules in a file""" total = 0 ifs = oechem.oemolistream(filename) mol = oechem.OEMol() while oechem.OEReadMolecule(ifs, mol): total += 1 return total
70fc84e2a1ef55c2f2f3d92b154979cd58a82d4a
71,808
def focal_lossIII(prediction_tensor, target_tensor, weights, gamma=2., epsilon=0.00001, ): """Compute loss function. Args: prediction_tensor: A float tensor of shape [batch_size, num_anchors, num_classes] rep...
1f08c50768705530fc9b54f4455f1673c5d96dba
71,809
import scipy def expected_loss(high_sim, low_sim, negative_sample_rate, push_tail=True): """ UMAP's true loss function, numpy implementation :param high_sim: np.array or scipy.sparse.coo_matrix high-dimensional similarities :param low_sim: np.array low-dimensional similarities :param negative_samp...
1cd14c08996d88ff7350023a52ac93eba2192bf9
71,810
def train_model() -> StructureModel: """ This Bayesian Model structure will be used in all tests, and all fixtures will adhere to this structure. Cause-only nodes: [d, e] Effect-only nodes: [a, c] Cause / Effect nodes: [b] d ↙ ↓ ↘ a ← b → c ↑ ↗ ...
d677b9e9bbf943b148f9cf7643fd56cd998c025d
71,811
def invoice(): """Create invoice.""" class CompanyInfo(object): """ Temporary hardcoded params until flask login is implemented. Then user info will contain these attributes. """ name = "" logo = url_for('static', filename="images/logo.png") job = "" ...
dd7ace0de4c4e3504a35cb3f75efb6c480c289fe
71,812
from operator import mul def persistence(n: int) -> int: """ >>> persistence(243) 2 """ a = list(str(n)) count = 0 while len(a) != 1: a = list(str(mul(map(int, a)))) count = count + 1 return count
d99efee2f40f10c95baec2c6233523a98a31ff1e
71,813
import re def validate_str(input,validate): """ This function returns true or false if the strings pass regexp validation. Validate format: substrname: "^\w{5,10}$", Validates that the string matches the regexp. """ if not re.match(validate,input) == None: # If the validation returned something, return...
400fd1cd7b4fa297f5916e80a39d7ef668deab1c
71,814
def searches(from_, to, hashids=None, device=None, query_name=None, source=None, total_hits=None, tz=None, format_=None, **opts): """ Return number of searches in a period grouped by date. """ query_params = parse_query_params({ 'from': from_, 'to': to, 'hashid': has...
a3f2d05f32839f8aba3fcfbcbc1c2170ca067c2e
71,815
def load_randomly_augmented_audio(path, sample_rate=16000, tempo_range=(0.85, 1.15), gain_range=(-6, 8)): """ Picks tempo and gain uniformly, applies it to the utterance by using sox utility. Returns the augmented utterance. """ low_tempo, high_tempo = tempo_range ...
9a4e60baee40723a81efb1aa88682e32482f6d48
71,816
from datetime import datetime def readable_timestamp(stamp): """ :param stamp: A floating point number representing the POSIX file timestamp. :return: A short human-readable string representation of the timestamp. """ if date.fromtimestamp(stamp) == date.today(): return str(datetime.fromti...
734f623052bed8171829307a07c82ad76760a9c3
71,817
import os def setup_augmented_formula(n_constr, constraints): """ Create a DIMACS file with the original formula augmented with LDPC XOR constraints. :param n_constr: The number of XORs to be actually added to the original formula. It may be less or equal to the number of ...
b027c0a0e941f57873378dd4a55546a1ddcb924f
71,818
def mention(sourceURL, targetURL, vouchDomain=None): """Process the Webmention of the targetURL from the sourceURL. To verify that the sourceURL has indeed referenced our targetURL we run findMentions() at it and scan the resulting href list. """ app.logger.info('discovering Webmention endpoint for...
3e36cf5aeca306061478cfadd2c7d6f755c233b3
71,819
def create_lasso_model(**kwargs): """Create lasso regression :return: id_model, unique str """ model = linear_model.Lasso(**kwargs) id_model = _save_estimator(model=model, type_model="lasso_regression") return id_model
fd789d828794d5eb515a274bb702f87ec92cc7f8
71,820
def legacy_network_info(network_model): """ Return the legacy network_info representation of the network_model """ def get_ip(ip): if not ip: return None return ip['address'] def fixed_ip_dict(ip, subnet): if ip['version'] == 4: netmask = str(subnet.a...
ad220b501b56e9c760c758dec4c9c03f8cd9394a
71,821
def load_ensemble_models(name, limit=100): """Load serialized ensemble model objects that share the same name from table.""" response = DB_HANDLE.get_records(table_name=ENSEMBLE_MODEL_TABLE_NAME, offset=0, limit=limit, options={"expression": "(name='" + str(name) + "')"}) ...
133371cd7f5ae77af65b40164f5e58895e13d2b0
71,822
def r_precision(r): """Score is precision after all relevant documents have been retrieved Relevance is binary (nonzero is relevant). >>> r = [0, 0, 1] >>> r_precision(r) 0.33333333333333331 >>> r = [0, 1, 0] >>> r_precision(r) 0.5 >>> r = [1, 0, 0] >>> r_precision(r) 1.0 ...
aec9362023a8cf146a869f081cf25e9589e3bee1
71,823
def pieChartInfoPlus(trips): """ Calculates the total distance per activity mode Parameters ---------- trips : dict - Semantic information (nested) Returns ------- list(data): list - labels of the activity modes list(data.values()): list - distance per activity mode """ la...
ad0306b2561b01a33c509b2c454f464e9c6ff8a3
71,824
from typing import Any from typing import Optional from typing import Dict import json def json_dumps(data: Any, **kwargs: Optional[Dict[str, Any]]) -> str: """Safe serialization of a Python dictionary to JSON string representation using all known encoders. Parameters ---------- data : Any A e...
f1ad879d42dc28d4be38faa75fdc3193aba35e22
71,825
import os import subprocess def build_flags(library, type_, path): """Return separated build flags from pkg-config output""" pkg_config_path = [path] if "PKG_CONFIG_PATH" in os.environ: pkg_config_path.append(os.environ['PKG_CONFIG_PATH']) if "LIB_DIR" in os.environ: pkg_config_path.a...
2fc526d4cb2fe6ad12e47bc7abebbcd9dc32780b
71,826
def sample_maximizers_simple(model, count, num_discrete_points): """ Samples maximizers from the GP by sampling real values at each discrete point and finding the argmax :param model: gpflow model :param count: number of maximizers :param num_discrete_points: number of discrete points over input spa...
ccb9fbdcf7ef7526a0c83163ab748515ab001755
71,827
def test_cli_with_string_annotation(): """Test to ensure CLI's work correctly with string annotations""" @hug.cli() def test(value_1: 'The first value', value_2: 'The second value'=None): return True assert hug.test.cli(test, True)
b02395d3d0da48c7be600ce5b09e7fa822cda388
71,828
def sigma_exp(p, q): """ Returns score of an expansion/compression. (Kondrak 2002: 54) """ q1 = q[0] q2 = q[1] return C_exp - delta(p, q1) - delta(p, q2) - V(p) - max(V(q1), V(q2))
e96f547032adec1b099c305d0a18a93959f62128
71,829
def user_is_anonymous( user_name_or_id ): """ Determine if the user name or ID corresponds to the anonymous user. """ try: user_name_or_id = int(user_name_or_id) except: pass if type(user_name_or_id) in [str, unicode]: if user_name_or_id.lower() == "anonymous": ...
6687adec454df9bbc1c942d291a934dd63f7dae3
71,830
import logging def subinit4_initGenUnits(PATHS, PPdb, config): """Initializes the GenUnit instances. Returns two containers: 1) GenFleet, a Series of GenUnit idx : GenUnit instance 2) GenCos, a dictionary of generator company (str) : GenUnit indices* belonging to that gen co *Used to subset GenFleet and PPdb....
f4c74e5b06f91206769e865d87a15d00d46c63c5
71,831
def kalman_predict(density, motion, dt): """得到KF的预测(Density类):density:Density类的实例,motion:motionModel,dt:sampling time""" F = motion.F(density.x, dt)#F x = motion.f(density.x, dt)#xkk_1=F*xk_1 P = F @ density.P @ F.T + motion.Q(dt)#Pkk_1 = F*Pk_1*F'+Q return Density(x=x, P=P)
e5f4110a22b20b793eb5707658ada139911542f5
71,832
import socket def is_multicast(address): """Return ``True`` iff address is a multicast address. This function is used to eliminate retransmissions for confirmable messages sent to multicast addresses. :param address: A socket address as supported by the Python socket functions: i.e. a pair (...
4177933096f85c6c303fc8c1f491ce8848e8957d
71,833
def onestep_reachability(p_center, ssm, k_ff, l_mu, l_sigma, q_shape=None, k_fb=None, c_safety=1., a=None, b=None, t_z_gp=None): """ Overapproximate the reachable set of states under affine control law given a system of the form: x_{t+1} = \mathcal{N}(\...
5ae4ebd0aa2d30d5ff0cdf02bd09f2f29fa4c9d9
71,834
def pathname(question, aid="pathname", absolute=False, must_exist=False, **kwargs): """Asks user for pathname, returns path.""" parser = abspath if absolute else normpath validf = lambda p: exists(p) if must_exist else always_true p_func = partial(process, parser, validf) return ask(question, aid=ai...
db6de1a6f6fd6ae9ed7ee463dff7cf777ad232d3
71,835
def areDefined(names, dic): """ Return True if all keys that have "names" are defined and are not "None". """ key_list = dic.keys() names = toList(names) for aName in names: if aName not in key_list: return False if dic[aName] == None: return False else: return True
d601804ad5d6eeb1cbfd32e64cbc4a0452beb17a
71,836
def is_weekend(date): """ returns True if day is on a weekend """ date = hlp.strip_date(date) return FederalHoliday(date).weekend
20f981f3c4cc5629350b47057669b95698f17066
71,837
def get_num_tasks(path: str) -> int: """ Gets the number of tasks in a data CSV file. :param path: Path to a CSV file. :return: The number of tasks. """ return len(get_header(path)) - 1
f592fa3f4a220b6888e915d6407f6de64fd046e6
71,838
def backbone_indices(mgrph): """ heavy atoms and hydrogen atoms not connected to heavy atoms """ hv_idxs = heavy_atom_indices(mgrph) hy_idxs = tuple(idx for idx in hydrogen_atom_indices(mgrph) if all(idx > nidx and atom_symbol(mgrph, nidx) == 'H' for nidx in a...
3b75df66951a4c34416446c274b76ba2e76d89d1
71,839
import sys def list_group_users(client, profile, group_name, token=""): """ Lists all user from the specified group """ result = [] try: if token: response = client.list_users_in_group( UserPoolId=profile["user_pool_id"], GroupName=group_name, ...
9b8ceb202557361a4a004edc9e18245d610bf315
71,840
def get_users(session, giveaway_url): """Get users that entered the given giveaway The function will loop through different available pages of the users list :param session: SG object HTMLSession :param giveaway_url: :return: List of Strings (usernames) """ if giveaway_url[-1] != "/": ...
31e24b095b1d0058630e5e8cff2538363e10479b
71,841
def interest_submit(): """ """ if current_user is None: flash('You must be logged in to submit interests!', 'danger') return redirect(url_for('account.login', next=request.path)) form = SubmitForm(request.form) user_id = current_user.id if form.validate_on_submit(): nam...
5eece1116149fe1d7df291f9ff31881b41baf36f
71,842
def _dense_to_one_hot(labels, num_classes): """Convert class labels from scalars to one-hot vectors.""" num_labels = labels.shape[0] index_offset = np.arange(num_labels) * num_classes labels_one_hot = np.zeros( shape=(num_labels, num_classes), dtype=np.uint8 ) labels_one_hot.flat[index_offset + labels.r...
931a471d318ac43d43d37dced270b50bd53b2bce
71,843
def Intersect(*args): """Create intersection of regular expressions. >>> re = Intersect(Re("a"), Re("b"), Re("c")) """ args = _get_args(args) sz = len(args) if z3_debug(): _z3_assert(sz > 0, "At least one argument expected.") _z3_assert(all([is_re(a) for a in args]), "All argumen...
b4c630a041253f9f98aeca2a76fd4eaece3a18b4
71,844
import random def pick_one(episode_id): """ pick a random file from the passed episode. """ blip_cli=blip_uploader.Blip_CLI() blip_cli.debug = False xml_code = blip_cli.Get_VideoMeta(episode_id) blip_meta = blip_cli.Parse_VideoMeta(xml_code) ogvs = [] for content in blip_meta['c...
54dcba27e7b65f7112e20aac79bc6f9bdb48845b
71,845
import collections def update(dictionary, updateDict): """ Generic function for updating dictionaries :param dictionary: old dict object :param updateDict: new dict object :return: updated dict """ for k, v in updateDict.items(): if isinstance(v, collections.Mapping): d...
66ae8ea0e41c6e4794ee57d8e276059a983b6043
71,846
def gen_data(dtype1, dtype2, shape1, shape2): """generate valid test data for truncate_div""" input1 = random_gaussian(shape1).astype(dtype1) input2 = random_gaussian(shape2).astype(dtype2) input2 = np.where(input2 == 0, np.ones_like(input2), input2) expec...
5c332934fee1abc567a109a9c6855c5dd4be10d6
71,847
from typing import Callable from re import T import signal def retry(func: Callable[[], T]) -> T: """ Retry the function with 30 second timeouts until it works - I've observed the getFirefoxDriver() without this freeze once (out of hundreds of runs...) so adding this as a safety measure. """ ...
04fa11a36180d75509223c16eed3268871779e61
71,848
import time import torch import sys def train(train_loader, model, criterion, optimizer, epoch, opt): """one epoch training""" model.train() batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() end = time.time() for idx, (images, labels) in enumerate(train_loade...
664f5c75f06f144358c7d83df00ce297597148ab
71,849
import requests def mocked_requests(*args, **kwargs): """Mock requests.get invocations.""" class MockResponse: """Class to represent a mocked response.""" def __init__(self, json_data, status_code): """Initialize the mock response class.""" self.json_data = json_data ...
9971543948e28b2e510ce0289eb3bc888c9722b8
71,850
def get_user(): """ :return: User """ return getattr(_tls, 'user', None)
2fa3ad1780eb22397f368d9009d8610a3a33c3c1
71,851
def get_node_list(): """returns a list of tuple with node_address and status as items""" node_list = list() cmd = "/opt/vertica/bin/admintools -t list_allnodes" out, err = run_os_command(cmd) if out: #node extraction logic goes here else: print("Error occured: {}".format(err)) ...
dbc54954f615b14e4dd3d57437b312d61ab491bc
71,852
def create_webdriver(): """ Creates a chrome webdriver with custom options""" options = webdriver.ChromeOptions() options.add_argument("--headless") # options.add_argument("window-size=1400,900") options.add_argument("--incognito") options.add_argument("--ignore-certificate-errors") WEBDRIVE...
5cd145fa57fb1d705a07f9c0d5f6eaf02f7c921d
71,853
import re def object_string_formatter( s, **kwargs): """ Makes attributes of object passed in as keyword arguments available as {OBJECTNAME.ATTRNAME} in the passed-in string and returns a string with the above arguments replaced with the attribute values of the corresponding object. E...
b5c25088c550e494fe141b426557be94cd43037e
71,854
def fillna(groupby, value=None, method=None, axis=None, limit=None, downcast=None): """ Fill NA/NaN values using the specified method value: scalar, dict, Series, or DataFrame Value to use to fill holes (e.g. 0), alternately a dict/Series/DataFrame of values specifying which value ...
6aa8a8cbc8beffc5c2526dd03585fa7d90b0e42d
71,855
def read_sbtabs(f): """Return reactions, fluxes, keqs, bounds.""" sbtabs = SBtabTools.openMultipleSBtabFromFile(f) tdict = dict([(t.getTableInformation()[1].upper(), t) for t in sbtabs]) expected_tnames = ['REACTION', 'RELATIVEFLUX', 'REACTIONCONSTANT', 'CONCENTRATIONCONSTRAINT'] ...
6d4db68d988bb794ec6ee23c452e071fa0b1c663
71,856
def remove_pointer(type): """removes pointer from the type definition If type is not pointer type, it will be returned as is. """ nake_type = remove_alias( type ) if not is_pointer( nake_type ): return type elif isinstance( nake_type, cpptypes.volatile_t ) and isinstance( nake_type.base...
3e5dde64c39994d2435368f2e8b205ae24463d18
71,857
def get_dbtype(f): """Opens input fasta file, examines the first 10 records, and returns either 'prot' or 'nucl' depending on what type the sequences are. """ # Get sequence to evaluate. concat_seq = '' # Determine file type. filetype = None with open(f) as infh: for...
966b87dcee4484737cb3e1e4ff665fad1b4f7fec
71,858
def _gr_spline3_ ( graph , opts = 'b1e1', *args ) : """Get 3-spline for the given graph >>> graph = ... >>> spline = graph.spline3() - see ROOT.TSpline3 """ prev_hash , spline3 = 0 , None attr = '__hash_spline3' if hasattr ( graph , attr ) : prev_hash , spline3 = ge...
bc3243238604dadae21e32e84e56157759c1000e
71,859
def book_parser(book_html, date, status): """ Парсит html-узел с книгой :param book_html: html-узел с книгой :param date: string or None - дата прочтения :param status: string - статус книги :return: Book or None """ book_data = handle_xpath(book_html, './/div/div/div[@class="brow-data"]...
56a717814742360499f5de90a84d46990b0de456
71,860
def lock(func): """装饰器, 用在func方法执行前后, 增加运行信息""" def wrapper(*argv): data = None mutex.acquire() data = func(*argv) mutex.release() return data return wrapper
9efec55952f836caff5be0c844faf6fed1ade04a
71,861
import os import json def getG2Inputs(conf, mnet): """Get dictionaries C, F, and flow info (RTT and path) for each traffic flow. Write these dictionaries to JSON files. Args: conf (ConfigHandler): ConfigHandler object containing user-specified configurations. mnet (NetworkSimulator): The ...
ca356119f3e797085529717c4ecfd46be3bd670a
71,862
from typing import OrderedDict def gen_list_pcs_to_check(duthost, mg_facts, collect): """ Generate list of mclag interfaces to check Args: duthost: DUT host object mg_facts: Dict with minigraph facts for each DUT collect: Fixture which collects main info about link connection "...
b49adb6dcc2d5c69721b9e21e41a3529789a559f
71,863
def make_image_loader_factory(): """Generate a factory function for constructing image loaders. Invoke the returned factory function by passing the name of the image loader class you want to construct, followed by the parameters for the constructor as named arguments (e.g., factory('Directory', dir...
fc9a19d936e20ed6777a489cf52c0755e7612465
71,864
def sample_mask(idx, l): """Create mask.""" mask = np.zeros(l) mask[idx] = 1 return np.array(mask, dtype=np.bool)
e06dd489b2518e305c34381b4e1f41dfdc555416
71,865
import codecs def jsonfile_to_docs(filename): """ :type filename: str """ f = codecs.open(filename, 'r', encoding='utf-8') docs = jsonpickle.decode(f.read()) """:type: list[text.text_theory.Document""" f.close() return docs
524676189db126c4622f117e84f7a1dfb19b8daa
71,866
def company_with_investment_projects_factory(): """Factory for a company with investment projects.""" company = CompanyFactory() for field in INVESTMENT_PROJECT_COMPANY_FIELDS: InvestmentProjectFactory(**{field: company}) return company
a9ea1f5dacc17a24ae2cba923c76455a114d367b
71,867
def create(): """ Create Address Function --- /api/addresss/address: post: summary: Create Adress Function. security: - APIKeyHeader: [] tags: - Address requestBody: description: Adress Functions required: true content: application/js...
46e72e4f3e21b2e1e8b87b5556daceb2d127aa54
71,868
def format_tag(organization, standard, version, tag_name): """ Format a YAML tag. """ tag = "tag:{0}:{1}/{2}".format(organization, standard, tag_name) if version is None: return tag if isinstance(version, AsdfSpec): version = str(version.spec) return "{0}-{1}".format(tag, ...
9d37cb7a8dd892862fb4e34c366679e8ebf48c66
71,869
def constrained_sage_poly_dual(f, gs, p=0, q=1): """ Compute the dual f_{SAGE}^{(p, q)} bound for inf f(x) : g(x) >= 0 for g \in gs. :param f: a Polynomial. :param gs: a list of Polynomials. :param p: a nonnegative integer, :param q: a positive integer. :return: a CVXPY Problem th...
427f48514943817acb0d53e01f80400ec909a60f
71,870
def findCharacter(stringList, patternCharacter): """ Find the specific character from the list and return their indices """ return([ind for ind, x in enumerate(list(stringList)) if x == patternCharacter])
32cc8fb5970c6cd3cefd161b9e13e340f1645d13
71,871
from . import retinanet from . import retinanet_nl def vgg_retinanet(num_classes, backbone='vgg16', inputs=None, modifier=None, channels=None, **kwargs): """ Constructs a retinanet model using a vgg backbone. Args num_classes: Number of classes to predict. backbone: Which backbone to use (one...
1cb29dea06ccab5505b2929c185cc9e66be2f8cf
71,872
def identify_ridge_lines(matr, max_distances, gap_thresh): """ Identify ridges in the 2D matrix. Expect that the width of the wavelet feature increases with increasing row number. Parameters ---------- matr: 2-D ndarray Matrix in which to identify ridge lines. max_distances: 1-D seq...
a9ce20c62ed906d67bdc274cc0ec3f62659dd3f8
71,873
import ast def TildeDetect(word): """Detect tilde expansion in a word. It might begin with LiteralPart that needs to be turned into a TildeSubPart. (It depends on whether the second token begins with slash). If so, it return a new word. Otherwise return None. NOTE: - The regex for Lit_TildeLike could...
0393ae754f38997faaaafebd427195c1da5434ea
71,874
from typing import Dict from typing import OrderedDict def state_dict2numpy(state_dict) -> Dict[str, np.ndarray]: """Convert Pytorch state dict to list of numpy arrays.""" np_state_dict = OrderedDict() for param in list(state_dict): np_state_dict[param] = state_dict[param].numpy() return np_st...
c4ad8feae42a312e0fff5743795d86ab6ae1e5b4
71,875
def drop_levels(index, levels): """Softly drop `levels` in `index` by their name/position.""" if not isinstance(index, pd.MultiIndex): return index levels_to_drop = [] if not isinstance(levels, (tuple, list)): levels = [levels] for level in levels: if level in index.names: ...
76baa12d0d109ef965298c9af0651dfd181bf604
71,876
def rescan_image(image_obj, db_session): """ Rescan an image for vulnerabilities. Discards old results and rescans and persists new matches based on current data. :param image_obj: :param db_session: :return: """ current_vulns = image_obj.vulnerabilities() log.debug('Removing {} curren...
842319e8abf46c88588c4aba65f0adca4ae6a047
71,877
from pathlib import Path def figure_test(test_function): """ A decorator for a test that verifies the hash of the current figure or the returned figure, with the name of the test function as the hash identifier in the library. A PNG is also created in the 'result_image' directory, which is created...
a233dec64356892f2f0397ea79aac172f5d870b7
71,878
from typing import Optional def _set_access_token(username : str, access_token : str, connect_string : str) -> Optional[str]: """ Sets the access_token for the connect request by doing the following: 1. retrieves the token configured for the connect_string from ...
d8f80106259e9db5bf23b4272dffa5b8ea1dc19e
71,879
import os def create_app(test_config=None): """create and configure the app""" app = Flask(__name__, instance_relative_config=True) app.secret_key = os.urandom(12) # Generic key for dev purposes only # ======== Routing ============================= # # -------- Home -----------------------------...
4c54fe769e6e17acf22f081ab392e5b1268dc3a0
71,880
from typing import List def test_catch_deep_task_react(scheduler: Scheduler) -> None: """ Catch should react to new task hashes deep in the workflow. """ @task() def deep(denom): calls.append("deep") return 1 / denom @task() def safe(): calls.append("safe") ...
7f9b0c6e66eb07fbdd891e6ab56f223142b69b96
71,881
def try_pop(d, key, default): """ >>> d = {"a": "b", "c": "d", "e": "f"} >>> try_pop(d, "g", "default") 'default' >>> d {'a': 'b', 'c': 'd', 'e': 'f'} >>> try_pop(d, "c", "default") 'd' >>> d {'a': 'b', 'e': 'f'} """ value = d.get(key, default) if key in d: d....
7f5c5def5363882a070cac5749be584e1a8e2e14
71,882
from typing import Optional import time def hack_vigenere(text: str, test_id: str) -> Optional[str]: """Attempt to determine Args: text (str): The encrypted text we are trying to hack. test_id (str): Specify whether using test one (known plaintext) or test two (dictionary attack) Returns...
835d114d7666fa8fdc661839fdf5930b1633a9c4
71,883
def load_prediction_coordinates(): """ Returns the coordinates of the predictions, and their associated colours, as a pandas DataFrame. """ logger.debug("started load_prediction_coordinates()") df = pd.read_csv( "data/oneQ_prediction_coords_with_colors.csv", index_col=0 ) logger....
a940f53866300aa50cc5d36ec767c70ced78d4b5
71,884
def cell_trap_getter_generator(priv_attr): """ Generates a getter function for the cell_trap property. """ def getter(self): if getattr(self, priv_attr) is None: data =\ ( self.gfpffc_bulb_1 - self.gfpffc_bulb_bg )/self.gfpffc_bulb_bg ...
15217adbd96ce44b361444867e5d9c6d202440f4
71,885
def shared_blockchain_instance(): """ This method will initialize ``SharedInstance.instance`` and return it. The purpose of this method is to have offer single default bitshares instance that can be reused by multiple classes. """ if not SharedInstance.instance: clear_cache() ...
78fed0d63da2351fe721730b51fdac1bded7878a
71,886
def check_punctuation(word): """ This detects the punctuation if the words start or end with punctuation, and removes it by remove_punctuation_from _end if so. """ punctuation = PUNC.value while len(word)>0 and (word[0] in punctuation or word[-1] in punctuation): word = remove_punctuatio...
16ba6b2f62bb9127583df9e193d5432193e5ed5a
71,887
def euclideanDistance(x_a, x_b): """ Calculates the Euclidean distance between two vectors Arguments: x_a (np.array): shape [m_features, ] a single vector a x_b (np.array): shape [m_features, ] a single vector b Returns: distance (float): Euclidean distance between vect...
13b14eeaba4de3b3b3bf2888a232c67bae7d0f45
71,888
def recover_signature_object(data, format_type=BBcFormat.FORMAT_BINARY): """Deserialize signature data""" sig = BBcSignature(format_type=format_type) sig.deserialize(data) return sig
55eeb93a1d27bd25ea5fcfcfccb24912de65a5d1
71,889
import sys def create_role_with_password(server, role_name, role_password): """ This function create the role. :param server: :param role_name: :param role_password: :return: """ try: connection = utils.get_db_connection(server['db'], ...
7188ab45072f8b3195e287927359cfd38d13d6bd
71,890
def SoftmaxCE(name=None): """Create a softmax layer with integrated Multinomial Cross Entropy loss. Applies the softmax activation function on 'default' input and puts results (per-class probabilities) in 'predictions'. It also takes class indices (0-based) as the 'targets' input, and computes the...
a6e708af82a595c48e8170e048bc024de1cafaf4
71,891
async def test_custom_agent(hass, hass_client): """Test a custom conversation agent.""" calls = [] class MyAgent(conversation.AbstractConversationAgent): """Test Agent.""" async def async_process(self, text, conversation_id): """Process some text.""" calls.append((...
14f89286a7a5c1898bab2c8c4abf21557e30efa5
71,892
import os import hashlib def safe_filename(name, extension=None, digest=None, max_length=_MAX_FILENAME_LENGTH): """Creates filename from name and extension ensuring that the final length is within the max_length constraint. By default the length is capped to work on most filesystems and the fallback to achieve...
4fb4bca965960d2e9074f65d0637d4232310ef75
71,893
def success(request): """ 增删改操作成功之后返回这个页面 """ return HttpResponse('success')
a6a03a5d85710a888da60460958eef7a253edb4a
71,894
def insertion_as_lsp_data(position: Position, new_text: str) -> LSP_TextEdit: """ Convert an expanded `Insertion` to a Language Server Protocol compatible dictionaries for display as JSON. Note: in LSP line numbers are zero-based, while our `Position`s are one-based. """ pos = {'line': posi...
231167cbc3d573365d26cdccb879a51addb5694c
71,895
def BOPDS_Tools_IsInterfering(*args): """ * Returns true if the type <theT> can be participant of an interference :param theT: :type theT: TopAbs_ShapeEnum :rtype: bool """ return _BOPDS.BOPDS_Tools_IsInterfering(*args)
b36ed58fb4043024fea2028e1423286c6a63ee17
71,896
def get_L_dash_prm_etrc_OS_0(): """主開口方向から時計回りに0°の方向の外気に面した玄関等の土間床等の外周部の長さ (m) Args: Returns: float: 主開口方向から時計回りに0°の方向の外気に面した玄関等の土間床等の外周部の長さ (m) """ return get_table_3(32, None)
3bb42fe76515da73615bd11ce0123c65f32c3d4a
71,897
def create_environment(env_config): """Creates an interest evolution environment.""" user_model = IEvUserModel( env_config['slate_size'], choice_model_ctor=choice_model.MultinomialProportionalChoiceModel, response_model_ctor=IEvResponse, user_state_ctor=IEvUserState, seed=env_config['...
51ee0fd00d4502ea1c9a4b4c58238c07751c9f0f
71,898
def neg_norm_probability_differences(detached_output, true_labels, loss): """ Calculates the difference between the two most probable classes and normalises it with tanh such that the resulting difference is between 0 and 1. The inverse of this difference is taken. This is multiplied by the current loss...
805189107e5641cd5e2628ef21a5e5884aa91d08
71,899