content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
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
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
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
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 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 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
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
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
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
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
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 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
from typing import Optional import torch def equadrupole(qc: BaseQCCalc, unit: Optional[str] = "Debye*Angst") -> torch.Tensor: """ Returns the electric quadrupole moment of the system, i.e. derivative of energy w.r.t. electric field. Arguments --------- qc: BaseQCCalc The qc calc obje...
6810c122f353e40a336365518b51b01b59199726
3,624,400
def get(key, nodename=None): """ A function to get a node pillar configuration key. CLI Example: salt * node.get hostname """ return _get_property(key, nodename, None)
5dde600e2aa9f4f256ae66f4468270969ecbb057
3,624,401
def quote_logvalue(value): """Return a value formatted for use in a logfmt log entry. The input is quoted if it contains spaces or quotes; otherwise returned unchanged """ s = str(value) if " " in s or '"' in s: s = s.replace('"', "\\" + '"') return f'"{s}"' return s
15dd0789b5a7ce4e18eece37ad0cac59d9cd2332
3,624,402
from datetime import datetime def create_new_form_search(data): """Create a new form search. :param dict data: the form search to be created. :returns: an form search model object. """ form_search = FormSearch() form_search.name = h.normalize(data['name']) form_search.search = data['sea...
69f3851e4b64173968264819d2cf8d1d23b07318
3,624,403
def split_filename(fn, name=None, prefix=None, suffix=None, stack_limit=2): """ Ermittle einen Namen und ein Label aus dem Dateinamen, der ggf. aus dem Aufrufstack ermittelt wird. Zunächst "richtige" Entwicklungs- oder installierte Quellen: >>> split_filename(...
59058b0513074ad8caed590aab66db01f2858252
3,624,404
from re import T import scipy def model2magcoords( xg: dict[str, T.Any], parm: xarray.DataArray, lalt: int, llon: int, llat: int, altlims: tuple[float, float] = None, mlonlims: tuple[float, float] = None, mlatlims: tuple[float, float] = None, ): """ Grid the scalar GEMINI outpu...
a70ba50945b06ea1771728b7e90750f2efd5b1d6
3,624,405
def flatten(master): """ :param dict master: a multilevel dictionary :return: a flattened dictionary :rtype: dict Flattens a multilevel dictionary into a single-level one so that:: {'foo': {'bar': { 'a': 1, 'b': True, ...
d31325219e43ee5c047c1a78589d94e2d7c62709
3,624,406
def network(ip): """Network an IP address belongs to. Parameters ---------- ip : str IP address. Returns ------- network_ip_with_prefix : str IP address of the network with prefix. """ ip, prefix = netParse(ip) return "{}/{}".format( ipS...
e38088b3b747deb365d061426737beb0f14fa9b1
3,624,407
def _build_pnasnet_base(images, normal_cell, num_classes, hparams, is_training, final_endpoint=None): """Constructs a PNASNet image model.""" end_points = {} def add_and_check_endpoint(endpoin...
4ada0f21e316b50982245894e55344b3fb772071
3,624,408
def _parse_advantage_prereq(el: et.Element, function_name: str) -> str: """Parse a <advantage_prereq> element and its children. Return a str of Python code that takes traits and trait_names as arguments and evaluates to True iff the prereqs are satisfied. """ if el.get("has") == "no": if le...
be9a1a85d66baf9e73452e6a890fa741185abb37
3,624,409
def m21_midievent_to_event(midievent): """Convert a music21 MidiEvent to a tuple of MIDI bytes.""" status = midievent.data + midievent.channel - 1 return (status, midievent.pitch, midievent.velocity)
3950b4e6715ac4de2dbdcc2d87d5cf51387a220c
3,624,410
import numpy def populate_impl_map(data_model): """ Map symbols to implementations. """ impl_map = { "==": _type_safe_equal, "=": _type_safe_equal, "!=": _type_safe_not_equal, "<>": _type_safe_not_equal, "<": numpy.less, # already checks types "<=": num...
fc854ec2baf90905f9bc65018453ac64b7fbc2de
3,624,411
from datetime import datetime def friendly_time(d: datetime.datetime) -> str: """Return "minutes ago" style date""" ad = Arrow.fromdatetime(d) other = Arrow.fromdatetime(datetime.datetime.utcnow()) return ad.humanize(other)
47f2ef48d44fbd40dbddf5ed76f37836992476f3
3,624,412
from typing import Container from typing import Sequence def power_set_str_v2(s: str) -> Container[Sequence]: """ Note: it doesn't take empty set into accout. """ # print all subsets of the remaining elements, with given prefix def _power_set_str_v2(prefix: str, s: str, result) -> None: ...
119a9e6118298f0d05ed3b14f43788e5d1c7ba49
3,624,413
from typing import Any def build_get307_request(**kwargs: Any) -> HttpRequest: """Redirect get with 307, resulting in a 200 success. See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder into your code flow. :return: Returns an :class:`~azure.core.rest.HttpR...
6730bb8391ff007d44533eaab25129d71719b7da
3,624,414
def svm_SVR_C( xM, yV, c_l, graph = True): """ SVR is performed iteratively with different C values until all C in the list are used. """ r2_l, sd_l = [], [] for C in c_l: print 'sklearn.svm.SVR(C={})'.format( C) clf = svm.SVR( C = C) clf.fit( xM, yV.A1) yV_pred = clf.predict(xM) r2, sd = regress_...
3e194e569b0c86a2047a35a58e430e814b539029
3,624,415
from typing import Union def solar_declination( doy: Union[np.ndarray, xr.DataArray] ) -> Union[np.ndarray, xr.DataArray]: """Solar declination from day of year [rad]. Parameters ---------- doy: array.py day of the year (1-365) Returns ------- Union[np.ndarray, xr.DataArray] ...
b8573dd30fc0adce404ff929083616afe9d46011
3,624,416
import logging import pandas def load_gwas(args, use_specific_targets): """Watch out! Pandas parser on occasion reads the column `position` as integer. Yikes.""" columns = ["variant_id", "panel_variant_id", "chromosome", "position", "non_effect_allele", "effect_allele","zscore"] if use_specific_targets is...
b3ece4db92bdb6aeacf950b2ac802fd48550fad3
3,624,417
import copy def merge_dict(d1, d2, overwrite=False): """Merge contents of d1 and d2 and return the merged dictionary Note: * The dictionaries d1 and d2 are unaltered. * If `overwrite=False` (default), a `RuntimeError` will be raised when duplicate keys exist, else any existing keys in d1 are s...
d680dcc3039804c340fc488a488fae1d891a8d1b
3,624,418
def handle_not_found(error: NotFound) -> Response: """Render the base 404 error page.""" rendered = jsonify({'code': error.code, 'error': error.description}) response = make_response(rendered) response.status_code = status.HTTP_404_NOT_FOUND return response
31944d23b89b60f0b6b7059ce717f52ff7c714e8
3,624,421
def compare_documents(sample_text_a: str, sample_text_b: str) -> float: """Compares two documents using spacy's bow model""" doc_a = nlp_en(sample_text_a) doc_b = nlp_en(sample_text_b) return doc_a.similarity(doc_b)
85dbce4ef6b8f1b6ca7cd7a8dbe54390de530ff3
3,624,422
def calc_fragment_mz(pep, frag_type, frag_num, frag_charge, mod=None) -> float: """ Example: pep = 'LGRPSLSSEVGVIICDISNPASLDEMAK' frag_type = 'y' frag_num = 10 frag_charge = 1 mod = '15,Carbamidomethyl;26,Oxidation;' -> 1091.5037505084001 :param pep: peptide sequence :param frag...
984af3bd523dcbac5a89e5405dabd8a5dabc062b
3,624,423
def invert_axis(document: vp.Document, invert_x: bool, invert_y: bool): """Inverts none, one or both axis of the document. This applies a relative scale operation with factors of 1 or -1 on the two axis to all layers. The inversion happens relative to the center of the bounds. """ bounds = docu...
ac822e0a93f27b20043e21e72b94d394ba85ddfb
3,624,424