content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_session_triplets(
sessions: List[int], match_types: List[int]
) -> Tuple[List[int], List[int], List[int]]:
"""Generate all possible triplets for each session.
:param sessions: A list of integers denoting session label
:param match_types: A list of integers denoting match type - 0 for anchor, 1 ... | 50,100 |
def _rotation_matrix_hme_to_hee(hmeframe):
"""
Return the rotation matrix from HME to HEE at the same observation time
"""
# Get the Sun-Earth vector
sun_earth = HCRS(_sun_earth_icrf(hmeframe.obstime), obstime=hmeframe.obstime)
sun_earth_hme = sun_earth.transform_to(hmeframe).cartesian
# Ro... | 50,101 |
def timestamp_before_update(mapper, connection, target):
"""Update `updated` property with current time on `before_update` event."""
target.updated = datetime.utcnow() | 50,102 |
def display_cluster_median_values(df_fit, df_orig, cluster_range):
"""Display a series of DataFrames for desired cluster range with median
feature values and size for each cluster.
Arguments:
----------
- df_fit: dataframe, preprocessed data containing the presumed clusters
- df_orig: data... | 50,103 |
def get_image(microscopy_collection, series):
"""Return microscopy image."""
image = microscopy_collection.image(s=series)
image = image[:, :, 0]
return image | 50,104 |
def goToDirectory(alias):
"""go to a saved directory"""
if not settings.platformCompatible():
return False
data = pickle.load(open(settings.getDataFile(), "rb"))
try:
data[alias]
except KeyError:
speech.fail("Sorry, it doesn't look like you have saved " + alias + " yet.")
speech.fail("Go to the directory y... | 50,105 |
def process_aa_snvs(aa_snv_dict, name, defs):
"""
Parameters
----------
aa_snv_dict: dict
name: str
defs: pandas.DataFrame
- genes or proteins dataframe from genes_and_proteins.py
"""
aa_snv = (
pd.DataFrame.from_dict(aa_snv_dict, orient="index", columns=["id"])
.... | 50,106 |
def test_cli(subprocess_check_call: MagicMock):
"""Should execute the cli command with the expected arguments."""
path = str(pathlib.Path("/foo/bar").absolute()).replace("\\", "/")
assert cli.main(["-d", path, "--tag-version=10.11.12"])
command = subprocess_check_call.call_args.args[0]
assert f"{pa... | 50,107 |
def use_file(filename):
""" Return a decorator which will parse a kicad file
before running the test. """
def decorator(test_method):
""" Add params to decorator function. """
@wraps(test_method)
def wrapper(self):
""" Parse file then run test. """
self.desi... | 50,108 |
def create_autoscaler(gce, mig, params):
"""
Create a new Autoscaler for a MIG.
:param gce: An initialized GCE driver object.
:type gce: :class: `GCENodeDriver`
:param mig: An initialized GCEInstanceGroupManager.
:type mig: :class: `GCEInstanceGroupManager`
:param params: Dictionary of ... | 50,109 |
def recog_with_two_models(args):
"""Decode with the given args.
Args:
args (namespace): The program arguments.
"""
set_deterministic_pytorch(args)
# Weiran: load both models.
model1, train_args1 = load_trained_model(args.model1)
assert isinstance(model1, ASRInterface)
model1.re... | 50,110 |
def chromium_all(*, min_major_version: int = 90, min_minor_version: int = 40) -> List[str]:
"""get chrome versions"""
resp = Request.get(CHROME_REP_URL)
versions = RE_CHROMIUM.findall(resp)
versions = [v for v in versions if len(v.split(".")) > 2 and (int(v.split(".")[-1]) >= min_minor_version
... | 50,111 |
def test_check_mod_args(mock_module,
mock_check_dsl_dependencies,
mock_has_interface_config,
mock_add_global_ospf,
mock_config_ospf_int):
"""
cl_quagga_ospf - check mod args
"""
instance = mock_module.return_... | 50,112 |
def test_input_type():
"""
Test for error if input is of a wrong type
Parameters
----------
None
Returns
-------
None
The test should pass and no asserts should be displayed.
"""
# Wrong dataframe input
try:
numerical_eda(
list(cars),
... | 50,113 |
def setup(hass, config):
"""Setup platfrom"""
async def async_auto_scale(call):
"""Call auto scale service handler."""
await async_handle_auto_scale_service(hass, call)
hass.services.register(
DOMAIN,
SERVICE_AUTO_SCALE,
async_auto_scale,
schema=AUTO_SCALE_S... | 50,114 |
def parse_command_line_args(args):
"""Parse command line arguments.
Args:
args ([str]): List of command line arguments and flags.
Returns
(argparse.Namespace): Parsed arguments from argparse
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'-s', '--schema',... | 50,115 |
def train_linear_clf(n_fits):
"""Called by the `/train` HTTP GET method in `logic.py` module.
Parameters
----------
n_fits : int
Number of partial fits applied to the linear estimator.
Returns
-------
dict
measured_accuracy : float
Accuracy of the linear classifier after application of the... | 50,116 |
def list_joysticks():
"""return list of all joystick names"""
joysticks = get_all_joysticks()
return [joy.get_name() for joy in joysticks] | 50,117 |
def write_csv(vendor,product,scrape_array):
""" creates a output file like "vendor-product.csv" and then writes mapped items in scrape_array"""
if not os.path.exists('output'):
os.makedirs('output')
if not os.path.exists('output/'+vendor):
os.makedirs('output/'+vendor)
if os.path.exists(... | 50,118 |
def kurtosis(inlist):
"""
Returns the kurtosis of a distribution, as defined in Numerical
Recipies (alternate defn in CRC Standard Probability and Statistics, p.6.)
Usage: lkurtosis(inlist)
"""
return moment(inlist, 4) / pow(moment(inlist, 2), 2.0) | 50,119 |
def compute_iou(box, boxes):
"""Calculates IoU of the given box with the array of the given boxes.
box: a polygon
boxes: a vector of polygons
Note: the areas are passed in rather than calculated here for
efficiency. Calculate once in the caller to avoid duplicate work.
"""
# Calculate inters... | 50,120 |
def far(scores, labels, frr_op):
"""
Calculates FAR from FRR operating point.
Parameters
----------
scores: np array
It holds the score information for all samples (genuine and impostor).
It is expected that impostor (negative) scores are, at least by design, greater than genuine (... | 50,121 |
def iso_to_plotly_time_string(iso_string):
"""Remove timezone info and replace 'T' delimeter with ' ' (ws)."""
# make sure we don't send timezone info to plotly
if (iso_string.split("-")[:3] == "00:00") or (iso_string.split("+")[0] == "00:00"):
raise Exception(
"Plotly won't accept times... | 50,122 |
def mk_vis_txt_pair_datalist(anno_path, data_ratio=1.0,
vis_id_key="coco_id", txt_key="caption"):
"""
Args:
anno_path: str, path to .jsonl file, each line is a dict
data_ratio: float, (0, 1], when < 1, use part of the data.
vis_id_key: str, image/video file i... | 50,123 |
def float_func(arg):
"""
Internal argument validation, have exceptions defined after a
chain of function calls
"""
exobj = putil.exh.get_or_create_exh_obj()
exobj.add_exception(
exname='illegal_argument',
extype=TypeError,
exmsg='Argument `arg` is not valid'
)
exo... | 50,124 |
def index_greater(array, prec=1e-8):
"""
Purpose:
Function for finding first item in an array that has a value greater than the first element in that array
If no element is found, returns None
Precision:
1e-8
Return:
int or None
"""
item=array[0]
for idx, val ... | 50,125 |
def _json_print(json):
""" Pretty print JSON """
print jsonlib.dumps(json, indent=4, separators=(',', ': ')) | 50,126 |
def get_ssl_sampler(labels, valid_num_per_class, annotated_num_per_class, num_classes):
"""
:param labels: torch.array(int tensor)
:param valid_num_per_class: the number of validation for each class
:param annotated_num_per_class: the number of annotation we use for each classes
:param num_classes: ... | 50,127 |
def load_parse_dict():
"""Dicts for parsing Arc line lists from NIST
Rejected lines are in the rejected_lines.yaml file
"""
dict_parse = dict(min_intensity=0., min_Aki=0., min_wave=0.)
arcline_parse = {}
# ArI
arcline_parse['ArI'] = copy.deepcopy(dict_parse)
arcline_parse['ArI']['min_in... | 50,128 |
def is_test(method) -> bool:
"""
Checks if the given method is a test method.
:param method: The method to check.
:return: True if the method is a test method,
False if not.
"""
return getattr(method, _constants.IS_TEST_ATTRIBUTE, False) | 50,129 |
def parseTargetDirect():
"""
Parse target dbms and set some attributes into the configuration singleton.
"""
if not conf.direct:
return
details = None
remote = False
for dbms in SUPPORTED_DBMS:
details = re.search(r"^(?P<dbms>%s)://(?P<credentials>(?P<user>.+?)\:(?P<pass>.... | 50,130 |
def data_transform(array, array2=np.asarray((None)),type='z_score_norm', means=None, stds=None):
"""
Transforms data in the given array according to the type
array :an nd numpy array.
array2 :an nd numpy array(optional-for multidimensional datasets)
type :'z_score_norm' = implements z score n... | 50,131 |
def load_items(reader):
"""Load items from HDF5 file:
* reader: :py:class:`guidata.hdf5io.HDF5Reader` object"""
with reader.group("plot_items"):
names = reader.read_sequence()
items = []
for name in names:
klass_name = re.match(
r"([A-Z]+[A-Za-z0-9\_]*)\_([0-9]*)", na... | 50,132 |
def zmatrix(file_prefix):
""" generate zmatrix JSONObject
:param file_prefix: path to file
:type file_prefix: str
:param json_prefix: top level keys
ex: ('energy', ['gaussian', 'b3lyp', 'cc-pvdz', 'RR'])
:type json_prefix: tuple
:return: instance of JSONObject class
:rtype: JSONObje... | 50,133 |
def sequence_nd(
seq,
maxlen=None,
padding: str = 'post',
pad_val=0.0,
dim: int = 1,
return_len=False,
):
"""
padding sequence of nd to become (n+1)d array.
Parameters
----------
seq: list of nd array
maxlen: int, optional (default=None)
If None, will calculate m... | 50,134 |
def random_dists(filename):
"""
Given a Excel filename with a row for each variable and columns for the
minimum and maximum, create a dictionary of Uniform distributions for
each variable.
Parameters
----------
filename : string
Number of parameter settings to generate
... | 50,135 |
def is_changed(event, old_event):
"""
Compares two events and discerns if it has changes that should trigger a push
:param event:
:param old_event:
:return: bool
"""
# Simple changes
if any(
event.get(field) != old_event.get(field) for field in ["severity", "certainty"]
):
... | 50,136 |
def print_guide():
"""Prints the rules of the game"""
print(RULES) | 50,137 |
def view(self, view_id):
"""Get a particular view belonging to a case group by providing view id
Arguments:
id(int): view id
Returns:
List of :class:`rips.generated.generated_classes.EclipseView`
"""
views = self.views()
for view_object in views:
if view_object.id == v... | 50,138 |
def enu2geodetic(
e: ndarray,
n: ndarray,
u: ndarray,
lat0: ndarray,
lon0: ndarray,
h0: ndarray,
ell: Ellipsoid = None,
deg: bool = True,
) -> Tuple[ndarray, ndarray, ndarray]:
"""
East, North, Up to target to geodetic coordinates
Parameters
----------
e : float
... | 50,139 |
def Standard_GUID_HashCode(*args):
"""
* H method used by collections.
:param aguid:
:type aguid: Standard_GUID &
:param Upper:
:type Upper: int
:rtype: int
"""
return _Standard.Standard_GUID_HashCode(*args) | 50,140 |
def get_import_stmt_str(alias_list, import_src=None, max_linechars=88):
"""
Construct an import statement by building an AST, convert it to source using
astor.to_source, and then return the string.
alias_list: List of strings to use as ast.alias `name`, and optionally also
`... | 50,141 |
def convert_into_decimal(non_binary_number: str, base: int) -> int:
"""
Converts a non binary string number into a decimal number
:param non_binary_number:
:param base:
:return: a decimal number
"""
decimal_number = 0
for digit in range(len(non_binary_number)):
decimal_number... | 50,142 |
def main():
"""
NAME
eqarea_magic.py
DESCRIPTION
makes equal area projections from declination/inclination data
SYNTAX
eqarea_magic.py [command line options]
INPUT
takes magic formatted sites, samples, specimens, or measurements
OPTIONS
-h prints help me... | 50,143 |
def sgld_sweep() -> Sequence[SGMCMCConfig]:
"""sweep for vanilla sgld."""
sweep = []
for learning_rate in [
1e-5, 5e-5, 1e-4, 5e-4, 1e-3, 5e-3, 1e-2
]:
for prior_variance in [0.01, 0.1, 0.5]:
sweep.append(SGMCMCConfig(learning_rate, prior_variance))
return tuple(sweep) | 50,144 |
def stringify(num):
"""
Takes a number and returns a string putting a zero in front if it's
single digit.
"""
num_string = str(num)
if len(num_string) == 1:
num_string = '0' + num_string
return num_string | 50,145 |
def zip_courses():
"""
function to intelligently zip all the courses
depending upon if their zips have been deleted
due to less number of downloads or not
"""
for root, dirs, files in os.walk(DATABASE_DIR, topdown=True):
flag = 0
for name in dirs:
if len(name) == 2:
flag = 1
break
if root[len(... | 50,146 |
def get_symbols(market):
"""
Gets top 100 symbols by market cap for which
historical and incremental data refresh dags will be run.
"""
@task()
def find_symbols(market):
"""
Gets the most popular X number of symbols and stores them
in the symbol table.
For crypto... | 50,147 |
def euc_distance(vertex, circle_obstacle):
"""
Finds the distance between the point and center of the circle.
vertex: Vertex in question.
circle_obstacle: Circle obstacle in question.
return: Distance between the vertex and the center of the circle.
"""
x = vertex[0] - circle_obstacle.posi... | 50,148 |
def less(x, y):
"""
Returns the truth value of (x < y) element-wise.
Parameters
----------
x : tensor
Must be one of the following types: float32, float64, int32, uint8,
int16, int8, int64, bfloat16, uint16, half, uint32, uint64.
y : tensor
A Tensor. Must have the same t... | 50,149 |
def get_commit_shas_since(sha: str, dir: str) -> typing.List[str]:
"""Gets the list of shas for commits committed after the given sha.
Arguments:
sha {str} -- The sha in the git history.
dir {str} -- An absolute path to a directory in the git repository.
Returns:
typing.List[str] -... | 50,150 |
async def test_cached_supported_features(hass, client, monkeypatch):
"""Test test supported features."""
monkeypatch.setattr(client, "is_on", False)
monkeypatch.setattr(client, "sound_output", None)
await setup_webostv(hass)
await client.mock_state_update()
# TV off, support volume mute, step, ... | 50,151 |
def decision_tree_learning(examples: list, attributes: list, parent_examples,
importance_function: callable):
"""
Decision tree learning algorithm as given in figure 18.5 in Artificial
Intelligence A Modern Approach.
:param examples: list of dictionaries containing examples t... | 50,152 |
def modified_bessel(times, bes_A, bes_Omega, bes_s, res_begin, bes_Delta):
""" Not Tested. """
b = np.where(times > res_begin + bes_Delta / 2.,
special.j0(bes_s * bes_Omega *
(- res_begin + times - bes_Delta / 2.) ),
(np.where(times < res_begin - bes_Delta / 2.,
spe... | 50,153 |
def predict_csr_val(csr_op, rs1_val, csr_val, csr_mask):
"""
Predicts the CSR reference value, based on the current CSR operation.
Args:
csr_op: A string of the CSR operation being performed.
rs1_val: A bitarray containing the value to be written to the CSR.
csr_val: A bitarray containing the current... | 50,154 |
def request(url: str, args: dict = None, method: str = 'GET'):
"""
Custom Method that requests data from requests_session
and confirms it has a valid JSON return
"""
response = request_session(url, method, args)
try:
# you only come here if we can understand the API response
retu... | 50,155 |
def link():
"""Link the user's account with ORCID (i.e. affiliates user with their org on ORCID)."""
# TODO: handle organisation that are not on-boarded
redirect_uri = url_for("orcid_callback", _external=True)
external_sp = app.config.get("EXTERNAL_SP")
if external_sp:
sp_url = urlparse(exte... | 50,156 |
def create_se3(ori, trans=None):
"""
Args:
ori (np.ndarray): orientation in any following form:
rotation matrix (shape: :math:`[3, 3]`)
quaternion (shape: :math:`[4]`)
euler angles (shape: :math:`[3]`).
trans (np.ndarray): translational vector (shape: :math:`[... | 50,157 |
def build_negative_log_likelihood(
image,
telescope_description,
oversampling,
min_lambda,
max_lambda,
spe_width,
pedestal,
hole_radius=0 * u.m,
):
"""Create an efficient negative log_likelihood function that does
not rely on astropy units internally by defining needed values as ... | 50,158 |
def kube_deploy_reloadbalance(name, namespace, d_app):
"""Re-loadbalance deployment resource."""
if not name:
s_msg = 'name is not defined.'
return (False, s_msg)
if not namespace:
s_msg = 'namespace is not defined.'
return (False, s_msg)
if not d_app:
s_msg = 'ap... | 50,159 |
def _ParseParameterType(type_string):
"""Parse a parameter type string into a JSON dict for the DF SQL launcher."""
type_dict = {'type': type_string.upper()}
if type_string.upper().startswith('ARRAY<') and type_string.endswith('>'):
type_dict = collections.OrderedDict([
('arrayType', _ParseParameterTy... | 50,160 |
def get_now_utc_epoch():
"""
Returns the epoch
:return:
"""
return int(time.time()) | 50,161 |
def validate_and_update_registration(transaction_executor, vin, current_owner, new_owner):
"""
Validate the current owner of the given vehicle and transfer its ownership to a new owner in a single transaction.
:type transaction_executor: :py:class:`pyqldb.execution.executor.Executor`
:param transaction... | 50,162 |
def patch_fakeuseragent():
"""Stub out fake useragent dep that makes requests."""
with patch("pylinky.client.UserAgent", return_value="Test Browser"):
yield | 50,163 |
def __flip(direction):
"""INTERNAL.
Flip the pixel map.
"""
global _pixel_map
flipped_pixel_map = deepcopy(_pixel_map)
for x in range(_w):
for y in range(_h):
if direction == "h":
flipped_pixel_map[x][y] = _pixel_map[(_w - 1) - x][y]
elif direct... | 50,164 |
def get_top_words(text: str, blacktrie: dict, top_n: int) -> List[str]:
"""Get top words in a string, excluding a predefined list of words.
Args:
text (str): Text to parse
blacktrie (dict): Trie built from a blacklist of words to ignore
top_n (int): Number of top words to return
Returns:
List[str]: List of... | 50,165 |
def get_fluid_colors(fXs, fVs, normalize=False):
## I realized that with limited data, this coloring does not make much sense
"""
Given the velocity field (Ux, Uy) at positions (X,Y), compute for every x in (X,Y) if the position is contributing to the inflow or the outflow. This can be obtained by u*x (scal... | 50,166 |
def getitem(x, item):
"""returns specific item of a tensor (Functional).
# Arguments
item: Item list.
# Returns
A new functional object.
"""
validate_functional(x)
res = x.copy()
ys = []
lmbd = [Lambda(lambda xx: xx.__getitem__(item)) for xx in x.outputs]
for l, y ... | 50,167 |
def norm_range(
data: torch.Tensor, min: float, max: float, per_channel: bool = True, out: Optional[torch.Tensor] = None
) -> torch.Tensor:
"""
Scale range of tensor
Args:
data: input data. Per channel option supports [C,H,W] and [C,H,W,D].
min: minimal value
max: maximal value
... | 50,168 |
def get_mvarg(size_pos, position="full"):
"""Take xrandrs size&pos and prepare it for wmctrl (MVARG) format
MVARG: <G>,<X>,<Y>,<W>,<H>
* <G> - gravity, 0 is default
"""
allowed = ["left", "right", "top", "bottom", "full"]
if position not in allowed:
raise ValueError(f"Position has... | 50,169 |
def delete_direct_messages(auth, author_id, server_id, del_pinned):
"""
:param auth: is a long string about 88 characters which can be found by inspecting network to discord
In the `Request Headers` -> `authorization`.
:param author_id:
:param server_id:
author_id and server_id ... | 50,170 |
def fr2date(edate, **kwargs):
"""
Wrapper function for :func:`date2date` with French input and
standard output date formats
That means `date2date(edate, fr=True, **kwargs)`;
but *fr* given in call will overwrite *fr=True*.
Examples
--------
>>> edate = ['12/11/2014 12:00', '01/03/2015 ... | 50,171 |
def plugin_test(myarg="default"):
"""
an example command that shows plugins
read plugin class from plugin-example section in my-app.ini
"""
klass=app_config.opt_string("plugin-example", "class")
if klass.startswith('.'): klass='MyApp.MyPlugins'+klass
plugin=factory(klass+'.Plugin', myar... | 50,172 |
def convert_species_tuple2chianti_str(species):
"""
Convert a species tuple to the ion name format used in `chiantipy`.
Parameters
-----------
species: tuple (atomic_number, ion_number)
Returns
--------
str
ion name in the chiantipy format
Examples
---------
>>> co... | 50,173 |
def calculate_version(validate=False, error_on_invalid=False):
"""Construct a version string from date, time, and short git hash
If input argument `validate` is set to `True`, this uses the
(non-standard, but pypi-installable) `packaging` module to check
the output version string. If the version is no... | 50,174 |
def vote(request, village_no, day_no):
"""投票処理"""
vote_id = request.POST['vote']
login_id = request.session.get('login_id', False)
participant = VillageParticipant.objects.get(village_no=village_no, pl=login_id, cancel_flg=False)
ability = VillageParticipantExeAbility.objects.get(village_participant... | 50,175 |
def read_header_offsets(file, block_size):
"""Reads the PBDF header (not checking the included file size) and returns the list of offsets adjusted to match
decrypted data positions.
Args:
file: The decrypted input file.
block_size (int): The block size in bytes at which end a checksum is pla... | 50,176 |
def level_2_win_play(x):
"""
Probability that a deck with x SSGs will win on the play using level two reasoning
:param int x: SSGs in deck
:return float:
"""
return sum([
level_2_hand_odds_play(i, x) * mull_to_play(i, x) for i in range(0, 8)
]) | 50,177 |
def getfullargspec(func):
"""Get the names and default values of a function's arguments.
A tuple of seven things is returned:
(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations).
'args' is a list of the argument names.
'varargs' and 'varkw' are the names of the * and ** argumen... | 50,178 |
def get_json(file_path):
"""
Faz a leitura de um arquivo Json com codificacao utf-8,
apenas para arquivos dentro do diretorio folhacerta_settings
:param file_path: (string) nome do arquivo json com extensao
:return: Dicionario com os dados do json
"""
with open(file_path, en... | 50,179 |
def color_array(arr, alpha=1):
""" take an array of colors and convert to
an RGBA image that can be displayed
with imshow
"""
img = np.zeros(arr.shape + (4,))
for row in range(arr.shape[0]):
for col in range(arr.shape[1]):
c = mpl.colors.to_rgb(arr[row, col])
img[... | 50,180 |
def test_train_test_split(get_traain_test_sp_data):
""" Test the train test split"""
train_test_split = create_train_test_split(get_traain_test_sp_data)
assert "train" in list(train_test_split.keys())
assert "test" in list(train_test_split.keys())
assert "validate" in list(train_test_split.keys... | 50,181 |
def main(args):
"""Splitting dataset"""
df = pd.read_csv("data/lenta-ru-news.csv", usecols=["text"]).dropna()
if args.sample is not None:
print(f"sampling {args.sample} texts")
df = df.sample(args.sample, random_state=args.sample)
train, valid = train_test_split(
df, random_state... | 50,182 |
def showturtle():
"""Makes the turtle visible.
Aliases: showturtle | st
No argument.
Example (for a Turtle instance named turtle):
>>> turtle.hideturtle()
>>> turtle.showturtle()
"""
return __SingletonTurtle().showturtle() | 50,183 |
def escape_the_maze(params, output_proto):
"""Escapes the maze."""
size = 4
boxes = [(0, 1, 0), (2, 0, 1), (1, 3, 1), (3, 1, 3)]
start = (3, 3, 0)
end = (1, 0, 0)
# Builds a map between each position in the grid and a unique integer between
# 0 and size^3 - 1.
index_map = {}
reverse... | 50,184 |
def accuracy_plot(model_list, tag='', testerror=False, savefile=None, title=None, errorbars=False,
loglog=False, ylim=None, fontsize=16, legend_fontsize=16, label_fontsize=16):
"""Accuracy Plot
======
Creates a plot of accuracy scores for experiments run with `ssl_trials`.
Parameter... | 50,185 |
def test_init(isolated_runner):
"""Test project initialization from template."""
# create the project
new_project = Path('test-new-project')
assert not new_project.exists()
result = isolated_runner.invoke(cli, INIT)
assert 0 == result.exit_code
assert new_project.exists()
assert (new_pro... | 50,186 |
def get_setting(db, name):
"""
Get a specific setting
@param db The database connection
@param name The setting's name
@return The setting's value
"""
result = _query(db, "SELECT value FROM settings WHERE name=%(name)s;", { "name" : name })
if len(result) > 0:
return getattr(res... | 50,187 |
def test_c_1__three_army_circular_movement():
"""
TURKEY: F Ankara Coast -> Constantinople Coast
A Constantinople -> Smyrna
A Smyrna -> Ankara
"""
game_map = generate_map()
turkey_starting_configuration = [
{'territory_name': 'Ankara Coast', 'unit_type': UnitTypes.FLE... | 50,188 |
async def test_dbus_settime(coresys: CoreSys):
"""Set timestamp on backend."""
test_dt = datetime(2021, 5, 19, 8, 36, 54, 405718, tzinfo=timezone.utc)
with pytest.raises(DBusNotConnectedError):
await coresys.dbus.timedate.set_time(test_dt)
await coresys.dbus.timedate.connect()
await cores... | 50,189 |
def test_fcg_fc_overlap_5(df_fc_overlap_5):
"""Split 2x2 overlapping fragments that result in 4 fragment graphs"""
df_fcg = fragment_combination_graph.generate(df_fc_overlap_5)
assert len(df_fcg.index) == 4
# test each of the fgraphs
# for i in range(len(df_fcg.index)):
# print(df_fcg.iloc[i... | 50,190 |
def set_up_directory_simple(rootdir, classname):
"""rootdir is the root directory,
classname is the wnid or human-readable name,
directory will be rootdir/classname
Creates directories if they don't exist;
throws an error if classname directories exist and aren't empty."""
dir_path = os.path.jo... | 50,191 |
def exa(args) -> None:
"""Install exa which is an Rust-implemented alternative to ls.
"""
if args.install:
if is_debian_series():
run_cmd("cargo install --root /usr/local/ exa")
elif is_macos():
brew_install_safe(["exa"])
elif is_fedora_series():
r... | 50,192 |
def check_table_exists(client: AitoClient, table_name: str) -> bool:
"""check if a table exists in the instance
:param client: the AitoClient instance
:type client: AitoClient
:param table_name: the name of the table
:type table_name: str
:return: True if the table exists
:rtype: bool
"... | 50,193 |
def bytes_to_str(s, encoding='latin-1'):
"""Extract null-terminated string from bytes."""
if b'\0' in s:
s, _ = s.split(b'\0', 1)
return s.decode(encoding, errors='replace') | 50,194 |
def get_time_delta(time_string: str) -> timedelta:
"""
Takes a time string (1 hours, 10 days, etc.) and returns
a python timedelta object
:param time_string: the time value to convert to a timedelta
:type time_string: str
:returns: datetime.timedelta for relative time
:type datetime.timedel... | 50,195 |
def test_tablemodel(mock_program_dao):
"""Get a data manager instance for each test function."""
# Create the device under test (dut) and connect to the database.
dut = RAMSTKDesignMechanicTable()
dut.do_connect(mock_program_dao)
yield dut
# Unsubscribe from pypubsub topics.
pub.unsubscrib... | 50,196 |
def weighmail(imap, folder, labels, observer=None):
"""Applies labels to message that meet size criteria.
imap - IMAPClient
folder - folder name to operate on
labels - list of Label tuples
observer - will call back to report progress
"""
imap.select_folder(folder)
for label in labels:... | 50,197 |
def lens_of(data):
"""Apply len(x) to elemnts in data."""
return len(data) | 50,198 |
def _format_phone(
phone: Any, output_format: str, fix_missing: str, split: bool, errors: str
) -> Any:
"""
Function to transform a phone number instance into the desired format.
The last component of the returned tuple contains a code indicating how the
input value was changed:
0 := the va... | 50,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.