content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _generate_indexed(array: IndexedArray) -> str:
"""Generate an indexed Bash array."""
return (
"("
+ " ".join(
f"[{index}]={_generate_string(value)}"
for index, value in enumerate(array)
if value is not None
)
+ ")"
) | 5,330,600 |
def main(argv=None):
"""Main entry point."""
known_args = parse_cmdline(argv)
metrics_dir = known_args.metrics_dir
metrics_files = [
join(metrics_dir, f)
for f in listdir(metrics_dir)
if isfile(join(metrics_dir, f))
]
metrics = [read_metrics_file(f) for f in metrics_files]
for m in metri... | 5,330,601 |
def up_date(dte, r_quant, str_unit, bln_post_colon):
""" Adjust a date in the light of a (quantity, unit) tuple,
taking account of any recent colon
"""
if str_unit == 'w':
dte += timedelta(weeks=r_quant)
elif str_unit == 'd':
dte += timedelta(days=r_quant)
elif str_unit ... | 5,330,602 |
def read_options() -> Options:
"""
read command line arguments and options
Returns:
option class(Options)
Raises:
NotInspectableError: the file or the directory does not exists.
"""
args: MutableMapping = docopt(__doc__)
schema = Schema({
"<path>": And(Use(get_path)... | 5,330,603 |
def test_generator_single_input_2():
"""
Feature: Test single str input
Description: input str
Expectation: success
"""
def generator_str():
for i in range(64):
yield chr(ord('a') + i)
class RandomAccessDatasetInner:
def __init__(self):
self.__data =... | 5,330,604 |
def to_keys_values_bson_dict_json():
"""
Convert Document to generic python types.
"""
class User(Document):
_id = fields.IntField()
name = fields.StringField()
user = User(_id=1, name="Jack")
# to tuple
assert user._fields_ordered == ("id", "name")
# to keys
asse... | 5,330,605 |
def SLINK(Dataset, d):
"""function to execute SLINK algo
Args:
Dataset(List) :- list of data points, who are also lists
d(int) :- dimension of data points
Returns:
res(Iterables) :- list of triples sorted by the second element,
first element is index of poin... | 5,330,606 |
def static_file(path='index.html'):
"""static_file"""
return app.send_static_file(path) | 5,330,607 |
def lazy_property(function):
""" Decorator to make a lazily executed property """
attribute = '_' + function.__name__
@property
@wraps(function)
def wrapper(self):
if not hasattr(self, attribute):
setattr(self, attribute, function(self))
return getattr(self, attribute)
... | 5,330,608 |
def basename(fname):
"""
Return file name without path.
Examples
--------
>>> fname = '../test/data/FSI.txt.zip'
>>> print('{}, {}, {}'.format(*basename(fname)))
../test/data, FSI.txt, .zip
"""
if not isinstance(fname, path_type):
fname = Path(fname)
path, name, ext = f... | 5,330,609 |
def validate_lockstring(lockstring):
"""
Validate so lockstring is on a valid form.
Args:
lockstring (str): Lockstring to validate.
Returns:
is_valid (bool): If the lockstring is valid or not.
error (str or None): A string describing the error, or None
if no error w... | 5,330,610 |
def decode_geohash_collection(geohashes: Iterable[str]):
"""
Return collection of geohashes decoded into location coordinates.
Parameters
----------
geohashes: Iterable[str]
Collection of geohashes to be decoded
Returns
-------
Iterable[Tuple[float, float]]
Collection o... | 5,330,611 |
def renormalize_sparse(A: sp.spmatrix) -> sp.spmatrix:
"""Get (D**-0.5) * A * (D ** -0.5), where D is the diagonalized row sum."""
A = sp.coo_matrix(A)
A.eliminate_zeros()
rowsum = np.array(A.sum(1))
assert np.all(rowsum >= 0)
d_inv_sqrt = np.power(rowsum, -0.5).flatten()
d_inv_sqrt[np.isinf... | 5,330,612 |
def load_gloria(
name: str = "gloria_resnet50",
device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu",
):
"""Load a GLoRIA model
Parameters
----------
name : str
A model name listed by `gloria.available_models()`, or the path to a model checkpoint containing ... | 5,330,613 |
def is_enabled():
"""
Check if `ufw` is enabled
:returns: True if ufw is enabled
"""
output = subprocess.check_output(['ufw', 'status'],
universal_newlines=True,
env={'LANG': 'en_US',
... | 5,330,614 |
def findExtraOverlayClasses(obj, clsList):
"""Determine the most appropriate class(es) for Chromium objects.
This works similarly to L{NVDAObjects.NVDAObject.findOverlayClasses} except that it never calls any other findOverlayClasses method.
"""
if obj.role==controlTypes.ROLE_LISTITEM and obj.parent and obj.parent.... | 5,330,615 |
def _fetch(
self,
targets=None,
jobs=None,
remote=None,
all_branches=False,
show_checksums=False,
with_deps=False,
all_tags=False,
recursive=False,
):
"""Download data items from a cloud and imported repositories
Returns:
int: number of successfully downloaded files
... | 5,330,616 |
def get_connected_input_geometry(blend_shape):
"""
Return an array of blend_shape's input plugs that have an input connection.
pm.listConnections should do this, but it has bugs when the input array is sparse.
"""
results = []
blend_shape_plug = _get_plug_from_node('%s.input' % blend_shape)
num_input_elements ... | 5,330,617 |
async def test_monthly_config_flow(hass: HomeAssistant) -> None:
"""Test we get the form."""
await setup.async_setup_component(hass, "persistent_notification", {})
# Initialise Config Flow
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}... | 5,330,618 |
def get_median_and_stdev(arr: torch.Tensor) -> Tuple[float, float]:
"""Returns the median and standard deviation from a tensor."""
return torch.median(arr).item(), torch.std(arr).item() | 5,330,619 |
def connect(user, host, port):
"""Create and return a new SSHClient connected to the given host."""
client = ssh.SSHClient()
if not env.disable_known_hosts:
client.load_system_host_keys()
if not env.reject_unknown_hosts:
client.set_missing_host_key_policy(ssh.AutoAddPolicy())
con... | 5,330,620 |
def _chf_to_pdf(t, x, chf, **chf_args):
"""
Estimate by numerical integration, using ``scipy.integrate.quad``,
of the probability distribution described by the given characteristic
function. Integration errors are not reported/checked.
Either ``t`` or ``x`` must be a scalar.
"""
t = np.asarr... | 5,330,621 |
def ParseTraceLocationLine(msg):
"""Parse the location line of a stack trace. If successfully parsed, returns (filename, line, method)."""
parsed = re.match(kCodeLocationLine, msg)
if not parsed:
return None
try:
return (parsed.group(1), parsed.group(2), parsed.group(3))
except IndexError as e:
lo... | 5,330,622 |
def test_datasets(test_client):
"""Test datasets route."""
response = test_client.get("datasets")
assert response.status_code == 200 | 5,330,623 |
def get_rl_params(num, similarity_name, reward_name):
""" Get RL model parameters (alpha and beta) based on <num>'s data.
<similarity_name> is the name of the similarity metric you want to
use, see fmri.catreward.roi.data.get_similarity_data() for details.
<reward_name> is the name of the data to... | 5,330,624 |
def return_arg_type(at_position):
"""
Wrap the return value with the result of `type(args[at_position])`
"""
def decorator(to_wrap):
@functools.wraps(to_wrap)
def wrapper(*args, **kwargs):
result = to_wrap(*args, **kwargs)
ReturnType = type(args[at_position])
... | 5,330,625 |
def extend(s, var, val):
"""Copy dict s and extend it by setting var to val; return copy."""
try: # Python 3.5 and later
return eval('{**s, var: val}')
except SyntaxError: # Python 3.4
s2 = s.copy()
s2[var] = val
return s2 | 5,330,626 |
def rx_reduce(observable: Observable, accumulator: AccumulatorOperator, seed: Optional[Any] = None) -> Observable:
"""Create an observable which reduce source with accumulator and seed value.
Args:
observable (Observable): source
accumulator (AccumulatorOperator): accumulator function (two argu... | 5,330,627 |
def test_build_manifest_fail2():
"""Test recursive definition"""
config_file = {'manifest': {
'$BASE': '$TMP/share',
'$TMP': '$BASE/share',
}}
with pytest.raises(Exception):
cfg.__build_manifest(config_file) | 5,330,628 |
def predict(image: Image.Image):
""" Take an image and run it through the inference model. This returns a ModelOutput object with all of the
information that the model returns. Furthermore, bounding box coordinates are normalized.
"""
logging.debug("Sending image to model for inference ...")
width,... | 5,330,629 |
def _make_header():
"""
Make vcf header for SNPs in miRs
""" | 5,330,630 |
def minimum_filter(
input,
size=None,
footprint=None,
output=None,
mode="reflect",
cval=0.0,
origin=0,
):
"""Multi-dimensional minimum filter.
Args:
input (cupy.ndarray): The input array.
size (int or sequence of int): One of ``size`` or ``footprint`` must be
... | 5,330,631 |
def lowpass(data, cutoff=0.25, fs=30, order=2, nyq=0.75):
"""
Butter low pass filter for a single or spectra or a list of them.
:type data: list[float]
:param data: List of vectors in line format (each line is a vector).
:type cutoff: float
:param cutoff: Desired cutoff frequency o... | 5,330,632 |
def format(value, limit=LIMIT, code=True, offset=0, hard_stop=None, hard_end=0):
"""
Recursively dereferences an address into string representation, or convert the list representation
of address dereferences into string representation.
Arguments:
value(int|list): Either the starting address to ... | 5,330,633 |
async def test_state_reporting(hass):
"""Test the state reporting."""
await async_setup_component(
hass,
SWITCH_DOMAIN,
{
SWITCH_DOMAIN: {
"platform": DOMAIN,
"entities": ["switch.test1", "switch.test2"],
"all": "false",
... | 5,330,634 |
def sogs_put(client, url, json, user):
"""
PUTs a test `client` request to `url` with the given `json` as body and X-SOGS-* signature
headers signing the request for `user`.
"""
data = dumps(json).encode()
return client.put(
url, data=data, content_type='application/json', headers=x_sog... | 5,330,635 |
def get_results(heading):
"""Get all records under a given record heading from PubChem/
Update results from those records."""
page = 1
results = {}
with tqdm(total=100) as pbar:
while True:
url = (f"https://pubchem.ncbi.nlm.nih.gov/rest/pug_view/annotations/heading/"
... | 5,330,636 |
def create_dictionary(documents):
"""Creates word dictionary for given corpus.
Parameters:
documents (list of str): set of documents
Returns:
dictionary (gensim.corpora.Dictionary): gensim dicionary of words from dataset
"""
dictionary = Dictionary(documents)
dictionary.compactif... | 5,330,637 |
def clone_bitarray(other, src=None):
"""
Fast clone of the bit array. The actual function used depends on the implementation
:param other:
:param src:
:return:
"""
if FAST_IMPL_PH4 and src is not None:
src.fast_copy(other)
return src
return to_bitarray(other) | 5,330,638 |
def _create_graph(
expressions: List[expression.Expression],
options: calculate_options.Options,
feed_dict: Optional[Dict[expression.Expression, prensor.Prensor]] = None
) -> "ExpressionGraph":
"""Create graph and calculate expressions."""
expression_graph = OriginalExpressionGraph(expressions)
canoni... | 5,330,639 |
def power_to_db(S, ref=1.0, amin=1e-10, top_db=80.0):
"""Convert a power spectrogram (amplitude squared) to decibel (dB) units
This computes the scaling ``10 * log10(S / ref)`` in a numerically
stable way.
Parameters
----------
S : np.ndarray
input power
ref : scalar or callable
... | 5,330,640 |
def is__str__equal(obj):
"""
Asserts if the string representation
equals the object type.
"""
assert isinstance(eval(str(obj)), type(obj)) | 5,330,641 |
def generate_arn(service, arn_suffix, region=None):
"""Returns a formatted arn for AWS.
Keyword arguments:
service -- the AWS service
arn_suffix -- the majority of the arn after the initial common data
region -- the region (can be None for region free arns)
"""
arn_value = "arn"... | 5,330,642 |
def prod_list(lst):
"""returns the product of all numbers in a list"""
if lst:
res = 1
for num in lst:
res *= num
return res
else:
raise ValueError("List cannot be empty.") | 5,330,643 |
def plot(x, f, gradient, Name):
"""
Graphs a function
"""
fplot = plt.figure(figsize=(16,9))
axis = plt.axis()
g= np.vectorize(f)
y = g(x)
grad = gradient(x)
plt.xlim()
plt.ylim()
plt.xlabel("x")
plt.ylabel("y")
title = 'label {},label {}'
plt.title(title.format(... | 5,330,644 |
def _main(argv):
"""
Handle arguments for the 'lumi-upload' command.
"""
parser = argparse.ArgumentParser(
description=DESCRIPTION,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
'-b',
'--base-url',
default=URL_BASE,
h... | 5,330,645 |
def create_attribute(representation_uuid, attribute_name):
"""create a representation of an attribute of a representation"""
try:
uuid = get_bus().create_attribute(representation_uuid, attribute_name, public=True)
return JsonResponse({'type': 'uuid', 'uuid': uuid})
except Exception as except... | 5,330,646 |
def get_current_git_hash(raise_on_error: bool = False) -> Optional[str]:
""" Return git hash of the latest commit
Parameters
----------
raise_on_error: bool, optional
If False (default), will return None, when it fails to obtain commit hash.
If True, will raise, when it fails to obtain ... | 5,330,647 |
def _raise_if_posterror(response):
"""raise error for failed POST request"""
if response.status_code not in [200, 201]:
LOG.error(response.text)
raise SimpleHTTPException(response) | 5,330,648 |
def test_annot_sanitizing(tmpdir):
"""Test description sanitizing."""
annot = Annotations([0], [1], ['a;:b'])
fname = str(tmpdir.join('custom-annot.fif'))
annot.save(fname)
annot_read = read_annotations(fname)
_assert_annotations_equal(annot, annot_read)
# make sure pytest raises error on c... | 5,330,649 |
def check_shift(start_time, end_time, final_minute, starting_minute, record):
"""
Função que verifica o turno da chamada e calcula o valor da ligação
:param start_time:
:param end_time:
:param final_minute:
:param starting_minute:
:return value:
"""
nem_start_time = start_time + (st... | 5,330,650 |
def s3_avatar_represent(user_id, tablename="auth_user", gravatar=False, **attr):
"""
Represent a User as their profile picture or Gravatar
@param tablename: either "auth_user" or "pr_person" depending on which
table the 'user_id' refers to
@param attr: additional H... | 5,330,651 |
def _activation_summary(x):
"""Helper to create summaries for activations.
Creates a summary that provides a histogram of activations.
Creates a summary that measure the sparsity of activations.
Args:
x: Tensor
Returns:
nothing
"""
# Remove 'tower_[0-9]/' from the name in case this is a multi-GPU ... | 5,330,652 |
def json_loader(path_to_json_file: str) -> Dict[str, List[str]]:
"""Reads a JSON file and converts its content in a dictionary.
Parameters
----------
path_to_json_file: str
The path to the JSON file.
Returns
-------
Dict[str, List[str]]
A dictionary of source codes with the... | 5,330,653 |
def writeJson(fname, data):
"""
Writes a Json file
"""
try:
with open(fname, 'w') as f:
json.dump(data, f)
except IOError:
raise Exception('Could not open {0!s} for writing'.format((fname))) | 5,330,654 |
def main( args ):
"""Main allows selection of the main subcommand (aka function).
Each subcommand launches a separate function. The pydoc subcommand
launches pydoc on this overall program file.
:param args: the main command line arguments passed minus subcommand
"""
#print globals().keys()
if len(args) == 0 or ... | 5,330,655 |
def check(local_args):
""" check args """
assert local_args.classes > 1
assert local_args.zoom_factor in [1, 2, 4, 8]
assert local_args.split in ['train', 'val', 'test']
if local_args.arch == 'psp':
assert (local_args.train_h - 1) % 8 == 0 and (local_args.train_w - 1) % 8 == 0
else:
... | 5,330,656 |
def test_manual_weights(tmpdir):
"""
'regrid' will accept a SCRIP format weights file as the target
"""
a0 = xarray.DataArray(
[[0, 1], [2, 3]],
name="var",
dims=["lat", "lon"],
coords={"lat": [-45, 45], "lon": [0, 180]},
)
a0.lat.attrs["units"] = "degrees_north"
... | 5,330,657 |
def get_region_solution_attribute(data, region_id, attribute, func, intervention):
"""Extract region solution attribute"""
regions = data.get('NEMSPDCaseFile').get('NemSpdOutputs').get('RegionSolution')
for i in regions:
if (i['@RegionID'] == region_id) and (i['@Intervention'] == intervention):
... | 5,330,658 |
def initialize_channels():
"""Create the channel objects"""
global_vars.CHANNEL_ARRAY.append(classes.Channel(0))
return | 5,330,659 |
def _reset_attributes(idaobject, attributes):
"""
Delete an attribute of a list of attributes of an object, if the attribute exists.
"""
if (not hasattr(attributes, "__iter__"))|isinstance(attributes, six.string_types):
attributes = [attributes]
for attribute in attributes:
try:
... | 5,330,660 |
def test_macsec_psk_shorter_ckn(dev, apdev, params):
"""MACsec PSK (shorter CKN)"""
try:
ckn = "11223344"
run_macsec_psk(dev, apdev, params, "macsec_psk_shorter_ckn",
ckn0=ckn, ckn1=ckn)
finally:
cleanup_macsec() | 5,330,661 |
def conv1x1(in_planes: int, out_planes: int) -> nn.Conv2d:
"""1x1 convolution"""
return nn.Conv2d(in_planes, out_planes, kernel_size=1, bias=True) | 5,330,662 |
def stop_session_safely(spark_session):
"""
Safely stops Spark session.
This is no-op if running on Databricks - we shouldn't stop session there since
it's managed by the platform, doing so fails the job.
"""
if not spark_session.conf.get("spark.home", "").startswith("/databricks"):
spar... | 5,330,663 |
def test_no_mines_init():
"""Asserts that initializing with no mines works properly"""
size = (30, 50)
ms_game = MinesweeperEnv(size, 0)
assert size == ms_game.board_size
assert ms_game.num_mines == 0
npt.assert_array_equal([], ms_game.hist)
npt.assert_array_equal([[SPACE_UNKNOWN] * size[1]... | 5,330,664 |
def make_ratio_map(amap, bmap):
"""Get the ratio of two PISA 2 style maps (amap/bmap) and return as another
PISA 2 style map."""
validate_maps(amap, bmap)
with np.errstate(divide='ignore', invalid='ignore'):
result = {'ebins': amap['ebins'],
'czbins': amap['czbins'],
... | 5,330,665 |
def _compose_duration(
components_tags: Collection[Tags]) -> Mapping[str, Sequence[str]]:
"""Returns summed duration tags."""
duration_seconds_values = [
component_tags.one_or_none(DURATION_SECONDS)
for component_tags in components_tags
]
if duration_seconds_values and None not i... | 5,330,666 |
def test_process_aggregating_cubes_with_overlapping_frt(
reliability_cube, overlapping_frt
):
"""Test that attempting to aggregate reliability calibration tables
with overlapping forecast reference time bounds raises an exception.
The presence of overlapping forecast reference time bounds indicates
... | 5,330,667 |
def feature_spatial(fslDir, tempDir, aromaDir, melIC):
""" This function extracts the spatial feature scores. For each IC it determines the fraction of the mixture modeled thresholded Z-maps respecitvely located within the CSF or at the brain edges, using predefined standardized masks.
Parameters
------------------... | 5,330,668 |
def p_translation_unit(p):
"""translation_unit : external_declaration
| translation_unit external_declaration"""
if len(p) == 2:
p[0] = [p[1]]
else:
p[0] = p[1] + [p[2]] | 5,330,669 |
def str_to_date(date_str, fmt=DATE_STR_FMT):
"""Convert string date to datetime object."""
return datetime.datetime.strptime(date_str, fmt).date() | 5,330,670 |
def create_elasticsearch_domain(name, account_id, boto_session, lambda_role, cidr):
"""
Create Elastic Search Domain
"""
boto_elasticsearch = boto_session.client('es')
total_time = 0
resource = "arn:aws:es:ap-southeast-2:{0}:domain/{1}/*".format(account_id, name)
access_policy = {"Versio... | 5,330,671 |
def get_user(email):
"""
param: username
returns User instance with user data, the MySQL error handle by the try-except senteces
"""
result = {}
connection = _connect_to_db()
try:
with connection.cursor() as cursor:
row_count = 0
e = 'none'
# Read... | 5,330,672 |
def index(request):
"""
A example of Function-based view
method:
get
request:
None
response:
type: html
"""
return HttpResponse("Hello, world. You're at the polls index.") | 5,330,673 |
def make_https_request(logger, url, jobs_manager, download=False, timeout_attempt=0):
"""
Utility function for making HTTPs requests.
"""
try:
req = requests_retry_session().get(url, timeout=120)
req.raise_for_status()
except requests.exceptions.ConnectionError as c_err:
logg... | 5,330,674 |
async def _return_exported_sender(self: 'TelegramClient', sender):
"""
Returns a borrowed exported sender. If all borrows have
been returned, the sender is cleanly disconnected.
"""
async with self._borrow_sender_lock:
self._log[__name__].debug('Returning borrowed sender for dc_id %d', sende... | 5,330,675 |
def info():
"""
Displays on the website of the page. @TODO - Add index.html for the site of Ubik.
:return: response for each get request on '/'.
"""
return about_response() | 5,330,676 |
def falshsort():
"""
Do from here: https://en.wikipedia.org/wiki/Flashsort
:return: None
"""
return None | 5,330,677 |
def random_word(text, label, label_map, tokenizer, sel_prob):
"""
Masking some random tokens for Language Model task with probabilities as in the original BERT paper.
:param tokens: list of str, tokenized sentence.
:param tokenizer: Tokenizer, object used for tokenization (we need it's vocab here)
:... | 5,330,678 |
def ITERATIVETEST_Error_Of_Input_Parameter_inZSubsample():
"""Tests occurrence of an error because of an invalid input value provided at field "inZSubsample"."""
Logging.infoHTML( "<b>ToDo: Add more \"TestData\" objects to maximize variations!</b>" )
testDataVariations = {
"Invalid_Variation_1" : __getInvalid... | 5,330,679 |
def test_xclip_failure():
"""Check that (mocked) failure raises an exception."""
with mock.patch('safe.clip.run') as run:
run.return_value = 1, 'foo', 'bar'
with pytest.raises(ClipboardError) as ei:
Xclip().get()
e = ei.value
assert 'failed with stderr: bar' in str(e... | 5,330,680 |
def _match_storm_objects(first_prediction_dict, second_prediction_dict,
top_match_dir_name):
"""Matches storm objects between first and second prediction files.
F = number of storm objects in first prediction file
:param first_prediction_dict: Dictionary returned by
`predi... | 5,330,681 |
def get_default_branch(base_url: str, auth: Optional[AuthBase], ssl_verify: bool = True) -> dict:
"""Fetch a reference.
:param base_url: base Nessie url
:param auth: Authentication settings
:param ssl_verify: ignore ssl errors if False
:return: json Nessie branch
"""
return cast(dict, _get(... | 5,330,682 |
def make_source_thesaurus(source_thesaurus=SOURCE_THESAURUS_FILE):
"""
Get dict mapping country name to `SourceObject` for the country.
Parameters
----------
source_thesaurus : str
Filepath for the source thesaurus data.
Returns
-------
Dict of {"Country": SourceObject} pairs.
"""
with open(source_thesaur... | 5,330,683 |
def extract_filter(s):
"""Extracts a filter from str `s`
Parameters
----------
s : str
* A str that may or may not have a filter identified by ', that HUMAN VALUE'
Returns
-------
s : str
* str `s` without the parsed_filter included
parsed_filter : dict
* filter... | 5,330,684 |
def sigmoid(
x,
sigmoid_type: str = "tanh",
normalization_range: Tuple[Union[float, int], Union[float, int]] = (0, 1)
):
"""
A sigmoid function. From Wikipedia (https://en.wikipedia.org/wiki/Sigmoid_function):
A sigmoid function is a mathematical function having a characteristic ... | 5,330,685 |
def test_get_nonexistent_public_key_fails(app, mock_get):
"""
Test that if there is no key found for the provided key id, a
JWTValidationError is raised.
"""
mock_get()
with pytest.raises(JWTError):
get_public_key(kid="nonsense") | 5,330,686 |
def interp(x, x1, y1, x2, y2):
"""Find a point along a line"""
return ((x2 - x) * y1 + (x - x1) * y2) / (x2 - x1) | 5,330,687 |
def msm_distance_measure_getter(X):
"""
generate the msm distance measure
:param X: dataset to derive parameter ranges from
:return: distance measure and parameter range dictionary
"""
n_dimensions = 1 # todo use other dimensions
return {
"distance_measure": [cython_wrapper(msm_dist... | 5,330,688 |
def gen_cpmfgp_test_data_from_config_file(config_file_name, raw_func,
num_tr_data, num_te_data):
""" Generates datasets for CP Multi-fidelity GP fitting. """
# Generate data
def _generate_data(_proc_func, _config, _num_data):
""" Generates data. """
ZX_proc = sample_from_config_space(_config, _num_data)... | 5,330,689 |
def csv_to_postgres(engine,
file: str,
table_name: str):
"""
Given a *.csv filepath, create a populated table in a database
:param engine: SQLAlchemy connection/engine for the target database
:param file: Full filepath of the *.csv file
:param table_name: ... | 5,330,690 |
def keypair() -> None:
"""
KeyPair administration commands.
""" | 5,330,691 |
def find_best_ref_match_partial(trb: str, ref_df: pd.DataFrame):
"""
Find the row in the given reference df that best matches the given TRB ONLY
"""
raise NotImplementedError | 5,330,692 |
def _custom_padd(a, min_power_of_2=1024, min_zero_padd=50,
zero_padd_ratio=0.5):
""" Private helper to make a zeros-mirror-zeros padd to the next power of
two of a.
Parameters
----------
arrays : np.ndarray,
array to padd.
min_power_of_2 : int (default=512),
mi... | 5,330,693 |
def encode_multipart_formdata(fields, files):
"""
Encode multipart data to be used in data import
adapted from: http://code.activestate.com/recipes/146306/
:param fields: sequence of (name, value) elements for regular form fields.
:param files: sequence of (name, filename, value) elements for data ... | 5,330,694 |
def is_recording():
""" return current state of recording key macro """
global recording
return recording | 5,330,695 |
def test_reward_is_given(complete_mazeworld_states):
"""Make sure the total reward received for completing the maze is about what is expected (tests Interval)
Args:
complete_mazeworld_states:list of every state from finishing mazeworld
"""
total_reward = 0.0
for _, reward, _, _ in complete... | 5,330,696 |
def download_image_urls(
urls_filename: Union[Path, str],
synsets: List[str],
max_concurrent: int = 50,
rewrite: bool = False
) -> Dict[str, Optional[List[str]]]:
"""Downloads urls for each synset and saves them in json format in a given path.
Args:
urls_filename: a path to the file whe... | 5,330,697 |
def generate_new_split(lines1, lines2, rng, cutoff=14937):
"""Takes lines1 and lines2 and combines, shuffles and split again. Useful for working with random splits of data"""
lines = [l for l in lines1] # lines1 may not be a list but rather iterable
lines.extend(lines2)
perm = rng.permutation(len(lines... | 5,330,698 |
def ProcessPeopleData():
"""
处理人物关系数据集
"""
people_data_path = './People/origin/all_data.txt'
processor = PeopleProcessor(people_data_path)
processor.relation_counts()
processor.data_cleaning()
processor.data_formatting()
processor.divide_datasets(do_dev=True, balance_sample=Fa... | 5,330,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.