content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def kalkulasi_waktu(
kecepatan_akhir: float, kecepatan_awal: float, percepatan: float
) -> float:
"""
Menghitung waktu
>>> kalkulasi_waktu(10, 22, 2.4)
-5.0
>>> kalkulasi_waktu(9, 0, 7.2)
1.25
"""
return (kecepatan_akhir - kecepatan_awal) / percepatan | a097b127732480c2f56a0b013fba7a22c34fbe2c | 610,226 |
def inter_cluster_mean_score(cluster, graph, mean=None):
"""
The method is based on the calculation of distances for each sample in a given cluster to
the specific centroid of cluster. If the centroid is not given by specifying mean, it is
calculated with the distance function that is provided by graph.... | b669eaba5805c299c797a5bd7ae30ef0b106e2bc | 610,228 |
def get_Text_sample(num):
"""get sample text
Args:
num(int): number of new lines
Returns:
str: lines of sample texts
"""
text = ""
for i in range(num):
text += f"-- Text {i} --\n\n"
return text | f31ab804db76b06b9794e9cbacbf2c84aede67f2 | 610,231 |
def basename(path):
"""Return the file name portion of a file path."""
return path.split("/")[-1] | 15bc5f9471478300dc946621bc525077216230fa | 610,234 |
def get_ldap_account_safely(user):
"""
Safely check if user has an LDAPAccountStatus record.
If exists, return it, otherwise returns None.
"""
if hasattr(user, 'ldapaccountstatus'):
return user.ldapaccountstatus | eb1bf94428e77d3862e631eda36b9c8a602294bb | 610,236 |
import time
import logging
def get_fps(start_time, frame_count):
""" Calculate and display frames per second processing """
if frame_count >= 1000:
duration = float(time.time() - start_time)
FPS = float(frame_count / duration)
logging.info("%.2f fps Last %i Frames", FPS, frame_count)
... | 0e871e0acb32a804570c910117ba36ae8cb19b0c | 610,241 |
def create_policy_bindings(member, roles):
""" Converts member+roles args to a proper policy bindings object. """
bindings = []
for role in roles:
bindings.append({'role': role, 'members': [member]})
return bindings | cd0257be88ff86cb849ac6506287c43bc4082bfb | 610,243 |
def as_rupiah(uang):
"""
return a number as rupiah.
eg: 2000000 => 2.000.000
"""
if uang is None:
return 'Rp. 0'
return 'Rp. {0:,}'.format(uang).replace(',', '.') | afeaadc4496b09ef83c4d6ba5d2a9a4cc11677ab | 610,244 |
import re
def parse_show_interface_brief(raw_result):
"""
Parse the 'show interface brief' command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the show interface brief command in a \
dictionary of the form:
::
{
... | a77fc3fc017af375c37e1841915d32b3be9b9915 | 610,247 |
import torch
def prepare_target(tensor: torch.Tensor) -> torch.Tensor:
""" Convert the target mask to long and remove the channel dimension. """
return tensor.long().squeeze(1) | 9b4343b43db2ab5a2df10352bcce7238abd56139 | 610,248 |
def _distance(mass_a, mass_b):
"""Computes the distance between two masses"""
ab = mass_a.pos - mass_b.pos
return (ab[0]**2 + ab[1]**2)**0.5 | 8741c7e040fe011799fb0624a706004320d5d51f | 610,249 |
import torch
def triu_indices(n, m=0, k=0):
"""Wrapper of `torch.triu_indices`.
Parameters
----------
n : int
Number of row of output tensor.
m : int, optional
Number of column of output tensor, by default 0
offset : int, optional
Offset to main diagonal, by default 0
... | 44810af4490c930533fb900a870706602dee71d1 | 610,251 |
from typing import Tuple
def split_package_string(package_name_version_build_string: str) -> Tuple[str, str, str]:
"""Helper method for parsing package_name_version_build_string.
Returns:
Tuple (package_name, build_version, build_string)
"""
package_nvbs_parts = package_name_version_build_str... | 9fb9e6dbba93430171fae3ae4976c01be6aa0d55 | 610,255 |
def is_tied(note):
"""Get a boolean from a general note saying if it is tied to the previous gnote."""
if note.tie is not None and (
note.tie.type == "stop" or note.tie.type == "continue"
):
return True
else:
return False | 5b8ee5c9e38c2a74b385f0aa79688a5b06079aab | 610,261 |
def str2bool(value):
"""
String to Boolean
"""
# because argparse does not support to parse "true, False" as python
# boolean directly
return value.lower() in ("true", "t", "1") | 1d8099c0b727bd72f3821f14a52f3cfcb4581efd | 610,271 |
def join_qualified(region, view):
"""
Given a region, expand outward on periods to return a new region defining
the entire word, in the context of Elm syntax.
For example, when the region encompasses the 'map' part of a larger
'Dict.map' word, this function will return the entire region encompa... | c95c45df94d1514ed9f829bab3a2f9bfabbb3c9d | 610,274 |
def sum_node_children_size(node):
"""
Calculate the sum of symbol size of all direct children.
"""
size = 0
for child in node.children:
size += child.size
return size | 095028b051ecd52c72a49c51077f135aab620d30 | 610,278 |
def get_level_data(user_level, all_data_info):
"""
Loops through the all_data list and adds the rows that match with the user selected level
to a new list called level_data.
Params:
1) user_level - This is the input received from the user
2) all_data_info - This is the list containing ... | b0c8a4224995fa9eff8be60e664abf057c35ad0f | 610,282 |
import re
def _pythonify_type(text):
"""
Convert valid Copperhead type expression to valid Python expression.
The Copperhead type language is very nearly syntactically valid
Python. To make parsing types relatively painless, we shamelessly
convert type expressions into similar Python expressions... | 67375cd7ca8691b7ffc66c7affac4c79d1260c6d | 610,284 |
def BuildVersion(major, minor, revision):
"""Calculates int version number from major, minor and revision numbers.
Returns: int representing version number
"""
assert isinstance(major, int)
assert isinstance(minor, int)
assert isinstance(revision, int)
return (1000000 * major +
10000 * minor... | 5cc0c6802308ced91db51eab1be79a94cac8e814 | 610,294 |
def getNamedElem(parent, nodename):
"""
Return first subnode of given parent with given tag name, or None
if there is no such subnode.
"""
nodes = parent.getElementsByTagName(nodename)
if nodes:
return nodes[0]
return None | 3f7e5292c97981586aedfd1cb102b2ac861db80f | 610,299 |
def maybe_quote(value):
"""
Quote a value for InfluxDB if necessary.
"""
if value[0] == "'" and value[-1] == "'":
return value
return "'{}'".format(value) | 39eb8ee783d88a472a28cf493aae8fb4161b17db | 610,300 |
import torch
def masked_mae_loss(y_pred, y_true):
"""Calculate masked mean absolute error loss
Args:
y_pred (torch.Tensor): Predicted values
y_true (torch.Tensor): True values
Returns:
torch.Tensor: Loss
"""
mask = (y_true != 0).float()
mask /= mask.mean()
loss =... | 7fb067bc7fbb145c4483c7d932143274f6db23a7 | 610,301 |
def is_record(type_field):
"""
Is the avro field a record or a non record?
Non-records return true. Fields that are scalar, null *or* a record
also return True.
"""
if isinstance(type_field, list):
for avro_type in type_field:
if isinstance(avro_type, dict):
i... | 305c9a5a43e4c306897e43800825b5be7d659ec1 | 610,302 |
def analysis_dir(tmp_path_factory):
"""
Creates and returns analysis directory
"""
analysis_dir = tmp_path_factory.mktemp("analysis", numbered=False)
return analysis_dir.as_posix() | 76b99f86d45a9d9336c25efd3617cd7fc53be9b2 | 610,305 |
def get_tasks_at_level(workflow, level):
"""
return the tasks at given level
Args:
workflow (DAG): DAG object of workflow
level (int): level which output tasks needed to be
Returns:
list(Node)
"""
tasks = []
for task in workflow.get_nodes():
if workflow.get... | 997ac52d3c2fdcd0857b1f77446c3006cceea6af | 610,306 |
def build_url() -> str:
"""Build url for standings source"""
return 'https://www.hockey.no/live/Standings?date=01.11.2020&tournamentid=397960&teamid=0' | 039f0ead632f9e2e9af54fc028552d9f8d7343b2 | 610,308 |
def is_backmutation(var):
"""
Check if SNP var is annotated as a backmutation.
Args:
var: A variant string representing a SNP
Returns:
True if marked as a backmutation, False otherwise.
"""
if '!' in var:
return True
return False | fb2b59213037616e7653e4dcea1720fd340e9669 | 610,309 |
def ArraySum(array:list, n:int=0):
"""
Sum of all the elements in the List using Recursion
"""
if n == len(array):
return 0
return array[n] + ArraySum(array,n+1) | 3b85290fd2ecd4e321e055bd3135a933bac41d45 | 610,313 |
def error_template(issue, lineno=0):
"""Formats an error reported by the tool."""
if lineno != 0 and lineno is not None:
return " ".join(["Line", str(lineno), issue])
return issue.capitalize() | 63ab180698a7160d0a14f1de488ceeedb1309bc2 | 610,318 |
def combination(n, r):
"""
:param n: the count of different items
:param r: the number of select
:return: combination
n! / (r! * (n - r)!)
"""
r = min(n - r, r)
result = 1
for i in range(n, n - r, -1):
result *= i
for i in range(1, r + 1):
result //= i
return ... | 8cb91596dc054caf28c1534e0bc109bab1af8bad | 610,319 |
def get_sub_examples_list(example):
""" Get the names of sub examples. if no sub examples, return the name of main example"""
sub_examples = []
if example['sub-repo-example']:
for sub in example['subs']:
sub_examples.append("%s/%s" % (example["name"], sub))
else:
sub_examples... | 232848e06f6311fce61952f6fedba9d720cd3081 | 610,321 |
import ssl
def setup_ssl(root, settings):
"""
Create an SSL context from a given file root and settings dict
:param root: Path root for the ssl directory
:param settings: Webserver settings dictionary
:return: New ssl context, or None if ssl settings aren't configured
"""
out = None
... | e4bbc1fc848234179f937f87697cbb0af0a3c8fe | 610,323 |
def get_prefix() -> str:
"""Beginning of all queries (prefixes used in the different queries in the project)
Returns:
str: Prefix lines
"""
return """
PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
PREFIX wikibase: <http://wikiba.se/... | e4e0b291cd7ac3d967e4f969db6bfd37aba64910 | 610,325 |
def item(self, drive=None, id=None, path=None):
"""Gets an item given the specified (optional) drive,
(optional) id, and (optional) path
Args:
drive (str): The drive that you want to use
id (str): The id of the item to request
path (str): The path of the item to request
Returns... | ad3f3306d31195b21485bb37f205e598586d0f45 | 610,327 |
def _determine_if_event(four_byte_int):
"""Checks if event bit is set."""
return four_byte_int >> 31 == 0 | 23531e5990ba01b06e730b72681e591077876356 | 610,330 |
def nodata(status_code):
"""Translate NODATA status codes from GnuPG to messages."""
lookup = {
'1': 'No armored data.',
'2': 'Expected a packet but did not find one.',
'3': 'Invalid packet found, this may indicate a non OpenPGP message.',
'4': 'Signature expected but not found.'... | cd7fc690073bcfa28bf4100402938fd234c05448 | 610,332 |
from typing import Any
import uuid
def is_valid_uuid(val: Any) -> bool:
"""Check if a string is a valid uuid."""
try:
uuid.UUID(str(val))
return True
except ValueError:
return False | b1493d6dd126923c891cd965e3a6293fe2de5279 | 610,333 |
def filter_group_answers(groups, group_filter):
"""Filter answers from groups using group_filter."""
return [group_filter(group) for group in groups] | 42f5c9cd721cd89cc728af06f5bb5759be7170ce | 610,334 |
from typing import Tuple
def bbox(polygon) -> Tuple[float, float, float, float]:
"""Compute the Bounding Box of a polygon.
:param polygon: List of coordinate pairs (x,y)
"""
x,y = 0,1
vtx = polygon[0]
minx, miny, maxx, maxy = vtx[x], vtx[y], vtx[x], vtx[y]
for vtx in polygon[1:]:
... | c0e07607a94ee6b7f6945622c39e06a11e2bf4d0 | 610,338 |
def xact_type(df):
"""
Adds transfer, expense, income category column to df
"""
def categorise(row):
if row['Master Category'] == "Transfer":
return 'Transfer'
if row['Master Category'] == "Income":
return 'Income'
return 'Expense'
df['Type'] = df.app... | 85ed7481225126a4ea5158147b9bbf82328e8811 | 610,339 |
def locale_to_lower_upper(locale):
"""
Take a locale, regardless of style, and format it like "en-us"
"""
if '-' in locale:
lang, country = locale.split('-', 1)
return '%s_%s' % (lang.lower(), country.upper())
elif '_' in locale:
lang, country = locale.split('_', 1)
r... | 28e5da76a2b70998a7584c972ad8fa3fac672d3e | 610,341 |
from typing import Any
def is_sdict(x: Any) -> bool:
"""check if an object is an `SDict` (a SAX S-dictionary)"""
return isinstance(x, dict) | 15d6fa57b81f9e8e942383e09315d5c61783cc38 | 610,342 |
def quick_inline(model, verbose_name=None, fields=None, readonly_fields=None,
can_delete=None, max_num=None, extra=None):
"""A shortcut for setting some tabular inline params.
All except `model` are optional.
"""
def decorator(Inline):
Inline.model = model
if fields:
... | d44e5dddda475d0ec3f3d0b6990b7bd1ca1dbd2d | 610,343 |
def __isIntType__(obj):
"""
Returns true if the obj is an integer
"""
return isinstance(obj, int) | eee879a09e2d3512ea6a375def15db779c9ca41d | 610,344 |
def toWordList(description):
"""
takes a description (unique string) and separates it to lowercase words (not distincts)
"""
return description.lower().split(" ") | baf26686132c0e7ebd314d6dbc772f64f404bc69 | 610,346 |
import random
import string
def pwgen(length=None):
"""Generate a random pasword."""
if length is None:
# A random length is ok to use a weak PRNG
length = random.choice(range(35, 45))
alphanumeric_chars = [
l for l in (string.ascii_letters + string.digits)
if l not in 'l0Q... | f5fab1f263b7a8c2507465ee5f64d4025c20847f | 610,360 |
def loc_to_block_cell_num(y, x):
"""
:param y: The y location of the cell on the board. Precondition: 0 <= y < 9
:param x: The x location of the cell on the board. Precondition: 0 <= x < 9
:return: The cell number offset inside a block
"""
return (y % 3) * 3 + (x % 3) | 89bb88fe30df677c2e58f539692dc9cd2b22ccff | 610,362 |
def get_unique_values(local_data, attr):
""" Given data set and attribute, returns
unique values that the attribute takes """
values = []
for element in local_data:
if element[attr] not in values:
values.extend([element[attr]])
return values | 740835395b497e1d7ca1359a5ccdb643956fda57 | 610,367 |
def force_repulsive(dist):
"""
Repulsive force between nodes.
Parameters
----------
dist : np.ndarray, [N, N, 1]
Distance between nodes.
area : int, optional
Area of the layout space, by default 1
Returns
-------
force_repulsive : np.ndarray, [N, N, 1]
Repulsive force between nodes.
""... | d8e0f208513bc72c82318d8226c6e4a802c6a882 | 610,373 |
def TransformValuesToCStyle(variables):
"""Returns variables with values replaced with strings suitable for print.
Args:
variables: A list in the form of [(prefix, var_name, values), ...].
Returns:
The same list as |variables| but some of values are replaced with
printable strings.
"""
def _ToC... | 36fc40d78b0c7b05d01ef7201856fec7e804c538 | 610,381 |
def write_pair(
new_reads_for,
new_reads_rev,
name,
for_seq_list,
for_qual_list,
rev_seq_list,
rev_qual_list,
mode,
final_number_of_pairs,
):
"""Function to write one pair with the combinations of fragment depending on
the chosen mode.
Parameters:
-----------
new... | 7acddf51d734b564c0cd6c3d04ab1c2ab347a16c | 610,383 |
def parse_autotaskprocessexception(e):
"""
AutotaskProcessException could have any exception wrapped inside of it,
so handle as an AutotaskAPIException if a response attr is present,
or handle as we would a regular exception we don't know about.
"""
response = getattr(e.exception, 'response', No... | 8902ddfb1688cd42cf2f0444d58ef7e8cc76314e | 610,387 |
def mass(particle):
"""
mass of a particle object, in GeV
"""
try:
xmass = particle.mass/1000. # convert particle mass in GeV
except:
xmass = 0.
return xmass | d3785e1b8a502f2b43be706e25c0eaae44bc927c | 610,396 |
def get_layer_granules(cat, coverage, store_obj):
"""Get all granules in a layer."""
granules = cat.list_granules(coverage['name'], store_obj)
return granules | 7eda670c689b725f350326b9ea33923000c7c7a2 | 610,399 |
def obj_value(var_list):
"""
The real function
:param var_list: position variables
:return: the solution as a number
"""
#Ackley
#value = -20*math.exp(-0.2*math.sqrt(0.5*((var_list[0]**2 + (var_list[1]**2))))) - math.exp(0.5*(math.cos(var_list[0]*2*math.pi) + math.cos(var_list[1]*2*math.pi))... | 4a5a0a35497ac6686d745193ec18ba8f0df5c9f3 | 610,400 |
def timefmt(sec):
"""Format time to min:sec format."""
return "%d:%02d" % (sec/60, sec%60) | 2c1274d1596b0d566ce8c2818559edeb2f27403f | 610,402 |
def default_terminating_function(engine, max_generations=100):
"""
By default the engine will finish after a certain number of generations have gone through
evolution.
Args:
engine:
The engine running the genetic algorithm.
max_generations:
The number of generati... | 554660671e648a43a8050edac566b0cbed1a76aa | 610,403 |
def hello(name: str) -> str:
"""
This is module function and it is added to documentation even if it does
not have a docstring. Function signature will be also generated respecting
regular and comment-style type annotations. Let's use PEP 257 format here.
Examples::
# Google-style code blo... | f48ea7e937d9a45c390cc98ad6c123c0ba543315 | 610,404 |
import math
def nCr(n, r, replace=False):
"""Number of combinations, with or without replacement
:param n: population length
:param r: sample length
:param replace: whether to use replacement
:return: int
"""
if n < 0 or r < 0:
raise ValueError("n and r must be positive")
if n... | d797c3891445b22cca14f0ad8e91d4edb2e891be | 610,407 |
import re
def RegCount(x: str):
"""
Input: String
Output: Integer
Counts the number of Upper Case, Lower Case, Special and Numerical Characters.
"""
c1,c2,c3,c4=0,0,0,0
for i in x:
if re.search("^[A-Z]+$",i):
c1+=1
elif re.search("^[a-z]+$",i):
c2+=1... | b46a99e2b0c8e68ed3165936290cdb9aae11c30c | 610,409 |
def norm_min_max_dict(dict1):
"""
min-max normalization for dictionary
:param dict1: input dictionary
:return: min-max normalized dictionary
"""
for key, value in dict1.items():
dict1[key] = round((dict1[key] - min(dict1.values())) / (max(dict1.values()) - min(dict1.values())), 3)
re... | 1a16d2b7392d9d4b1e746c0cdf576f37c1688a41 | 610,410 |
def poly_to_box(poly):
"""Convert a list of polygons into an array of tight bounding boxes."""
x0 = min(min(p[::2]) for p in poly)
x1 = max(max(p[::2]) for p in poly)
y0 = min(min(p[1::2]) for p in poly)
y1 = max(max(p[1::2]) for p in poly)
boxes_from_polys = [x0, y0, x1, y1]
return boxes_fr... | 8b7de23b9aea9c6398d8ddf50f16db1bc5533476 | 610,412 |
def q_to_nu(q):
"""Convert mass ratio (>= 1) to symmetric mass ratio."""
return q / (1. + q)**2. | 28e7efbb53a3d7842aa2ad98181fe642d979259f | 610,416 |
def follow_path(obj, path, create_missing=False):
"""Given a dict and a '/' separated path, follow that path and return the
value at that location.
Examples:
obj={ a: { b: { c: { d: 'foo' } } } }
path="/a/b"
returns obj['a']['b']
Arguments:
obj: the object to look in
path: the path to foll... | 1c1fe9c3070bde68edf77e855bbafa9eb3a93cc2 | 610,418 |
import logging
def get_logger(name=None):
"""Return a logger for a module, if the name is given.
This is equivalent to `logging.getLogger('willie.modules.' + name)` when
name is given, and `logging.getLogger('willie')` when it is not. The latter
case is intended for use in Willie's core; modules shou... | ac9985d222cf30a5f91c17ab5c1f8c978083eac3 | 610,420 |
import pickle
def pickle_to_bytes(redis_server, hkey, key):
"""Convert pickled matrix stored in entry under `key`
in Redis hash under `hkey` to bytes.
Args:
redis_server: Redis server containing hash under `hkey`.
hkey (str): Key under which Redis hash is stored.
key (str): Key ... | c430d4036bfcdc78644de4de13342a329c0de7fb | 610,422 |
def get_bbox_obj_detection(bbox):
"""
Get the coordinates of the 4 corners of a
bounding box - expected to be in 'xyxy' format.
Result can be put directly into a napari shapes layer.
Order: top-left, bottom-left, bottom-right, top-right
numpy style [y, x]
"""
if bbox.shape[1] == 3:
... | ddae1f37884300c10ad140c29f807d2fc634b2ae | 610,424 |
def _build_restart_filename(restart_dir, startdate):
"""Construct restart filename."""
restart_file = "%s/LIS_RST_NOAH39_%4.4d%2.2d%2.2d0000.d01.nc" \
%(restart_dir, startdate.year, startdate.month, startdate.day)
return restart_file | 187d96629a5398fd6433d1f35c12b487f5055e4b | 610,426 |
from typing import List
def is_sorted(array: List[float]):
"""A helper function to determine if an array is sorted"""
for i in range(len(array) - 1):
if array[i] > array[i + 1]:
return False
return True | d4a9651ee0acac51e46300ffd3cf8a717e341b43 | 610,428 |
def edgeos_action(object, on=None):
"""
Return the appropriate EdgeOS configuration command to send with *object*.
Unless *on* is specified, return "set" if *object* evaluates to ``True`` or
"delete" if *object* evaluates to ``False``.
When *on* is specified, if *object* evaluates to ``True``, the... | 47ed4a10c22f1e439ffe93105b21f584825e4040 | 610,430 |
def get_base_score(df, ctl_genes):
"""Get LFC of each guide when paired with controls
Parameters
----------
df: DataFrame
Anchor guides paired with all of their target guides. Has columns "anchor_guide" and "lfc"
ctl_genes: list
Control genes
Returns
-------
DataFrame
... | 355b2788e1a1984e02f89c0da89a34320f28a240 | 610,432 |
def load_text(filename):
"""
Load lines from a plain-text file and return these as a list, with
trailing newlines stripped.
"""
with open(filename) as input_fd:
lines = input_fd.read().splitlines()
return lines | 193cf5abae20c86389bb2bc626402d9949a609e4 | 610,434 |
def sbi_addition(sbi_code):
"""Creates link to SBI-code explanation."""
base = "https://sbi.cbs.nl/cbs.typeermodule.typeerservicewebapi/content/angular/app/#/code?sbicode="
link = base+str(sbi_code)
return link | 76368f8ffb8090773101706c790d58a778cc1e68 | 610,439 |
def flow_and_head_loss_report(case_dom):
"""Return a string containing the final calculated volumetric flow and head
loss in each pipe
Args:
case_dom (dict): Pipe flow network data model
Returns:
(str): Table containing the final calculated volumetric flow and head
loss in ea... | 6c1dc3a367c111fda0509312ae2b8c14ab5c37d9 | 610,440 |
def mode(arr):
"""get the most frequent value"""
return max(set(arr),key=arr.count) | 2e052209d2e641ec1de71caa2352b4e9f98b2a70 | 610,441 |
def cls_decl(node):
"""Get the declaration of a class."""
return node.body[2] | 8303a870f0575400fd5ede11018912324428abb5 | 610,442 |
def filter_objects(filter, *objects):
"""
filter multiple objects
Parameters
----------
filter : list
boolean list
objects :
objects to filter
Returns
-------
objects :
filtered objects
"""
new_objects = []
for o in objects:
new_objects... | 4a76b390990eddf9256d08db76d9ab7f429f1ff2 | 610,443 |
from typing import Sequence
def common_prefix_length(a: Sequence, b: Sequence) -> int:
"""
Find the longest common prefix of two sequences.
"""
for i in range(len(a)):
if i >= len(b) or a[i] != b[i]:
return i
return len(a) | 4660dc3cbad20a26428d8e943085d0d5ff915747 | 610,450 |
def ndim2spatial_axes(ndim):
"""
>>> ndim2spatial_axes(3)
(-3, -2, -1)
>>> ndim2spatial_axes(1)
(-1,)
"""
return tuple(range(-ndim, 0)) | ba1323e717c512553127dfded11e0865a15133f7 | 610,455 |
import re
def degenerate_document_path_and_return_doc_name(document_path):
"""Takes a document path and returns just the generic document name
An inverse function for `get_document_path` which returns what would have been
the `document_name` param (i.e. removes all framework slug, supplier id and bucket ... | eb2919a8d11b7aabe5b7ac7752d2f75a01501446 | 610,459 |
import torch
def classification_acc(predict, label):
"""
Calculate classification accuracy: correct_result / sample_number
Args:
predict(torch.Tensor): predictions, shape (sample_number, class_number), in the form of one-hot coding.
label(torch.Tensor): labels, shape (sample_number), in t... | 5641b792d0797b3a49eb39341d50b16d4450936c | 610,460 |
def _CheckPNGFormat(input_api, output_api):
"""Checks that .png files have a format that will be considered valid by our
test runners. If a file ends with .png, then it must be of the form
NAME_expected(_(skia|skiapaths))?(_(win|mac|linux))?.pdf.#.png
The expected format used by _CheckPngNames() in testing/corp... | 8647b99f2c3b4155fa8574eec43b9ce7f58cc7e5 | 610,462 |
def remove_blanks(d):
"""
Returns d with empty ('' or None) values stripped
"""
empty_keys = []
for key in d:
if d[key]=='' or d[key]==None:
# del d[key] raises runtime exception, using a workaround
empty_keys.append(key)
for key in empty_keys:
del d[key]
return d | 9f228d69b51cf4e57d883ce0750e2601ebc70494 | 610,464 |
from typing import Tuple
from typing import Optional
def parse_item_stack(data_in: str, allow_ranges: bool = True) -> Tuple[str, bool, Optional[int], Optional[int]]:
"""
Allows the following formats to define either an item or a tag:
'namespace:path' -> item
'#namespace:path' -> tag
Also allows th... | 78d66fdb99c45327af67ddec83b6646fdd21e2ba | 610,465 |
def clean_rec(rec):
"""
replaces empty strings with 'None' so that a NULL will be inserted instead of ''
"""
for i in range(len(rec)):
if rec[i] == '':
rec[i] = None
return rec | e78e684f0d520c749518bc1208a68f22c20642d0 | 610,468 |
def _extract_name(line: str) -> str:
"""Accepts a UniProt DE line (string) as input. Returns the name with
evidence tags removed.
"""
tokens = line[19:-2].split(" {")
name = tokens[0]
return name | 16675f43e27328db3656b51a79681754dad606bf | 610,469 |
def _await_resolution(reactor, d):
"""advance the clock until the deferred completes.
Returns the number of milliseconds it took to complete.
"""
start_time = reactor.seconds()
while not d.called:
reactor.advance(0.01)
return (reactor.seconds() - start_time) * 1000 | a7bf4b826bebbe01d2d9876da48d6572d4044e3f | 610,471 |
def is_rel(s):
"""
Check whether a set represents a relation (of any arity).
:param s: a set containing tuples of str elements
:type s: set
:rtype: bool
"""
# we have the empty relation, i.e. set()
if len(s) == 0:
return True
# all the elements are tuples of the same len... | 3c229fff7c05622d009a3af5c111753b837cad08 | 610,472 |
def filter_hsv_to_s(hsv):
"""
Experimental HSV to S (saturation).
Args:
hsv: HSV image as a NumPy array.
Returns:
Saturation values as a 1-dimensional NumPy array.
"""
s = hsv[:, :, 1]
s = s.flatten()
return s | fecd0be1e7aac2545f676a7b063e9e9bc47b8d39 | 610,473 |
def drop_unused_columns(df):
"""Removes stop_columns from dataframe"""
stop_columns = {
'Наявність (відсутність) заборгованості зі сплати '
'аліментів на утримання дитини',
'Передвиборна програма',
'Декларація'
}
return df.drop(columns=[c for c in df.columns if c in stop_... | 98ddbb1d29f1cf20782aaf11efe2a93c97305235 | 610,476 |
def exp(rv):
"""
Returns the exponentiation of a random variable
"""
return rv.exp() | 006307d2569be92fb389ad7f42d0354e124c9b48 | 610,477 |
def strip_leading_slash(path: str) -> str:
"""Strips leading slash from the path, except when it's a root."""
return path.rstrip("/") if path and path != "/" else path | 23c51c1c548e0d4976c7ca772a362438d2658fea | 610,479 |
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (Dictionary) raw structured data to process
Returns:
Dictionary. Structured data with the following schema:
{
"time": string,
"uptime": string,
... | 8c7af3ee640aa1e2092cc57518a05ea8b3b9f95f | 610,481 |
def add_integer(a, b=98):
"""Adds two integers.
Arguments:
a (int) -- first argument must be an integer or float.
b (int) -- seccond argument must be an integer or float.
default value: 98
Raises:
TypeError: var must be an integer.
TypeError: var must be ... | b441019facfc1aa5e8329af6ccefb92536aa1b72 | 610,483 |
def get_remote_addr(request):
""" Get IP address of user making request can be used for other logging"""
ip_address = request.META.get("HTTP_X_FORWARDED_FOR", None)
if ip_address:
# X_FORWARDED_FOR returns client1, proxy1, proxy2,...
ip_address = [x.strip() for x in ip_address.split(",")][0]... | 628e528983facda5bece09e241883646ce1b2db3 | 610,485 |
def fuel_burn_rule(mod, prj, tmp):
"""
If no fuel_burn_rule is specified in an operational type module, the
default fuel burn is 0.
"""
return 0 | 57eee2899911697aa1f6c22f0ef69859061e818a | 610,487 |
def augment_image(img, rotate, rand_brightness_contrast):
"""
Function for augmenting single image.
:param img: image to be augmented
:param rotate: rotation function
:param rand_brightness_contrast: brightness & contrast altering function
:return: ... | cb7712942589f9b5e74106ed11496c628d0f5b76 | 610,488 |
def get_shib_idp_en_name(names):
"""
Returns a name in English for a Shibboleth IDP, or the first available
name if no English name was provided.
Args:
names (list): list of {"lang": "", "value": ""} dictionaries
Example:
[
{
"value": ... | 8225fb2ff50b3036822fba1c28c40f235ff4439e | 610,489 |
def _format_bootstrap_report(result):
"""Formats a `_BootstrapResult` as a complete report str.
The information presented includes:
- The results of a bootstrap to test how often the test fails
- A confidence interval on the probability of the
`assertAllMeansClose` failing, assuming the empirical distribut... | b586b03a77f7c39b70a23c719e8fbce422f062a9 | 610,490 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.