content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def md5hash(door: str, index: int) -> str: """ Calculate the md5 hash for the given Door ID and integer index. """ return md5((door + str(index)).encode("utf-8")).hexdigest()
e04936086a1ad43300a973a3b017a6d9a13c4129
3,624,300
import paddle.fluid as fluid def select_layer(input, name, slice_point, axis=1): """ build a layer of type 'Slice' using fluid Args: @input (variable): input fluid variable for this layer @name (str): name for this layer @slice_point (list): parameter from caffe's Slice layer ...
3a8bc396b441c8ba21fd157c626560ff7224eb19
3,624,301
def find_dom_root(parent_dom_node, dom_node): """ .. seealso:: :meth:`find_placeable_dom_tree_roots` """ if dom_node is None or parent_dom_node is None: return None if dom_node.getparent() == parent_dom_node: return dom_node elif dom_node.getparent() is None: return None ...
51cab59b4e07655277166281e8290fc9eee0e7be
3,624,302
def size_subtrees(tree: dict, root: str, tokenizer=get_tokenizer(), extra_tokens: int = 1): """ Args: tree: The tree in full_tree format of dict_to_full_tree. root: The node whose sub-trees sizes are to be measured up. ...
bea59e174f723abcc0e4280d8241a332cba3705d
3,624,303
from typing import Optional from typing import Union from typing import List import warnings from pathlib import Path def remove_tags( input: Optional[str] = 'dagmc.h5m', output: Optional[Union[str, List[str]]] = 'dagmc_removed_tag.vtk', tags: Optional[Union[str, List[str]]] = 'graveyard', verbose: Op...
4b29c41cbaa612ed3999fa024b4bd4ad21e8459a
3,624,304
def burst(wait=-1, rounds=-1, repeat=-1, req=-1, res=-1): """Creates a burst specification. Works only when netperf is compiled with --enable-intervals. For example, burst(wait=1, rounds=2, repeat=10, req=2000, res=1) will: 1) send 10 back to back 2KB requests and wait to get all 1B reponses. ...
2c741f3d9a8911b921605926e1dfd5c3db5e3916
3,624,305
def new_color(wks_id,r,g,b): """ Adds the given color to the end of the color map of the given workstation and returns the integer index of the the new color. index = Ngl.new_color(wks, red, green, blue) wks -- The identifier returned from calling Ngl.open_wks. red, green, blue -- Floating point values between 0....
3b356767c30fa7a678bccdddbbb0b85a39a80b70
3,624,306
import os def pathCorrectCase(path): """ return a normalized file path to the given path. Fixes any potential case errors. """ if os.path.exists(path): return path parts = path.replace("\\", "/").split('/'); if parts[0] == '~': newpath = os.path.expanduser('~') ...
ab8b825d899c28c17b292311c2a1cef284bb00c6
3,624,307
import subprocess def _safe_call(cmd_list): """Makes a subprocess check_call and outputs a clear error message on failure and then exits""" try: subprocess.check_output(cmd_list) return True except subprocess.CalledProcessError as err_thrown: print('Error while calling "%s"', err_t...
5bf517b5f0d5bd05b30f269dd75ea9217aeff5d4
3,624,308
def reverse_bits(num): """ reverses the bits representing the number :param num: a number treated as being 32 bits long :return: the reversed number """ result = 0 for i in range(32): result <<= 1 result |= num & 1 num >>= 1 return result
262e589cf366065018a57cd6a6c443bdd8eb638e
3,624,309
def generate_ODGD_spec_chirped(F1, F2, Fs, lengthOdgd=2048, Nfft=2048, \ Ot=0.5, t0=0.0, \ analysisWindowType='sinebell'): """ generateODGDspecChirped: generates a waveform ODGD and the corresponding spectrum, using as analysis window th...
5f31cd8b350a2f7cc8225b9ab34b11e54d619b70
3,624,310
def batch_norm(inputs, scope=None, is_training=None): """BN for the first input""" assert inputs.get_shape().ndims == 4 with tf.variable_scope(scope): output = tf.layers.batch_normalization(inputs, training=is_training) return output
66db87e8a2a1a99884d5d4de006095a961287ed3
3,624,311
def prepare_rf_acp( normaliser_model, ntrees, n_folds_acp, random_state=None, smoothing=False ): """ Prepare an acp with a random forest for continuous calibration Parameters ---------- normaliser_model ntrees n_folds_acp random_state smoothing Returns ------- """ ...
18e2e8a89aec398e591380542f1e3423a4e69473
3,624,312
def calculate_total_profit(df): """ 1. Считает итоговую прибыль :param df: - датафрейм с колонкой '<DEAL_RESULT>' :return: - итог применения стратегии """ return df.dropna()['<PERFORMANCE>'].values[-1]
918e200d276dbd3c630b5bdcb11cf771f36950e5
3,624,313
def memoize(a, b): """ 测试函数缓存 的装饰器 :param a: :param b: :return: """ return json_resp(str(_add(a, b)))
6843de03de410615f58654573b5709f5e84c7b4c
3,624,314
def before_emit(message, data, level, **options): """ this method will call `before_emit` method of all registered hooks. :param str message: the log message that must be emitted. :param dict | object data: data that is passed to logging method. :param int level: log level. """ return get_...
40a7f9af7b28d9a028c1a140097f7e7b99d47dcd
3,624,315
def find_save_mean_stay_time_table(traj_data_df=None, bin_to_coord_df=None): """Find and save the mean stay time of each bin.""" mean_stay_time_df = traj_data_df.groupby( ["no_bin", "boat_id"])["time_array"].sum().reset_index() mean_stay_time_df.rename({"time_array":"total_stay_time"}, axis=1, inpla...
dd0396650e1ca9154a84a0db58ea1a843be12ea2
3,624,316
def getMatrixListFromPoint(point): """ Args: point (MPoint) Returns: list """ return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, point.x, point.y, point.z, 1]
70a032f17fb9da468fa6011569fc42717008d8ec
3,624,317
import threading def show_progress(fun, msg, args = (), rate = 0.3): """Displays a spinner while the given function is running.""" q = Queue() def new_fun(q, a): q.put(fun(*a)) t = threading.Thread(target = new_fun, args = (q, args)) t.start() loading = ['|', '/', '-', '\\'] i = 0...
119abb3db550761d7b2f3b28e558ac8a50577a83
3,624,318
def receberInt(msg = '\tDigite um número inteiro: '): """ -> Valida a entrada de um número inteiro pelo teclado*Caso a entrada seja inválida será exigidauma nova entrada. :param msg:mensagem a ser impressa :return:número inteiro recebido """ while True: resp = input(msg).stri...
2140bb872ac8acc73e0148129344f4a4e91e69a0
3,624,319
import requests def convert_using_api(from_currency, to_currency): """ convert from from_currency to to_currency by requesting API """ convert_str = from_currency + '_' + to_currency options = {'compact': 'ultra', 'q': convert_str} api_url = 'https://free.currencyconverterapi.com/api/v5/convert' result = request...
f261dcf6c97a8e5697e6b1005513b34f755f541f
3,624,320
import hashlib def sha224(msg): """ :return: BitString of the hash """ return hashlib.sha224(msg).digest()
1339e988a0f26bd4068112b12e312cdf7df38586
3,624,321
def test_crypt(secret, hash): """check if :func:`crypt.crypt` supports specific hash :arg secret: password to test :arg hash: known hash of password to use as reference :returns: True or False """ assert secret and hash return safe_crypt(secret, hash) == hash
16fc28a474ba5ee1faaf4abf8d98ca38484c6ec7
3,624,322
def plotc(ax,x,y,z,yerr=None,xr=None,yr=None,zr=None,size=5,cmap='rainbow',colorbar=False,xt=None,yt=None,zt=None,label=None,linewidth=0,marker='o',draw=True,orientation='vertical',labelcolor='k',tit=None,nxtick=None,nytick=None,rasterized=None,alpha=None) : """ Plots a scatter plot with point color-coded by z ...
fc400a124ce20206604644706882d91c1bef6dd9
3,624,323
from aiida.backends.djsite.manager import DjangoBackendManager from aiida.backends.sqlalchemy.manager import SqlaBackendManager def get_backend_manager(backend): """Get an instance of the `BackendManager` for the current backend. :param backend: the type of the database backend :return: `BackendManager` ...
ccc360f3143af5905ffdc8142385eb0e92c61445
3,624,324
def all_candidate_sampler(true_classes, num_true, num_sampled, unique, seed=None, name=None): """Generate the set of all classes. Deterministically generates and returns the set of all possible classes. For testing purposes. There is no need to use this, since you might as well use f...
1f0d4bb75b12e48713d36d3219a2768e6ae4d89a
3,624,325
def _ilabel_to_state(labels, num_labels, ilabel_log_probs): """Project ilabel log probs to state log probs.""" num_label_states = _get_dim(labels, 1) blank = ilabel_log_probs[:, :, :1] blank = array_ops.tile(blank, [1, 1, num_label_states + 1]) one_hot = array_ops.one_hot(labels, depth=num_labels) one_hot ...
1ff2a305ca27115acba012300ffe7fd23c55d228
3,624,326
import json def loads(filepath, schemapath=None): """ This function loads a JSON file validating its contents against a given schema. For the validation, the library "jsonschema" is used. """ with open(filepath, 'r') as file: json_object = json.load(file) if schemapath: _log....
3f83dbebf2f177192b2ab5a942a34c1e81d666d3
3,624,327
def add_dims_to_array(image: np.ndarray) -> np.ndarray: """Adds 2 extra dimensions to the image array. The 1st dimension indicates the number of images per sample. The 4th dimension indicates that the image is in grayscale (single channel). Args: image (np.ndarray): The input image. Return...
030450d41af798c7ac629db89fffbc52bb9b0a9b
3,624,328
import time def TimestampFromTicks(ticks): """Construct an object holding a timestamp value from the given ticks value (number of seconds since the epoch). This function is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. :rtype: :class:`datetime.datetime` "...
8d3914507f7f12e9b9b560d916625c8910a09b3c
3,624,329
import os def get_matlab(): """ Return a running MatlabProcess instance. """ global _proc if _proc is None: path = os.path.dirname(__file__) model_path = os.path.join(path, 'model') # _proc = matlab_proc.MatlabProcess(cwd=model_path) _proc = matlab.engine.start_matlab()...
6cc8f895541931415ed756fedcc6b1e52c2b4469
3,624,330
def get_mouseState(): """ get current mouse activation state """ with open('/home/noah/.config/i3/mousestate') as fp: arr = fp.readlines() if len(arr) > 0: if arr[0] == "0": return {'full_text' : '%s' % "", 'name' : 'mousestate', "color": "#888888"} elif...
8ee7d2644bbc3ec7fbdec50a4c98e1f508626841
3,624,331
def prefix_as_comment(comment_prefix, text): """Adds comment prefixes to new lines in comments """ return text.replace('\n', '\n' + comment_prefix)
805f8e6260435a558b70e24f6692fc2a7dc6e764
3,624,332
import os def list_all_measurement_stations(json_dir): """Returns a list of the GIC measurement stations available. Parameters: ----------- json_dir :: str Directory containing json files for all stations with measurements. Returns: -------- all_st :: list List of all sta...
2df2e7aada147bef31588c11d2c59ea18e2fd32f
3,624,333
def get_transform(opt): """Basic process to transform PIL image to torch tensor""" transform_list = [] osize = [opt.loadSize[0], opt.loadSize[1]] fsize = [opt.fineSize[0], opt.fineSize[1]] if opt.isTrain: if opt.resize_or_crop == 'resize_and_crop': transform_list.append(transform...
98f91eea59ef4326a48007d3381036ffe6b3129b
3,624,334
def list_datamaskdef(ranger_client: RangerClient, service_type: str): """ Returns `dataMaskDef` properties from service definitions. """ return ranger_client.get_servicedefs_by_type(service_type)
5e6e4e8008046c17929ef4f4bd39bf73054b7b4b
3,624,335
def get_balanced_batches( n_trials, rng, shuffle, n_batches=None, batch_size=None ): """Create indices for batches balanced in size (batches will have maximum size difference of 1). Supply either batch size or number of batches. Resulting batches will not have the given batch size but rather the nex...
c506ca8f4b600b6b135e25c1a7625e05bcecf098
3,624,336
def qualified_version() -> str: """Get the qualified version of this module.""" return f"Meilisearch Python (v{__version__})"
2624cd12e644ce4da2e59f0e5ee4660e30c66894
3,624,337
import re def remove_brackets(s): """Remove brackets [] () from text """ return re.sub(r'[\(\(].*[\)\)]', '', s)
82685dfa66c2b1185a3e106f7289af5856c8e56e
3,624,338
def read_dataset(path, **filter_by): """Filters by filter_by if given, or reads entire dataset. path is a string in dot notation showing which fields the data is under (eg. 'raw.obj_pit'). competition is the competition code. **filter_by is of the form foo=bar and is the key value pair to filter da...
7a5c5b0b5b9d1fc7100656bc54d1c3a119e24609
3,624,339
def test_result(): """Test callback process_result.""" def pr(value): return value + 1 command = Command("method", "path", {}, process_result=pr) assert command.result is None assert command.raw_result is None command.process_result(0) assert command.result == 1 assert command...
3a0b0ea446f89b6d6c7998115a72432199229ff5
3,624,340
def make_lines(data, precision=None): """Extract points from given dict. Extracts the points from the given dict and returns a Unicode string matching the line protocol introduced in InfluxDB 0.9.0. """ lines = [] static_tags = data.get('tags') for point in data['points']: elements ...
c2210bdaa377c83242cbe821a3ae70042d7e5c03
3,624,341
def subdivide_joint(joint1 = None, joint2 = None, count = 1, prefix = 'joint', name = 'sub_1', duplicate = False): """ Add evenly spaced joints inbetween joint1 and joint2. Args: joint1 (str): The first joint. If None given, the first selected joint. joint2 (str): The second joint. If N...
0946b2bd8e9d2ae80d6e11a7ea36e40ab44b7aa7
3,624,342
def red(message, bold=False): """ Color in red """ return colour('red', message, bold)
1b25cbf1aeeb23e2664815097948f95a9643fed2
3,624,343
from datetime import datetime def create_datediff_test_df(): """Create DataFrame for DateDifferenceTransformer tests.""" df = pd.DataFrame( { "a": [ datetime.datetime(1993, 9, 27, 11, 58, 58), datetime.datetime(2000, 3, 19, 12, 59, 59), date...
a7e9ae069e051fe3887a7e4b4ddc4b93a4e9082a
3,624,344
def get_channel_id(channel_name, channel_type): """ Fetches the ID of a Slack Channel or User Args: channel_name: (string) The name of the channel / name of user / slack id of channel/user channel_type: (string) The Channel type, either "user" or "channel" or "slack_id" Returns: ...
c814bd47414396f67947324a76171da3413b03fe
3,624,345
def createLimit(name, maxValue): """Create a new Limit with the given name and max value. :type name: str :param name: the name of the new Limit :type maxValue: int :param maxValue: the maximum number of running frames for this limit :rtype: opencue.wrappers.limit.Limit :return: the newly c...
a7d11ce7f06c0abe83b9a915e8f03ad13d96dcbd
3,624,346
def get_bounding_box(vehicle, camera, sensor_transform): """ Get vehicle bounding box and project to sensor image. Args: -vehicle (carla.vehicle or ObstacleVehicle): vehicle object. -camera (carla.sensor.camera.rgb): The CARLA sensor object. -sensor_transform (carla.Transform): senso...
ee33cf14c03f1b19d25cecc631821b728107d3d8
3,624,347
def calcAbsolutePercentageError(actualResult, forecastResult): """ Calculates Absolute Percentage error. returns float """ return (abs((actualResult - forecastResult)/actualResult)) * 100
6212f368477ece2a6f602ab8cdc865eeedafc864
3,624,348
def section_areas(neurite): """Section areas.""" return _map_sections(sf.section_area, neurite)
c338e47bc2e7f3cf3da93b33b384b3ef20f2cfa9
3,624,349
def set_type_labelling(node, type_label): """ Sets type labelling of the given node :param node: str :param type_label: str """ if not type_label or type_label not in maya_constants.TYPE_LABELS or not attribute_exists(node, 'type'): return False type_index = maya_constants.TYPE_LAB...
caec998af5d6fd6c1eedc9e98a6c6ff68cae72db
3,624,350
def dataset(paths_or_factories, filesystem=None, partitioning=None, format=None): """ Open a dataset. Parameters ---------- paths_or_factories : path or list of paths or factory or list of factories Path to a file or to a directory containing the data files, or a list of...
835320d451febe8273ee7d8b62d8ac831fb87b7b
3,624,351
import requests import atexit import argparse import traceback import sys def main(): """Entry point.""" session = requests.Session() atexit.register(on_exit, session) parser = argparse.ArgumentParser(description='Download file from Illumina BaseSpace.') def check_tries_within_range(arg): ...
eb759cc574d875fa4010306152cce2090126cb27
3,624,352
from typing import Set def get_references(content: str) -> Set[URI]: """Get the unique set of references in a string.""" return set(URI(ref) for ref in re_ref.findall(content))
c525b829052a38b18b270aedeb417b89e3ffc450
3,624,353
from functools import reduce def array_intersection(arrays_list, fields): """ Find and return the intersecting entries in multiple arrays. Parameters ---------- arrays_list : :obj:`iterable` Iterable of input structured arrays fields : :obj:`iterable` Iterable of fields to us...
c591ab02401e78567edfd7e46541d417706f022e
3,624,354
def numeric_density(pressure: FloatLike, temperature: float = 300) -> FloatLike: """Calculate numeric density of a gas. Args: pressure (float): pressure in mTorr temperature (float): temperature Returns: float: Numeric density (atoms per cubic meter) """ return pressure * M...
19287df57254fc71be88a1f04349b06ae0815050
3,624,355
def is_postgres_connected() -> bool: """ Check we can reach the main postgres and perform a super simple query Returns `True` if so, `False` otherwise """ try: with connections[DEFAULT_DB_ALIAS].cursor() as cursor: cursor.execute("SELECT 1") except DjangoDatabaseError: ...
42aa6ba7623e7a68013378a5e4cfa852e640ec4b
3,624,356
def match_hyperparameter(hp, parameters): """ Given a partial hyperparameter name hp find the corresponding full name in parameters """ matches = [] for par in parameters: if hp == par: matches.append(par) if len(matches) != 1: raise ValueError('{} matches found for ...
edf4d19638ee077d5dcf903db0b1ff1325a20fb0
3,624,357
from datetime import datetime def current_week() -> int: """Compute today's MAVEN science week number. """ return week_from_date(datetime.date.today())
e6b7bb438fe2a7607264d099c926fd783bfce300
3,624,358
import json def download_status(): """ 监测 global / local 是否执行完毕, 是否可以下载的状态 :return: """ print("download_status\n") if (Common.reg_status.get("global") == "true" and Common.reg_status.get( "local") == "no local") or ( Common.reg_status.get("global") == "true" and Common....
89ca7a13f5f9a953893c319cd26b48ab52ea5711
3,624,359
import collections def _organize_runs_by_lane(run_info): """Organize run information collapsing multiplexed items by lane. Lane is the unique identifier in a run and used to combine multiple run items on a fastq lane, separable by barcodes. """ items = _normalize_barcodes(run_info["details"]) ...
a0513b258bdc3adf695d79cfd38637b3ca4690b3
3,624,360
def can_embed_image(repo, fname): """True if we can embed image file in HTML, False otherwise.""" if not repo.info.embed_images: return False return ("." in fname) and ( fname.split(".")[-1].lower() in ["jpg", "jpeg", "png", "gif"] )
40bfdd8c32ddd5f3d3bd2ae074494ba34e6fc1f1
3,624,361
def should_sync_model(model): """ whether or not the given Django model is something the i18n sync should process. We care about models that: - extend the Internationalizable model defined by this module - are not proxy models (unless the model explicitly opts in to translation) """ ...
773d95522a1fddcdd95eaa4b98e3e05010c17c18
3,624,362
def get_modal_triggers(offend_atoms, implied_modalities): """ :param offend_atoms: set of offending modal atoms at given w :param implied_box: set of tuples representing implied boxes and implied diamonds :return set of antecedent atoms in modal implications """ triggers = set() for atom i...
fb98cfba81a12ee0c0c466ceb601929da959fc84
3,624,363
def to_24bit_gray(mat: np.ndarray): """returns a matrix that contains RGB channels, and colors scaled from 0 to 255""" return np.repeat(np.expand_dims(_normalize(mat) * 255, axis=2), 3, axis=2).astype(np.uint8)
7798cbf5e954a6d6d391eb1133f7cc2fa7fcfd60
3,624,364
def check_client_ip_and_token_ip(request): """ Checking client ip with token ip """ if request.auth is None: return False if getattr(request.auth, 'payload') is None: return False token_real_ip = request.auth.payload.get(api_settings.USER_IP_CLAIM, '') real_ip = get_real_ip...
8ddf1a9a43935abc3478fd680d19629c36436ea0
3,624,365
def _find_file_or_404(path, force): """Gets the full path and extension, or raises 404.""" try: return _find_file(path, force) except ValueError: abort(404)
042a2f2aff496110c1b2079d3b705bb6972c5a96
3,624,366
def calc_qs(temp, pres): """ Elemental Function to determine the precipitation estimate for each value of tempreature and omega at each grid point. (func to be used in starmap multithreading) ------------------ Input : temp : temperature value at a grid point. omega_da : vertical velocit...
dd48b1d799ae9eb676cb031d93756a7697bb1806
3,624,367
def datetime_to_isoformat(dt): #============================= """ Convert a Python datetime to an ISO 8601 representation. :param dt: A Python :class:~`datetime.datetime`. :return: A string representation of the date and time formatted as ISO 8601. """ iso = dt.isoformat() if iso.endswith('+00:00'): retu...
508ce4ea3e0905aab0b16c6b28fa4e9304e18b08
3,624,368
import os def om_wrapper(J, initial_DVs, dJ, H, bounds, **kwargs): """ Custom optimization wrapper to use OpenMDAO optimizers with dolfin-adjoint. Follows the API as defined by dolfin-adjoint. Parameters ---------- J : object Function to compute the model analysis value at a ...
13883a8fe12aa948f6f3a097f94f3774d667713b
3,624,369
import inspect def command(*args, **kwargs): """ Message command hook """ def _command_hook(func): add_plugin_function(plugin_function( func, callback_type.CMD, kwargs, inspect.stack()[2][1])) return func # this decorator is being used directly if len(args) == 1 an...
75b0aa0a3b5ce1b6870fdcd1a2d4af0c7cd679e7
3,624,370
import functools import warnings import textwrap def deprecated(since, message='', name='', alternative='', pending=False, addendum='', removal=''): """ Decorator to mark a function or a class as deprecated. Parameters ---------- since : str The release at which this API bec...
5913f8f2f8ad8a80a17bc3b979d0f2fd9aed0056
3,624,371
from typing import Optional from typing import Dict from typing import Any import re from typing import Iterable from typing import cast def analyse_args( analyser: Analyser, opt_args: Args, sep: str, nargs: int, action: Optional[ArgAction] = None, ) -> Dict[str, Any]: """ ...
8d58a2cc60ce5dab7f4ecf060c8e9aa47eabd829
3,624,372
def pytest_fixture_setup(fixturedef, request): """Support async fixtures.""" func = fixturedef.func # Fix aiolib fixture if fixturedef.argname == 'aiolib': def fix_aiolib(*args, **kwargs): """Convert aiolib fixture value to a tuple.""" aiolib = func(*args, **kwargs) ...
b2fa1d33ee029f3cbf3a05b128e615272bbafca4
3,624,373
import os def test_aws_availability(): """ Test if aws s3 is available """ s3_status = os.system('aws s3 ls s3://stpubdata --request-payer requester > /tmp/aws.x') if s3_status == 0: s3_sync = 'cp' # As of late October 2018, 's3 sync' not working with 'stpubdata' else: s3_sync...
889eb45d3e7556b6ffe80258cc96e12b24c79ccd
3,624,374
def calculate_character_error_rate(groundtruth, transcription): """Calculate character error rate""" groundtruth = normalize_sentence(groundtruth) transcription = normalize_sentence(transcription) return ed.eval(transcription, groundtruth) / len(groundtruth)
a391972052d35a97952511a06292ed2ca9a463b0
3,624,375
import os def occupancy_over_time(output_dir, scenario_parameters, operator_attributes, dir_names, op_id, show=False, bin_size=DEF_TEMPORAL_RESOLUTION, evaluation_start_time=None, evaluation_end_time=None): """ this function creates a plot of the different vehicle occupancies over time ...
902731a9b5a9dc58f2042a1d894f14e49058baad
3,624,376
import os import logging import json def read_file(): """Read kamonohashi config file. If not exists or invalid, raise Exception. :rtype: dict """ require_login = "Log into KAMONOHASHI first to use 'account login' command." if os.path.exists(config_file_path): logging.info('open config fi...
984ed5bc4c429b8dec33f3f01355ce2c73f321c3
3,624,377
def parse_commamd (cmd): """Parses a command provide from the command line. Parses a command found on the command line. I Args: cmd: The command, e.g. `paste` or `type:hello` Returns: a list of command, data """ parts = cmd.split(":") data = ":".join(parts[1:]) return (parts[...
c1a40f1508cb568e3a2ebf5b82f96baf81108fe1
3,624,378
def _merge_dataset_polarity_scores() -> pd.DataFrame: """ Merges the dataset of news articles annotated with named entities with the pre-calculated polarity scores. """ dataset = _load_dataset_with_entities() polarity_scores = _load_polarity_scores() utils.get_logger().debug('Data loading: Adding polar...
0e0149d378d2067b2be5c1c1d30c11f26540b171
3,624,379
import json def read_dataset_json(path): """ Read playlists from dataset json file Parameters: - path - absolute path of the file """ with open(path, "r") as f: data = json.load(f) return data["playlists"]
06b5e6b6d07c549ed459d9567efd316f6412c13b
3,624,380
import os def classification_set(target_dir, train_dirs, test_dirs): """ collect annotation files in target dir (target_dir/data_dir/class_dir/image_file) :param target_dir: root path that contains data set :param train_dirs: directory list used for train data :param test_dirs: directory list used...
2be890e09afd1475f1a19214bfb9f69ad66bdbfb
3,624,381
def _factor(lexer): """Return a factor expression.""" tok = _expect_token(lexer, FACTOR_TOKS) # '~' F toktype = type(tok) if toktype is OP_not: return ('not', _factor(lexer)) # '(' EXPR ')' elif toktype is LPAREN: expr = _expr(lexer) _expect_token(lexer, {RPAREN}) ...
950b606ab6c624812fc56b93de5d087f92ec8f81
3,624,382
def pad_string(data, size, padding_character=' ', direction='left'): """This new function will determine if it will pad to the left or the right by using an if statement.""" if direction == 'left': data.rjust(size, padding_character) elif data == 'right': data.ljust(size, padding_character) ...
4a53a448e965c2ea1227360edca774567c4797a4
3,624,383
def read_ascii_ply(filename): """Reads a PLY file encoded in ASCII format. NOTE: this util method is not intended to be comprehensive PLY reader and serves as part of demo application. Args: filename: path to a PLY file to read. Returns: numpy `[dim_1, 3]` array of vertices, `[dim_1, 3]` array of c...
30c0bb7469a79e62b6bf47b454e6f7dc9320bba4
3,624,384
from typing import Dict from typing import List def to_sql(dialect: Dialect, model: SqlModel) -> str: """ Give the sql to query the given model :param dialect: SQL Dialect :param model: model to convert to sql :return: executable select query """ compiler_cache: Dict[str, List['SemiCompile...
d1005709122a4379c6b8c9a8f5b0088932fa08e7
3,624,385
def disttar_suffix(env, sources): """tar archive suffix generator""" env_dict = env.Dictionary() if env_dict.has_key("DISTTAR_FORMAT") and env_dict["DISTTAR_FORMAT"] in ["gz", "bz2"]: return ".tar." + env_dict["DISTTAR_FORMAT"] else: return ".tar"
ef0b5378d3efaae68edb4c5cbaa5541c21f82a55
3,624,386
def _data_qubit_parity(q: complex) -> bool: """To optimally interleave operations, it's useful to split into a checkerboard pattern.""" return (q.real // 2 + q.imag) % 2 != 0
92f5b9288eb5a009befd7c99c7e7f67f589100a6
3,624,387
def normalize(word): """ Normalizes the word for synsets() or Sentiwordnet[] by removing diacritics (PyWordNet does not take unicode) and replacing spaces with underscores. """ if not isinstance(word, str): word = str(word) if not isinstance(word, str): try: word = wo...
d642bf0d0a766ea3d010c0997bdf0309ad1602b0
3,624,388
import os def test_put_copy_many_files_gcp(tmpdir, conn_cnx, db_parameters): """[gcp] Puts and Copies many files.""" # generates N files number_of_files = 10 number_of_lines = 1000 tmp_dir = generate_k_lines_of_n_files(number_of_lines, number_of_files, tmp_dir=str(tmpdir.mkdir('data'))) table_...
185d4440f45c8d11348cdce9ac77b67ca6567ec5
3,624,389
def get_traits_by_germplasm(germplasmId): # noqa: E501 """Returns all phenotypes for a germplasm that we have # noqa: E501 :param germplasmId: Unique database ID for the germplasm :type germplasmId: str :rtype: List[Phenotype] """ return 'do some magic!'
8fd66bd49b0276217e6422b42f5f8fa6115df060
3,624,390
import colorsys import random def draw_boxes_and_labels_to_image_with_json(image, json_result, class_list, save_name=None): """Draw bboxes and class labels on image. Return the image with bboxes. Parameters ----------- image : numpy.array The RGB image [height, width, channel]. json_resul...
f44ebf98d83530986a657fce02bd1fc05820833b
3,624,391
import typing def sampled_softmax_loss(positive_keys: tf.Tensor, inputs: tf.Tensor, num_samples: int, de_config: de_config_pb2.DynamicEmbeddingConfig, var_name: typing.Text, service_address: ty...
9c1a1fb396932548fed2b22ae3bae53bca727998
3,624,392
async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: """Set up Netgear component.""" router = NetgearRouter(hass, entry) try: await router.async_setup() except CannotLoginException as ex: raise ConfigEntryNotReady from ex hass.data.setdefault(DOMAIN, {})...
129defe60332f7f7dfbb400af3a5c42e0b69917a
3,624,393
import six import inspect import sys import logging import functools def patch_plugs(phase_user_defined_state=None, phase_diagnoses=None, **mock_plugs): """Decorator for mocking plugs for a test phase. Usage: @plugs(my_plug=my_plug_module.MyPlug) def my_phase_that_uses_my...
30ab694352ec185b2c40601a84f55bebf02ebaf6
3,624,394
import re def get_hosts(r_config, r_dest): """ :param r_config: 主机组配置[dir] :param r_dest: 目标主机组 [str] :return: [list] """ matched_str = [] rst = [] for key in r_config.keys(): if re.match(r_dest, key): matched_str.append(key) for key in matched_str: rs...
dd4becccdc8ad64cd59a7936a6a4e14f3d515123
3,624,395
def purge(objects): """purge notification or program data""" objects = objects.lower() if not objects: return no_args_msg if objects not in object_map.keys(): return error_msg queryset = object_map[objects] msg = "Purging {} {}".format(queryset.count(), objects) queryset.dele...
49920925889fe02228a9cda59011977f3bba7020
3,624,396
from typing import Any from typing import Sequence from typing import Tuple def mixture_channel( val: Any, default: Any = RaiseTypeErrorIfNotProvided) -> Sequence[ Tuple[float, np.ndarray]]: """Return a sequence of tuples for a channel that is a mixture of unitaries. In contrast to `mixture` this...
8070b283a8c1bbcbb730e64581218898c82ef769
3,624,397
from typing import List def get_dropped_pks(engine: Engine, table: Table, from_commit: str, to_commit: str) -> List[dict]: """ Given table_metadata, a connection, and a pair of commits, will return the list of pks that were dropped between the two commits. :param engine: :param table: :param f...
5ab8c807605814161384582b400536747ec85063
3,624,398
def get_mode_from_params(params): """Returns the mode in which this script is running. Args: params: Params tuple, typically created by make_params or make_params_from_flags. Raises: ValueError: Unsupported params settings. """ if params.forward_only and params.eval: raise ValueError(...
35564684eef73adf821989dea27bfdc7de0443ae
3,624,399