content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def plot(*args, **kwargs):
"""Plot the csv file.
Usage: ph plot
ph plot --index=col
ph plot --kind=bar
ph plot --kind=scatter --x=col1 --y=col2
ph plot --style=k--
"""
try:
import matplotlib.pyplot as plt
except ImportError:
exit("plo... | 5,328,600 |
def strip_names(ttx_path):
"""Clear several nameIDs to prevent the font from being installable on desktop OSs.
ttx_path: Path of the .ttx font to be modified.
"""
# nameIDs which will be erased
nameIDs = [1, 2, 4, 16, 17, 18]
tree = parse(ttx_path)
root = tree.getroot()
for child in ro... | 5,328,601 |
def pull_sls_hardware(sls_file=None):
"""Query API-GW and retrieve token.
Args:
sls_file: generated sls json file.
Returns:
API token.
"""
if sls_file:
sls_hardware = [
hardware[x] for hardware in [sls_file.get("Hardware", {})] for x in hardware
]
... | 5,328,602 |
def create_virtual_service(clientToken=None, meshName=None, meshOwner=None, spec=None, tags=None, virtualServiceName=None):
"""
Creates a virtual service within a service mesh.
A virtual service is an abstraction of a real service that is provided by a virtual node directly or indirectly by means of a virtu... | 5,328,603 |
def copy(stream, credentials, direction, hdfsFile=None, hdfsFileAttrName=None, localFile=None, name=None):
"""Copy a Hadoop Distributed File to local and copy a local file to te HDFS.
Repeatedly scans a HDFS directory and writes the names of new or modified files that are found in the directory to the output s... | 5,328,604 |
def normalize(value: str) -> str:
"""Normalize a string by removing '-' and capitalizing the following character"""
char_list: List[str] = list(value)
length: int = len(char_list)
for i in range(1, length):
if char_list[i - 1] in ['-']:
char_list[i] = char_list[i].upper()
retur... | 5,328,605 |
def encryptpwd(ctx, encrypt_password, salt):
"""设置加密密码"""
assert len(encrypt_password) > 0, "No encrypt-password"
am = ctx.obj.account_manager
am.set_encrypt_password(encrypt_password, salt)
am.save() | 5,328,606 |
def save_data(userId, columns, tableName, searchTerm="", objType="", sortBy=None,
tableId=None, isDefaultOnDashboard=False, maxRows=0,
dashboard=None, clone=False, row=0, grid_col=0, sizex=0,
sizey=0):
"""
Saves the customized table in the dashboard. Called by save_sear... | 5,328,607 |
def heatmap(plot,
client_color=False,
low=(255, 200, 200), high=(255, 0, 0),
spread=0, transform="cbrt", **kwargs):
"""
Produce a heatmap from a set of shapes.
A heatmap is a scale of how often a single thing occurs.
This is a convenience function that encodes a commo... | 5,328,608 |
def add_comment_to_task(task_id, comment, status=None):
"""
Adds comment to given task
:param task_id:
:param comment:
:param status:
:return:
"""
task = get_task(task_id, as_dict=True)
if not task:
return
if not status:
status = gazu.task.get_task_status(task)
... | 5,328,609 |
def score(h,r,t):
"""
:param h: (batch_size, dim)
:param r: (dim, )
:param t: (dim, )
:return:
"""
return np.dot(h, np.transpose(r*t)) | 5,328,610 |
def migrate_file(file_name, file_content):
"""Migrate file."""
return V4Migrator(file_name, file_content).migrate() | 5,328,611 |
def _GetOrganizedAnalysisResultBySuspectedCL(analysis_result):
"""Group tests it they have the same suspected CLs."""
organized_results = defaultdict(list)
if not analysis_result:
return organized_results
for step_failure in analysis_result.get('failures', []):
step_name = step_failure['step_name']
... | 5,328,612 |
def volume_division(in_volume1, in_volume2):
"""Divide a volume by another one
Args:
in_volume1 (nibabel volume): data will be a [m,n,o] array
in_volume2 (nibabel volume): data will be a [m,n,o] array
Returns:
out_volume (nibabel volume): data will be a [m,n,o] array,
d... | 5,328,613 |
def sparse_eye(num_rows,
num_columns=None,
dtype=dtypes.float32,
name=None):
"""Creates a two-dimensional sparse tensor with ones along the diagonal.
Args:
num_rows: Non-negative integer or `int32` scalar `tensor` giving the number
of rows in the resulting mat... | 5,328,614 |
def count_num_sents_cluster(sents_vectors, sections_sents, n_clusters):
"""
Cluster sentences and count the number of times that sentences from each
section appear in each cluster.
Ex: 4 sents from introduction and 3 sentences from conclusion in cluster x.
"""
labels, centroids = cluster_sents(s... | 5,328,615 |
def add_kubelet_token(hostname):
"""
Add a token for a node in the known tokens
:param hostname: the name of the node
:returns: the token added
"""
file = "{}/credentials/known_tokens.csv".format(snapdata_path)
old_token = get_token("system:node:{}".format(hostname))
if old_token:
... | 5,328,616 |
def check_password_pwned(password, fast=False):
"""Check if a password is in the pwned-passwords list.
:param password: The plaintext password
:param fast: Whether the check should finish quickly, even if that may
indicate not being able to check the password. This should
... | 5,328,617 |
def is_plugin_loaded(plugin_name):
"""
Return whether given plugin is loaded or not
:param plugin_name: str
:return: bool
"""
return maya.cmds.pluginInfo(plugin_name, query=True, loaded=True) | 5,328,618 |
def drydown_service(lat: float = Query(...), lon: float = Query(...)):
"""Babysteps."""
return handler(lon, lat) | 5,328,619 |
def service_vuln_iptable(hostfilter=None):
"""Returns a dict of services. Contains a list of IPs with (vuln, sev)
'0/info': { 'host_id1': [ (ipv4, ipv6, hostname), ( (vuln1, 5), (vuln2, 10) ... ) ] },
{ 'host_id2': [ (ipv4, ipv6, hostname), ( (vuln1, 5) ) ] }
"""
service_dict = {}
# go ... | 5,328,620 |
def validate_tier_name(name):
"""
Property: Tier.Name
"""
valid_names = [WebServer, Worker]
if name not in valid_names:
raise ValueError("Tier name needs to be one of %r" % valid_names)
return name | 5,328,621 |
def version_get(): # noqa: E501
"""Version
Version # noqa: E501
:rtype: InlineResponse2006
"""
response = InlineResponse2006()
version = Version()
v = CoreApiVersion.query.filter_by(active=True).first()
if v:
version.version = v.version
version.reference = v.reference... | 5,328,622 |
def language_register(df):
"""
Add 'training language', 'test language', 'training register' and 'test register'
columns to a dataframe.
This assumes that:
- the dataframe contains a 'training set' and 'test set' column
- the sets mentioned in these columns are properly documented in
th... | 5,328,623 |
def balances(cfg, wdir, plotpath, filena, name, model):
"""Plot everything related to energy and water mass budgets.
This method provides climatological annal mean maps of TOA, atmospheric
and surface energy budgets, time series of annual mean anomalies in the
two hemispheres and meridional sections of... | 5,328,624 |
def example_seg_2() -> Dict[str, Any]:
"""
Simple evaluation example for dice score for multiclass semantic segmentation
Inputs are 4 pairs of segmentation files: one including predictions and one targets
"""
# define iterator
def data_iter():
dir_path = pathlib.Path(__file__).parent.res... | 5,328,625 |
def clone_pod(module, array):
"""Create Pod Clone"""
changed = True
if not module.check_mode:
changed = False
if get_target(module, array) is None:
if not get_destroyed_target(module, array):
try:
array.clone_pod(module.params['name'],
... | 5,328,626 |
def init(request):
"""
Wraps an incoming WSGI request in a Context object and initializes
several important attributes.
"""
set_umask() # do it once per request because maybe some server
# software sets own umask
if isinstance(request, Context):
context, request = reques... | 5,328,627 |
def fetch_arm_sketch(X, ks, tensor_proj=True, **kwargs_rg):
"""
:param X: the tensor of dimension N
:param ks: array of size N
:param tensor_proj: True: use tensor random projection,
otherwise, use normal one
:param kwargs_rg:
:return: list of two, first element is list of arm sketches
a... | 5,328,628 |
def fitness(member):
"""Computes the fitness of a species member.
http://bit.ly/ui-lab5-dobrota-graf"""
if member < 0 or member >= 1024:
return -1
elif member >= 0 and member < 30:
return 60.0
elif member >= 30 and member < 90:
return member + 30.0
elif member >= 90 and member < 120:... | 5,328,629 |
def test_multiple_messages() -> None:
"""
Tests the order of multiple messages.
"""
messages = [
CommitMessage(Position(pos), Payload("M %d" % pos)) for pos in range(10)
]
def checker(source: FakeSourceBackend, producer: FakeProducerBackend):
source.mocked_fetch.assert_called()... | 5,328,630 |
def style_loss(content_feats, style_grams, style_weights):
"""
Computes the style loss at a set of layers.
Inputs:
- feats: list of the features at every layer of the current image.
- style_targets: List of the same length as feats, where style_targets[i] is
a Tensor giving the Gram matri... | 5,328,631 |
def get_annotations(joints_2d, joints_3d, scale_factor=1.2):
"""Get annotations, including centers, scales, joints_2d and joints_3d.
Args:
joints_2d: 2D joint coordinates in shape [N, K, 2], where N is the
frame number, K is the joint number.
joints_3d: 3D joint coordinates in shape... | 5,328,632 |
def Intensity(flag, Fin):
"""
I=Intensity(flag,Fin)
:ref:`Calculates the intensity of the field. <Intensity>`
:math:`I(x,y)=F_{in}(x,y).F_{in}(x,y)^*`
Args::
flag: 0= no normalization, 1=normalized to 1, 2=normalized to 255 (for bitmaps)
Fin: input field
... | 5,328,633 |
def index(request):
"""
Display the index for user related actions.
"""
export_form = ExportForm(request.POST or None)
return render(request, "users/index.html", {"export_form": export_form}) | 5,328,634 |
def test_topic_regex() -> None:
"""Test the regex property."""
for parts, topic in BASIC_TOPICS:
t = Topic(parts)
assert t.regex == compile(f"^{topic}$")
for parts, topic, example in WILDCARD_TOPICS:
t = Topic(parts)
assert t.regex.match(example)
assert not t.regex.m... | 5,328,635 |
def build():
"""Compile the site into the build directory."""
clean()
_mkdir_if_not_present(BUILD_DIR)
# compile html pages
for src_file in _iter_paths(JS_DIR, '*'):
dest_path = os.path.join(BUILD_DIR, src_file.name)
src_path = os.path.join(JS_DIR, src_file.name)
shutil.copy... | 5,328,636 |
def test_load_vep97_parsed_variant(one_vep97_annotated_variant, real_populated_database, case_obj):
"""test first parsing and then loading a vep v97 annotated variant"""
# GIVEN a variant annotated using the following CSQ entry fields
csq_header = "Allele|Consequence|IMPACT|SYMBOL|Gene|Feature_type|Feature... | 5,328,637 |
def test_network_predictions():
"""Tests imbDRL.metrics.network_predictions."""
X = [7, 7, 7, 8, 8, 8]
with pytest.raises(ValueError) as exc:
metrics.network_predictions([], X)
assert "`X` must be of type" in str(exc.value)
X = np.array([[1, 2], [2, 1], [3, 4], [4, 3]])
y_pred = metric... | 5,328,638 |
def _get_javascript_and_find_feature_flag(client: HttpSession, script_uri: str, headers: Dict[str, Any] = None) -> Any:
"""
Read through minified javascript for feature flags
"""
flag_str = None
# Since this is a large request, read incrementally
with client.get(
script_uri,
... | 5,328,639 |
def write(msg, level='INFO', html=False, attachment=None, launch_log=False):
"""Write the message to the log file using the given level.
Valid log levels are ``TRACE``, ``DEBUG``, ``INFO`` (default since RF
2.9.1), ``WARN``, and ``ERROR`` (new in RF 2.9). Additionally it is
possible to use ``HTML`` pse... | 5,328,640 |
def next_power_of_two(v: int):
""" returns x | x == 2**i and x >= v """
v -= 1
v |= v >> 1
v |= v >> 2
v |= v >> 4
v |= v >> 8
v |= v >> 16
v += 1
return v | 5,328,641 |
def triangle(times: np.ndarray, amp: complex, freq: float, phase: float = 0) -> np.ndarray:
"""Continuous triangle wave.
Args:
times: Times to output wave for.
amp: Pulse amplitude. Wave range is [-amp, amp].
freq: Pulse frequency. units of 1/dt.
phase: Pulse phase.
"""
... | 5,328,642 |
def add_token(token_sequence: str, tokens: str) -> str:
"""Adds the tokens from 'tokens' that are not already contained in
`token_sequence` to the end of `token_sequence`::
>>> add_token('', 'italic')
'italic'
>>> add_token('bold italic', 'large')
'bold italic large'
>>>... | 5,328,643 |
def aggregate_values(mapping: dict, agg_fcn: Literal["mean", "prod"]):
"""Aggregates the values of the input (nested) mapping according to the
specified aggregation method. This function modifies the input in place.
Parameters
---------
mapping
The mapping to be aggregated.
agg_fcn
... | 5,328,644 |
def ket2dm(psi):
"""
convert a ket into a density matrix
Parameters
----------
psi : TYPE
DESCRIPTION.
Returns
-------
TYPE
DESCRIPTION.
"""
return np.einsum("i, j -> ij", psi, psi.conj()) | 5,328,645 |
def _make_feature_stats_proto(
stats_values,
feature_name):
"""Creates the FeatureNameStatistics proto for one feature.
Args:
stats_values: A Dict[str,float] where the key of the dict is the name of the
custom statistic and the value is the numeric value of the custom
statistic of that feat... | 5,328,646 |
def build_lr_scheduler(
cfg, optimizer: torch.optim.Optimizer
) -> torch.optim.lr_scheduler._LRScheduler:
"""
Build a LR scheduler from config.
"""
name = cfg.NAME
if name == "WarmupMultiStepLR":
return WarmupMultiStepLR(
optimizer,
cfg.STEPS,
cfg.... | 5,328,647 |
def mock_gateway_features(
tasks: MagicMock, transport_class: MagicMock, nodes: dict[int, Sensor]
) -> None:
"""Mock the gateway features."""
async def mock_start_persistence() -> None:
"""Load nodes from via persistence."""
gateway = transport_class.call_args[0][0]
gateway.sensors.... | 5,328,648 |
def cconv(x, y, P):
""" Periodic convolution with period P of two signals x and y
"""
x = _wrap(x, P)
h = _wrap(y, P)
return np.fromiter([np.dot(np.roll(x[::-1], k+1), h) for k in np.arange(P)], float) | 5,328,649 |
def add_arguments():
"""
Function to parse the command line arguments
Options:
[-f]: Name of text file with corpus
"""
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file', type=str,
help="The file with the text.")
return parser.pa... | 5,328,650 |
def assert_(val: bool, msg: Literal["Spin 7 failed"]):
"""
usage.scipy: 2
"""
... | 5,328,651 |
async def publish_summary_as_entry(
db_session: Session,
bot_installation_id: uuid.UUID,
issue_pr,
content: Any,
context_id: str,
summary: EntrySummaryReport,
) -> Any:
"""
Publish summary from locust or checks to Bugout entry.
If entry were deleted from journal it creates new one.
... | 5,328,652 |
def keypoint_loss_targets(uvd, keys_uvd, mparams):
"""Computes the supervised keypoint loss between computed and gt keypoints.
Args:
uvd: [batch, order, num_targs, 4, num_kp] Predicted set of keypoint uv's
(pixels).
keys_uvd: [batch, order, num_targs, 4, num_kp] The ground-truth set of uvdw
coo... | 5,328,653 |
def RunTests():
"""Runs all functions in __main__ with names like TestXyz()."""
sys.exit(_RunAll('Test', _RunOneTest)) | 5,328,654 |
def get_initial_epoch(log_path):
"""
从log文件中获取最近训练结束时的epoch,重新运行代码后会接着这个epoch继续训练。
"""
initial_epoch = 0
if tf.gfile.Exists(log_path):
with open(log_path) as log_file:
line_ind = -1
for _, line in enumerate(log_file):
line = line.strip()
... | 5,328,655 |
def categorise_town_flood_risk(stations, dt, degree, risklevel=3, plot=False):
"""A function that takes a list "stations" of station objects, performs polyfit over a period of "dt" days up to a "degree" degree and then returns towns with their respective flood risk.
The flood risk is determined by three toleran... | 5,328,656 |
def create_clients(num_clients, client_data, input_str='input', label_str='label', client_str='client-',
distribute=False):
"""
create K clients
:param config: network_config
:param num_clients: the number of clients
:param client_data: Dictionary of clients data. data[client][inp... | 5,328,657 |
def l2_loss(
h: typing.Callable[[np.ndarray, np.ndarray], np.ndarray],
grad_h: typing.Callable[[np.ndarray, np.ndarray], np.ndarray],
theta: np.ndarray,
x, y):
"""l2_loss: standard l2 loss.
The l2 loss is defined as (h(x) - y)^2. This is usually used for linear
regression in the sum of squa... | 5,328,658 |
def test_multiple_read():
"""
>>> from uliweb.i18n import gettext_lazy as _, i18n_ini_convertor
>>> from io import StringIO
>>> x = Ini(env={'_':_}, convertors=i18n_ini_convertor, lazy=True)
>>> buf = StringIO(\"\"\"
... [default]
... option = 'abc'
... [other]
... option = default.o... | 5,328,659 |
def BestLogLikelihood(aln, alphabet=None, exclude_chars = None,
allowed_chars='ACGT', motif_length=None, return_length=False):
"""returns the best log-likelihood according to Goldman 1993.
Arguments:
- alphabet: a sequence alphabet object.
- motif_length: 1 for nucleotide, 2 for dinucle... | 5,328,660 |
def process_h5_file(h5_file):
"""Do the processing of what fields you'll use here.
For example, to get the artist familiarity, refer to:
https://github.com/tbertinmahieux/MSongsDB/blob/master/PythonSrc/hdf5_getters.py
So we see that it does h5.root.metadata.songs.cols.artist_familiarity[songidx]
... | 5,328,661 |
async def test_options_flow(hass: HomeAssistant) -> None:
"""Test we get the form."""
# Create MockConfigEntry
config_entry: MockConfigEntry = MockConfigEntry(
domain=const.DOMAIN,
data={"country": "GB", "subdiv": "England"},
title="UK Holidays",
)
config_entry.add_to_hass(h... | 5,328,662 |
def run_geometry_engine(index=0):
"""
Run the geometry engine a few times to make sure that it actually runs
without exceptions. Convert n-pentane to 2-methylpentane
"""
import logging
logging.basicConfig(level=logging.INFO)
import copy
from perses.utils.openeye import iupac_to_oemol
... | 5,328,663 |
def test_match_type() -> None:
"""Tests matching string type."""
assert type(match_type(b"hello", bytes)) is bytes
assert type(match_type(b"hello", str)) is str
assert type(match_type(u"hello", bytes)) is bytes
assert type(match_type(b"hello", str)) is str | 5,328,664 |
def add_changes_metrics(df, connection):
"""This function joins the data from the jira_issues table with the data
from the FTS3 table. It gets, for each issue, the number of lines_added,
lines_removed and files_changed.
"""
out_df = df.copy()
metrics = df["key"].apply(get_commits_from_issue, arg... | 5,328,665 |
def binary_str(num):
""" Return a binary string representation from the posive interger 'num'
:type num: int
:return:
Examples:
>>> binary_str(2)
'10'
>>> binary_str(5)
'101'
"""
# Store mod 2 operations results as '0' and '1'
bnum = ''
while num > 0:
bnum = str... | 5,328,666 |
def sample_target_pos(batch_size,TARGET_MAX_X, TARGET_MIN_X, TARGET_MAX_Y, TARGET_MIN_Y):
"""
Sample target_position or robot_position by respecting to their limits.
"""
random_init_x = np.random.random_sample(batch_size) * (TARGET_MAX_X - TARGET_MIN_X) + \
TARGET_MIN_X
random_in... | 5,328,667 |
def clf_perceptron(vector_col:str,
df_train:pd.DataFrame,
model:Perceptron,
) -> list:
"""return classification for multi-layer perception
Arguments:
vector_col (str): name of the columns with vectors to classify
df_train (pd.DataFrame): dataframe with traini... | 5,328,668 |
def compute_phot_error(flux_variance, bg_phot, bg_method, ap_area, epadu=1.0):
"""Computes the flux errors using the DAOPHOT style computation
Parameters
----------
flux_variance : array
flux values
bg_phot : array
background brightness values.
bg_method : string
backg... | 5,328,669 |
def set_timed_message(update: Update, context: CallbackContext):
""" Creates a job that outputs a user-defined message in a certain time. """
try:
time_str = context.args[0]
content_args = context.args[1]
for s in context.args[2:]:
content_args += (" " + s)
if check_v... | 5,328,670 |
def reflect_table(conn, table_name, schema='public'):
"""Reflect basic table attributes."""
column_meta = list(get_column_metadata(conn, table_name, schema=schema))
primary_key_columns = list(get_primary_keys(conn, table_name, schema=schema))
columns = [Column(**column_data) for column_data in column_... | 5,328,671 |
def evaluate(c, config_name, predecessors=False, successors=False):
"""Evaluate model for given configuration.
"""
run_workflow_tasks(
c,
get_task_workflow('model_evaluate', predecessors, successors),
config_name
) | 5,328,672 |
def get_token(token_file):
"""
Reads the first line from token_file to get a token
"""
with open(token_file, "r") as fin:
ret = fin.read().strip()
if not ret:
raise ReleaseException("No valid token found in {}".format(token_file))
return ret | 5,328,673 |
def get_description(soup):
"""Извлечь текстовое описание вакансии"""
non_branded = soup.find('div', {'data-qa':'vacancy-description'})
branded = soup.find('div', {'class':'vacancy-section HH-VacancyBrandedDescription-DANGEROUS-HTML'})
description = non_branded or branded
return description.get_text(... | 5,328,674 |
def read_fits(fn: Path, ifrm: int, twoframe: bool) -> np.ndarray:
"""
ifits not ifrm for fits!
"""
if fits is None:
raise ImportError('Need Astropy for FITS')
# memmap = False required thru at least Astropy 1.3.2 due to BZERO used...
with fits.open(fn, mode='readonly', memmap=False) as f... | 5,328,675 |
def normalize(arrList):
"""
Normalize the arrayList, meaning divide each column by its standard deviation if that
standard deviation is nonzero, and leave the column unmodified if it's standard deviation
is zero.
Args:
arrList (a list of lists of numbers)
Returns:
list, list: A... | 5,328,676 |
def test_ipywidgets(sphinx_run):
"""Test that ipywidget state is extracted and JS is included in the HTML head."""
sphinx_run.build()
# print(sphinx_run.status())
assert sphinx_run.warnings() == ""
assert "js_files" in sphinx_run.env.nb_metadata["ipywidgets"]
assert set(sphinx_run.env.nb_metadat... | 5,328,677 |
def get_reddit_backup_urls(mode):
"""
Parse reddit backups on pushshift.io
:param mode: 'Q' for questions, 'A' for answers
:return: dict of (year, month): backup_url
"""
mode = {'Q': 'submissions', 'A': 'comments'}[mode]
page = requests.get(REDDIT_URL + mode)
soup = BeautifulSoup(page.co... | 5,328,678 |
def collect_elf_segments(elf, file_type, segment_els, section_prefix, namespace, image, machine, pools):
"""
Process all of the segment elements in a program/kernel, etc.
"""
elf_seg_names = elf_segment_names(elf)
shash = segments_hash(segment_els)
# Test that every segment element references a... | 5,328,679 |
def follow_operation(operation_uri: str, unpack_metadata=None):
"""
Params:
operation_uri: URI of the operation to follow.
unpack_metadata: Function to unpack the operation's metadata. Return a line of text to summarize
the current progress of the operation.
... | 5,328,680 |
def getStrVector(tarstr,cdict,clen=None):
"""
将字符串向量化,向量的每一项对应字符集中一种字符的频数,字符集、每种字符在向量中对应的下标由cdict提供
"""
if not clen:
clen=len(cdict.keys())
vec=[0]*clen
for c in tarstr:
vec[cdict[c]]+=1
#vec[cdict[c]]=1
return vec | 5,328,681 |
def process_request(registry: ServiceRegistry, url: str) -> str:
""" Given URL (customer name), make a Request to handle interaction """
# Make the container that this request gets processed in
container = registry.create_container()
# Put the url into the container
container.register_singleton(ur... | 5,328,682 |
def percent_color(percentage: float) -> str:
""" Generate a proper color for a percentage for printing. """
color = 'red'
if percentage > 30:
color = 'yellow'
if percentage > 70:
color = 'green'
return colored(percentage, color) | 5,328,683 |
def _generate_image_and_label_batch(image, image_raw, label, min_queue_examples,
batch_size, shuffle):
"""Construct a queued batch of images and labels.'''
example: min_fraction_of_examples_in_queue = 0.4
min_queue_examples = int(NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN *
... | 5,328,684 |
def parsePDB(pdb, altloc='A', model=None):
"""Return an :class:`.AtomGroup` and/or dictionary containing header data
parsed from a PDB file.
This function extends :func:`.parsePDBStream`.
See :ref:`parsepdb` for a detailed usage example.
:arg pdb: a PDB identifier or a filename
"""
title,... | 5,328,685 |
def elgamal_add(*ciphertexts: ElGamalCiphertext) -> ElGamalCiphertext:
"""
Homomorphically accumulates one or more ElGamal ciphertexts by pairwise multiplication. The exponents
of vote counters will add.
"""
assert len(ciphertexts) != 0, "Must have one or more ciphertexts for elgamal_add"
pads ... | 5,328,686 |
def find_min_cost_thresholds(roc_curves, base_rates, proportions, cost_matrix):
"""Compute thresholds by attribute values that minimize cost.
:param roc_curves: Receiver operating characteristic (ROC)
by attribute.
:type roc_curves: dict
:param base_rates: Base rate by attribute.... | 5,328,687 |
def get_content_type_encoding(curi):
"""
Determine the content encoding based on the `Content-Type` Header.
`curi` is the :class:`CrawlUri`.
"""
content_type = "text/plain"
charset = ""
if curi.rep_header and "Content-Type" in curi.rep_header:
(content_type, charset) = extract_cont... | 5,328,688 |
def truncate_errors(install_stdout, install_errors, language_detection_errors,
compile_errors, max_error_len=10*1024):
"""
Combine lists of errors into a single list under a maximum length.
"""
install_stdout = install_stdout or []
install_errors = install_errors or []
langua... | 5,328,689 |
def is_balanced(expression: str) -> bool:
"""
Checks if a string is balanced.
A string is balanced if the types of brackets line up.
:param expression: is the expression to evaluate.
:raise AttributeError: if the expression is None.
:return: a boolean value determining if the string is balanced... | 5,328,690 |
def get_committee_assignment(state: BeaconState,
epoch: Epoch,
validator_index: ValidatorIndex
) -> Optional[Tuple[Sequence[ValidatorIndex], CommitteeIndex, Slot]]:
"""
Return the committee assignment in the ``epoch`` for ``v... | 5,328,691 |
def is_custfmt0(*args):
"""
is_custfmt0(F) -> bool
Does the first operand use a custom data representation?
@param F (C++: flags_t)
"""
return _ida_bytes.is_custfmt0(*args) | 5,328,692 |
def create_procedure(server, db_name, schema_name, func_name, s_type,
s_version, with_args=False, args=""):
"""This function add the procedure to schema"""
try:
connection = utils.get_db_connection(db_name,
server['username'],
... | 5,328,693 |
def test_update_preferred_places_case_first_option(sample_person):
"""Test changing preferred exits change first to second"""
sample_person.update_preferred_places(PossibleExits.CAFE)
assert sample_person.preferred_places_today == [
PossibleExits.BAR, PossibleExits.CAFE, PossibleExits.CINEMA
... | 5,328,694 |
def test_nb():
"""Test notebook code"""
godag = get_godag("go-basic.obo", optional_attrs={'relationship'})
go_leafs = set(o.item_id for o in godag.values() if not o.children)
virion = 'GO:0019012'
gosubdag_r0 = GoSubDag(go_leafs, godag)
nt_virion = gosubdag_r0.go2nt[virion]
print(nt_virion)
... | 5,328,695 |
def get_nfa_by_graph(
graph: nx.MultiDiGraph, start_nodes: Set[int] = None, final_nodes: Set[int] = None
) -> NondeterministicFiniteAutomaton:
"""
Creates a Nondeterministic Finite Automaton for a specified graph.
If start_nodes and final_nodes are not specified, all nodes are considered start and end.
... | 5,328,696 |
def just_info(*msg):
""" Print a log line, but respecting the graph """
line = ""
if settings.print_group_name:
line += " "*(settings.GROUP_NAME_WIDTH+1)
if settings.print_tracks:
line += tracks.write()
line += " " + " ".join(map(str, msg))
logging.getLogger('mupf').info(line) | 5,328,697 |
def print_key_val(init, value, pre_indent=0, end=','):
"""Print the key and value and insert it into the code list.
:param init: string to initialize value e.g.
"'key': " or "url = "
:param value: value to print in the dictionary
:param pre_indent: optional param to set the level of in... | 5,328,698 |
def not_found_error(e):
"""HTTP 404 view"""
# Ignore unused arguments
# pylint: disable=W0613
return render_template("errors/404.html"), 404 | 5,328,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.