content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _generic_mixer(slice1, slice2, mixer_name, **kwargs):
"""
Generic mixer to process two slices with appropriate mixer
and return the composite to be displayed.
"""
mixer_name = mixer_name.lower()
if mixer_name in ['color_mix', 'rgb']:
mixed = _mix_color(slice1, slice2, **kwargs)
... | 58e5a36162382bee9c521a6be2221dfb8fdfe258 | 3,597,898 |
def _MakeSplitDimension(value, enabled):
"""Return dict modelling a BundleConfig splitDimension entry."""
return {'value': value, 'negate': not enabled} | de4d44598e5c9c76e46b57b4b07f41698dbe983d | 3,597,899 |
def attr_pairlist(obj,names=None,types=pod_types,skip_callable=True,skip_private=True,skip_trailing_underscore=True):
"""return a list of tuples (a1,v1)... if names is a list ["a1",...], or all the attributes if names is None. if types is not None, then filter the tuples to those whose value's type is in types'"""... | 28616414fb6c1b4239a82c69b9aaee679780d087 | 3,597,900 |
from ..devices import pin_factory
def pi_info(revision=None):
"""
Returns a :class:`PiBoardInfo` instance containing information about a
*revision* of the Raspberry Pi.
:param str revision:
The revision of the Pi to return information about. If this is omitted
or ``None`` (the default... | dfd2ce4d247029773c4f867d5d28c9ca42b63a6c | 3,597,901 |
def check_register_quantity(count, modbusFunction):
"""
function to check count keyword in each modbus command configured in the template
when count value > 1 it generates the error.
otherwise function return count value
The following condition trigger error with "count":2
{
"name": "PLC... | 0eaf124110c2b7f881aa36ba9efcbbe2ebec9b3d | 3,597,902 |
def get_download_params(request):
"""Check whether structures have been previously downloaded
Args:
request
Returns:
protein_params, other_params
"""
protein_param_flags = ['pdb_info', 'bound_info',
'cif_info', 'mtz_info',
'dif... | 816d305d85e0a5b04f2bc7da6e815662075d33df | 3,597,904 |
import math
def calc_easing_degree_for_proportion(proportion):
"""
Calculates a reasonable easing degree for a given proportion.
"""
return -math.log10(proportion) + 1 | feeab6e87fba3060cbd37f89f3e0391df1bc1102 | 3,597,905 |
def spatial_mean(tensor, ndim=1):
"""
Average `tensor` over the last dimensions; keep only the first `ndim` ones.
"""
if tensor.ndim > ndim:
return tensor.mean(tuple(range(ndim, tensor.ndim)))
return tensor | 19bcf5df1d197069842792b9bd5d07a5e223d609 | 3,597,906 |
def merge_sort(array):
"""Сортировка слиянием Сложность n^2"""
l = len(array)
if l == 1:
return array
first = array[:l/2]
second = array[l/2:]
res = merge(merge_sort(first), merge_sort(second))
return res | eb982fb880f55140f5781deac703b9bacada8278 | 3,597,907 |
def random_color():
"""
Return random color.
:return: Color tuple
"""
return randrange(0, 255), randrange(0, 255), randrange(0, 255) | c8ffdc98ff19f1a9e66c3f34665dea8118719913 | 3,597,908 |
def dot_tridiagonal(lap, P):
"""
Dot product for tridiagonal operator.
Parameters
----------
lap: ndarray(shape(N//2+1, 2, N), dtype=float)
Tridiagonal operator (typically laplacian).
P: ndarray(shape=(N,N), dtype=complex)
Input matrix.
Returns
-------
W: ndarray(sh... | 0e10ae91432eb0b1123caa94fcc14fa898efb140 | 3,597,910 |
def get_csv_as_dataframe(path):
"""Take CSV path. Return pandas dataframe.
"""
return pd.read_csv(path,
index_col='trial_index',
converters={'participant_id': lambda x: str(x)}
) | 3ca78ae6c749cc26dd9af9f1b5ac00f682ba97fe | 3,597,911 |
import binascii
def get_address_bytes_from_string(address_string):
"""
Given a Bluetooth address as a string, optionally delimited by colons (':'), return the
bytes representation of the address.
:param address_string: A Bluetooth address string, optionally delimited by commas. This value is case-in... | 88e83d5916c461e34300a330603e3975320d6568 | 3,597,913 |
def sampling(args):
"""Reparameterization trick by sampling fr an isotropic unit Gaussian.
# Arguments
args (tensor): mean and log of variance of Q(z|X)
# Returns
z (tensor): sampled latent vector
"""
z_mean, z_log_var = args
batch = K.shape(z_m... | 1f04c94d87e6521a9d15039c603ea9a35eb42d20 | 3,597,914 |
from typing import Dict
from typing import Any
from typing import Union
def get_asset_command(client: Client, args: Dict[str, Any]) -> Union[str, CommandResults]:
"""
Retrieve the asset of the specified UUID from Global Inventory.
:param client: The Client object used for request
:param args: The com... | 341ed3fa5a7cf6a6c570927e125657bf80cdb126 | 3,597,915 |
def createChargeExchangeRates_MS(Z, A, pressure, ionTemperature):
""" An implementation using the work of Salzborn and Mueller from 1977 paper.
"""
chargeExchangeRates = [0] * (Z + 1)
h2Density = pressure * __TORR__
print("Number density of background gas... %s cm^-3"%'{:.2e}'.format(h2Densit... | ca04ca8c77fef3a57f11887dc2feff22f004993b | 3,597,916 |
import json
def gettraffic(request):
"""
Return the traffic for the interface
"""
datasets_in = []
datasets_in_i = []
datasets_out = []
datasets_out_o = []
label = "KBps"
try:
intf = get_ipaddress()
intf = intf['interface'][0]
traffic = get_traffic(intf)
... | 5f484c2b6bbfd9a72a85c3ca86012a287ae8db34 | 3,597,917 |
def _is_hop_by_hop(header_name):
"""Return True if 'header_name' is an HTTP/1.1 "Hop-by-Hop" header."""
return _hoppish(header_name.lower()) | d734b43819d0e5bd451fe0d9eb34bee0c39698d8 | 3,597,918 |
def trace_dirichlet_expansion(field):
"""
u0, u1 = trace_dir_asy(field)
Return the fist two terms of the asymptotic expansion of the trace along the
ellipse.
Parameters
----------
field : Field
Field object from the dataclass
Returns
-------
u0 : Function
θ ↦ c... | 37258a2127824d0f0131dc89edb056ec36b2b7b0 | 3,597,919 |
from typing import Dict
from typing import Any
def _extract_model_description(field: BaseType) -> Dict[str, Any]:
"""
Load title and description from Schematics metadata.
:param field: field to extract metadata from
:return a dict with optional title and description keys
"""
metadata = field... | 62a24ff731129c4f824189f86bf5dd7dc37cf4db | 3,597,920 |
def compute_wavelets(thth, thph, phph, rot_sph):
"""
Computes symmetric strain tensor components
(in spherical coords, from tape)
"""
exx, eyy, exy, rot = [], [], [], [];
for i in range(len(thth)):
eyy.append(1e9*thth[i])
exy.append(-1e9*thph[i])
exx.append(1e9*phph[i])
... | 2562e00673e99b105dbdd9d89410f436cf1feae0 | 3,597,921 |
import logging
def post_assembly_ids(assembly_id_list, df_row, args):
"""Coordinate posting of assembly IDs to Entrez and retrieval of webenv and query key.
:param assembly_id_list: list, list of assmebly IDs
:param df_row: pd series, row from dataframe
:param args: parser arguments
Return WebEn... | 0be24e4e9e9dbe069b5dabed636897ee84f27c66 | 3,597,922 |
def threshold_connect_components(map, threshold, copy=True):
""" Given a map with some coefficients set to zero, segment the
connect components with number of voxels smaller than the
threshold and set them to 0.
Parameters
----------
map: ndarray
The map to segme... | c5138eb24cbd6e6766af73cd59fe4fcd70df4b67 | 3,597,923 |
import requests
def geo_coder(search_text):
"""
Get latitude and longitude given a search text
:param search_text: search text
:return: latitude and longitude
"""
payload = {
'app_id': HERE_APP_ID,
'app_code': HERE_APP_CODE,
'searchtext': search_text
}
response ... | 21b4a5dc066ef78926ab6510710cc8e72bee8d84 | 3,597,924 |
def read_cp2k(in_name, pop="ESP"):
"""
Read the charges and energy in a cp2k output file.
Uses CP2K 4.1 formats. Choose between Mulliken, Hirshfeld or RESP charges.
Parameters
----------
in_name : str
Name of the file to read
pop : str
Kind of charge to read: mulliken, esp ... | 228edd15ed160bd319ec0e30a91e54b2fb9490c1 | 3,597,926 |
def get_val_test_acc(data):
"""Parses log file to retrieve test and val accuracy."""
data = [x.split() for x in data if len(x.split()) > 1]
val_acc_idx = data[-4].index('val_{}'.format(FLAGS.target))
test_acc_idx = data[-3].index('test_{}'.format(FLAGS.target))
val_acc = data[-4][val_acc_idx + 2]
test_acc =... | 0f940d5feaec287a035b167d985ed9158e3a4008 | 3,597,927 |
def _decode_asn1_string(data):
"""Convert ASN.1 string to a Unicode string.
"""
if isinstance(data, BMPString):
return bytes(data).decode("utf-16-be")
else:
return bytes(data).decode("utf-8") | 0a5a47807ddcb3eedf46a52ce2acd60a83955103 | 3,597,928 |
def compute_mean_rt(df):
"""
Computes subject-wise mean RT
Input
---
df : dataframe
aggregate response data
Returns
---
array of subject-wise mean RTs
"""
return df.groupby('subject').rt.mean().values | 04b51953a8a5fa37fc746e32416bd0b598cfb138 | 3,597,929 |
def create_environment(name, application, cname=None, tier="web",
key_pair=None, instance_type="t2.micro",
profile=None, role=None, healthcheck_url=None):
"""Create an Elastic Beanstalk environment.
Note: you can add OptionsToRemove, just like OptionSettings. Those... | cfaf34aea49137fa545daa6464e46458791c8c7b | 3,597,930 |
import numpy
import pandas
def pairwise_discover_test(x, g=None, alternative="less", fdr_method="DBH"):
"""
Perform many pairwise mutual exclusivity or co-occurrence tests.
Parameters
----------
x : DiscoverMatrix
g : array_like, optional
An optional grouping vector for the rows of `... | 0ee2a7b804c27881052e856c6ce79cc6ae7a7ab3 | 3,597,931 |
import google
import time
def execute_search(locations, distance, query):
"""
Searches each API module at the given location(s) and distance.
:param locations: User supplied lat/long point(s)
:param distance: How far to search (meters)
:param query: The niche, i.e. restaurants, bars, etc
:ret... | a0059d43dfcbdfa63c2d5b943d0fb4b97df665eb | 3,597,932 |
from pathlib import Path
from datetime import datetime
def read_sxm_v1(path):
"""
Need to update this docstring
Inputs:
path: string. Specifies the full file path (including file extension) of the file to be imported.
Outputs:
data: SPMImage. Contains the imported data.
"""
... | ba77d27a41282a2d2aeb9e96e2f85af88d340c26 | 3,597,933 |
import re
def add_iteration_suffix(name):
"""
adds iteration suffix. If name already ends with an integer it will continue iteration
examples:
'col' -> 'col_01'
'col' -> 'col_01'
'col1' -> 'col2'
'col_02' -> 'col_03'
"""
# pylint: disable=import-outside-toplevel
... | 8021f1bc131f0a303bfaa06caa39e77f1de0dff9 | 3,597,934 |
def _overlay_heatmap(heatmap, image):
# type: (Image, Image) -> Image
"""
Blend (combine) ``heatmap`` over ``image``,
using alpha channel values appropriately (must have mode `RGBA`).
Output is 'RGBA'.
"""
# note that the order of alpha_composite arguments matters
overlayed_image = Imag... | 8673f302171123ce91752d2923c289aedae28016 | 3,597,935 |
def book_edit(book_id: int):
"""Edits book entry.
Args:
book_id: ID of the book to be edited
"""
book = Upload.get_by_id(book_id)
if not book:
return abort(404)
form = BookEditForm()
if request.method == 'GET':
form.name.data = book.name
form.description.dat... | a1f768731c691db5ae7ec436e8f6ebfad2a3af86 | 3,597,936 |
from typing import Set
from typing import FrozenSet
def to_dataframe(schedules: Set[FrozenSet[str]]) -> pd.DataFrame:
"""
Converts the set of schedules into a pandas DataFrame for ease
of representation.
"""
max_courses = max(len(schedule) for schedule in schedules)
columns = list(range(1, max... | 3823b8af6659a5f525332ea888bd0b2f860645ae | 3,597,937 |
import functools
def cache_result(cache_key, timeout):
"""A decorator for caching the result of a function."""
def decorator(f):
cache_name = settings.WAFER_CACHE
@functools.wraps(f)
def wrapper(*args, **kw):
cache = caches[cache_name]
result = cache.get(cache_... | a1df85774f02f437a10cdf34f84dca384686cd3d | 3,597,938 |
def suggest(alias, max=3, cutoff=0.5):
""" Suggest a list of aliases which are similar enough
"""
aliases = matchers.keys()
similar = get_close_matches(alias, aliases, n=max, cutoff=cutoff)
return similar | 403468ee7db8cf9408903643b4ad644ef589e96d | 3,597,940 |
def min_max(tr):
"""Return the ratio of minimum to maximum of a trace.
Parameters
----------
tr : 1D array of float
The input profile.
Returns
-------
mm : float
The ratio of the minimum value in `tr` over the maximum.
Examples
--------
>>> tr = np.array([0.8, ... | 8fcb533f22addf95ccf6e75e3d116dfe928aa6ca | 3,597,941 |
def audsley(self):
"""
This method is an implementation of the audsley's algorithm.
This method will recursively look for a lowest priority-viable until the list's length is equals to 1.
If it does not find an LPV the method returns False and this means that the task set is not schedul... | 7018c59431f0a037ee3563ea97cbd7656a9848da | 3,597,942 |
def init_from_mat(mat_file_name, structs=None):
"""
Loads nested structs from a .mat file, defines the relevant classes and instantiates them.
mat_file_name - for example "matlab.mat" generated by typing "save" in MATLAB.
sructs - the stucts to get from the .mat file or None to get all of them.
Usa... | d13a1f8a3bde2466868a2f8e5226a94bdb2024de | 3,597,943 |
def LoadWorkerpoolConfigFromPath(path, messages):
"""Load a workerpool config file into a WorkerPool message.
Args:
path: str. Path to the JSON or YAML data to be decoded.
messages: module, The messages module that has a WorkerPool type.
Raises:
files.MissingFileError: If the file does not exist.
... | e061f25a53ba743040df6ebed601c76efff78fdf | 3,597,944 |
def f(x): # 2
"""Simple recursive function.""" # 3
if x == 0: # 4
return 1 # 5
return 1 + f(x - 1) | ad71b050af9f3e634b8afab7565bc4df1c3f1222 | 3,597,945 |
def log_decoding_SLog3(y, bit_depth=10, in_legal=True, out_reflection=True):
"""
Defines the *Sony S-Log3* log decoding curve / electro-optical transfer
function.
Parameters
----------
y : numeric or array_like
Non-linear *Sony S-Log3* data :math:`y`.
bit_depth : int, optional
... | 3ca6987316be229f695266dc747e4679c588aa94 | 3,597,946 |
def lat_to_y_spherical(lat: float | ndarray) -> float | ndarray:
"""
Convert latitude to Y EPSG:3857 WGS 84/Pseudo-Mercator.
Parameters
----------
lat : float
Represents latitude.
Returns
-------
float
Y offset from your original position in meters.
Examples
--... | cfa634e68d8e894918d3733ad253b0164a41481b | 3,597,947 |
import math
def oxy(Soc, Voffset, Tau20, A, B, C, E, P, K, T, S, V):
"""SBE equation for converting engineering units to oxygen (ml/l).
asdasdas
Original equation from calib sheet dated 2014:
Oxygen (ml/l) = Soc * (V + Voffset) * (1.0 + A * T + B * T + C * T ) * OxSol(T,S) * exp(E * P / K)
"""
... | 5467fdab12de64c2adff37b5ae1fdcfdf3733d49 | 3,597,951 |
def binary_to_string(num):
"""
This solution is a straight python implementation of Gayle's solution
in CtCI.
"""
if num >= 1 or num <= 0:
return 'ERROR'
binary = []
binary.append('.')
while num > 0:
#Setting a limit on length: 32 characters
if len(binary) >= 32:... | 0752ddbf8ce76a3779fc6fba3cccf9b6ec66bca6 | 3,597,952 |
def phase_HalleyMarcus(phase):
"""Halley-Marcus composite dust phase function.
This is appropriate for use when calculating the brightness of cometary coma.
Parameters
----------
phase : float or array
Phase angle (degrees).
Returns
-------
phi : float or array
Phase fu... | fe26b41e9cc353c6d1d07138b1422e309d3fc477 | 3,597,953 |
def rotate_basis(P, alpha=0., beta=0., gamma=0.):
"""Rotate coordinate basis for point P by specified angles."""
Rx = np.array([[1., 0., 0.],
[0., np.cos(alpha), -np.sin(alpha)],
[0., np.sin(alpha), np.cos(alpha)]])
Ry = np.array([[np.cos(beta), 0., np.sin(beta)],
... | c0e73936d35e9f88f1e55bf19a078ec22649db5d | 3,597,955 |
import gzip
from pathlib import Path
import tqdm
def reduce(year_from=1968, year_to=9999, sample_size=0) -> pd.DataFrame:
"""
Data Set Reduction
Iterate through files and fields defined in the package to extract specified
data from the fixed width files store in the local Gzip cache, and aggregate
... | 5f4712f0074ab0c843efbb52b475a287ed5fa658 | 3,597,956 |
def _assert_float_dtype(dtype):
"""Validate and return floating point type based on `dtype`.
`dtype` must be a floating point type.
Args:
dtype: The data type to validate.
Returns:
Validated type.
Raises:
ValueError: if `dtype` is not a floating point type.
"""
if not dtype.is_floating:
... | 7aee4b4bc4b389b718b3e7a8cb9a77c37fd4ff1e | 3,597,957 |
def get_value(str_val):
"""convert a string into float or int, if possible."""
if not str_val:
return ""
if str_val is None:
return ""
try:
val = float(str_val)
if "." not in str_val:
val = int(val)
except ValueError:
val = str_val
return val | a3c7deee4110ea25a88f8568139015be20fef1d0 | 3,597,958 |
def tag_citation_string(citation: str):
""" End point to tag a citation
Parameters
----------
citation: str
Returns
-------
JSON
Predicted tags for the given citation
"""
global parscit_model
if parscit_model == None:
parscit_model = NeuralParscit()
predict... | 7a586b5a73fc98f070df17bd04a285e201c16fe5 | 3,597,959 |
def relation_bet_point_and_line( point, line ):
"""Judge the realtion between point and the line, there are three situation:
1) the foot point is on the line, the value is in [0,1];
2) the foot point is on the extension line of segment AB, near the starting point, the value < 0;
3) the foot point is o... | 92a1ed906ee4d7fbb97fa46668fedbbd5f704fba | 3,597,960 |
import json
import requests
def manage_falcon_host(_aid, action):
"""
:param _aid: aid of host in falcon console.
:param action: allowed values unhide_host / hide_host
:return:
"""
url = "https://api.crowdstrike.com/devices/entities/devices-actions/v2?action_name="+action
payload = json.d... | 68b9bb506236cc6005313e646b6b0de6cb622930 | 3,597,961 |
def escape_quotes(value):
"""
DTD files can use single or double quotes for identifying strings,
so " and ' are the safe bet that will work in both cases.
"""
value = value.replace('"', "\\"")
value = value.replace("'", "\\'")
return value | 1aa6e5f2325bfc293dff6e34b77117284d5bd018 | 3,597,962 |
def retrieve_diff_latencies(simdirs):
"""
Retrieve all kinds of latencies (flit, packet, network) simulation result
from the dummy simulation directories.
Parameters
----------
simdirs : list(str)
The list of dummy simulation directories.
Returns
-------
tuple
The r... | 3673b061c6842d9a2d2eaf579069e1e645cba560 | 3,597,963 |
import json
def init_population(ind_init, filename):
"""
create initial population from json file
ind_init: [class] class that and individual will be assigned to
filename: [string] string of filename from which pop will be read
returns: [list] list of Individual objects
"""
with ope... | 015b4d6b81dc44e325393535fc7abd65ca26db55 | 3,597,964 |
import csv
def load_annotations(annot_filepath):
"""
Fetch annotations (sorted based on start time) from a 'Raven selection table' file.
Returns an Nx2 numpy array of start-end time pairs.
"""
with open(annot_filepath, 'r', newline='') as seltab_file_h:
csv_reader = csv.reader(seltab_file... | 4144558b929bbc6e4bb8b5cc2ba09ad2d35a1410 | 3,597,965 |
import random
def shuffle(l):
"""
Returns the shuffled list.
"""
l = list(l)
random.shuffle(l)
return l | 4945d5d57ecaf3c9b8340f3f20c5e960938f3914 | 3,597,966 |
def load_data(path):
""" Load train/test csv data to pandas.Dataframe
"""
df = pd.read_csv(path)
return df | b98f3d605ec2427fb712c44b0ed11ea18bcb5f43 | 3,597,967 |
from pathlib import Path
from typing import Set
import logging
def merged_hot_locations(gql_sess: gql.GQL, long_path, short_path: Path) -> HotLocations:
"""Read the topN TSV files for long and short fragments and merge them."""
locs = HotLocations()
for path in (long_path, short_path):
s: Set[str... | d92c7ce2d806409e1b77f7310de5840819c0457e | 3,597,969 |
def _make_key(
args, kwargs, typed,
fast_types={int, str, frozenset, type(None)},
kwargs_mark=(object(),),
):
"""
Make a cache key from optionally typed positional and keyword arguments
The key is constructed in a way that is flat as possible rather than
as a nested structure that would tak... | 674b14df59e87989035713334882e846ca6afea0 | 3,597,971 |
from typing import Union
def get_lowest_taxon(
images: pd.DataFrame, return_rank: bool = False
) -> Union[pd.Series, tuple]:
"""
Gets the lowest identified taxa and ranks.
Parameters
----------
images : DataFrame
DataFrame with the project's images.
return_rank : bool
Whet... | 9fdc27ceb8f7b4363ac33cee7c478e4d477473ab | 3,597,972 |
def extract_feature(feature, generator):
"""Compute a feature vector."""
logger.info("Computing feature %s with windows %s and arguments %s",
feature.__class__.__name__, feature.windows, feature.kwargs)
if not generator.loaded_itype == feature.base_image:
logger.info("Loading base im... | 8fb714e354ed03b7374559faee17823e081822fe | 3,597,973 |
def setup(hass, config):
""" Setup weblink component. """
links = config.get(DOMAIN)
for link in links.get('entities'):
if ATTR_NAME not in link or ATTR_URL not in link:
_LOGGER.error("You need to set both %s and %s to add a %s",
ATTR_NAME, ATTR_URL, DOMAIN)
... | da5b2f6e1cf19db16ca671384cd165759df3043d | 3,597,974 |
def init_layout():
"""
Initializes a layout dict for Plotly figures.
:return:
"""
layout = {
"xaxis": {
"title": "Frequency (MHz)",
"tickformat": ".,"
},
"yaxis": {
"title": "Flux (Jy/beam)",
"tickformat": ".,"
},
... | 545520e0059f5bd61c743cc604adcb28d6f3a6e4 | 3,597,975 |
def _star(inner: str) -> str:
"""Convenience function
Takes a string representations of a regular expression, where the empty
string is considered as matching the empty langage, and returns its star
regular expression.
"""
if len(inner) > 0:
return f'({inner})*'
return 'ε' | cd3636cf0d39e4f9a74ef397dc47446320c3f0ea | 3,597,976 |
def merge_dicts(dict1, dict2):
""" Recursively merges dict2 into dict1 """
if not isinstance(dict1, dict) or not isinstance(dict2, dict):
return dict2
for k in dict2:
if k in dict1:
dict1[k] = merge_dicts(dict1[k], dict2[k])
else:
dict1[k] = dict2[k]
retur... | 486d2bfb335e47c7eddc5d104191ee00dfe73a8e | 3,597,978 |
def _num_parity_bits_needed(length: int):
"""
Given the length of a DATA bitstring, returns the number of parity bits needed for Hamming SEC codes.
An additional parity bit beyond this number of parity bits is needed to achieve SECDED codes.
"""
n = _next_power_of_two(length)
lower_bin = floor(log2(n))
upper_bin... | 9608ead1da6e007f474382d632b85e1178e6fff0 | 3,597,979 |
def load_data(stat_metrics_file, sys_metrics_file=None):
"""Loads the data from the given stat_metric and sys_metric files."""
stat_metrics = pd.read_csv(stat_metrics_file) if stat_metrics_file else None
sys_metrics = pd.read_csv(sys_metrics_file) if sys_metrics_file else None
if stat_metrics is not No... | dda83fdf00d2a08f26cc691c1ce99208a22047bc | 3,597,980 |
def dns_deupsert(action, cluster_name, record, ip_address, zone_id):
"""
deupset stands for (De - delete, up - update, sert - Insert)
Function perform delete, update, insert entry to Route53 hosted Zone.
Args:
action, cluster_name, record (dns name), ip_address (master_ip), zone_id
Returns:... | 32e644efedea52d53eed5d56ad840ccc04e4ca12 | 3,597,981 |
def stack_real_to_complex(ds_real, lazy=False):
"""
Puts the real and imaginary sections of the provided matrix (in the last axis) together to make complex matrix
Parameters
------------
ds_real : :class:`numpy.ndarray`, :class:`dask.array.core.Array`, or :class:`h5py.Dataset`
n dimensional... | 4a654523062efe0b8f7fa5eabc1f107f85b81fcf | 3,597,983 |
def downgrade_config(cfg: CN, to_version: int) -> CN:
"""
Downgrade a config from its current version to an older version.
Args:
cfg (CfgNode):
to_version (int):
Note:
A general downgrade of arbitrary configs is not always possible due to the
different functionalities i... | 28114779268382bb0324e99d75d94f8af20d516f | 3,597,984 |
def HasChromiumProperty(funcName, propertyList):
"""Return 1 if the function or any alias has any property in the
propertyList"""
for funcAlias in [funcName, NonVectorFunction(funcName), VectorFunction(funcName)]:
if funcAlias:
props = ChromiumProps(funcAlias)
for p in propertyList:
if p in props:
r... | d5de3f2c2712a02fc15666fa4adae725acbe7ddf | 3,597,985 |
def map_AGI2NCBI(NCBI_gene_list_filtered, genes_of_interest):
"""map AGI gene IDs to NCBI IDs"""
# read in NCBI list
NCBI_list = pd.read_table(NCBI_gene_list_filtered, sep="\t", header=0)
# Add AGI column to NCBI_list
NCBI_list_AGI = NCBI_list.assign(
AGI=NCBI_list.Aliases.str.extract(r"(.*... | 522ebb0605665464af8826dc1538845cde7de044 | 3,597,986 |
def get_constraint_list_cov(x_train, y_train, x_control_train, sensitive_attrs, sensitive_attrs_to_cov_thresh):
"""
get the list of constraints to be fed to the minimizer
"""
constraints = []
for attr in sensitive_attrs:
attr_arr = x_control_train[attr]
attr_arr_transformed, index... | 3d4da476a15bb2d19020dcfba951d76ba65d0e0b | 3,597,987 |
def rv_model_from_samples(rv_samples: np.ndarray) -> np.ndarray:
"""
Get RV median model and 1-sigma envelope from many sample RV curves
:param rv_samples: Input RV samples with shape (n_pts, n_samples)
:type rv_samples: np.ndarray
:return: RV Model and error (shape: (npts, 2)), first column is mod... | c7675c7fe0043a61b90e5eff517ceadae7dd4ed5 | 3,597,988 |
from typing import Iterable
def score_precision_binary(
y_true: Iterable[float], y_prob: Iterable[float], threshold: float = 0.5, counts: TFPN = None
) -> float:
"""
Computes the precision of a set of predictions compared to the ground truth.
"""
counts = counts or _compute_tfpn_counts(y_true, y_p... | 846e7ed692c8d1dae53d7ac0c764431525e84627 | 3,597,989 |
def validate_board(board):
"""
Function that founds if playground is ready for start of the game.
>>> validate_board([\
"**** ****",\
"***1 ****",\
"** 3****",\
"* 4 6****",\
" 9 5 ",\
" 6 83 *",\
"3 2 **",\
" 8 2***",\
" 2 ****"\
])
True
>>> va... | 5e20275fdbc6477e7faa84e63b25ff96b1c40ffe | 3,597,992 |
def tasks_few_samples():
"""Provide a few sample tasks, all with unique summaries and owners."""
return (
Task("Learn Pytest", "Florian", True),
Task("Master Pytest", "Chris", False),
Task("Teach Pytest", "Thomas", False)
) | cb28b6cbc467c30f2fb0d49122ebed17400f157d | 3,597,993 |
def format_stdout_stderr(stdout, stderr, max_len=TELEMETRY_MESSAGE_MAX_LEN):
"""
Format stdout and stderr's output to make it suitable in telemetry.
The goal is to maximize the amount of output given the constraints
of telemetry.
For example, if there is more stderr output than stdout output give
... | 57c905b72b5079cf69e1aa3c28a7a8f7378df0a5 | 3,597,994 |
def get_user_by_id(user_id):
"""Getting all the users with username or has username as a substring"""
user = User.query.filter(User.id == user_id).first()
return user | 55617189346fa70ef64c4ddd51c84053854408db | 3,597,995 |
def ecdf(x):
"""
Auxiliary function for multiple_test_correction
"""
nobs = len(x)
return arange(1, nobs+1) / float(nobs) | 12bf0f22b3fb9dc8c4f307caf621dc1d53e66ed6 | 3,597,996 |
def sigma_N(n):
"""number operator"""
return np.diag(range(n)) | 70bd6df940c5a4bf328c6a807110185290d8d45b | 3,597,997 |
def whitespace_around_operator(logical_line):
"""
Have exactly 1 space left and right of the operator.
"""
match = not_one_ws_around_operators_match(logical_line)
if match and not 'lambda' in logical_line:
return match.start(1), "E225 operators shall be surrounded by a single space on each s... | 9a9bdfe9d8a0a157849c2b5748ec9e8551cf142b | 3,597,998 |
import random
def add_gaussian_noise(key, raw, noise_std, randomized):
"""
Adds gaussian noise to `raw`, which can used to regularize it.
Args:
key: jnp.ndarray(float32), [2,], random number generator.
raw: jnp.ndarray(float32), arbitrary shape.
noise_std: float, The standard devi... | b60f6fdff1d32c112d4160f6c8b07c3363b78a95 | 3,597,999 |
def create_evaluation_data(path,pos_file_path):
""" シミュレーション結果を整形してJSに返す関数
Args:
path [str]: JS側から入力されたシミュレーション結果フォルダパス
Returns:
[list]: 整形されたグラフ作成用のデータと定量評価用の表データを返す
"""
print('ファイルを読み込みます')
print(path)
evaluatoin_result_arr = [[],[],[]]
evalController = Evalu... | 279f391291a898c8b955b9609e23622d0d45ec86 | 3,598,000 |
def monitor(**kwargs):
"""
Monitors messages on bus until limit or duration is reached.
Optional arguments:
- wait (bool): Wait for each message/line to read according to the default timeout of the serial connection (default 1 second). Otherwise there will only be waiting on the first line. line/mess... | fa66b3a51aefdbd80b98ccdd31757aa70d4b027f | 3,598,001 |
def is_bios_profile_enabled(handle, name, server_id=1):
"""
Args:
handle (ImcHandle)
name (str): Name of the bios profile.
Corresponds to the name field in the json file.
server_id (int): Id of the server to perform
this operation on C3260 pla... | 4d5439517384a09d3b492ed4a3a62b6faea8ae78 | 3,598,002 |
def ewma_vectorized(data, alpha, offset=None, dtype=None, order='C', out=None):
"""
Calculates the exponential moving average over a vector.
Will fail for large inputs.
:param data: Input data
:param alpha: scalar float in range (0,1)
The alpha parameter for the moving average.
:param of... | 1ed1a4d79bfce285268c3ff2c028d7eb2c0813d7 | 3,598,003 |
from src.uarch.gpu.amd_gpu import amd
from src.uarch.gpu.nvidia_gpu import nvidia
def gpu(dev, ven):
"""
Extracts µarches matching the provided data,
for GPUs; if possible.
"""
if not dev or not ven:
return
elif "1002" in ven:
items = amd
elif "10de" in ven:
items... | 65504907efaca0be78abb4408942b9f122ba00eb | 3,598,004 |
def set_customers_page(request):
"""Sets the page of the selectable customers sections.
"""
result = simplejson.dumps({
"html": (
("#customers-inline", customers_inline(request)),
("#customers-filters-inline", customers_filters_inline(request)),
),
}, cls=LazyEnco... | 5ed5079070a12a915d573b8b4ab87adce0b1b458 | 3,598,005 |
from copy import deepcopy
from datetime import datetime
def _get_schedule(start_day=date.today()+timedelta(days=1), num_days=6):
"""Gets the schedule for one week from the specified day as a parameter (inclusive).
Should no parameter given, 'tomorrow' is used as default and schedule for a week time.
:par... | b4256556c29ede6ba847028b9fafcfd6d71a707e | 3,598,006 |
def zzX_rem(f, g):
"""Returns polynomial remainder in Z[X]. """
return zzX_div(f, g)[1] | 80c158c429b0a898318145e4d6bcd0b3e88c4a1d | 3,598,007 |
import time
def update_file(file_id, file_path):
"""
Updates a file (that must exist in Box folder) given its identifier.
:param file_id: File identifier.
:param file_path: File path.
:return: File identifier if the update was successful, None otherwise.
"""
box_client = Client(JWTAuth.fro... | 46ad92385dfb833459f9ce01ea3f3d858c6a8fa1 | 3,598,009 |
import json
def get_user_from_term(input):
"""
Get user from an input string
example:
jccli create-user \
--json "{\"email\": \"jc.tester1@sagebase.org\", \"username\": \"jctester1\"}"
:param user_file:
:return: a SystemUser
"""
user = {}
if input != "":
try:
... | 1f7bdaa637453f429a78f140c741b797e0f79877 | 3,598,010 |
def vec2num(vec):
"""Convert list to number"""
num = 0
for node in vec:
num = num * 10 + node
return num | ffce787a02bc9f2bc5669dd8fb622bdff1fc941b | 3,598,011 |
def _CheckLocalPatches(sourceroot, local_patches):
"""Do an early quick check of the passed-in patches.
If the branch of a project is not specified we append the current branch the
project is on.
Args:
sourceroot: The checkout where patches are coming from.
"""
verified_patches = []
manifest = git.M... | e0230fb7ed1fb42799afd2468b512f4238e04612 | 3,598,012 |
def unknown_request(path: str):
"""
route for all unknown requests in API
this return an error JSON response
"""
err_msg = "Unknown request at path '{}'".format(path)
return WikishieldApiResult.build_err_res(err_msg), 404 | e91bb2ef62f7de1bf49534a6a67d61553781fd48 | 3,598,013 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.