content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def find_closest_frame(utc, timestamp):
"""
Takes timestamp as datetime object, returns the frame number corresponding to the cloest frame to that time
Briefly sets the index to datetime column, then sets it back
"""
index_holder = utc.index
utc.index = utc.datetime
closest_loc = utc.index.g... | 19b588176203777e04a596ac36fff7d0b96ad7f8 | 567,222 |
def assign_region(vheight, region_hmax={"D":115.0,"E":150.0,"F":900.0},
region_hmin={"D":75.0,"E":115.0,"F":150.0}, case="upper"):
"""Assign an ionospheric region based on virtual height.
"D" (75 - 115 km)
"E" (115 - 200 km) is detected at distances lass than 900 km
"F" (200 -900 km) i... | 92b6f3206a4e069baa0e0cdf17a36af98015d3e8 | 567,223 |
def pproc_command(commands):
"""
Creates a pproc command from a list of command strings.
"""
commands = " ".join([
"\"{}\"".format(command) for command in commands
])
return "pproc {}".format(commands) | c8dd6335d2bbee254b914534d0110102a5cdcfab | 567,229 |
import torch
def add_noise(x, variance=0.1):
"""
Function for adding gaussian noise
:param x (torch.FloatTensor): Input for adding noise
:param variance (float): Variance for adding noise
"""
return x * (1 + (variance ** 0.5) * torch.randn_like(x)) | f297e4c9c67fba05140746bab2fd2846b72429d7 | 567,232 |
def choose_models_with_recall(models_df, group_min_recalls, labels_col='label',
recall_col='recall', algorithm_col='algorithm',
hyperparameters_col='hyperparameters'):
"""
Selects algorithm and hyperparameters of best model for a specific
recall va... | 88d13b994ee42edc54b64ead4e33f1f108f7c5e1 | 567,241 |
def test_climate_aware(distinct_keywords: float, total_keywords: float, article_cai: float) -> bool:
"""Returns whether an article with given parameters is climate aware or not."""
return distinct_keywords >= 8 and total_keywords >= 15 and article_cai >= 0.02 | 8ede63a4e311000ecaefc82f16c9e97e6afbdacf | 567,243 |
def convert_dll_name_to_str(dll_name):
"""
Convert dll names from 'bytes' to 'str'.
Latest pefile returns type 'bytes'.
:param dll_name:
:return:
"""
# Imported here to avoid circular import.
if isinstance(dll_name, bytes):
return str(dll_name, encoding='UTF-8')
else:
... | 7feac2ef1f945a08802bc2ca2a1c779b7ba1c9af | 567,245 |
def DictSolution(nums: list[int], target: int) -> list[int]:
"""
Given an array of integers `nums` and an integer `target`, return indices
of the two numbers such that they add up to `target`.
You may assume that each input would have exactly one solution, and you may
not use the same element twice... | 279477d4fe4f83a623ed941d5c04e1f0e96f880d | 567,250 |
import hashlib
def checksum_file(scheme, path):
"""Return the checksum (hex digest) of a file"""
h = getattr(hashlib, scheme)()
with open(path, 'rb') as f:
chunk = f.read(65535)
while chunk:
h.update(chunk)
chunk = f.read(65535)
return h.hexdigest() | c504f33e29e669bde01cc698e239d26cc9aad351 | 567,251 |
def little_endian(num):
"""returns a string with the hexadecimal little endian representation of the parameter"""
return " ".join([f"0x{i:X}" for i in num.to_bytes(4, "little")]) | 1d06921597604a1ce40f76dd8f46970cab4ea2ae | 567,252 |
from datetime import datetime
def get_semester_bounds(date):
"""Returns the two dates that bound the current candidate semester.
Assumes that there are only spring and fall semesters, separated at 07/01."""
if date.month < 7:
return datetime(date.year, 1, 1), datetime(date.year, 7, 1)
else:
... | 3cfe81dad1d0aa5138844d2f0831a9aef8bbcdc1 | 567,256 |
def build_windows_time(high_word, low_word):
"""
Generate Windows time value from high and low date times.
:param high_word: high word portion of the Windows datetime
:param low_word: low word portion of the Windows datetime
:return: time in 100ns since 1601/01/01 00:00:00 UTC
"""
retur... | 70be7aa48e575db2c8bb178c24d99f5cc6a6e910 | 567,258 |
def constant_time_compare(val1, val2):
"""
Returns True if the two strings are equal, False otherwise.
The time taken is independent of the number of characters that match.
Theoretically, this is useful in avoiding timing attacks related to
simple string equality checks.
"""
if len(val1) !... | 4f8639962d2f92fd03d71d4fc1e99e22a86e5d06 | 567,262 |
def filter_monoatomic_ions(array):
"""
Filter all atoms of an atom array, that are monoatomic ions
(e.g. sodium or chloride ions).
Parameters
----------
array : AtomArray or AtomArrayStack
The array to be filtered.
Returns
-------
filter : ndarray, dtype=bool
... | 3d7f8769610e9db76dd865a9f6a54988ee050ef0 | 567,264 |
def blue_channel(image):
"""Return the blue channel."""
return image[:, :, 2] | c67e1659cdde9a7e8a756049022d867dc890f016 | 567,265 |
def double_layer_cover_reflection_coefficient(transmission_coef_1, reflection_coef_1, reflection_coef_2) -> float:
"""
The reflection coefficient
Equation 8.15
:param float transmission_coef_1: the transmission coefficients of the first layer
:param float reflection_coef_1: the reflection coefficien... | 2ade4790406bc3929487f12d25ce27c08d3760ca | 567,266 |
def import_class_from_module_string(fqpn_str):
"""
Given a FQPN for a class, import and return the class.
:param str fqpn_str: The FQPN to the class to import.
:returns: The class given in the FQPN.
"""
components = fqpn_str.split('.')
# Generate a FQPN with everything but the class nam... | 972062e7a5ec3c026d3b164f2bae1440587d06f5 | 567,268 |
def reduce_zero(Q, coeffs, offset, exact_form=None):
"""
Applies cohomology relation to incorporate `x^2 y^0` term
into `x^0 y^0` and `x^1 y^0` terms.
INPUT:
- ``Q`` -- cubic polynomial
- ``coeffs`` -- list of length 3 lists. The
`i^{th}` list [a, b, c] represents
`y^{2(i - offs... | 8bc619f472004354b630b4a82be99a9a60ff44a7 | 567,270 |
import typing
def is_self_referenced(a_type: typing.Any) -> bool:
"""
Given a python type, return True if is self referenced, meaning
that is instance of typing.ForwardRef, otherwise False
Arguments:
a_type (typing.Any): python type
Returns:
bool
Example:
a_type = ty... | 4c3163abef82cee2ec95383e5264811dd83ab957 | 567,271 |
import colorama
def check_match(str1=str(),str2=str()):
"""
check_match(first string, second string)\n
Checks the second string to the first one,
returns a list of mismatched indexes and
prints both strings highlighting the errors in the second string with red color.\n
If the string lenghts a... | 9434c26b331926e88547f9201988e89bc3396b7b | 567,273 |
def predict_letters(letters, lts_lambda, silences=True):
"""
To predict using Letter To Sound Rules we pad the word with zeros (as done
in Festival LTS training. Then we choose the right tree for each character
in our word and predict the phonemes, that are returned in a list.)
"""
phonemes = []... | 148f181799fb2a34fb68ba29266dbb7a3f56dfd1 | 567,274 |
def score_distance(d, ka, coop=1):
"""
Given some distance d, returns a score on (0,1]. A d of 0 scores 0, and a d of inf scores 1.
gamma defines the distance at which the score is 0.5. Modeled off the Hill equation
Args:
d: The value to score
ka: The value at which the score is 0.5
... | 8717e2fddc70bd4fa4e09307d37d2942570c449a | 567,279 |
def EntityKind(key):
"""Given entity primary key as Reference Proto, returns entity kind.
Args:
key: primary key of entity in ReferenceProto form.
Returns:
Kind of entity in string format. Returns '' if
kind cannot be determined in some unexpected scenario.
"""
if key.path().element_list():
... | b00bc1ec608ebc3fe3e57b6231a68a05a0e744e3 | 567,281 |
import tempfile
def create_vault_password_file(module):
"""Create a vault password file."""
with tempfile.NamedTemporaryFile(delete=False) as f:
f.write(module.params['vault_password'])
return f.name | bdb51ba6f0db73b58c19af562be64a5cba015638 | 567,295 |
def setup_bot(bot):
"""Does one time initialization for this bot.
Returns True if it's fine to start the bot right away. Otherwise, the calling
script should exit.
Example: making this script starts automatically on user login via
os_utilities.set_auto_startup_win() or os_utilities.set_auto_startup_osx().
... | f048559116cdf4ca9f8a2ff7b60eac5125f50d60 | 567,297 |
def normalize_attrs(attrs):
""" normalize attributions to between -1 and 1 """
bound = max(abs(attrs.max()), abs(attrs.min()))
return attrs / bound | 629b7732da7bca006e7f8feeee8254d4fac2a6cd | 567,303 |
def square(a):
"""Returns the square of a."""
return a ** 2 | 7ce222c53d495777e6bc363743512f2c3af80c68 | 567,311 |
from typing import List
from typing import Any
def get_avg(values: List[Any]):
"""Get average value of a list.
Args:
values: A list of values.
Returns:
The average value in the list.
"""
valid_total = len(values)
running_sum = 0.0
for value in values:
if value ==... | c265b891eb3cccd02e95e57997702af3401328be | 567,312 |
def init_game(n_rows, n_columns, red_discs, yellow_discs):
"""Init an empty game with some initial moves.
Game is a 2D grid indexed from top left (0,0) to bottom right.
"""
game = [[" " for _ in range(n_columns)] for _ in range(n_rows)]
for x, y in red_discs:
game[x][y] = "R"
for x, y... | 9c11e9c692174100d64378d8ed13db27066e38bd | 567,314 |
def prepare_upload(request, url, **kwargs):
"""Directly uploads to the given URL"""
return url, {} | d89acc19097119e0411bcba0d7a7c16ffdf143d8 | 567,318 |
def user_unicode(self):
"""Change user string representation to use the user's email address."""
return self.email | 58d839871fcd1ab0dd45109cd80f2f420b5aa9bd | 567,322 |
import functools
def doc_lru_cache(function=None, **lru_cache_kwargs):
"""
Decorator that allows keeping a function's docstring when using functools.lru_cache.
Parameters
----------
function : Callable
The function to use. If used as a decorator and lru_cache_kwargs
are specified,... | 1d300fc81bf447b48193f6940a1187bd4c6d2df3 | 567,328 |
def merge( *dictionaries ):
"""
Helper toward immutable dictionary 'updates' (ala assoc or merge-ing a map in clojure)?
:param dictionaries: one or more dictionaries to merge, left to right
:return: single dict
"""
output = {}
for d in dictionaries:
output.update( d )
return outp... | cb3bc77a87e238428d8a139dc0a90f5421fba523 | 567,334 |
import torch
def sigmoid_to_tanh(x: torch.Tensor):
"""[0,1] -> [-1,+1]"""
out = x * 2.0 - 1.0
return out | 522f2159b02bd28d3c63802c9e4e9f04d303d2d0 | 567,335 |
from typing import Set
import re
def parse_list_of_tables(txt: str) -> Set[str]:
"""
Parses list of tables from function find_tables(), finds ones that mention algorithms
:param txt: chunk of text
:return: set of all pages mentioning algorithm table
"""
rr = re.compile(r"^.+?(?:[Ff]unction|[Aa... | a2505788a3ee8dc9fde02b0e4c6601388f5cc316 | 567,341 |
def _isASCII(mthd: str) -> bool:
"""
Check if the given method contains only ASCII characters. From https://stackoverflow.com/a/27084708/5768407.
:param mthd: the method to verify contains only ASCII characters
:returns: returns a boolean representing whether or not the given method contains only ASCII... | 22fbec9ea7bf8f86078a5df4387303523b2f4cc9 | 567,342 |
import base64
def base64_2_str(base64_encode):
"""
Args:
base64_encode: base64编码str
Returns: str(utf-8)
"""
base64_decode = base64.b64decode(base64_encode).decode('utf-8')
return base64_decode | 0f9f520843122d25eae17f6167f589c8fdc81e5f | 567,345 |
import re
def get_between(word, start, end):
"""
匹配两个字符之间的任何字符串
:param word: 被匹配字符串
:param start: 开始字符串
:param end: 结束字符串
:return: str
"""
return re.findall(f'{start}([\s\S]*){end}', word) | 368f3322bc1b864e1a0586813e6830d336c0b8c7 | 567,346 |
def modify_config(pipeline_config):
"""Modifies pipeline config to build the correct graph for TPU."""
# faster_rcnn.use_static_shapes and faster_rcnn.use_static_shapes_for_eval
# are set to True in order for detection_model.use_static_shapes to be True.
# We need to set this so that clip_to_window in _predict_... | f32735518ec87e11da540ecad0cd6fbfaab7f54e | 567,347 |
async def is_nsfw_or_private_predicate(ctx):
"""A predicate to test if a channel is NSFW or private
:param ctx: The context of the predicate
"""
return not ctx.guild or ctx.channel.is_nsfw() | 71ea83e063cfe744ea384fb5e298b112d61c69de | 567,348 |
def ynplus1(func, yn,t,dt,**kwargs):
"""evolve Runge kutta with function func which takes two input arguments
yn and t and possibly extra arguments
Parameters
------------
yn : iterable
value at the previous iteration
t : float
the time at current iteration
dt : float
... | 975c86d2a5ffb9ce8e1675462cbdc6186633d829 | 567,349 |
import io
import csv
def write_to_mem_csv(rows: list[dict], header: list[str]) -> io.StringIO:
"""Writes a list of rows and header to an in-memory CSV string.
Args:
rows (List[Dict]): List of records to add to the CSV.
header (List[str]): Header to add to the CSV.
Returns:
io.Str... | 2d4e593e028dfdfd0b6c247c7ca0403517462eed | 567,353 |
def output_dir(tmpdir):
"""Given a temporary dir, create an `output` subdirectory inside it and
return its path (not a str but a py.path instance).
"""
return tmpdir.mkdir('output') | 1676e4a5fd3a52e55478fa9d462accba647de09f | 567,354 |
def eye(n, K):
"""
Returns an identity matrix of size n.
Examples
========
>>> from sympy.matrices.densetools import eye
>>> from sympy import ZZ
>>> eye(3, ZZ)
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]
"""
result = []
for i in range(n):
result.append([])
for j in r... | b36669b4951c1592a0c23f471f352614e4de0270 | 567,356 |
def keylists(d):
"""
Return list of key lists to every leaf node in a nested dict.
Each key list can be used as an argument to dictget.
d: nested dict
"""
l = []
for k, v in d.items():
if isinstance(v, dict):
sublists = keylists(v)
for sli in sublists:
... | a701f06caeda595a56d4cdd80e6d59aa7b7d2185 | 567,361 |
def iteritems(d):
"""Return iterable items from a dict."""
if hasattr(d, 'iteritems'):
return d.iteritems()
else:
return iter(d.items()) | 486bde92caee32e906af640c269275f800a6ab8f | 567,363 |
def get_subdomain(environment):
"""
Get the Salesforce sub-domain based on Production or Test
"""
return 'login' if environment == 'Production' else 'test' | 32434f40c31e6b0e6143421898595a6b861dba37 | 567,367 |
import itertools
def flatten(gen):
"""Flatten a sequence, but only one level deep."""
return itertools.chain.from_iterable(gen) | a15b84d9741962a4e4588253a41bb8b538635bfa | 567,374 |
from re import VERBOSE
def is_verbose(verbosity: str) -> bool:
"""
Validates if verbosity is verbose.
:param verbosity: String. verbosity value
:return: Boolean. is verbosity verbose
"""
return verbosity == VERBOSE | df30899b6179910ff1bc403741e905e94692af3e | 567,379 |
def get_mangled_ir_symbol(module_name, function_name, parametric_values = None):
"""Returns the mangled IR symbol for the module/function combination.
"Mangling" is the process of turning nicely namedspaced symbols into
"grosser" (mangled) flat (non hierarchical) symbol, e.g. that lives on a
package af... | 92a618e28f9200ec843ef3e7fbd8ea5e1e9d262a | 567,382 |
def mock_id_formatter(issue, format='long', **kwargs):
"""
Always return the issue id converted to its string representation.
"""
return str(issue['id']) | 1a0f3232879c7b7123cd369292f299535ca0f2e8 | 567,384 |
def diff_nomod(ctx):
"""Get the unmodded difficulty values of a map."""
return {
"cs": ctx.beatmap.diff_size,
"ar": ctx.beatmap.diff_approach,
"od": ctx.beatmap.diff_overall,
"hp": ctx.beatmap.diff_drain,
"sr": ctx.beatmap.difficultyrating,
"bpm": ctx.beatmap.bpm,... | 4e025ed19b6deeb1a88d41d1d940940a034c4430 | 567,389 |
def build_logname(input_filename, process_type='svm'):
"""Build the log filename based on the input filename"""
suffix = '.{}'.format(input_filename.split('.')[-1])
if isinstance(input_filename, str): # input file is a poller file -- easy case
logname = input_filename.replace(suffix, '.log')
e... | e5fa6c0711a673c91d14e4222ec3e2878da6d5b0 | 567,392 |
from typing import Any
import importlib
def import_object(import_path: str) -> Any:
"""Imports an object from a given import path"""
if "." not in import_path:
raise ValueError(f"Import path {import_path} doesn't reference an object in a module.")
module_name, object_name = import_path.rsplit(".",... | c3b5a0298722046e58ef4dd4212aceae5381eb9b | 567,395 |
def swap_bits(x, i, j):
"""
Swap the ith and jth indices in 'x'.
"""
# Extract the i and j indices to see if they differ.
if (x >> i) & 1 != (x >> j) & 1:
# Retrieve the bits to flip by shifting to
# the ith and jth indices. Create a bit mask.
bit_mask = (1 << i) | (1 << j)
# Flip bits.
#... | a6e788884ea970ef70878f803a1d0616e904e793 | 567,396 |
from datetime import datetime
def timedelta_is_negative(td):
"""Checks whether timedelta is negative (would move date/datetime to the past)."""
return datetime.now() > datetime.now() + td | 2e3bdf7eb65a0fd07c8016cdf707a21ef56b84a6 | 567,402 |
def find_index(text, pattern, start=0):
"""Return the starting index of the first occurrence of pattern in text,
or None if not found.
Runtime Complexity: θ(n) Space Complexity: θ(1)"""
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is... | fff8d4415e02b2ec56084c652c8afbbf4d1bc884 | 567,406 |
def parse_version(revision):
"""Convert semver string `revision` to a tuple of integers"""
return tuple(map(int, revision.split("."))) | 30765dc8e71bab009336d1b3dce92d27b0da99db | 567,408 |
def _read_reset(fobj):
""" Read file-like `fobj` from current position, reset position
Parameters
----------
fobj : file-like object
Implements ``tell``, ``seek`` and ``read``.
Returns
-------
contents : str
Contents read from file-like from starting position, as given by
... | 5d717b09085de4ba7263ec58533611ea42e930b2 | 567,409 |
def groups(user):
"""
Returns all groups the user is a member of.
:param user: the logged-in user
:return: Array of groups
"""
try:
my_groups = user.groups.all()
return my_groups
except Exception as e:
print(e) | 5a6978c69cb4e8c9a5a60961d598d6ce8f22aff7 | 567,412 |
def rk4(x, v, t, h, deriv):
"""
Core Rk4 algo for calculating one step ahead.
This version is limited to 2nd order eq's of the type
dx^2/dt^2 + p(t,x,v)*dx/dt + q(t,x,v)*x = r(t,x,v)
Input:
- x: x (t)
- v: v (t)
- t: Initial time (t_n)
- h: Stepsize (t_{n+1} = t_... | 54880065a2eaefc37126eb2f2ba56a1108aaa6f4 | 567,413 |
def _first_largest(scores):
""" Similar to max, but returns the first element achieving the high score
If max receives a tuple, it will break a tie for the highest value
of entry[i] with entry[i+1]. We don't want that here - to better match
with the results of other tools, we want to be able to define w... | f0b1bf881aa2e932043bdbf2999bf65dd5490e56 | 567,420 |
def clear_end(line: str, chars: list):
"""
Clears line's end from unwanted chars.
Parameters
----------
line : str
Line to be cleared.
chars : list of chars
Unwanted chars.
Returns
-------
line : str
Given line, cleared from unwanted chars.
"""
whil... | df02f36436b588669c95ee0db2fbddb5c588a19a | 567,428 |
def collect_properties_text(schema_dict):
"""
Recurses into an OpenAPIv3 hierarchy and returns property data valueable for full text indexing.
That's mainly the property name and a description, if present.
"""
ret = []
if "description" in schema_dict:
ret.append(schema_dict["description"... | fd0167d65508462d3c9e0b3bb09ce1e7a409dbf3 | 567,431 |
import torch
def pairwise_distance(point_cloud):
"""
Args:
point_cloud: tensor (batch_size, num_points, num_dims)
Returns:
pairwise distance: (batch_size, num_points, num_points)
"""
batch_size = point_cloud.size()[0]
point_cloud = torch.squeeze(point_cloud)
if batch_size==1:
... | 83ee4ab7557f0afc6663649ce38877fcca2c60af | 567,433 |
def get_end_time(op):
"""Return the end time string of the operation."""
return op.get('metadata', {}).get('endTime') | c670976423cefe7a12478839eeac0e984f660bb5 | 567,434 |
import torch
def reduce(to_reduce: torch.Tensor, reduction: str) -> torch.Tensor:
"""
Reduces a given tensor by a given reduction method
Args:
to_reduce : the tensor, which shall be reduced
reduction : a string specifying the reduction method ('elementwise_mean', 'none', 'sum')
Retur... | fae66b941d193c636133f4aa5b16afd3b889037c | 567,440 |
def sensitivity(cm):
"""True positives vs all positives.
Args:
cm (2x2 np.array): A confusion matrix.
Returns:
float: Sensitivity of the classifier.
"""
return cm[0,0]/(cm[0,0] + cm[0,1]) | 9b01c77d6c81fb2e898cc26ddac8202b6c5b96d6 | 567,443 |
def sum_shared_values(values_list):
"""Sum the values in the entry info list by index. The first item of every list in values_list is summed, and
so on. If a float representing a sum can be converted into a whole number integer, do so.
:param values_list: A list of lists. Each list consists of strings repr... | 5179dc547736f4f4e72f99d47d75b94a6cb0ac5f | 567,444 |
from shutil import which
def check_requirements(program):
"""
Check if required programs are installed
"""
# From https://stackoverflow.com/a/34177358
return which(program) is not None | 5eb9cc90c8cbe9a52fbf88a5ae9ec70e6b428f40 | 567,446 |
def error_failed_passed(testdir):
"""Create test_error_failed_passed.py with one test for each outcome."""
return testdir.makepyfile(
test_error_failed_passed="""\
import pytest
@pytest.fixture
def error():
assert False
def test_error(error):
ass... | bfe029f7f325765c583dffe792ad93eb4f7fa788 | 567,447 |
def generate_rendered_template(jinja_environment, template_filename, **kwargs):
"""Returns rendered template
args:
jinja_environment: Jinja2 Parser from get_jinja_parser
template_filename: Path to template that will be used
kwargs: Keyword arguments containing the fields on `template_filename` and
... | c2e5002ac21c49e5e7093fe60f683397dba1c41b | 567,452 |
import textwrap
def unicode_escape(string: bytes) -> str:
"""Conterprocess of :meth:`bytes.decode('unicode_escape')`.
Args:
string: The bytestring to be escaped.
Returns:
The escaped bytestring as an encoded string
Example:
>>> b'\\x09'.decode('unicode_escape')
'\\\... | d9b59718695e0ea3cfe27bcb15705235baff1168 | 567,458 |
def to_number(var):
"""Convert to number or return None
"""
try:
if '.' in var:
raise ValueError
return int(var)
except ValueError:
try:
return float(var)
except ValueError:
return None | ebee9832b1c7f3f59ac545023130c7909825af61 | 567,459 |
from typing import List
import functools
def product(weights: List[int]) -> int:
"""Returns the product of a list of integers"""
return functools.reduce(lambda a, b: a * b, weights, 1) | dc0d9f5c5323a0d3759887d00ad23a6cf67f5772 | 567,460 |
def _get_detail_value(var, attr):
"""
Given a variable and one of its attributes that are available inside of
a template, return its 'method' if it is a callable, its class name if it
is a model manager, otherwise return its value
"""
value = getattr(var, attr)
# Rename common Django class n... | 8a7e15e7c1f0dd5355485b0da383964ae9f4fe37 | 567,464 |
def traverse_service(type_context, service_proto, visitor):
"""Traverse a service definition.
Args:
type_context: type_context.TypeContext for service type.
service_proto: ServiceDescriptorProto for service.
visitor: visitor.Visitor defining the business logic of the plugin.
Return... | e31152319a588ea41cf045fc65798babcd214083 | 567,465 |
def build_device_status(device):
"""
Builds an integer representation of the device status bit-field.
:param device: the lewis device
:return: int representation of the bit field
"""
status_bits = [
device.is_controller_ok(),
device.is_up_to_speed(),
device.is_able_to_run... | 98ce9d222446e0f75bb78dd19880aef5d9680b85 | 567,467 |
def get_expected_output_bcf_files_dict(base_out):
"""
:param base_out: Base path structure for log files. For example, if the expected path for
the log is 'work/step.path/log/step.bcf', the argument should be
'work/step.path/log/step'.
:type base_out: str
:return: Returns dictionary with expect... | 934120b4b8a86f6c0797d1befefdf9fc7a76d2e1 | 567,471 |
import random
def makeVerificationPairsFromClsDict(data, npos, nneg):
"""Makes npos positive and nneg negative pairs from the given data.
The data is given a dictionary of cls->data.
Returns (pos, neg), which are both sets.
Pairs are sorted, to test for equality.
Note that this can get stuck in an... | 2a883b21ae2bf9963640737afdc744902474ce11 | 567,472 |
def maze_simulation_step(env, net):
"""
The function to perform one step of maze simulation.
Arguments:
env: The maze configuration environment.
net: The maze solver agent's control ANN
Returns:
The True if maze agent solved the maze.
"""
# create inputs from the current ... | 05a66ab3834b8fe3bb3cd9190e562196b759afb3 | 567,476 |
def create_empty_node(code, depth):
"""Returns a sitemap node with no children"""
return {"code": code, "depth": depth, "children": []} | d44feb99d84c7797947fa83b645309661a1c1b03 | 567,478 |
from typing import Union
def flatten_dict(d: Union[dict, list], sep: str = '.') -> dict:
"""Flatten a dict so that it does not have any nested dicts or lists.
Nested keys will be concatenated using the separator, sep. For example,
{'a': {'b': ['x', 10]}} becomes {'a.b.0': 'x', 'a.b.1': 10}.
This makes... | c5b26e15009cbb3c8551f67df894c0c01c0dff67 | 567,481 |
import torch
def th_rand_rng(low, high, n=1):
""" pull uniform random sample(s) from [a,b) """
if n == 1:
return (high-low)*float(torch.rand(n)[0])+low
else:
return (high-low)*torch.rand(n).numpy()+low | a88f4684e8de915254d31622b372912c5a734f3a | 567,482 |
def reshape(data, status=None):
"""
Reshape data for convenient plotting.
"""
if data.shape[1] == 3:
data = data[data[:,2] == status][:,:2]
elif data.shape == (0,):
return data.reshape(2, -1)
return data.T[::-1] | 921558292a522f0d7854fa17fc707f5994259adf | 567,483 |
import re
def compress_spaces(line: str) -> str:
"""Compresses all instances of multiple whitespace in a row down to a single space"""
return re.sub(r'\s+', ' ', line).strip() + '\n' | 4fdf4df41e22b4a7cdc36ca772711af6a3d62d39 | 567,487 |
import string
def first_alpha(search_string):
"""
Returns the first ASCII letter.
Parameters
----------
string: str
The string in which to look for the first ASCII letter.
Returns
-------
str
Raises
------
ValueError
No ASCII letter was found in 'search_s... | 0534bb31725d693993bbd0b168695509153f7c1a | 567,488 |
def conv_outsize(in_size, kernel_size, padding, stride):
"""
Computes the size of output image after the convolution defined by the input arguments
"""
out_size = (in_size - kernel_size + (2 * padding)) // stride
out_size += 1
return out_size | 132acb902d9680cdce0f992349a177b069b989ee | 567,492 |
def set_allow_agent_initiated_activation(api, configuration, api_version, api_exception, allow):
""" Configures whether agent-initiated activation is allowed. Demonstrates how to set a single system property.
:param api: The Deep Security API modules.
:param configuration: Configuration object to pass ... | 02ba27382de2c81f0547eb8475891cc8878442a4 | 567,495 |
def exclude_higher_botelev(pfafs, pfaf_res, seg_topo):
""" Exclude segments that have higher BottomElev than reservoir BotElev
input: pfafs: list with all segments
pfaf_res: reservoir pfaf code
seg_topo: (geo)pandas dataframe with BotElev and PFAF per segment
output: pfaf_belowres: ... | 20e55ae354cdca4f426cbfdb80c32b6b8835188d | 567,497 |
def searchexact(text, table, fieldname, session):
"""
Universal exact search function for table/field name
:param text: search text (string)
:param table: db table class object
:param fieldname: dbtable field object
:param session: Database session object
:return: query results
"""
... | 24aa23bef68f6f5eb1203167d3903ddc21341035 | 567,498 |
def encode_revisions(revision_array):
"""
Takes a list of integer revision numbers and converts to a TortoiseSVN-like
format. This means we have to determine what numbers are consecutives and
collapse them into a single element (see doctest below for an example).
@type revision_array: list of... | cf08a6c8a2068f7746cfdd08c58f1dbcc51691ec | 567,499 |
def sorted_equality(v1, v2, read):
"""
Equality for fields where the values must be sorted before equality tested.
"""
return sorted(v1) == sorted(v2) | ff9a4cfd917b04dda5655ef2c28489f9fa46626c | 567,501 |
def boolean(truth):
"""Convert truth to boolean."""
if str(truth).lower() in ['true', 'yes', '1', 'none']:
return True
else:
return False | 4288efdfd92140d16ac01bc0291d627dcb1ed416 | 567,503 |
def format_datetime_for_google_api(dt):
"""
String-ifies a datetime value in the format expected by Google APIs
Args:
dt (datetime.datetime):
Returns:
str: The datetime formatted for use in a Google API request
"""
return dt.isoformat() | febc197e197ae5f09055e8e4cd319d59ad36ca47 | 567,504 |
def xr_check_lon_lat_match(xr_data_1, xr_data_2, lon_name='lon', lat_name='lat'):
"""
Check whether longitude and latitude coordinates of xarray Datasets/DataArrays are equal.
Args:
xr_data_1: first xarray Dataset or DataArray, with longitude and latitude dimensions
xr_data_2: second xarray... | 8b6efe02f6e9bbe5c5adeb754567960f21c4557c | 567,505 |
def _nested_encode(x, encoding):
"""Encode each string in a nested list with `encoding`."""
if isinstance(x, list):
return [_nested_encode(v, encoding) for v in x]
else:
return x.encode(encoding) | defd4f522a0480b7a1a2c4122b96cf5ac07c802e | 567,506 |
import time
def timestamp_to_date(timestamp):
"""
Converts a timestamp, format 13134234
to a date, format 2020-01-23
"""
return time.strftime("%Y-%m-%d", time.gmtime(timestamp)) | 7ace75c927775d519436fb437a799666e127f61f | 567,510 |
def binary_search(items, item, comparator, lo=0, hi=None):
"""
Does a binary search on a list using a custom comparator
:param items: sorted list of items to search
:param item: item to find
:param comparator: fn(x, y) => 0 if x == y, 1 if x > y, -1 if x < y
:param lo: lower boundary to search, ... | 72098d0804932bfdced39d3b5a4b8ad0fabdcf4e | 567,517 |
def is_requirement(line):
"""
Return True if the requirement line is a package requirement.
Returns:
bool: True if the line is not blank, a comment, a URL, or an included file
"""
return not (
line == '' or
line.startswith('-r') or
line.startswith('#') or
lin... | 6206ebb8096c3f930b451ca279fde07d75333546 | 567,518 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.