content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def value_at_path(d, path): """ access value by object path :param d: dict or list of dict :param path: object path like `Data.1.UHostId` :return: any value access by path """ if d is None: return indices = path.split(".") result = d for i, key in enumerate(indices): ...
cc3724a21893b9f40a6a069a836bbc8a30ac369e
3,606,100
def __virtual__(): """ Only work on Windows """ if salt.utils.platform.is_windows(): return __virtualname__ return False
f239909adbf99047da87316176b4dcd06cfa7a77
3,606,101
from typing import List import shutil def _get_build_bf_command(args: dict, in_fn: List[str]) -> List[str]: """Helper function to compose command to get the final Bloom Filter :arg dict args: Dict of arguments. :arg str in_fn: Path to file where the reads will be read :ivar dict args: Dict of argume...
9736a1825613dd518361bb1a5ded9b266293017a
3,606,102
import http def parse_xml(body, code, headers): """ Return a dictionary. Transformation is done assuming: 1. If a tag indicates its value type, we'll try to cast it. 2. Siblings with the same tag name, become a list. 3. Attributes become a dict key starting with '@'. <duck> <n...
05dcbbc5912a2b87158dcfa1e70505e0d6da1137
3,606,103
import sys def _is_venv(): """ :return: """ return hasattr(sys, 'real_prefix') or getattr(sys, 'base_prefix', sys.prefix) != sys.prefix
87a6434bd4b572abbacf5b8bb81250e6287181d4
3,606,104
def is_user_diabetic(avg_glucose_level): """ desc: converts avg_glucose_level to category based on ADA Guidelines https://www.diabetes.org/a1c/diagnosis args: avg_glucose_level (float) : glucose level in blood based on mg/dL returns: blood_cat (string) : blood sugar category """ ...
59b8a9937f620c28eb51da4ef56c493d1b2177d8
3,606,105
import time def get_Into_School_Page(logger, school_dict, driver): """ 进入学校界面,获取学校相关信息 :param logger: :param school_dict: 读取包含学校名和学校链接的字典 :param driver: :return: dict: 课程信息字典,包含课程名、上课人数、课程链接、学校 """ school_list = list(school_dict['校名'].values()) school_url_list = list(school...
aa1131e67b1bdfc1eee8f3066101a3dcfe3ec24f
3,606,106
def id_for_fund(fund): """Retrieves the integer identification number for the specified fund. Parameters ---------- fund: String. The fund whose integer identifier is requested. """ cur.execute("SELECT id FROM funds WHERE fund='{}'".format(fund)) return cur.fetchone()[0]
0cc830d45a8c4597f27cb3aa7b615fc9fb889d72
3,606,107
import hmac def verify_cron_job(cron_domain: str, secret_key: str) -> bool: """verify if the executor of the cron job is authorized""" is_domain: bool = hmac.compare_digest( cron_domain, config_instance.CRON_DOMAIN) is_secret: bool = hmac.compare_digest( secret_key, config_instance.CRON_SE...
af29a82c74e66a39d0e331ed7eee4461c3f15a1d
3,606,108
import os def _generate_version(base_version): """Generate a version with information about the git repository""" pkg_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if not _is_git_repo(pkg_dir) or not _have_git(): return base_version if _is_release(pkg_dir, base_version) a...
0e63fe530b71bc1602c499fe7c4e3916c3a34df9
3,606,109
import re def tokenize(text): """ :param text: string to tokenize :return: text in form as clean token """ url_regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+' detected_urls = re.findall(url_regex, text) for url in detected_urls: text = text....
5bc06666995920898599339a4d250c066fd36451
3,606,110
def label_sem_map(sem: np.ndarray, sort: bool=True) -> np.ndarray: """ Labels a given semantic segmentation map Args: --------- sem (np.ndarray): semantic segmentation map. Shape (H, W) sort (bool, default=True): sort the semantic areas by size in descending orde...
084237973f9bd28fce3fa2cf6f231c9d8553da57
3,606,111
import array def formatTilePlanar(tile, nPlanes): """Convert an 8x8 pixel image to planar tile data, 8 bytes per plane.""" if (tile.size != (8, 8)): return None pixels = iter(tile.getdata()) outplanes = [array.array('B') for i in range(nPlanes)] for y in range(8): ...
5ff30470a1392744139a5577f2a51a519f58ab42
3,606,112
def gen_factory(func, seq): """Generator factory returning a generator.""" # do stuff ... immediately when factory gets called print("build generator & return") return (func(*args) for args in seq)
9188f5959ec2feb52b83f20f40474f91f4cbfe08
3,606,113
from typing import Optional def get_api_version_set(api_management_name: Optional[str] = None, name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetApiVersionSetResult:...
d24d5730dbd4f39dc4963616b99186a2287de8d5
3,606,114
import logging def retrieve_inventory(vault_name): """Initiate an Amazon Glacier inventory-retrieval job To check the status of the job, call Glacier.Client.describe_job() To retrieve the output of the job, call Glacier.Client.get_job_output() :param vault_name: string :return: Dictionary of inf...
97c5a6ef67139014004241558e6b07564cfd195a
3,606,115
def _validate_satellite_dates(satellite, start, end): """Validate the start and end times for the satellite. Uses the known operational dates of the satellites to adjust the start date if needed. It also selects the Amazon S3 bucket to use. Returns: a tuple of (start, S3 bucket). If the start ...
3fe5aaedd35f6bd1e5addf7fc54fb88341993dc0
3,606,116
def _parseExpectedWords(wordList, defaultSensitivity=80): """Parse expected words list. This function is used internally by other functions and classes within the `transcribe` module. Expected words or phrases are usually specified as a list of strings. CMU Pocket Sphinx allows for additional 'sen...
83512a86ae112de79bd84e1d9ea3ebebcb4cdefd
3,606,117
import json def create_json_report(occurrences, filename, report_dir=False): """Create a JSON file containing the raw data that can be queried for further analysis.""" if report_dir: report_filepath = report_dir + '/' + filename + '.json' else: report_filepath = ANALYSIS_DIRECTORY_PATH + '...
d958a8f2027cc2a15179fdd218e23e4e451cf342
3,606,118
def AAPIEnterPedestrian(idPedestrian, originCentroid): """Execute command once a pedestrian enters the Aimsun instance.""" return 0
7dc133cb3ed7e5dc0adcfb5ee271faa9c94b2418
3,606,119
def add_bbox_to_image(image, bbox, color='red', width=3): """Adds a bounding box to the image. Args: image: A PIL image. bbox: (ymin, ymax, xmin, xmax) box. color: Color to draw the box with. Returns: A PIL image with the bounding box drawn. """ output = image.copy(...
fc3a35a3bcf94ac690eef5788c98d1d825410c26
3,606,120
def registerErrorHandler(f, ctx): """Register a Python written function to for error reporting. The function is called back as f(ctx, error).""" ret = libxsltmod.xsltRegisterErrorHandler(f, ctx) return ret
aedeedee6bfaec690574e1cbba9e446053d24d82
3,606,121
import os def get_cached_execution_id(): """Gets the cached execution object. Returns: execution: the execution resource name """ cache_path = _get_cache_path() if not os.path.isfile(cache_path): raise exceptions.Error(_NO_CACHE_MESSAGE) try: cached_execution = files.ReadFileContents(cache_p...
fbf79f056af519955c064f5c67670631804c40a3
3,606,122
import numpy as np from scipy.io import loadmat import numpy as np import h5py from numpy import fromfile, empty, append def reading_data(data_file, data_choice): """ This function is adapted to take in any 3 files of the following types: .bin, .mat or h5. The reader is designed to read in uint16 cast data. ...
72b0a7681eda06de8c967b895676de948e9ee064
3,606,123
def exp_quadratic_action_reward(action, weights=None, gradient=False, hessian=False): """Exponential quadratic action reward :math:`reward = 0.5 exp(\sum_{i}^{dimA} (a_i * w_i)^2)` Args: action (np.ndarray): weights (np.ndarray or float or None): gradient (bool): Calculate rewa...
6da236a3512dc48f2795941f8ce77282a577da3a
3,606,124
def split_leading_indent(line, max_indents=None): """Split line into leading indent and main.""" indent = "" while ( (max_indents is None or max_indents > 0) and line.startswith((openindent, closeindent)) ) or line.lstrip() != line: if max_indents is not None and line.startswith(...
2bcf803b84d7d2a01929562a2376e94299389dc8
3,606,125
import six import os def get_file_name_list(paths, ending=None): """Returns the list of files contained in any sub-folder in the given paths (can be a single path or a list of paths). :param paths: paths to the directory (a string or a list of strings) :param ending: if given, restrict to fil...
c02e81e426937caed9c1d17c5e83147597e54a1a
3,606,126
async def view_available_recipes(): """ Returns the list of recipes available for the coffee machines """ recipes = [i for i in database.get_recipes().find()] for i in recipes: del i['_id'] return {"recipes": recipes}
57ecac022799f1ff00f17bd0b93cce63b10a2a91
3,606,127
def nanmean(x, axis=0): """Compute the mean over the given axis ignoring NaNs. Parameters ---------- x : ndarray input array axis : int axis along which the mean is computed. Returns ------- m : float the mean. """ x, axis = _chk_asarray(x, axis) x = x.cop...
d024c28224927de7c86737b75179263b25ae2687
3,606,128
def _handle_doi_url(attrs: Attrs, new: bool = False) -> Attrs: """ Screen for reference to a DOI, and generate a URL. If the :ref:`.DOI` pattern is used, it will generate a link with the doi as a the target. We need to intercept these links, and generate a real URL. """ href = attrs[(None, ...
d4dfbe800569aa2ec126a063f965f001869b2374
3,606,129
from scipy.linalg import cho_solve def regression(objectsA, objectsB, xyarr, P, scale, amp, chol): """ Perform regression on the gaussian processes for the the distortion map. This uses the input data to push known values onto a new grid, using the covariance properties of the GP.""" # Compute e...
8026047406736c0327dc308584a0a6caa8c744a5
3,606,130
def convert_bbox_from_coco(bbox): """Convert a bounding box array from the COCO format [x1, y1, w, h] to the format [x1, y1, x2, y2]. """ x1, y1 = (bbox[0], bbox[1]) x2, y2 = (x1 + bbox[2], y1 + bbox[3]) return np.array([x1, y1, x2, y2])
53405114df8903d4013bcb4a2558b39830c232ef
3,606,131
def make_csd(shape, scale, npart): """Create cell size distribution and save it to file. Log-normal distribution from scipy is used. Creates ``diameters.txt`` file with sphere diameters. Args: shape (float): shape size parameter of log-normal distribution scale (float): scale size para...
dcf1b8ca969f9028d5a8e61a5c545843ecf8adc2
3,606,132
def ISNA(cell) -> func_xltypes.Boolean: """Returns True if the cell is #N/A. Don't call validate_args here because we allow errors to be passed in. """ return isinstance(cell, xlerrors.NaExcelError)
10ce93efdc7243072a09c02e6ff2ecf6d3d7aba8
3,606,133
from typing import Optional def get_compartment(id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetCompartmentResult: """ This data source provides details about a specific Compartment resource in Oracle Cloud Infrastructure Identity service. Gets th...
6cab80b11c0426acb744dc1e2e2bb8947a38db78
3,606,134
import logging def get_tabula_Umean() -> pd.DataFrame: """Return building_stock dataframe""" pth = path_tabula_Umean() if not pth.exists(): logging.warning(f"file: {pth} not found... start downloading it") download.download_population() tab = pd.read_csv(pth, sep="|", index_col=0) ...
20a7661fad75a87d11eceac6d932459be03906c3
3,606,135
import requests def sign_in_to_server(server, username, password, site="", ssl_cert_pem=None): """ Signs in to the server specified with the given credentials 'server' specified server address 'username' is the name (not ID) of the user to sign in as. Note that most of the functions i...
1e2b68609264f7c27ba8937e1b1f845e37523fb8
3,606,136
def test_wait_until_true_once_found(mock_time_sleep): """wait_until_true max_attempts 1.""" mock = MagicMock() mock.side_effect = [ 'expected value', 'test string 2', ] def decorate_me(arg1, arg2): """Test static decorator syntax.""" assert arg1 == 'v1' asser...
76e64fe0ab9d0c0f1b3b704994e5a5fa9933cb5c
3,606,137
def latest(treant): """Get the latest data file available based on a sort. """ return pipe( treant.glob('*.nc'), sorted, last, lambda leaf: leaf.abspath, )
5abff0b89a3aa7ea269c14f8d590c2057fc50161
3,606,138
import functools def admin_required(f): """ Decorator to apply to views that require an admin to access. """ @login_required @functools.wraps(f) def wrapper(request, *args, **kw): if action_allowed(request, amo.permissions.ADMIN_TOOLS): return f(request, *args, **kw) ...
333112eddf1372b7997f20a26a359bdaa175effb
3,606,139
import json def article(request, article_id): """Article page with article with uuid, and list of 3 quotes.""" if request.method == 'POST': cf = CommentForm(request.POST) if cf.is_valid(): c = Comment(text=cf.cleaned_data['text'], article_id=article_id) ...
5fbb397421dac0b686b25b8c30cdad33d4316332
3,606,140
def is_upper_diff(text: str) -> bool: """Check if some words are all caps while others aren't. Args: text (str): Text to parse through and check if some words are capitalized while others aren't Returns: bool: True if some words all caps while others aren't, False otherwise """ current_word = "" upper_word...
d50e42795961d9d0a0c409cf9ff61dac5b709151
3,606,141
import requests def delete_menu(access_token): """ 删除菜单 请谨慎使用 http请求方式:GET https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN :param str access_token: ACCESS_TOKEN :rtype: json """ menu_url = 'https://api.weixin.qq.com/cgi-bin/menu/delete?access_token={ac...
fb52f406d52b2dad2aedfd8c04913a3ca94b6ca1
3,606,142
def _generate_trades_df_response(trades_df): """ Generates JSON response from trades Attributes ---------- trades_df: DataFrame of Trades """ trades_df = trades_df.drop( columns=["symbol", "trade_id", "stop_loss", "take_profit"] ) trades_df = trades_df.rename( colum...
34244801babedeb75ec21001ea99a9e8aef863e2
3,606,143
import os def is_stub(path: str) -> bool: """Does path refer to a stubs file? Currently check if there is a 'stubs' directory component somewhere in the path. """ # TODO more precise check dirname, basename = os.path.split(path) if basename == '': return False else: st...
c8cd5fe53609f05843e8af67dbac92bf6592419b
3,606,144
def measurement(qreg=int(0), creg=int(0)): """Generate QASM that takes a measurement from a qubit and stores it in a classical register. Args: qreg(int): Number of the Qubit to measure. (default 0) creg(int): Number of the Classical Register to store the measurement to. (default...
9a9a24f390bf0745e7cdfe80bb1893f77161c171
3,606,145
import urllib def unparse_transport_url(transport, secure=True): """ Unparse a transport URL; that is, synthesize a transport URL from a dictionary similar to that one returned by parse_transport_url(). :param transport: The dictionary containing the transport URL components...
dba2e123908e3cf98ce4c1a415ac33b54475bd6b
3,606,146
def get_vplex_port_parameters(): """This method provide parameter required for the ansible port module on VPLEX""" return dict( cluster_name=dict(required=True, type='str'), port_name=dict(required=True, type='str'), enabled=dict(required=False, type='bool'), state=dict(requi...
9533cf6ff8eedd943b88c9cd08ea16407aa9ee64
3,606,147
def projection_error(p1, p, pt, pt1): """ Based on Hartley and Zisserman p.285 this function triangulates image correspondences and computes the reprojection error by back-projecting the points into the image. This is the classic cost function (minimization problem) into the gold standard metho...
76046d81d270c98cc9f6f68fe36c9c22b257d9c3
3,606,148
import os from datetime import datetime def get_modification_date(filename: str) -> str: """Returns modification date of a given file.""" t = os.path.getmtime(filename) return str(datetime.datetime.fromtimestamp(t))[:19]
b57125984a2d7097d54c38e74ee3e55f3f136a9a
3,606,149
def createMainSizer(parent, granparent, ID, title, pos, size, style): """ Function to create control dialogs. """ pre = _precreate(granparent, ID, title, pos, size, style) return _postcreate(parent, pre)
71ff10b4d4d8cf4b4ed42decf2fee46f2fece9fc
3,606,150
import os def create_app(config_name): """ An flask application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/ Arguments: config_name: the key value if the config.config dict, e.g. 'dev', 'test', 'product', 'default' """ app = Flask...
bb83669c98246822c7e820e04a231a8424e8d4a3
3,606,151
def _arr(*shape): """ Construct an array of a specified consisting of values [0, _arr.size) filled in row-major order. Parameters ---------- *shape : int Returns ------- numpy.ndarray""" return np.arange(np.prod(shape)).reshape(shape)
c364ce0da3ee43b5cdb96cb1600ea98346ca4620
3,606,152
def fixedtext_features(X, target_keynames, align): """ Extract fixed-text features (press-press latency and key-hold duration) from the raw data sample X, given the target key sequence and keystroke alignment (correspondence) method. """ timepress, timerelease = timepressrelease(X, target_keynames, ...
898a16d348613ba454d7cbed23a7ac9265927110
3,606,153
def sset_list(args): """ List sample sets in a workspace """ return __get_entities(args, "sample_set")
5ba593935829a3350ee804426372e1f299095df1
3,606,154
import os def connect_to_mongodb(): # pragma: no cover # TODO(cmei4444): restructure to be consistent with other services """Connects to MongoDB Atlas database. Returns events collection if connection is successful, and None otherwise. """ class Thrower(): # pylint: disable=too-few-public-meth...
92e687008576b9c3feadfc2a27bbd23051fc80ec
3,606,155
def _GetNodeDiskState(_, node): """Converts node's disk state for query result. """ disk_state = node.disk_state if disk_state is None: return _FS_UNAVAIL return dict((disk_kind, dict((name, value.ToDict()) for (name, value) in kind_state.items())) for (disk...
d9efd107b00df05db76f0fcefc1a615ed52fd5ad
3,606,156
def dylan_stretchy_vector_size(vector): """Return size of a stretchy vector""" representation = dylan_slot_element_by_name(vector, 'stretchy-representation') return dylan_integer_value(dylan_slot_element(representation, SIMPLE_OBJECT_VECTOR_SIZE))
3f928c575117480596d3a45747987ec6fa617d85
3,606,157
def remote_ip(local_ip): """ Given an IP address, this function calculates the remaining available IP address under the assumption that it is a /30 network. In other words, given one link net address, this function returns the other link net address. :type local_ip: string :param local_ip:...
d784ef13f9625c5f5285193af82ac056b66929b7
3,606,158
def generate_mixture_indicator(number_obeservations): """Generate the variable that will be used for mixture generation Args: - number_obeservations : number of obeservations Returns: - mixture_indicator: mixture indicator variable """ mixture_indicator = np.random.randint(0, 2, (number_o...
34e65e64ba3dafbc4809fc5cb0a3c2ab10cac81b
3,606,159
def __local_pa(soup): """ Gets the most read news from Pará Local News (Rede Liberal) :param soup: the BeautifulSoup object :return: a list with the most read news from Rede Liberal page """ return __get_local_g1_news(soup)
5c9b44175ec9321eda290ae403bbbaf732f54a3c
3,606,160
def adjacent(p): """Return the positions adjacent to position p""" return ( (p[0] + 1, p[1], p[2]), (p[0] - 1, p[1], p[2]), (p[0], p[1] + 1, p[2]), (p[0], p[1] - 1, p[2]), (p[0], p[1], p[2] + 1), (p[0], p[1], p[2] - 1), )
988597e0abd150ae60b556e52a217bd8a136707b
3,606,161
async def goodbye(): """ used in our randomized redirect """ return {"message": "Goodbye"}
2a0ce1fe99497b55cfd9a9853cd75a0c7eddac40
3,606,162
def to_stereo(waveform): """ Convert a waveform to stereo by duplicating if mono, or truncating if too many channels. :param waveform: a (N, d) numpy array. :returns: A stereo waveform as a (N, 1) numpy array. """ if waveform.shape[1] == 1: return np.repeat(waveform, 2, axis=-1) if ...
03478d970e7be1d4eb24201deeb3e5c330ab00af
3,606,163
def metrics_from_stats(stats): """Compute metrics to report to hyperparameter tuner.""" labels, probs = stats['labels'], stats['probs'] # Reshape binary predictions to 2-class. if len(probs.shape) == 1: probs = np.stack([1-probs, probs], axis=-1) assert len(probs.shape) == 2 predictions = np.argmax(pro...
932116c02f54bee9ff2ee953cb91d19b20de5fc7
3,606,164
def prepare_ocp( biorbd_model: biorbd.Model, final_time: float, n_shooting: int, use_sx: bool, weights: np.ndarray, use_excitations=False, use_collocation=False, ) -> OptimalControlProgram: """ Prepare the ocp Parameters ---------- biorbd_model: str The path to t...
8bda9f58789dc5f2ce6a286b7cef0ac3f2f9d2d9
3,606,165
def update_pubmed(pub_uri, doi=None, pmid=None, inVivo=True): """ Given the uri of a pub in VIVO and a module concept dictionary, update the PubMed attributes for the paper, and include RDF to add to the concept dictionary if necessary """ ardf = "" srdf = "" if inVivo: # Get the pa...
1eda48fbb5d561f9a53e6b18732153180c58a087
3,606,166
def ldns_resolver_set_tsig_keydata(*args): """LDNS buffer.""" return _ldns.ldns_resolver_set_tsig_keydata(*args)
72519065a9a1e33584b05eb063f406f4c048e0e3
3,606,167
def make_table(*list_of_list): """ :param list_of_list: list of list of strings :returns: a valid rst table """ lcols = [len(x) for x in list_of_list[0]] for li in list_of_list : # compute the max length of the columns lcols = [ max(len(x), y) for x,y in zip(li, lcols)] form = '| ' ...
77153451571e70a77d6bd525bd252aa7efe1c693
3,606,168
import re def replace_special_whitespace_chars(text: str) -> str: """It's annoying to deal with nonbreaking whitespace chars like u'xa0' or other whitespace chars. Let's replace all of them with the standard char before doing any other processing.""" text = re.sub(r"\s", " ", text) return text
17be082a827039264cd75fb7459fc31eb7f617dd
3,606,169
def _extract_missing(values): """Extract missing values from `values`. Parameters ---------- values: set Set of values to extract missing from. Returns ------- output: set Set with missing values extracted. missing_values: MissingValues Object with missing valu...
ad3661fa7e77a37792f864fc1acf404c23abca4d
3,606,170
import re def processSets(results): """Process set results to be displayed in the set selection window :param List[Dict[str, Union[int, str, Dict[str, str]]]] results: A list of raw set results :return: A list of processed results in table form :rtype: List[Union[str, int]] """ rows = [] ...
bf050015474691402d2d992070c487b45cc34a42
3,606,171
def min(a): """ Returns the minimum value of an array """ try: return _onp.min(a) except TypeError: return _cas.mmin(a)
9cadece2ff36ab06b2a3b11bf954aa45c4d3c874
3,606,172
def tf_fidelity(A, B): """Calculates the fidelity between tensors A and B. Args: A, B (tf.Tensor): List of tensors (hilbert_size, hilbert_size). Returns: float: Fidelity between A and B """ sqrtmA = tf.matrix_square_root(A) temp = tf.matmul(sqrtmA, B) temp2 = tf.matmul(temp...
02cabadfde5fec73614d39c58fb77c49837b07eb
3,606,173
def test(dir: str, endpoint: str): """Pipeline of validation the test using the files present in dir""" dataset_id = load_dataset(dir, endpoint) events = get_events_of_interest(dir, endpoint, dataset_id) clean_server(endpoint, dataset_id) return evaluate(events, dir)
dfd2942da1460136c5b6814009c787e2da45aa63
3,606,174
def 查找文件或目录(名称, 路径=None, 精确=False): """ # list(查找文件或目录('ping', exact=True)) # list(查找文件或目录('bin')) # list(查找文件或目录('bin')) # list(查找文件或目录('*cc*')) # list(查找文件或目录('cmake*')) """ return ub.find_path(名称, 路径, 精确)
5e14e7950e8107e280924538614243cb2735d11a
3,606,175
def get_aliases(record): """ Get all aliases associated with this DID / GUID """ # error handling done in driver aliases = blueprint.index_driver.get_aliases_for_did(record) aliases_payload = {"aliases": [{"value": alias} for alias in aliases]} return flask.jsonify(aliases_payload), 200
e0643198a3b34afc69e758b651f35b7e46225dc3
3,606,176
def _create_internal_transaction_type(row) -> TransactionType: """Create a suitable transaction type according to the given row.""" return TransactionType.from_row(row, is_internal=True)
eb6453a9c5a2ccbcce157b66456132255a43c676
3,606,177
import glob import os def identify_project_name(directory="."): """ Identify the project name by identifying the project file """ project_files = glob.glob(os.path.join(directory, "*.pro")) if len(project_files) == 1: return project_files[0].rpartition(".")[0] # Just the prefix without ".p...
35bce15397ddccef546220b42656889e2b398b1b
3,606,178
from typing import Optional from typing import Dict async def incoming( message, chain_name=None, tx_hash=None, height=None, seen_ids: Optional[Dict]=None, check_message=False, retrying=False, bulk_operation=False, ): """New incoming message from underlying chain. For regular ...
b4fa7e9d85c13ab211071d965cb29361ed2b0cf3
3,606,179
def handle_update_lessons(lesson_id): """Handle updating an existing lesson log""" updateform = UpdateLesson() form = NewLesson() if updateform.validate_on_submit(): lesson_id = updateform.lesson_id.data lesson_time = updateform.lesson_time.data updateform.lesson_time.data = '' ...
9e948c6d1cc9998b3ba9db5b4f6c971ad0c77f07
3,606,180
import json def read_transcripts(src_bucket, guid): """Get the transcripts JSON file from the S3 bucket. Args: src_bucket (str): A string containing the S3 source bucket. guid (str): A string containing the unique ID. Returns: spoken_text (str): A string with the text the custome...
61430b62d78ccefad578bdc27004d55622988572
3,606,181
def preprocess(): """ 数据准备阶段 :return: """ # 1. 加载数据文件 x_text, y = load_data_and_labels(FLAGS.positive_data_file, FLAGS.negative_data_file) # 文本进行向量化 sentences, max_document_length = padding_sentences(x_text, '<PAD>') x = np.array(embedding_sentences(sentences, FLAGS.word2vec_fname...
c39adc82e6ce1e3bd4d70638246ce77e1dac9134
3,606,182
def umfpack_dl_triplet_to_col(*args): """ umfpack_dl_triplet_to_col(SuiteSparse_long n_row, SuiteSparse_long n_col, SuiteSparse_long nz, SuiteSparse_long const [] Ti, SuiteSparse_long const [] Tj, double const [] Tx, SuiteSparse_long [] Ap, SuiteSparse_long [] Ai, double [] Ax, SuiteSparse_long ...
7d1f910c581e23843020dce8621577aa9117a6b2
3,606,183
def two_sequences_in_parallel(sequence1, sequence2): """ Demonstrates iterating (looping) through TWO sequences in PARALLEL. This particular example assumes that the two sequences are of equal length and returns the number of items in sequence2 that are bigger than their corresponding item in sequ...
c5dbce5f99d5c2efeee4048ec1451ea63f404fef
3,606,184
def find_middle(arr: list) -> int: """ checks if the size of the list is odd, and will be sorted by the order_int_list() function, and return the median number Args: arr (list): if the size of the list is even, will return an raise ValueError Returns: int: the median number of the ...
edab12bfcb9ff77249a51137fc5a8bb0778c5ac8
3,606,185
def GetHostTuple(): """Returns compiler tuple for the host system.""" return portage.settings['CHOST']
8a741c6cae7b1e8faec774b5e7fa57f5a6258747
3,606,186
def str_to_tag(in_str: str) -> BaseTag: """Convert string representation to pydicom Tag The string can be a keyword, or two numbers separated by a comma """ if in_str[0].isupper(): res = tag_for_keyword(in_str) if res is None: raise ValueError("Invalid element ID: %s" % in_s...
54f58de4f3769b31f7419964f83ed1e35cefcd49
3,606,187
def plot_out_csv(data): """Uncomment everything you want to have on a plot """ columns = ['time', 'cwnd1', 'cwnd2', 'cwnd3', 'rtt1', 'rtt2', 'rtt3', 'bytes1', 'bytes2', 'byt...
26ae9e475440fb651bbc759294ca4681606e337b
3,606,188
def meta_seq_number(num): """ Creates a sequence number meta message. Parameters ---------- num : byte The sequence number """ msb = num & (0x7F << 7) lsb = num & 0x7f return [kMetaMsg, kSeqNumber, 2, msb, lsb]
f428479ffdcc6f552f36d03b317538230c80c3e1
3,606,189
import yaml def get_all_comments(): """ すべての項目名と項目名コメント取得する Returns ------- comments_list : dict {項目名: [項目名コメント, ...], ...} """ with open(COMMENTS_YAML, "r") as f: comments_yaml = yaml.safe_load(f) tables = comments_yaml["comments"] comments_list = {} ...
44dcfb524bdeb4a32204c5ef6a2b33f449f3b747
3,606,190
def vime_semi(x_train, y_train, x_unlab, x_test, parameters, p_m, K, beta, file_name): """Semi-supervied learning part in VIME. Args: - x_train, y_train: training dataset - x_unlab: unlabeled dataset - x_test: testing features - parameters: network parameters (hidden_dim, batch_siz...
9e57f4c99f8c2c2dc27d118207f6ff3efdad8490
3,606,191
def no_aug_generator(data, target, batch_size=32, gradient=False): """Custom image generator that manipulates image/target pairs to prevent overfitting in the Convolutional Neural Network. Parameters ---------- data : array Input images. target : array Target images. batch_si...
984ce538d0a660fc34c20cca81d741ed2a38c34d
3,606,192
def image_crop(src, x1, y1, x2, y2): """ Crop image from (x1, y1) to (x2, y2). Parameters ---------- :param src: Input image in BGR format :param x1: Initial coordinates for image cropping :param y1: Initial coordinates for image cropping :param x2: End coordinates of image cropping ...
6ab70dc644d0d7054ea70fadcf7ec0ca381918d8
3,606,193
def gm_variance(W, A, s): """ Calculate the maximum variance for a single query in workload W. Parameters ---------- s is the privacy cost """ m, n = A.shape mI = np.eye(m) # pseudoinverse of matrix A pA = np.linalg.inv(A) sigma = np.sqrt(1/s) Var = W @ pA BXB = Var ...
d1d1dc12ae402b2e6f307d717bf367e8df03ec95
3,606,194
from typing import NamedTuple import pydantic def settings_env_names( settings_class: CommonSettings = CommonSettings, ) -> NamedTuple: """ returns the current environment variable names for the settings class and value """ try: _ = SettingsClassName.validate(settings_class) except...
c84f0fd067728288c4253f546d391ae838bf9590
3,606,195
import array def parse_siemens_b_matrix(value: bytes) -> np.ndarray: """ Parses the Siemens B matrix header field value. Parameters ---------- value : bytes Raw B matrix header field value Returns ------- np.ndarray Parsed B matrix """ raw = list(array.array("...
462df1b3dd78e37365a1d515e931dde47471c86a
3,606,196
from typing import Union import asyncio def maybe_defer(inter: disnake.Interaction, *, delay: Union[float, int] = 2.0, **options) -> asyncio.Task: """Defer an interaction if it has not been responded to after ``delay`` seconds.""" loop = inter.bot.loop if delay <= 0: return loop.create_task(inter....
e64d2fded53559de7344e77a3d42f421a4c481ba
3,606,197
def block1(x, filters, bottleneck=False, stride=1, expansion=1, normalization='bn', activation='relu', name=None): """A basic residual block. Args: x: input tensor. filters: integer, filters of the bottleneck layer. bottleneck...
ef3bb272fc66f1108f6ecf7f2408fd1418b76b0a
3,606,198
def build_dense_decoder_model( *, original_dim, latent_dim, dense_dims, activation="relu", verbose=False, **kwargs ): """ Builds dense decoder network for 1-d xrd data Parameters ---------- original_dim: int original dimensionality of xrd data (i.e. the length of any one sample) lat...
cfb492765449d4021531f84443b0897dada0b89b
3,606,199