content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import unittest
def test():
"""Runs the unit tests without test coverage."""
tests = unittest.TestLoader().discover('cabotage/tests', pattern='test*.py')
result = unittest.TextTestRunner(verbosity=2).run(tests)
if result.wasSuccessful():
return 0
return 1 | bcb57638bea41f3823cd22aa7a43b159591ad99b | 4,000 |
def nm_to_uh(s):
"""Get the userhost part of a nickmask.
(The source of an Event is a nickmask.)
"""
return s.split("!")[1] | 5e6c07b7b287000a401ba81117bc55be47cc9a24 | 4,001 |
def upload_example_done(request, object_id):
"""
This view is a callback that receives POST data
from uploadify when the download is complete.
See also /media/js/uploadify_event_handlers.js.
"""
example = get_object_or_404(Example, id=object_id)
#
# Grab the post data sent by our ... | b748cb1708ddfdd2959f723902c45668c8774df2 | 4,002 |
def epoch_in_milliseconds(epoch):
"""
>>> epoch_in_milliseconds(datetime_from_seconds(-12345678999.0001))
-12345679000000
"""
return epoch_in_seconds(epoch) * 1000 | 75ae0779ae2f6d1987c1fdae0a6403ef725a6893 | 4,003 |
def get_workspaces(clue, workspaces):
"""
Imports all workspaces if none were provided.
Returns list of workspace names
"""
if workspaces is None:
logger.info("no workspaces specified, importing all toggl workspaces...")
workspaces = clue.get_toggl_workspaces()
logger.info("T... | aae8b5f2585a7865083b433f4aaf9874d5ec500e | 4,004 |
import pprint
def create_hparams(hparams_string=None, hparams_json=None, verbose=True):
"""Create model hyperparameters. Parse nondefault from given string."""
hparams = tf.contrib.training.HParams(
training_stage='train_style_extractor',#['train_text_encoder','train_style_extractor','train_style_att... | d4d255241b7322a10369bc313a0ddc971c0115a6 | 4,005 |
def ChromiumFetchSync(name, work_dir, git_repo, checkout='origin/master'):
"""Some Chromium projects want to use gclient for clone and dependencies."""
if os.path.isdir(work_dir):
print '%s directory already exists' % name
else:
# Create Chromium repositories one deeper, separating .gclient files.
par... | 8bb0f593eaf874ab1a6ff95a913ef34b566a47bc | 4,006 |
def kld_error(res, error='simulate', rstate=None, return_new=False,
approx=False):
"""
Computes the `Kullback-Leibler (KL) divergence
<https://en.wikipedia.org/wiki/Kullback-Leibler_divergence>`_ *from* the
discrete probability distribution defined by `res` *to* the discrete
probabilit... | 430ad6cb1c25c0489343717d7cf8a44bdfb5725d | 4,007 |
def article_detail(request, slug):
"""
Show details of the article
"""
article = get_article_by_slug(slug=slug, annotate=True)
comment_form = CommentForm()
total_views = r.incr(f'article:{article.id}:views')
return render(request, 'articles/post/detail.html',
{'article': ar... | 079d31509fe573ef207600e007e51ac14e9121c4 | 4,008 |
def deactivate(userid, tfa_response):
"""
Deactivate 2FA for a specified user.
Turns off 2FA by nulling-out the ``login.twofa_secret`` field for the user record,
and clear any remaining recovery codes.
Parameters:
userid: The user for which 2FA should be disabled.
tfa_response: Use... | 1ac0f5e716675ccb118c9656bcc7c9b4bd3f9606 | 4,009 |
def hsi_normalize(data, max_=4096, min_ = 0, denormalize=False):
"""
Using this custom normalizer for RGB and HSI images.
Normalizing to -1to1. It also denormalizes, with denormalize = True)
"""
HSI_MAX = max_
HSI_MIN = min_
NEW_MAX = 1
NEW_MIN = -1
if(denormalize):
scaled... | 7f276e90843c81bc3cf7715e54dadd4a78162f93 | 4,010 |
from typing import Optional
def safe_elem_text(elem: Optional[ET.Element]) -> str:
"""Return the stripped text of an element if available. If not available, return the empty string"""
text = getattr(elem, "text", "")
return text.strip() | 12c3fe0c96ffdb5578e485b064ee4df088192114 | 4,011 |
def resource(filename):
"""Returns the URL a static resource, including versioning."""
return "/static/{0}/{1}".format(app.config["VERSION"], filename) | b330c052180cfd3d1b622c18cec7e633fa7a7910 | 4,012 |
import os
def get_legacy_description(location):
"""
Return the text of a legacy DESCRIPTION.rst.
"""
location = os.path.join(location, 'DESCRIPTION.rst')
if os.path.exists(location):
with open(location) as i:
return i.read() | 1d91c9875d6a6de862bed586c5bf4b67eb6e8886 | 4,013 |
import csv
def read_q_stats(csv_path):
"""Return list of Q stats from file"""
q_list = []
with open(csv_path, newline='') as csv_file:
reader = csv.DictReader(csv_file)
for row in reader:
q_list.append(float(row['q']))
return q_list | f5bee4859dc4bac45c4c3e8033da1b4aba5d2818 | 4,014 |
def _validate(config):
"""Validate the configuation.
"""
diff = set(REQUIRED_CONFIG_KEYS) - set(config.keys())
if len(diff) > 0:
raise ValueError(
"config is missing required keys".format(diff))
elif config['state_initial']['status'] not in config['status_values']:
raise ... | 07c92e5a5cc722efbbdc684780b1edb66aea2532 | 4,015 |
def exp_by_squaring(x, n):
"""
Compute x**n using exponentiation by squaring.
"""
if n == 0:
return 1
if n == 1:
return x
if n % 2 == 0:
return exp_by_squaring(x * x, n // 2)
return exp_by_squaring(x * x, (n - 1) // 2) * x | ef63d2bf6f42690fd7c5975af0e961e2a3c6172f | 4,016 |
def _compare(expected, actual):
"""
Compare SslParams object with dictionary
"""
if expected is None and actual is None:
return True
if isinstance(expected, dict) and isinstance(actual, SslParams):
return expected == actual.__dict__
return False | 4a82d1631b97960ecc44028df4c3e43dc664d3e5 | 4,017 |
def update_token(refresh_token, user_id):
"""
Refresh the tokens for a given user
:param: refresh_token
Refresh token of the user
:param: user_id
ID of the user for whom the token is to be generated
:returns:
Generated JWT token
"""
token = Token.query.filter_by(refr... | 0b91cf19f808067a9c09b33d7497548743debe14 | 4,018 |
from re import X
def minimax(board):
"""
Returns the optimal action for the current player on the board.
"""
def max_value(state, depth=0):
if ttt.terminal(state):
return (None, ttt.utility(state))
v = (None, -2)
for action in ttt.actions(state):
v =... | 8de42db3ad40d597bf9600bcd5fec7c7f775f84d | 4,019 |
import random
def random_order_dic_keys_into_list(in_dic):
"""
Read in dictionary keys, and return random order list of IDs.
"""
id_list = []
for key in in_dic:
id_list.append(key)
random.shuffle(id_list)
return id_list | d18ac34f983fbaff59bfd90304cd8a4a5ebad42e | 4,020 |
from typing import Union
from pathlib import Path
from typing import Dict
import json
def read_json(json_path: Union[str, Path]) -> Dict:
"""
Read json file from a path.
Args:
json_path: File path to a json file.
Returns:
Python dictionary
"""
with open(json_path, "r") as fp:... | c0b55e5363a134282977ee8a01083490e9908fcf | 4,021 |
def igraph_to_csc(g, save=False, fn="csc_matlab"):
"""
Convert an igraph to scipy.sparse.csc.csc_matrix
Positional arguments:
=====================
g - the igraph graph
Optional arguments:
===================
save - save file to disk
fn - the file name to be used when writing (appendmat = True by de... | 12ea73531599cc03525e898e39b88f2ed0ad97c3 | 4,022 |
def xml2dict(data):
"""Turn XML into a dictionary."""
converter = XML2Dict()
if hasattr(data, 'read'):
# Then it's a file.
data = data.read()
return converter.fromstring(data) | 0c73989b4ea83b2b1c126b7f1b39c6ebc9e18115 | 4,023 |
def balance_dataset(data, size=60000):
"""Implements upsampling and downsampling for the three classes (low, medium, and high)
Parameters
----------
data : pandas DataFrame
A dataframe containing the labels indicating the different nightlight intensity bins
size : int
The number... | 93cd5888c28f9e208379d7745790b7e1e0cb5b79 | 4,024 |
def updateStopList(userId, newStop):
"""
Updates the list of stops for the user in the dynamodb table
"""
response = dynamodb_table.query(
KeyConditionExpression=Key('userId').eq(userId))
if response and len(response["Items"]) > 0:
stops = response["Items"][0]['stops']
else:
... | 433ae6c4562f6a6541fc262925ce0bba6fb742ec | 4,025 |
import re
def is_blacklisted_module(module: str) -> bool:
"""Return `True` if the given module matches a blacklisted pattern."""
# Exclude stdlib modules such as the built-in "_thread"
if is_stdlib_module(module):
return False
# Allow user specified exclusions via CLI
blacklist = set.unio... | 391d63a4d8a4f24d1d3ba355745ffe0079143e68 | 4,026 |
def api_detach(sess, iqn):
"""
Detach the given volume from the instance using OCI API calls.
Parameters
----------
sess: OCISession
The OCISEssion instance..
iqn: str
The iSCSI qualified name.
Returns
-------
bool
True on success, False otherwise.
... | f52baa2a647c112fdde386afd46fc04fe4fe9da3 | 4,027 |
def ComponentLibrary(self, lib_name, *args, **kwargs):
"""Pseudo-builder for library to handle platform-dependent type.
Args:
self: Environment in which we were called.
lib_name: Library name.
args: Positional arguments.
kwargs: Keyword arguments.
Returns:
Passthrough return code from env.St... | 8169be26c5ac30e090809fa80e3d5657a3616772 | 4,028 |
def _build_geojson_query(query):
"""
See usages below.
"""
# this is basically a translation of the postgis ST_AsGeoJSON example into sqlalchemy/geoalchemy2
return func.json_build_object(
"type",
"FeatureCollection",
"features",
func.json_agg(func.ST_AsGeoJSON(query.s... | dd7a0893258cf95e1244458ba9bd74c5239f65c5 | 4,029 |
import urllib
def url_encode(obj, charset='utf-8', encode_keys=False, sort=False, key=None,
separator='&'):
"""URL encode a dict/`MultiDict`. If a value is `None` it will not appear
in the result string. Per default only values are encoded into the target
charset strings. If `encode_keys... | 2106032d6a4cf895c525e9db702655af3439a95c | 4,030 |
from datetime import datetime
def create_export_and_wait_for_completion(name, bucket, prefix, encryption_config, role_arn=None):
"""
Request QLDB to export the contents of the journal for the given time period and S3 configuration. Before calling
this function the S3 bucket should be created, see
:py:... | 9fb6f66dc02d70ffafe1c388188b99b9695a6900 | 4,031 |
def sample_student(user, **kwargs):
"""create and return sample student"""
return models.Student.objects.create(user=user, **kwargs) | a70c3a181b1ee0627465f016953952e082a51c27 | 4,032 |
from datetime import datetime
def normalise_field_value(value):
""" Converts a field value to a common type/format to make comparable to another. """
if isinstance(value, datetime):
return make_timezone_naive(value)
elif isinstance(value, Decimal):
return decimal_to_string(value)
retur... | 3cbc4c4d7ae027c030e70a1a2bd268bdd0ebe556 | 4,033 |
import sys
def edit_wn_list(item_list, list_name, all_values, tenant_file_name):
"""
Edit WAN network list
:param item_list: Item list to save
:param list_name: Name of List
:param all_values: All values
:param tenant_file_name: File-system friendly tenant_name
:return: shallow copy of ite... | 624b383d9a5aa6a925c790787de01b14dfa50dce | 4,034 |
from typing import Any
from typing import Tuple
from typing import List
import collections
import yaml
def parse_yaml(stream: Any) -> Tuple[Swagger, List[str]]:
"""
Parse the Swagger specification from the given text.
:param stream: YAML representation of the Swagger spec satisfying file interface
:r... | 7155520db98bf1d884ba46f22b46297a901f4411 | 4,035 |
import itertools
def dataset_first_n(dataset, n, show_classes=False, class_labels=None, **kw):
"""
Plots first n images of a dataset containing tensor images.
"""
# [(img0, cls0), ..., # (imgN, clsN)]
first_n = list(itertools.islice(dataset, n))
# Split (image, class) tuples
first_n_imag... | ed8394fc2a1b607597599f36545c9182a9bc8187 | 4,036 |
def unit_conversion(thing, units, length=False):
"""converts base data between metric, imperial, or nautical units"""
if 'n/a' == thing:
return 'n/a'
try:
thing = round(thing * CONVERSION[units][0 + length], 2)
except TypeError:
thing = 'fubar'
return thing, CONVERSION[units]... | 96bfb9cda575a8b2efc959b6053284bec1d286a6 | 4,037 |
import functools
def timed(func):
"""Decorate function to print elapsed time upon completion."""
@functools.wraps(func)
def wrap(*args, **kwargs):
t1 = default_timer()
result = func(*args, **kwargs)
t2 = default_timer()
print('func:{} args:[{}, {}] took: {:.4f} sec'.format(... | d572488c674607b94e2b80235103d6f0bb27738f | 4,038 |
from typing import List
from typing import Optional
import os
def plot_rollouts_segment_wise(
segments_ground_truth: List[List[StepSequence]],
segments_multiple_envs: List[List[List[StepSequence]]],
segments_nominal: List[List[StepSequence]],
use_rec: bool,
idx_iter: int,
idx_round: Optional[i... | e5ea2a8b9007be06599e9946aa536f93a72624e2 | 4,039 |
def fade_out(s, fade=cf.output.fade_out):
"""
Apply fade-out to waveform time signal.
Arguments:
ndarray:s -- Audio time series
float:fade (cf.output.fade_out) -- Fade-out length in seconds
Returns faded waveform.
"""
length = int(fade * sr)
shape = [1] * len(s.shape)
shape[0] = length
win ... | 0b554dbb1da7253e39c651ccdc38ba91e67a1ee4 | 4,040 |
def create_arch(T, D, units=64, alpha=0, dr_rate=.3):
"""Creates the architecture of miint"""
X = K.Input(shape=(T, D))
active_mask = K.Input(shape=(T, 1))
edges = K.Input(shape=(T, None))
ycell = netRNN(T=T, D=D, units=units, alpha=alpha, dr_rate=dr_rate)
yrnn = K.layers.RNN(ycell, return_sequences=True)
Y = ... | cc9723657a7a0822d73cc78f6e1698b33257f9e0 | 4,041 |
def redact(str_to_redact, items_to_redact):
""" return str_to_redact with items redacted
"""
if items_to_redact:
for item_to_redact in items_to_redact:
str_to_redact = str_to_redact.replace(item_to_redact, '***')
return str_to_redact | f86f24d3354780568ec2f2cbf5d32798a43fdb6a | 4,042 |
def FibreDirections(mesh):
"""
Routine dedicated to compute the fibre direction of components in integration point for
the Material in Florence and for the auxiliar routines in this script. First three directions
are taken into the code for Rotation matrix, so always it should be present i... | 9408702e72dde7586f42137ad25a0a944ed28a93 | 4,043 |
def put(consul_url=None, token=None, key=None, value=None, **kwargs):
"""
Put values into Consul
:param consul_url: The Consul server URL.
:param key: The key to use as the starting point for the list.
:param value: The value to set the key to.
:param flags: This can be used to specify an unsig... | 3b80283da426e5515026fb8dc0db619b2a471f41 | 4,044 |
def prepare_w16():
"""
Prepare a 16-qubit W state using sqrt(iswaps) and local gates,
respecting linear topology
"""
ket = qf.zero_state(16)
circ = w16_circuit()
ket = circ.run(ket)
return ket | 74d0599e1520aab44088480616e2062153a789aa | 4,045 |
import requests
def get_All_Endpoints(config):
"""
:return:
"""
url = 'https://{}:9060/ers/config/endpoint'.format(config['hostname'])
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
body = {}
response = requests.request('GET', url, headers=headers, data=body, auth=HTTPBasi... | f74ad8ba7d65de11851b71318b2818776c5dc29b | 4,046 |
import os
import filelock
import tempfile
import zipfile
import shutil
def download_if_needed(folder_name):
""" Folder name will be saved as `.cache/textattack/[folder name]`. If it
doesn't exist on disk, the zip file will be downloaded and extracted.
Args:
folder_name (str): path to fol... | efbb4e024c217a946ce8d35d26b94c33aa5f0615 | 4,047 |
import os
def get_local_repository_directory():
""" Return settins.LOCAL_REPO_DIR.
Ruturn None on any errors.
"""
if os.path.isdir(settings.LOCAL_REPO_DIR):
return settings.LOCAL_REPO_DIR
else:
logger.error("Local repository directory not found. LOCAL_REPO_DIR: '{}'.".format(se... | 8c9730687a933ddf8ec8049cd25f6393bd1a33d5 | 4,048 |
import pandas
import numpy
def synthetic_peptides_by_subsequence(
num_peptides,
fraction_binders=0.5,
lengths=range(8, 20),
binding_subsequences=["A?????Q"]):
"""
Generate a toy dataset where each peptide is a binder if and only if it
has one of the specified subsequences.
... | d4cfa202043e3a98a7960246a7d8775ff147201c | 4,049 |
def gce_zones() -> list:
"""Returns the list of GCE zones"""
_bcds = dict.fromkeys(['us-east1', 'europe-west1'], ['b', 'c', 'd'])
_abcfs = dict.fromkeys(['us-central1'], ['a', 'b', 'c', 'f'])
_abcs = dict.fromkeys(
[
'us-east4',
'us-west1',
'europe-west4',
... | 10e684b2f458fe54699eb9886af148b092ec604d | 4,050 |
def empty_netbox_query():
"""Return an empty list to a list query."""
value = {
"count": 0,
"next": None,
"previous": None,
"results": [],
}
return value | 9b017c34a3396a82edc269b10b6bfc6b7f878bc3 | 4,051 |
import psutil
import time
def get_process_metrics(proc):
""" Extracts CPU times, memory infos and connection infos about a given
process started via Popen(). Also obtains the return code. """
p = psutil.Process(proc.pid)
max_cpu = [0, 0]
max_mem = [0, 0]
conns = []
while proc.poll() is No... | 7be8688debbde33bbcfb43b483d8669241e029d6 | 4,052 |
def tau_from_T(Tobs, Tkin):
"""
Line optical depth from observed temperature and excitation temperature in Kelvin
"""
tau = -np.log(1.-(Tobs/Tkin))
return tau | 089cdc9ae3692037fa886b5c168e03ee2b6ec9ce | 4,053 |
def create_classes_names_list(training_set):
"""
:param training_set: dict(list, list)
:return: (list, list)
"""
learn_classes_list = []
for k, v in training_set.items():
learn_classes_list.extend([str(k)] * len(v))
return learn_classes_list | 0b30153afb730d4e0c31e87635c9ece71c530a41 | 4,054 |
def getSpecialDistribution(queries, kind, burstCount=1, requestsPerBurst=1,
pauseLength=1.0):
"""get a distribution that virtualizes some specifique network situation.
totalTime is the total amount of time the query transmission will take.
Used parameters for the distributions:
- bursts: burstCount, requestsPerBur... | 8e95c7de1f0699f31f975cbe57915cef74016a22 | 4,055 |
from petastorm.spark import SparkDatasetConverter
def get_petastorm_dataset(cache_dir: str, partitions: int=4):
"""
This Dataloader assumes that the dataset has been converted to Delta table already
The Delta Table Schema is:
root
|-- sample_id: string (nullable = true)
|-- value: string (nullable... | 27f6777b2c1cebad08f8a416d360a2b7096febec | 4,056 |
def get_corners(square_to_edges, edge_to_squares):
"""Get squares ids of squares which place in grid in corner."""
return get_squares_with_free_edge(square_to_edges, edge_to_squares, 2) | 1370f472aedf83f7aa17b64a813946a3a760968d | 4,057 |
async def get_untagged_joke():
"""
Gets an untagged joke from the jokes table and sends returns it
:return: json = {joke_id, joke}
"""
df = jokes.get_untagged_joke()
if not df.empty:
response = {"joke": df["joke"][0], "joke_id": int(df["id"][0])}
else:
response = {"joke": "No... | a2dde1d5ddba47beb5e7e51b9f512f0a861336da | 4,058 |
def map_parallel(function, xs):
"""Apply a remote function to each element of a list."""
if not isinstance(xs, list):
raise ValueError('The xs argument must be a list.')
if not hasattr(function, 'remote'):
raise ValueError('The function argument must be a remote function.')
# EXERCISE:... | 1fe75868d5ff12a361a6aebd9e4e49bf92c32126 | 4,059 |
def log_interp(x,y,xnew):
"""
Apply interpolation in logarithmic space for both x and y.
Beyound input x range, returns 10^0=1
"""
ynew = 10**ius(np.log10(x), np.log10(y), ext=3)(np.log10(xnew))
return ynew | 16ef0cc494f61c031f9fd8f8e820a17bb6c83df8 | 4,060 |
def inten_sat_compact(args):
"""
Memory saving version of inten_scale followed by saturation.
Useful for multiprocessing.
Parameters
----------
im : numpy.ndarray
Image of dtype np.uint8.
Returns
-------
numpy.ndarray
Intensity scale and saturation of input.
"""... | 9624891f9d09c13d107907fcd30e2f102ff00ee2 | 4,061 |
def masseuse_memo(A, memo, ind=0):
"""
Return the max with memo
:param A:
:param memo:
:param ind:
:return:
"""
# Stop if
if ind > len(A)-1:
return 0
if ind not in memo:
memo[ind] = max(masseuse_memo(A, memo, ind + 2) + A[ind], masseuse_memo(A, memo, ind + 1))
... | 03d108cb551f297fc4fa53cf9575d03af497ee38 | 4,062 |
import torch
def unique_pairs(bonded_nbr_list):
"""
Reduces the bonded neighbor list to only include unique pairs of bonds. For example,
if atoms 3 and 5 are bonded, then `bonded_nbr_list` will have items [3, 5] and also
[5, 3]. This function will reduce the pairs only to [3, 5] (i.e. only the pair i... | e974728ad831a956f1489b83bb77b15833ae9b82 | 4,063 |
def permission(*perms: str):
""" Decorator that runs the command only if the author has the specified permissions.
perms must be a string matching any property of discord.Permissions.
NOTE: this function is deprecated. Use the command 'permissions' attribute instead.
"""
def decorator(func):
... | b0ef0dfec36a243152dff4ca11ab779d2c417ab8 | 4,064 |
from re import T
def validate_script(value):
"""Check if value is a valid script"""
if not sabnzbd.__INITIALIZED__ or (value and sabnzbd.filesystem.is_valid_script(value)):
return None, value
elif (value and value == "None") or not value:
return None, "None"
return T("%s is not a valid... | d4a5d6922fb14524bc9d11f57807d9a7f0e937f1 | 4,065 |
async def post_user(ctx: Context, user: MemberOrUser) -> t.Optional[dict]:
"""
Create a new user in the database.
Used when an infraction needs to be applied on a user absent in the guild.
"""
log.trace(f"Attempting to add user {user.id} to the database.")
payload = {
'discriminator': ... | 25a6a710d7d94cc9837d9d67408a09fd6ff48596 | 4,066 |
from typing import List
def delete(ids: List = Body(...)):
"""
Deletes from an embeddings index. Returns list of ids deleted.
Args:
ids: list of ids to delete
Returns:
ids deleted
"""
try:
return application.get().delete(ids)
except ReadOnlyError as e:
ra... | 9075db7c7dd174b850d1d4acbe1cdb4001162b5d | 4,067 |
def main():
""" Simple Event Viewer """
events = None
try:
events = remote('127.0.0.1', EventOutServerPort, ssl=False, timeout=5)
while True:
event_data = ''
while True:
tmp = len(event_data)
event_data += events.recv(numb=8192, timeout=1).decode('latin-1')
if tmp == len(event_data):
bre... | d96500a3114785dbb408681e96d7ffb7a5c59d04 | 4,068 |
def fsi_acm_up_profiler_descending(vp1, vp2, vp3):
"""
Description:
Calculates the VEL3D Series A and L upwards velocity data product VELPTMN-VLU-DSC_L1
for the Falmouth Scientific (FSI) Acoustic Current Meter (ACM) mounted on a McLane
profiler.
Because of the orientation of th... | e176ff1b23bf4b5624cdc8a698d03c8d2ee1947a | 4,069 |
from typing import Tuple
def colour_name(colour: Tuple[int, int, int]) -> str:
"""Return the colour name associated with this colour value, or the empty
string if this colour value isn't in our colour list.
>>> colour_name((1, 128, 181))
'Pacific Point'
>>> colour_name(PACIFIC_POINT)
'Pacific... | e596bf802b8f168e6c8d9bd9b8e4113b61e7fd58 | 4,070 |
def score_fn(subj_score, comp_score):
"""
Generates the TextStim with the updated score values
Parameters
----------
subj_score : INT
The subjects score at the moment
comp_score : INT
The computer's score at the moment'
Returns
-------
score_stim : psychopy.visual.t... | 2d52b4c8d47543c6c1c98e5aa7feb8c3341ff7a4 | 4,071 |
def parse_write_beam(line):
"""
Write_beam (type -2)
If btype = −2, output particle phase-space coordinate information at given location V3(m)
into filename fort.Bmpstp with particle sample frequency Bnseg. Here, the maximum number
of phase- space files which can be output is 100. Here, 40 and ... | 7ce86ae39a51ea8d4636e37bea26edd3caae19e8 | 4,072 |
def get_tone(pinyin):
"""Renvoie le ton du pinyin saisi par l'utilisateur.
Args:
pinyin {str}:
l'entrée pinyin par l'utilisateur
Returns:
number/None :
Si pas None, la partie du ton du pinyin (chiffre)
"""
# Prenez le dernier chaine du pinyin
tone = pin... | fc0b02902053b3f2470acf952812573f5125c4cf | 4,073 |
def authIfV2(sydent, request, requireTermsAgreed=True):
"""For v2 APIs check that the request has a valid access token associated with it
:returns Account|None: The account object if there is correct auth, or None for v1 APIs
:raises MatrixRestError: If the request is v2 but could not be authed or the user... | 6c3f60df233cc030dfc3ec2658bd2a70c5a20aed | 4,074 |
def gen_rho(K):
"""The Ideal Soliton Distribution, we precompute
an array for speed
"""
return [1.0/K] + [1.0/(d*(d-1)) for d in range(2, K+1)] | 40382af047d0f2efba0eb6db17c28b92e47d3c92 | 4,075 |
import numpy as np
def assert_array_max_ulp(a, b, maxulp=1, dtype=None):
"""
Check that all items of arrays differ in at most N Units in the Last Place.
Parameters
----------
a, b : array_like
Input arrays to be compared.
maxulp : int, optional
The maximum number of units in t... | 8ca9698e5b213f753002535061b17aeb59f12e83 | 4,076 |
def Ambient_Switching(crop_PPFDmin, Trans, consumption):
"""
Inputs: consumption (returned from Light_Sel)
"""
#How much energy can you save if you switch off when ambient lighting is enough for plant needs?
#Assume that when ambient is higher than max recommended PPFD, that the greenhouse is cloaked, allowin... | 5a8ab9d6eb0c6b3ddd7bb3f7efb1599b952aa345 | 4,077 |
from typing import Callable
def get_numerical_gradient(position: np.ndarray, function: Callable[[np.ndarray], float],
delta_magnitude: float = 1e-6) -> np.ndarray:
""" Returns the numerical derivative of an input function at the specified position."""
dimension = position.shape[0]
... | a439acd3934006e2b8f9188e3204e12ef3885ae5 | 4,078 |
import matplotlib.pyplot as plt
from scipy.signal import periodogram
from .dipole import Dipole
def plot_psd(dpl, *, fmin=0, fmax=None, tmin=None, tmax=None, layer='agg',
ax=None, show=True):
"""Plot power spectral density (PSD) of dipole time course
Applies `~scipy.signal.periodogram` from SciP... | 2fdcb69c88991bb4137587e98b068a912bd66f75 | 4,079 |
def stable_point(r):
"""
repeat the process n times to
make sure we have reaches fixed points
"""
n = 1500
x = np.zeros(n)
x[0] = np.random.uniform(0, 0.5)
for i in range(n - 1):
x[i + 1] = f(x[i], r)
print(x[-200:])
return x[-200:] | 9d9c32abfb0fea74abb32ec8cebd8c76738669b1 | 4,080 |
def vary_on_headers(*headers):
"""
A view decorator that adds the specified headers to the Vary header of the
response. Usage:
@vary_on_headers('Cookie', 'Accept-language')
def index(request):
...
Note that the header names are not case-sensitive.
"""
def decorator(fu... | 9892ac00aa31b0e294f79b2d1539d6d79f3eaed7 | 4,081 |
import pathlib
from typing import Dict
from typing import Union
import logging
def load_frames(
frame_dir: pathlib.Path,
df_frames: pd.DataFrame,
) -> Dict[int, Dict[str, Union[str, np.ndarray]]]:
"""Load frame files from a directory.
Args:
frame_dir: Path to directory where frames are stored... | 81de670c0b42d40cf71ca7d46e63be57dc9c3f12 | 4,082 |
def non_daemonic_process_pool_map(func, jobs, n_workers, timeout_per_job=None):
"""
function for calculating in parallel a function that may not be run
a in a regular pool (due to forking processes for example)
:param func: a function that accepts one input argument
:param jobs: a list of input arg... | 41fbdaae1e584839692eae4d5034ffd6828eb5c7 | 4,083 |
import random
import textwrap
from datetime import datetime
def result_list_handler(*args: list, **kwargs) -> str:
"""
Handles the main search result for each query. It checks whether there are any result for this qeury or not.
1. If there was results, then it sorts and decorates the them.
2 O... | c0fb0db46e3c47d24b06c290ba9d0129eb436edf | 4,084 |
def flip_mask(mask, x_flip, y_flip):
"""
Args:
mask: バイナリマスク
[height, width]
"""
mask = mask.copy()
if y_flip:
mask = np.flip(mask, axis=0)
if x_flip:
mask = np.flip(mask, axis=1)
return mask | d3d783fb3e5913448f4e9d06f1f96d89559a686c | 4,085 |
def sbn2journal(sbn_record, permalink_template="http://id.sbn.it/bid/%s"):
"""
Creates a `dbmodels.Journal` instance out of a dictionary with metadata.
:param record: the dictionary returned by `resolution.supporting_functions.enrich_metadata()`
:return: an instance of `dbmodels.Journal`
"""
bi... | 059b00aeb81dd1bdbc987f31c045b6eb5aedc3b3 | 4,086 |
def median(data):
"""Calculates the median value from |data|."""
data = sorted(data)
n = len(data)
if n % 2 == 1:
return data[n / 2]
else:
n2 = n / 2
return (data[n2 - 1] + data[n2]) / 2.0 | ad2b3f7eb3f5446c81c6c400bc16c7833e75c05c | 4,087 |
import tqdm
import time
import torch
import logging
from typing import OrderedDict
def evaluation(eval_loader,
model,
criterion,
num_classes,
batch_size,
ep_idx,
progress_log,
scale,
vis_params,
... | cb42241366cc1b5672c8953fd78e5bbcacf879da | 4,088 |
from typing import Optional
def split_text_by_length(text: str,
length: Optional[int] = None, # 方案一:length + delta
delta: Optional[int] = 30,
max_length: Optional[int] = None, # 方案二:直接确定长度上下限
min_length: Optional[int... | 60bf713a2cbe3eff85237d9637a303668a9f436b | 4,089 |
def _tfidf_fit_transform(vectors: np.ndarray):
""" Train TF-IDF (Term Frequency — Inverse Document Frequency)
Transformer & Extract TF-IDF features on training data
"""
transformer = TfidfTransformer()
features = transformer.fit_transform(vectors).toarray()
return features, transformer | c38aa629d11258291f306052ac0e4c9c2a474ebd | 4,090 |
from typing import List
def _is_missing_sites(spectra: List[XAS]):
"""
Determines if the collection of spectra are missing any indicies for the given element
"""
structure = spectra[0].structure
element = spectra[0].absorbing_element
# Find missing symmeterically inequivalent sites
symm_s... | 0ae7ad0622e8ec398306e05def214b0ad40fd90f | 4,091 |
def get_objects(params, meta):
"""
Retrieve a list of objects based on their upas.
params:
guids - list of string - KBase IDs (upas) to fetch
post_processing - object of post-query filters (see PostProcessing def at top of this module)
output:
objects - list of ObjectData - see t... | 17d38a1a5e09847700537076c0bfefdd55947682 | 4,092 |
import os
def heat_transfer_delta():
"""
:return: net - OpenModelica network converted to a pandapipes network
:rtype: pandapipesNet
:Example:
>>> pandapipes.networks.simple_water_networks.heat_transfer_delta()
"""
return from_json(os.path.join(heat_tranfer_modelica_path, "delta.jso... | 276c691ef5e6cdbb7a8fa7a0ce878d0962cc06a1 | 4,093 |
import os
def extract(file_path, extract_path):
"""
Extract if exists.
Args:
file_path (str): Path of the file to be extracted
extract_path (str): Path to copy the extracted files
Returns:
True if extracted successfully, False otherwise
"""
if (os.path.exists(file_pa... | 8887e0796db6980d1b06610e9d95f29faf232c75 | 4,094 |
def parseMidi(midifile):
"""Take a MIDI file and return the list Of Chords and Interval Vectors.
The file is first parsed, midi or xml. Then with chordify and
PC-Set we compute a list of PC-chords and Interval Vectors.
"""
mfile = ms.converter.parse(midifile)
mChords = mfile.chordify()
chor... | 8c803c297eee5cc29a78d6c8b864a85e8bfd3d52 | 4,095 |
def get_similarity(s1, s2):
"""
Return similarity of both strings as a float between 0 and 1
"""
return SM(None, s1, s2).ratio() | 3964670a69a135fbc6837e9c68a2e7ac713d67dc | 4,096 |
from typing import Union
from typing import Sequence
from re import T
def concrete_values_from_iterable(
value: Value, ctx: CanAssignContext
) -> Union[None, Value, Sequence[Value]]:
"""Return the exact values that can be extracted from an iterable.
Three possible return types:
- ``None`` if the arg... | 3acdda92df4e27d4eecf39630570b90049580d6d | 4,097 |
import os
def ReadSimInfo(basefilename):
"""
Reads in the information in .siminfo and returns it as a dictionary
"""
filename = basefilename + ".siminfo"
if (os.path.isfile(filename)==False):
print("file not found")
return []
cosmodata = {}
siminfofile = open(filename,"r")
line = siminfofile.readline()... | 74b568d953c155f8998e051a83b35b003377ac26 | 4,098 |
def quat_conjugate(quat_a):
"""Create quatConjugate-node to conjugate a quaternion.
Args:
quat_a (NcNode or NcAttrs or str or list or tuple): Quaternion to
conjugate.
Returns:
NcNode: Instance with quatConjugate-node and output-attribute(s)
Example:
::
... | 2bff8b1e472ad2975ba96084843004ce86205f9f | 4,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.