content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def send(instance, client, formatter, format_config, messages, gap, batch):
"""sends data and prints the time it took to send it
:param instance: transport class instance
:param client: client to use to send send
:param string format: formatter to use
:param dict format_config: formatter configurat... | 5,338,700 |
def str2num(s):
"""Convert string to int or float number.
Parameters
----------
s : string
String representing a number.
Returns
-------
Number (int or float)
Raises
------
TypeError
If `s` is not a string.
ValueError
If the string does ... | 5,338,701 |
def forward_signal(signum, proc):
"""Forward signal to child."""
if not proc.poll():
proc.send_signal(signum) | 5,338,702 |
def get_html_templates_path():
"""
Return path to ABlog templates folder.
"""
pkgdir = os.path.abspath(os.path.dirname(__file__))
return os.path.join(pkgdir, "templates") | 5,338,703 |
def new_log(infile_history=None, extra_notes=None, git_repo=None):
"""Create a new command line log/history.
Kwargs:
infile_history (dict): keys are input file names and values are the logs for those files
extra_notes (list): List containing strings of extra information (output is one list item p... | 5,338,704 |
def pre_delete_category(sender, instance, **kwargs):
"""
Receiver that is called after a category is deleted. Makes associated Air
Quality project inactive.
"""
try:
category = AirQualityCategory.objects.get(category=instance)
category.project.status = 'inactive'
category.pr... | 5,338,705 |
def validate_export_node(node_label):
"""
Raise a ``UserError`` if there is any reason that nodes with the type
specified by ``node_label`` should not be exported. This m
Args:
node_label (str): string of the node type
Return:
None
Raises:
UserError: if the node cannot... | 5,338,706 |
def generate_permutation(perm, n):
"""
Let's generate all possible permutations
Now it is a SMART generator which can cut dead ends
"""
if len(perm) == n:
# Congrats! U have found a legit solution. Let me make it in [[x1, y1], [x2, y2], [x3, y3] ... [xn, yn]] format
# queens_pos = []
# for x ... | 5,338,707 |
def _get_new_args_dict(func, args, kwargs):
"""Build one dict from args, kwargs and function default args
The function signature is used to build one joint dict from args and kwargs and
additional from the default arguments found in the function signature. The order
of the args in this dict is the orde... | 5,338,708 |
def hellinger_funct(x,P,Q):
"""
P,Q should be numpy stats gkde objects
"""
return np.sqrt(P(x) * Q(x)) | 5,338,709 |
def VM_BUILD(*names):
"""build a virtual machine
This task builds a virtual machine image from scratch. This
usually takes some time and may require the original ISO
image and a product key of the operating system.
Run this task without arguments to build images for all
registered VMs.
""... | 5,338,710 |
def main() -> None:
"""Run Program."""
root = tk.Tk()
GUI(root)
print("To begin file upload:\n")
print("1. Load your recipient's public key")
print("2. Select a file or a directory for upload (not both)")
print("3. Write SFTP username, server and port to SFTP Credentials")
print("4. Load... | 5,338,711 |
def print_annotation(name, value, xml):
"""Writes some named bits of information about the current test run."""
if xml:
print escape(name) + " {{{"
print escape(value)
print "}}}"
else:
print name + " {{{"
print value
print "}}}" | 5,338,712 |
def clean_collection(collection):
"""Iterates through the images in the Collection and remove those that don't exist
on disk anymore
"""
images = collection.images()
number_purged = 0
for image in images:
if not os.path.isfile(image.get_filepath()):
logger.info('Removing Imag... | 5,338,713 |
def human_date(date):
""" Return a string containing a nice human readable date/time.
Miss out the year if it's this year
"""
today = datetime.datetime.today()
if today.year == date.year:
return date.strftime("%b %d, %I:%M%P")
return date.strftime("%Y %b %d, %I:%M%P") | 5,338,714 |
def main():
#
# "a" is a string at index 0 and
#
"""
Lista de palavras onde:
"A" é uma string no índice 0 e
"E" é uma string no índice 4
"""
letters = ["a", "b", "c", "d", "e"]
print(letters)
assert letters[0] == "a"
assert letters[4] == letters[-1] ==... | 5,338,715 |
def compute_thickness(wmP, kdTreegm, kdTreewm):
"""
This function..
:param wmP:
:param kdTreegm:
:param kdTreewm:
:return:
"""
# Find the closest point to the gray matter surface point
gmIndex = kdTreegm.FindClosestPoint(wmP)
gmP = kdTreegm.GetDataSet().GetPoint(gmIndex)
# c... | 5,338,716 |
def sync(args):
"""Synchronize your local repository with the manifest and the real world.
This includes:
- ensures that all projects are cloned
- ensures that they have the correct remotes set up
- fetches from the remotes
- checks out the correct tracking branches
- if the local branch is not ... | 5,338,717 |
def cytoband_interval():
"""Create test fixture for Cytoband Interval."""
return CytobandInterval(
start="q13.32", end="q13.32"
) | 5,338,718 |
def _get_proxy_class(request):
""" Return a class that is a subclass of the requests class. """
cls = request.__class__
if cls not in _proxy_classes:
class RequestProxy(cls):
def __init__(self, request):
self.__dict__ = request.__dict__
self.__request = re... | 5,338,719 |
def test_yaml_representation():
"""
Testing the yaml_representation method
"""
name = 'Donut'
description = {'This is an old fasion donut'}
properties = ['eatable', 'pickable']
item = Item(name, description, properties)
assert isinstance(item.yaml_representation(), dict) | 5,338,720 |
def rebuilt_emoji_dictionaries(filename):
"""
Rebuilds emoji dictionaries, given a csv file with labeled emoji's.
"""
emoji2unicode_name, emoji2sentiment = {}, {}
with open(filename) as csvin:
for emoji in csv.DictReader(csvin):
for key, value in emoji.items():
if... | 5,338,721 |
def send_message(receiver, message):
"""
Send message to receivers using the Twilio account.
:param receiver: Number of Receivers
:param message: Message to be Sent
:return: Sends the Message
"""
message = client.messages.create(
from_="whatsapp:+14155238886", body=message, to=f"what... | 5,338,722 |
def stem_list(tokens: list) -> list:
"""Stems all tokens in a given list
Arguments:
- tokens: List of tokens
Returns:
List of stemmed tokens
"""
stem = PorterStemmer().stem
return [stem(t) for t in tokens] | 5,338,723 |
def unique(s):
"""Return a list of the elements in s, but without duplicates.
For example, unique([1,2,3,1,2,3]) is some permutation of [1,2,3],
unique("abcabc") some permutation of ["a", "b", "c"], and
unique(([1, 2], [2, 3], [1, 2])) some permutation of
[[2, 3], [1, 2]].
For best speed... | 5,338,724 |
def execute(command: str, cwd: str = None, env: dict = None) -> str:
"""Executes a command and returns the stdout from it"""
result = subprocess.run(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=cwd,
env=env,
shell=True,
check=False,
)
... | 5,338,725 |
def get_ground_truth_assignments_for_zacharys_karate_club() -> jnp.ndarray:
"""Returns ground truth assignments for Zachary's karate club."""
return jnp.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1,
0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) | 5,338,726 |
def actions_loop(once, scope, rses, sleep_time, dark_min_age, dark_threshold_percent,
miss_threshold_percent, force_proceed, scanner_files_path):
"""
Main loop to apply the CC actions
"""
hostname = socket.gethostname()
pid = os.getpid()
current_thread = threading.current_thre... | 5,338,727 |
def read_frames_from_dir(_dir, _type='png'):
""" Read frames from the dir, and return list """
paths = os.listdir(_dir)
valid_paths = []
for path in paths:
if _type in path: valid_paths.append(path)
valid_paths = ns.natsorted(valid_paths)
frames = []
for path in valid_paths:
frames.append( np.array(Image.ope... | 5,338,728 |
def _append_binary_content(buffer, b):
"""Serializes binary value (without bounds) to the buffer."""
# the content should be padded to full 4-byte word
buffer.write(b.value)
length = len(b.value)
length_rounded = _round_to_4(length)
buffer.write((length_rounded - length) * "\x00") | 5,338,729 |
def sort_places_versus_distance_from_coordinates(
list_places: List[Place], gps_coord: Tuple[float, float]
) -> List[Place]:
"""Oder list of places according to the distance to a reference coordinates.
Note: this helper is compensating the bad results of the API. Results in the API
are generally sorted... | 5,338,730 |
def solve_part2_coordinate_subdivision(boxes: List[Tuple[str, Box]]) -> int:
""" An alternative method to solve part 2 which uses coordinate subdivisions to make a new grid.
On the puzzle input, this is roughly a 800x800x800 grid, which actually takes some time to compute through (~3 min)
It runs all the ex... | 5,338,731 |
def decodeSignal(y, t, fclk, nbits) :
"""
This file reads in digitized voltages outputted from the
QCM Antenna Master Controller Board and outputs time,logic code number
pairs.
The encoding scheme is as follows:
HEADER: 3 clock cycles HIGH, followed by 3 clock cycles LOW
SIGNAL: 1 clock cycle LOW, followed by 1... | 5,338,732 |
def sqrt_price_to_tick(sqrt_price):
"""
TODO: finish documentation
See formula 6.8 in the white paper.
We use the change of base formula to compute the log as numpy doesn't have
a log function with an arbitrary base.
:param sqrt_price:
:return:
"""
base = np.sqrt(1.0001)
return... | 5,338,733 |
def recurring_fraction_repeat_length(nominator, denominator):
"""Takes a fraction like 1/6, and returns 1 as 1/6 = 0.16666666.
Takes 1/7 and returns 6 as 1/7 = 0.148257148257."""
a = highest_common_factor([nominator, denominator])
nominator = int(nominator/a)
denominator = int(denominator/a)
... | 5,338,734 |
def getStateName(responseText: str) -> str:
"""Parse state name in title field.
Args:
responseText: response.text object from requests.
Returns: State string name.
"""
soup = Soup(responseText, "html.parser")
logging.debug("Ingesting soup: %s", soup.prettify())
if soup.title:
... | 5,338,735 |
def find_dead_blocks(func, cfg):
"""Find all immediate dead blocks"""
return [block for block in cfg if not cfg.predecessors(block)
if block != func.startblock] | 5,338,736 |
def load_tsv_to_pickle(filename):
""" Open tsv to dict """
with open(filename, "r", encoding="utf-8") as tsv:
equivalencies = {}
for row in tsv:
if not row:
break
try:
page_title_norm, rd_title_norm = row.strip().lower().replace('_', ' ').s... | 5,338,737 |
def _mcse_sd(ary):
"""Compute the Markov Chain sd error."""
_numba_flag = Numba.numba_flag
ary = np.asarray(ary)
if _not_valid(ary, shape_kwargs=dict(min_draws=4, min_chains=1)):
return np.nan
ess = _ess_sd(ary)
if _numba_flag:
sd = np.float(_sqrt(svar(np.ravel(ary), ddof=1), np.... | 5,338,738 |
def dfs_predecessors(G, source=None):
"""Return dictionary of predecessors in depth-first-search from source."""
return dict((t,s) for s,t in dfs_edges(G,source=source)) | 5,338,739 |
def convert_batchnorm(net, node, model, builder):
"""Convert a transpose layer from mxnet to coreml.
Parameters
----------
network: net
A mxnet network object.
layer: node
Node to convert.
model: model
An model for MXNet
builder: NeuralNetworkBuilder
A neu... | 5,338,740 |
def main():
"""
Main function to test the data generator module.:
"""
data_set, labels = gen_data_set(n_normals=1000, n_moons=100, n_scurves=100, n_circles=100)
plot_figure(data_set, labels, 'name.eps')
save_data(data_set, labels, './Synthetic_data.txt') | 5,338,741 |
def merge_all_sections(prnt_sctns, child_sctns, merge_within_sections=False):
""" Merge the doc-sections of the parent's and child's attribute into a single docstring.
Parameters
----------
prnt_sctns: OrderedDict[str, Union[None,str]]
child_sctns: OrderedDict[str, Union[None,str]]
Returns
... | 5,338,742 |
def input_fn(is_training, data_dir, batch_size, num_epochs=1):
"""Input_fn using the tf.data input pipeline for CIFAR-10 dataset.
Args:
is_training: A boolean denoting whether the input is for training.
data_dir: The directory containing the input data.
batch_size: The number of samples per batch.
... | 5,338,743 |
def combine_catchments_covered_by_the_same_lake_arcgis(
Routing_Product_Folder
):
"""Define final lake river routing structure
Generate the final lake river routing structure by merging subbasin
polygons that are covered by the same lake.
The input are the catchment polygons and river segements
... | 5,338,744 |
def search(term, aur):
"""Search the official repositories
"""
if aur:
secho()
_bar('Arch Core')
try:
remote = get_output('pacman', '-Ss', term)
except CalledProcessError:
remote = ''
def echo_result(name, repo, version, description, installed=False):
sec... | 5,338,745 |
def _eye(sys: brax.System, qp: brax.QP) -> List[float]:
"""Determines the camera location for a Brax system."""
d = {}
for joint in sys.config.joints:
if joint.parent not in d:
d[joint.parent] = []
po, co = joint.parent_offset, joint.child_offset
off = onp.array([po.x, po.y, po.z]) - onp.array([... | 5,338,746 |
def num_list(to_parse):
"""
Creates list from its string representation
Arguments:
to_parse {string} -- String representation of list, can include 'None' or internal lists, represented by separation with '#'
Returns:
list[int] -- List represented in to_parse
"""
if len(... | 5,338,747 |
def secret(secret):
"""Secret validation handler."""
if not secret:
raise ValidationError("Missing a secret to encrypt.")
if len(secret) > 150:
raise ValidationError(
"The secret needs to have less than 150 characters.") | 5,338,748 |
def main():
"""Main."""
torch.manual_seed(args.seed)
# Experiment Information
print_experiment_info(args)
dataloaders, G, optimizer_g, writer = train_setup(args)
optimizer_g, lr = lr_scheduler_withoutDecay(optimizer_g, lr=args.lr)
# scheduler_g = optim.lr_scheduler.StepLR(optimizer_g, step... | 5,338,749 |
def total_scatter_matrix(data):
"""
Total sum of square (TSS) : sum of squared distances of points around the baycentre
References : Clustering Indices, Bernard Desgraupes (April 2013)
"""
X = np.array(data.T.copy(), dtype=np.float64)
for feature_i in range(data.shape[1]):
X[fea... | 5,338,750 |
def save_camera_zip(camera_id, year, month, file_path=None):
"""
Download a camera ZIP archive.
:param camera_id: int, camera ID
:param year: int, year
:param month: int, month
:param file_path: str, optional, path to save file
:return: bool, status of download
"""
# Setup file name... | 5,338,751 |
def test_cyme_to_json():
"""Test the JSON writer with CYME models as input."""
from ditto.readers.cyme.read import Reader
from ditto.store import Store
from ditto.writers.json.write import Writer
cyme_models = [
f
for f in os.listdir(os.path.join(current_directory, "data/small_cases... | 5,338,752 |
def read_user(str):
""" str -> dict """
pieces = str.split()
return {
'first': pieces[0],
'last': pieces[1],
'username': pieces[5],
'custID': pieces[3],
'password': pieces[7],
'rank': 0,
'total': 0
} | 5,338,753 |
def log_page_timing(sender, **kwargs):
"""
Collects and stores page timing information, which the client may send at the end of a page view.
The extra information will be added in to the original VIEWED event representing the page view.
"""
event_id = kwargs['event_id']
times = kwargs['times']
... | 5,338,754 |
def lweekdate(weekday, year, month, nextDay=0):
"""
Usage
lastDate = lweekdate(weekday, year, month, nextDay)
Notes
Date of last occurrence of weekday in month
returns the serial date number for the last occurrence of Weekday in the given
year and month and in a week that also contains NextDay.
Weekda... | 5,338,755 |
def multi_polygon_gdf(basic_polygon):
"""
A GeoDataFrame containing the basic polygon geometry.
Returns
-------
GeoDataFrame containing the basic_polygon polygon.
"""
poly_a = Polygon([(3, 5), (2, 3.25), (5.25, 6), (2.25, 2), (2, 2)])
gdf = gpd.GeoDataFrame(
[1, 2],
geome... | 5,338,756 |
def isort():
"""Run isort on the source and test files"""
subprocess.run(
[
"poetry",
"run",
"isort",
"tmt_carddeck",
"tests",
],
check=True,
) | 5,338,757 |
def get_or_create_pull(github_repo, title, body, head, base, *, none_if_no_commit=False):
"""Try to create the PR. If the PR exists, try to find it instead. Raises otherwise.
You should always use the complete head syntax "org:branch", since the syntax is required
in case of listing.
if "none_if_no_co... | 5,338,758 |
def get_board_properties(board, board_path):
"""parses the board file returns the properties of the board specified"""
with open(helper.linux_path(board_path)) as f:
board_data = json.load(f, object_pairs_hook=OrderedDict)
return board_data[board] | 5,338,759 |
def pytest_sessionstart(session):
""" This should run first as it creates the temporary filder when run on the xdist master."""
if _is_xdist_master(session):
# perform cleanup
session.config.hook.pytest_harvest_xdist_init()
# mark the fixture store as to be reloaded
FIXTURE_STOR... | 5,338,760 |
def extract_tweets_and_labels(filename ):
""" Extract tweets and labels from the downloaded data"""
print ('Step 3: Reading the data as a dataframe')
df=pd.read_csv(filename, header=None, encoding='iso-8859-1')
df.columns=['Label','TweetId','Date','Query','User','Text']
print ('Read {... | 5,338,761 |
def test_noun_chunks_is_parsed_it(it_tokenizer):
"""Test that noun_chunks raises Value Error for 'it' language if Doc is not parsed."""
doc = it_tokenizer("Sei andato a Oxford")
with pytest.raises(ValueError):
list(doc.noun_chunks) | 5,338,762 |
def test_iconutil_fails(infopl, alfred4, tempdir):
"""`iconutil` throws RuntimeError"""
with FakePrograms("iconutil"):
icns_path = os.path.join(tempdir, "icon.icns")
with pytest.raises(RuntimeError):
notify.png_to_icns(PNG_PATH, icns_path) | 5,338,763 |
def test_fbeta_score_inconsistancy():
"""Test of `fbeta_score` with input inconsistency."""
y_pred = np.array([0, 1])
y_true = np.array([1])
with pytest.raises(InvalidInput):
fbeta_score(y_pred, y_true, 2) | 5,338,764 |
def parse_command(command):
"""
Parse the given one-line QF command analogously to parse_file().
"""
m = re.match(r'^\#?([bdpq]|build|dig|place|query)\s+(.+)', command)
if m is None:
raise ParametersError("Invalid command format '%s'." % command)
# set up details dict
det... | 5,338,765 |
def clear_screen():
"""
Clears the screen
"""
# Clear the previously drawn text:
if sys.platform == 'win32':
os.system('cls') # Clears Windows terminal.
else:
os.system('clear') | 5,338,766 |
def _run(cmd: Union[str, List[str]]) -> List[str]:
"""Run a 'cmd', returning stdout as a list of strings."""
cmd_list = shlex.split(cmd) if type(cmd) == str else cmd
result = subprocess.run(cmd_list, capture_output=True)
return result.stdout.decode('utf-8').split("\n") | 5,338,767 |
def test_check_description_git_url():
""" Does DESCRIPTION file contain an upstream Git repo URL? """
from fontbakery.profiles.googlefonts import (
com_google_fonts_check_description_git_url as check,
description,
descfile)
# TODO: test INFO "url-found"
bad_desc = description(descfile(TEST_FILE("c... | 5,338,768 |
def get_repository_username(repo_url):
"""
Returns the repository username
:return: (str) Repository owner username
"""
repo_path = _get_repo_path(repo_url)
return repo_path[0] | 5,338,769 |
def get_logger():
"""Grab the global logger instance.
If a global IPython Application is instantiated, grab its logger.
Otherwise, grab the root logger.
"""
global _logger
if _logger is None:
from IPython.config import Application
if Application.initialized():
... | 5,338,770 |
def process_y(y_train: pd.Series, max_mult=20, large_sampsize=50000):
"""
Drop missing values, downsample the negative class
if sample size is large and there is significant class imbalance
"""
# Remove missing labels
ytr = y_train.dropna()
# The code below assumes the negative class is ove... | 5,338,771 |
def _distance(y1, y2):
"""1D distance calculator"""
inner = (y2 - y1) ** 2
d = np.sqrt(inner)
return d | 5,338,772 |
def main():
""" This section is for arguments parsing """
module = AnsibleModule(
argument_spec=dict(
pn_cliusername=dict(required=False, type='str'),
pn_clipassword=dict(required=False, type='str', no_log=True),
pn_commands_file=dict(required=True, type='str'),
... | 5,338,773 |
def create_container(context, values):
"""Create a new container.
:param context: The security context
:param values: A dict containing several items used to identify
and track the container, and several dicts which are
passed
into the Drivers when m... | 5,338,774 |
def build_model_from_pb(name: str, pb_model: Callable):
"""
Build model from protobuf message.
:param name: Name of the model.
:param pb_model: protobuf message.
:return: Model.
"""
from google.protobuf.json_format import MessageToDict
dp = MessageToDict(pb_model(), including_default_v... | 5,338,775 |
def create_proof_of_time_pietrzak(discriminant, x, iterations, int_size_bits):
"""
Returns a serialized proof blob.
"""
delta = 8
powers_to_calculate = proof_pietrzak.cache_indeces_for_count(iterations)
powers = iterate_squarings(x, powers_to_calculate)
y = powers[iterations]
proof = pr... | 5,338,776 |
def resample_dataset ( fname, x_factor, y_factor, method="mean", \
data_min=-1000, data_max=10000 ):
"""This function resamples a GDAL dataset (single band) by a factor of
(``x_factor``, ``y_factor``) in x and y. By default, the only method used
is to calculate the mean. The ``data_min`` and ``d... | 5,338,777 |
def int2bytes(number, fill_size=None, chunk_size=None, overflow=False):
"""
Convert an unsigned integer to bytes (base-256 representation)::
Does not preserve leading zeros if you don't specify a chunk size or
fill size.
.. NOTE:
You must not specify both fill_size and chunk_size. Only one... | 5,338,778 |
def compFirstFivePowOf2(iset={0, 1, 2, 3, 4}):
"""
task 0.5.6
a comprehension over the given set whose value is the set consisting
of the first five powers of two, starting with 2**0
"""
return {2**x for x in iset} | 5,338,779 |
def sdc_pandas_dataframe_getitem(self, idx):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************
Pandas API: pandas.DataFrame.getitem
Get data from a DataFrame by indexer.
Limitations
-----------
Supported ``key`` can be one of the following:
... | 5,338,780 |
def display_finds_meta(r):
"""A list of urls in r is displayed as HTML"""
rows = ["<tr><td><img src='{row}'</td><td><a href = {meta} target='_'>{meta}</a></td></tr>".format(row=row, meta=row) for row in r]
return HTML("""<html><head></head>
<body>
<table>
{rows}
</table>
</body>
... | 5,338,781 |
def __pairwise__(iterable):
""" Converts a list of elements in a list of pairs like:
list -> (list[0], list[1]), (list[2], list[3]), (list[4], list[5]), ...
:param iterable: Input list.
:return: List of pairs of the given list elements.
"""
a = iter(iterable)
return zip(a, a) | 5,338,782 |
def _generateTriangleSequence():
"""
Generates list of elements following sequence of triangle numbers.
Returns:
sequenceElements - List of elements following the sequence.
"""
sequenceElements = []
totalCharactersInNewSequence = 0
total = 1
currentAddend = 2
while totalCharac... | 5,338,783 |
def normalize_neurons_range(neurons, standard_diagonal_line: int or float):
"""
:param neurons: should be refined.
:param standard_diagonal_line: pre-defined standard length of diagonal line of xoy plate
:return: neurons, width_scale, [width_span, height_span, z_span]
width_scale: The leng... | 5,338,784 |
def distort_image(image):
"""Perform random distortions to the given 4D image and return result"""
# Switch to 3D as that's what these operations require
slices = tf.unpack(image)
output = []
# Perform pixel-wise distortions
for image in slices:
image = tf.image.random_flip_left_right... | 5,338,785 |
def tablebyname(filehandle, header):
"""fast extraction of the table using the header to identify the table
This function reads only one table from the HTML file. This is in contrast to `results.readhtml.titletable` that will read all the tables into memory and allows you to interactively look thru them. The f... | 5,338,786 |
def BuildDataset():
"""Create the dataset"""
# Get the dataset keeping the first two features
iris = load_iris()
x = iris["data"][:,:2]
y = iris["target"]
# Standardize and keep only classes 0 and 1
x = (x - x.mean(axis=0)) / x.std(axis=0)
i0 = np.where(y == 0)[0]
i1 = np.where(y... | 5,338,787 |
def label_train_spaces(ctx: cairo.Context, train: trains.Train, radius_factors=1, broken_spaces:Sequence=None):
"""Draw material name and thickness of the spaces.
Args:
radius_factors (scalar or sequence): Factor by which the average interface radii is multiplied to place the text. If
a sca... | 5,338,788 |
def main(config_dir: Path, default_config: str, results_dir: Path):
"""Run all config files instead of the default one.
Ideally, these runs are parellellized instead of run in sequence."""
for config_file in config_dir.iterdir():
if config_file.name != default_config:
output_path = resul... | 5,338,789 |
def read_tile(file, config):
"""Read a codex-specific 5D image tile"""
# When saving tiles in ImageJ compatible format, any unit length
# dimensions are lost so when reading them back out, it is simplest
# to conform to 5D convention by reshaping if necessary
slices = [None if dim == 1 else slice(No... | 5,338,790 |
def rmsd(V, W):
""" Calculate Root-mean-square deviation from two sets of vectors V and W. """
D = len(V[0])
N = len(V)
rmsd = 0.0
for v, w in zip(V, W):
rmsd += sum([(v[i] - w[i]) ** 2.0 for i in range(D)])
return np.sqrt(rmsd / N) | 5,338,791 |
def partition(f, xs):
"""
partition :: (a -> Bool) -> [a] -> ([a], [a])
The partition function takes a predicate a list and returns the pair of
lists of elements which do and do not satisfy the predicate.
"""
yes, no = [], []
for item in xs:
if f(item):
yes.append(item)
... | 5,338,792 |
def workflow(gid, lat, lon):
"""Do Some Work Please"""
res = []
for year in range(2010, 2016):
print("Processing GID: %s year: %s" % (gid, year))
uri = ("http://mesonet.agron.iastate.edu/iemre/multiday/"
"%s-01-01/%s-12-31/%s/%s/json"
) % (year, year, lat, lon)
... | 5,338,793 |
async def restore(rc: RestClient, fc_entries: List[FCMetadata], dryrun: bool) -> None:
"""Send the fc_entries one-by-one to the FC.
PUT if FC entry already exists. Otherwise, POST with uuid.
"""
for i, fcm in enumerate(fc_entries):
print(f"{i}/{len(fc_entries)}")
logging.debug(fcm)
... | 5,338,794 |
def bvp2_check():
"""
Using scikits.bvp_solver to solve the bvp
y'' + y' + sin y = 0, y(0) = y(2*pi) = 0
y0 = y, y1 = y'
y0' = y1, y1' = y'' = -sin(y0) - y1
"""
from math import exp, pi, sin
lbc, rbc = .1, .1
def function1(x , y):
return np.array([y[1] , -sin(y[0]) -y[1] ])
def boundary_conditions(y... | 5,338,795 |
def test_location_invalid():
"""Test constructing invalid URIs."""
with pytest.raises(pa.ArrowInvalid, match=".*Cannot parse URI:.*"):
flight.connect("%")
with pytest.raises(pa.ArrowInvalid, match=".*Cannot parse URI:.*"):
ConstantFlightServer("%") | 5,338,796 |
def get_zarr_store(file_path):
"""Get the storage type
"""
import zarr
ZARR_STORE_MAP = {"lmdb": zarr.LMDBStore,
"zip": zarr.ZipStore,
"dbm": zarr.DBMStore,
"default": zarr.DirectoryStore}
suffix, subsuffix = get_subsuffix(file_path)... | 5,338,797 |
def test_integration_ref():
"""
GIVEN schema that references another schema and schemas
WHEN column_factory is called with the schema and schemas
THEN SQLAlchemy boolean column is returned in a dictionary with logical name and
the spec.
"""
spec = {"$ref": "#/components/schemas/RefSchema... | 5,338,798 |
def image_5d_iterator(file_name, rescale=False):
"""Iterate over all series with (name, data)
Args:
file_name (str): path to file
rescale (bool, optional): rescale to min/max. Defaults to False.
Yields:
(str, numpy.array): Tuple of series name and pixel content as 5D array
"""
... | 5,338,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.