content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def encode_date(o):
""" Encodes a Python datetime.date object as an ECMA-262 compliant
date string."""
return o.isoformat() | df3fcd5ae1e66a7ac59ad3f9c9ed96743279892b | 649,547 |
def format_discord_link(link: str, guild_id: int):
"""
Format a discord link to a channel or message
"""
link = link.lstrip("<").rstrip(">").rstrip("/")
for prefix in (
f"https://discord.com/channels/{guild_id}/",
f"https://www.discord.com/channels/{guild_id}/",
):
if li... | 5f4a37d90b8f9adcb2483174e1e3ed271dd0ed44 | 649,550 |
def get_species(df):
"""Return species of top hit from input DataFrame
of Mash results."""
try:
species = df.sort_values("Mash-distance").loc[0, "species"]
return species
except KeyError:
print("Can't find the species in the input mash_dict!") | 0df34487353d8461f80ba43b0b2f132e03c7bbff | 649,552 |
def locus_tag(ncrna):
"""
Get the locus tag of the gene, if present.
"""
return ncrna.get("gene", {}).get("locusTag", None) | 76e39c3904e3d2621d253f8f59cd0e8640f18ef7 | 649,553 |
import math
def printXYZDegrees(self):
"""Print X, Y, and Z components in degrees."""
return ("[%f, %f, %f]" % (math.degrees(self.x), math.degrees(self.y), math.degrees(self.z))) | 8f48563c13e170a18b1c9a9e6385a842e307d177 | 649,555 |
import itertools
def fast_filter(msgs):
"""
Grabs an arbitrary subset of 100 messages from the stream.
Convenient for fast testing.
"""
return itertools.islice(msgs, 100, 1100, 10) | b996f0f9e7dfbc437e29407ad4a1eab7afedb79d | 649,558 |
def suspend_ha(fw_conn):
"""Suspend HA
Args:
fw_conn (PanDevice): A panos object for device
Returns:
results (Element): XML results from firewall
"""
command = ('<request><high-availability><state><suspend>'
'</suspend></state></high-availability></request>')
res... | 85b0cae258b29be6cebe83133233d27da0f77e0e | 649,562 |
def round_half_integer(x):
""" Rounds number to nearest floating point half integer.
Args:
x (number): quantity to be rounded
Returns:
float: number rounded to (generally exact) integer or half integer
"""
return round(2*float(x))/2 | e7f148ddd47a719b46d489c9839f3b39beffaa87 | 649,570 |
def _temp_analyze_files(tmpdir):
"""Generate temporary analyze file pair."""
orig_img = tmpdir.join("orig.img")
orig_hdr = tmpdir.join("orig.hdr")
orig_img.open('w+').close()
orig_hdr.open('w+').close()
return str(orig_img), str(orig_hdr) | bf834d958342a29998273197e3df9142c9a6b505 | 649,575 |
def is_all_upper(s):
"""Returns True if the whole of the string s is upper case."""
return sum(c.isupper() for c in s) == len(s) | 05b44185f9a40cdb2a54acd25a2e66845188f852 | 649,576 |
import hashlib
def hash_password_hashlib(password: str) -> str:
"""encrypt user password using hashlib
Args:
password (str): user password
Returns:
str: password encrypted
"""
return hashlib.md5(password.encode('utf-8')).hexdigest() | 3fdbdc98a5aba5eaa447be48590a8a8bed7d4c64 | 649,577 |
def approx_eq(x, y, tolerance=1e-15):
"""Whether x is within tolerance of y."""
return abs(x - y) < tolerance | 8351d9b29a303df488ef2b569727fa3d8a1f0865 | 649,580 |
import typing
def transform_any_str_list(data: typing.Any) -> typing.List[str]:
"""
Helper function for transforming any type to an list of strings split by "\n"
:param data: the data to transform
:return: the transformed data
"""
if type(data) == str:
return data.split("\n")
if ty... | 9b38e6d451dc2a7e0959469e85c43591469c9cb9 | 649,581 |
def node2feature(node_idx, data_shape):
"""Convert node index from CNN activation vector into 3 features including
index of channel, row and column position of the filter.
Return a tuple of (channel index, row index, column index).
"""
#data_size = {'conv1': [96, 55, 55],
# 'conv2': ... | 03e7418da417ca47f604e924d2ef59136fe34c7c | 649,583 |
import itertools
def feature_engineering(df, cat_cols):
"""
This function is used for feature engineering
:param df: the pandas dataframe with train/test data
:param cat_cols: list of categorical columns
:return: dataframe with new features
"""
# this will create all 2-combinations of valu... | acb8729d29b2edf272471c0d63046960f0fffc01 | 649,586 |
def parabola_1D(xdata, a, b, c):
"""
Calculates a parabola of the form: a*(x-b)**2 + c
"""
return a*(xdata-b)**2 + c | 4b0615269136b908651b3c55486935ec283a1ba2 | 649,587 |
def remove_file_extension(file_name):
"""e.g.: remove_file_extension("hi.jpg") == "hi"
It does not mutate file_name (str is immutable anyway)
:param file_name: <str>
:return: it returns the file_name without the extension
"""
return file_name[:file_name.rindex('.')] | b16329451959063b23c92f6bafa46ccdaf0ac3b8 | 649,588 |
import re
def get_assembly_line_pattern(stripped):
"""
Return regexp pattern used for matching regular assembly lines in the file.
Support for stripped and non-stripped versions.
Need to match non-stripped lines:
'0x00007ffff7fbf158 <+120>: and $0xfffffffffffffff8,%r12'
and stripped lines:
... | 527fa2c7f35eae1cfd71fa3a98a85017281ffbb7 | 649,591 |
def active_view(request, view_name):
"""
Sets an HTML class attribute depending on the selection.
:param request: HttpRequest
:param view_name: (str)
:return: (str) HTML class attribute
"""
resolve_view_name = getattr(request.resolver_match, 'view_name', None)
if resolve_view_name is ... | c2773fb42995bb6286605cb49385c2f63bdf2f7a | 649,592 |
def iso_format(datetime):
"""
Generates an ISO formatted datetime based on what the LaunchKey API expects.
This is a standard ISO datetime without microseconds.
:param datetime: datetime.datetime object
:return: ISO formatted string IE: 2017-10-03T22:50:15Z
"""
return datetime.strftime("%Y-%... | 8b98ac0d2accbc9c8be2805886c1805f7e77fe9f | 649,595 |
import time
def epoch_milliseconds(d):
"""Convert a datetime to a number of milliseconds since the epoch."""
return time.mktime(d.timetuple()) * 1000 | 4f66faf9daf425af56c64c875e294c9ef02c7752 | 649,597 |
def get_number_alien_rows(game_settings, starship_height, alien_height):
"""Returns the number of alien rows."""
available_space_y = game_settings.screen_height - (3 * alien_height) - 3 * starship_height
number_alien_rows = int(available_space_y / (2 * alien_height))
return number_alien_rows | c99145704a7cf4bfc6474b9ca078f2f1dbf82915 | 649,600 |
def confirm_delete(profile):
"""Prompt user to enter Y or N (case-insensitive) to continue."""
answer = ""
while answer not in ["y", "n"]:
answer = input("Delete PROFILE '%s' [Y/N]? " % profile).lower()
return answer == "y" | 3df026972ea37775f9bdf0b40d69d65ca64b897a | 649,602 |
def TourTypeDayShift_idx_rule(M):
"""
Index is (start window, tour type, shift length, day, week)
:param M: Model
:return: Constraint index (list of tuples)
"""
return [(i, t, k, j, w) for i in M.WINDOWS
for t in M.activeTT
for k in M.tt_length_x[t]
for j in... | a2ebe1390b07ab5590062fb39e84f14f6043e01c | 649,606 |
def Mc_eta_m1_m2(m1, m2):
"""
Computes the symmetric mass-ratio (eta)
and chirp mass (Mc) from the component masses
input: m1, m2
output: Mc, eta
"""
Mc = (m1*m2)**(3./5.)/(m1+m2)**(1./5.)
eta = m1*m2/(m1+m2)**2
return Mc, eta | e57a65d64cb2f44770c76b8ce37e021b7bc21280 | 649,607 |
def is_native(s):
"""Return True for native strings, i.e. for str on Py2 and Py3."""
return isinstance(s, str) | 1bf9a5a60d61096a651d4e73abec980cbb99e5ce | 649,608 |
import json
def example_json41(example_json_file41):
"""Load the DataCite v4.1 full example into a dict."""
return json.loads(example_json_file41) | bc8abd2cf6f8f6eb765b328f13ed3ccf3941c3d6 | 649,612 |
def add_depend_on(status, name):
"""
Add the names of the packages that depend on the current package.
Parameters
status : dict, main package contents
name : str, current package name
"""
# list for those that dependends on this package
depon = []
for key in status:
# try bl... | 80698e57d530b1f460ee545bf92c5ac74af862a4 | 649,614 |
def MakeGray(rgbTuple, factor, maskColour):
"""
Make a pixel grayed-out. If the pixel matches the `maskColour`, it won't be
changed.
:param `rgbTuple`: a tuple representing a pixel colour;
:param `factor`: a graying-out factor;
:param `maskColour`: a colour mask.
"""
if rgbTuple != mas... | 949e88735522cadc9d7060b630a6b4781c484782 | 649,618 |
async def async_api_reportstate(hass, config, directive, context):
"""Process a ReportState request."""
return directive.response(name="StateReport") | 3ee0b8b8e4ca874a43e9d7cf3aae9b426eda0e43 | 649,621 |
def rotate_axes(xs, ys, zs, zdir):
"""
Reorder coordinates so that the axes are rotated with zdir along
the original z axis. Prepending the axis with a '-' does the
inverse transform, so zdir can be x, -x, y, -y, z or -z
"""
if zdir == 'x':
return ys, zs, xs
elif zdir == '-x':
... | 9e052ba6af47789a50cb55ea2bab8ea2494e5632 | 649,629 |
def CubicIn(start=0.0, finish=1.0):
"""
Cubically increasing, starts very slow : f(x) = x^3
"""
def cubic_in_easing(sprite, delta):
return start + (delta * delta * delta) * (finish - start)
return cubic_in_easing | ff4ce295db2fcb1eac69404a0949eadf38918825 | 649,630 |
def get_message(tweet):
"""
Get the message attribute on a Tweet object.
The attribute available depends on the parameters on the query to Twitter.
"""
try:
message = tweet.full_text
except AttributeError:
message = tweet.text
return message | 7cffb76ee7795095857a48c7780f4362d37869e3 | 649,631 |
import math
def magnitude(v):
"""
Get the magnitude of a vector.
"""
return math.sqrt(sum(v[i] * v[i] for i in range(len(v)))) | 429005042c1794b793c7fd531e406840ec330717 | 649,632 |
def pathFromFileSystem(fspath):
"""
Turn a local filesystem path into a package file path.
(Inside the package metadata, we always store paths in unix format)
"""
return fspath.replace("\\", "/") | 1aedacde20943550591be887cd4641c98e94eab5 | 649,641 |
def dropLabels(collection, feature_type):
"""
Drop labels and return features + labels separately
--args
collection (pandas DF): dataset containing features + labels
feature_type (str): determines which labels to drop
--returns
labels (pandas series): series containing all label names
collection_features (pan... | 1af8c27d2dc58fd99dd0a55a300016f3f3654132 | 649,644 |
from typing import Union
from pathlib import Path
import yaml
def load_config(*args: Union[str, Path]) -> dict:
"""
Load config yaml files from path.
:param args: path(s) of the file(s) containing configuration parameters
"""
config = {}
for filepath in args:
with open(filepath) as fil... | dcb1be810d10731643cb8649a815506387098526 | 649,645 |
import collections
import json
def seq_length_to_json(df):
"""Convert sequence length distribution to JSON object.
Args:
df: DataFrame containing a subset of sequence length.
Returns:
String: A JSON-formatted string for visualization of sequence length distribution.
"""
json... | 7e81df92f412869013b79067ad976c01cda345d3 | 649,648 |
import platform
import unittest
def _requires_unix_version(sysname, min_version):
"""Decorator raising SkipTest if the OS is `sysname` and the version is less
than `min_version`.
For example, @_requires_unix_version('FreeBSD', (7, 2)) raises SkipTest if
the FreeBSD version is less than 7.2.
"""
... | e7c269e3d1596eed92f4e1bb7e64b6091d1e5428 | 649,650 |
def indentation(level, word):
"""
Returns a string formed by word repeated n times.
"""
return ''.join([level * word]) | b4d500767329b06e43803bf95e8c9306bfc870df | 649,657 |
def find_elements_that_sum_to_2020(input: list[int]) -> tuple[int, int]:
"""Find elements of the input that sum to 2020."""
for value in input:
remainder = 2020 - value
if remainder in input:
return value, remainder
raise ValueError("unable to find 2 elements that sum to 202... | c6e5264720cd1ac69df289f81f5d9bce26d3875c | 649,658 |
def validate_strings(*args):
"""
Checks that all given arguments have a string type (e.g. str, basestring,
unicode etc)
Args:
*args: values to be validated.
Returns:
bool: True if all arguments are of a string type. False otherwise.
"""
for arg in args:
if not isins... | 9b7688c2e9cda14405b3f911c123ec54165ce061 | 649,660 |
def forceIterable(x):
"""Forces a non iterable object into a list, otherwise returns itself
:param list x: the object
:return: object as a list
:rtype: list"""
if not getattr(x, '__iter__', False):
return list([x])
else:
return x | c3bfa94fd02502eb4f86a43799cd3c2e638260bf | 649,661 |
def strip_html(response):
"""
Strips HTML header/footer from a response.
This is useful when trying to embed HTML into
an existing page through use of an external API.
"""
return (
response.content.decode("utf-8")
.replace("<!DOCTYPE html>\n\n<html>", "")
.replace("</html... | 7016f8d365d6843a2399af068ccadb54d3c5a114 | 649,667 |
import torch
def scatter(tensor, devices, chunk_sizes=None, dim=0, streams=None):
"""Scatters tensor across multiple GPUs.
Arguments:
tensor (Tensor): tensor to scatter.
devices (Iterable[int]): iterable of ints, specifying among which
devices the tensor should be scattered.
... | e3b1260b3fe199ccdbab75d52a05f6991a623554 | 649,668 |
from typing import Tuple
def calculate_unmatched_exposure(ub: list, ul: list) -> Tuple:
"""Calculates worse-case exposure based on list
of (price, size)
returns the tuple (profit_if_win, profit_if_lose)
The worst case profit_if_win arises if all lay bets are matched and the selection wins.
The wo... | abf5379785c46bfd95b968e0e78c4bfde0e3f955 | 649,672 |
import hashlib
def alternative_hash(value):
"""Quick way of doing a hash.
This used to be hash(), but in Python 3 it is seeded and returns
different values.
Security is not an issue here so md5 is used as its cheap.
"""
return hashlib.md5(repr(value).encode('utf-8')).hexdigest() | 0aea265ba8eba124ca8e50143fc74c2865f0977d | 649,674 |
from typing import Callable
import click
def base_vwq_url_option(command: Callable[..., None]) -> Callable[..., None]:
"""
An option decorator for choosing the base VWQ URL.
"""
click_option_function = click.option(
'--base-vwq-url',
type=click.STRING,
default='https://cloudrec... | bc77fc116ef302a447a2e88db48f30217df41504 | 649,683 |
import getpass
def handle_credentials(email,password,prompt="Password: "):
"""
Sort out email and password for accessing Galaxy
Arguments:
email (str): Galaxy e-mail address corresponding to the user
password (str): password of Galaxy account corresponding to
email address; if None th... | bc0d309b9d72ed201c0a641c456439bca0d3992b | 649,686 |
import smtplib
def get_server_reference(
username, smtp_password, aws_smtp_endpoint, aws_smtp_port, **kwargs):
"""
Returns smtplib.smtp reference using the specified parameters.
Call sendmail on the returned reference to send emails.
See the example configuration file for explanations on wher... | 878080608a513887fce905ba036940acbc2d15d8 | 649,690 |
from typing import Iterable
from typing import AnyStr
from typing import Set
def prepare_selected_fields(fields: Iterable[AnyStr], default: Set[AnyStr]) -> Set[AnyStr]:
"""Check for selected fields of the query.
:param fields: Iterable object with all field names that should be selected by the query
:par... | 2ac71b9fe59a3bede6a7c95847a4e54635d979da | 649,694 |
def qualified_name(object_instance):
"""Return the fully qualified type name of an object.
:param object_instance: Object instance.
:return: Fully qualified name string.
"""
if hasattr(object_instance, '__module__'):
return object_instance.__module__ + '.' + type(object_instance).__na... | f3b909b08603391c1661c05fa2ba34e848483a6a | 649,702 |
import hashlib, base64
def get_hashing(string_repr, length=None):
"""Get the hashing of a string."""
hashing = base64.b64encode(hashlib.md5(string_repr.encode('utf-8')).digest()).decode().replace("/", "a")[:-2]
if length is not None:
hashing = hashing[:length]
return hashing | 93e35f706087a1d4dfc0842797d65e8863b0b818 | 649,706 |
def bce_loss(input, target):
"""
Numerically stable version of the binary cross-entropy loss function.
As per https://github.com/pytorch/pytorch/issues/751
See the TensorFlow docs for a derivation of this formula:
https://www.tensorflow.org/api_docs/python/tf/nn/sigmoid_cross_entropy_with_logits
... | d4c9a218049334d5535b01337c83085a88efdf8b | 649,707 |
def best_fit(X, Y):
"""
Calculate linear line of best fit coefficients (y = kx + c)
"""
xbar = sum(X)/len(X)
ybar = sum(Y)/len(Y)
n = len(X) # or len(Y)
numer = sum([xi*yi for xi, yi in zip(X, Y)]) - n * xbar * ybar
denum = sum([xi**2 for xi in X]) - n * xbar**2
if denum != 0:
... | 8e742308975c7147daa01d801430d246582a19ca | 649,711 |
import itertools
def augment_graph(graph, reads_dict, add_reads=False, min_mappings=0):
"""Add read nodes to graph according to read mapping file
Args:
graph (networkx Graph): contig assembly graph
reads_dict (str): Dict of read objects
add_reads: add read nodes if True, otherwise add... | 254bc07b09044e3467c13b85d5bd72f6e76210a6 | 649,713 |
def select_device(on_gpu: bool) -> str:
"""Selects the appropriate device as requested.
Args:
on_gpu (bool): Selects gpu if True.
Returns:
str:
"gpu" if on_gpu is True otherwise returns "cpu"
"""
if on_gpu:
return "cuda"
return "cpu" | a52de9949e549584bd06b31b58051ca3cf29483e | 649,721 |
def get_value(tixi, xpath):
""" Check first if the the xpath exist and that a value is stored
at this place. Returns this value. It returns a:
- float value if the value can be read as a float
- boolean if the value is 'True'/'False',
- otherwise a string
Source :
* TIXI functions: http... | 4fd9ba4e9c90b2f486db16f5a7fd7d3e8b884d1b | 649,722 |
def _find_og_ent(ent, base_ents):
"""Find the original entity referenced by $ref entity."""
id = ent["$ref"]
return next(bent for bent in base_ents if ("$id" in bent) and bent["$id"] == id) | b986452077ae6bd0b86ecdcbdf2a262ac32a8c0f | 649,723 |
import torch
def inner_product_normalized(x, y):
"""
Calculate the inner product between the given normalized vectors,
giving a result between -1 and 1.
"""
return torch.sum(x * y, dim=-1).clamp(min=-1, max=1) | d2b57bba4d04ef4ecbd3aa4c7fa0f4957671c2cd | 649,725 |
def create_queries_subset(eval_size):
"""
Create queries to extract a evaluation and training dataset from a preprocess BigQuery table.
Parameters
----------
eval_size : float
fraction of the data to the evaluation dataset
Returns
-------
eval_query: str
query for the e... | f5e16663549051d9a59fecc74d6440ded9026548 | 649,728 |
def DecodePrivate(curve, bb):
"""
Decode a private key from bytes. Note that the length must match the
expected value (32 bytes for both do255e and do255s) and the value
is verified to be in the proper range (1 to r-1, with r being the
prime order of the do255* group).
"""
sk = curve.SF.Deco... | 6b0f4fb2f3e2ccc8e6deebadfb79cf05afa2315f | 649,729 |
import math
def float_zero(a):
"""Test if a equals zero, a more tolerant version than
:py:func:`float_equal(a, 0)`.
"""
return math.isclose(a, 0, abs_tol=1e-6) | 483c6a3cf5b8805bf7313c0b2f9a7d412d6b2f5c | 649,731 |
def example_distribution_config(ref):
"""Return a basic example distribution config for use in tests."""
return {
"CallerReference": ref,
"Origins": {
"Quantity": 1,
"Items": [
{
"Id": "origin1",
"DomainName": "asdf.... | 0658a70defe608929c6c71032308847ac87033a0 | 649,732 |
def parse_args(arg_list, keywords):
"""
parses a list of args, for either plain args or keyword args
args matching the keyword take the next argument as a value
missing values or duplicate keywords throw ValueError
returns a list and a dict
>>> args, kwargs = parse_args(arglist, ('keya', 'keyb')... | c6b70ada106b9b2e9b9c2ad3a9526450193c0039 | 649,744 |
def helper_parse_if(if_string : str):
"""
Parses the if_string manually to test for equality between its
members.
>>> helper_parse_if("this == this")
True
>>> helper_parse_if("2>3")
False
>>> helper_parse_if("40 >= 40")
True
"""
try:
i... | 9d5c8c445946819b0a7597edaae81f51f74cd06b | 649,745 |
from typing import Union
import uuid
def str_to_uuid(in_uuid: Union[str, uuid.UUID]) -> uuid.UUID:
"""
Convert str uuid to uuid.UUID.
Provided as a convenience function if the identifier must be changed in the future.
Args:
in_uuid (str or uuid.UUID): The uuid to be converted.
Returns:
... | c735a08b2f3e0876ff640afe9b2e710cfaed136f | 649,746 |
def remove_duplicates_list(raw_list):
"""Return a list with just unique items.
Only works with a list of items, not with nested lists.
Args:
raw_list (list): List with duplicate items.
Returns:
unique_list (list):: List with only one instance of each item.
"""
... | bcca231ea46fb7da089196794402c0d1a8b082f7 | 649,748 |
import six
import ast
def dict_or_none(val):
"""Attempt to dictify a value, or None."""
if val is None:
return {}
elif isinstance(val, six.string_types):
return dict(ast.literal_eval(val))
else:
try:
return dict(val)
except ValueError:
return {} | dc64646cc463b301c12f51c7dc87e5991405ee70 | 649,754 |
def addMiddlePoints(p1, p2, n = 2):
""" Function to calculate the middle point between two points
Args:
p1: (Required) set of coordinates of first point
p2: (Required) set of coordinates of second point
n: (Required) number of divisions
"""
x_1 = p1[0]
y_1 = p1[1]
... | af007dc1c80b13d5047bd71dfcf94d08e3b4cb0d | 649,755 |
def mrr(ground_truth, prediction):
"""
Compute Mean Reciprocal Rank metric. Reciprocal Rank is set 0 if no predicted item is in contained the ground truth.
:param ground_truth: the ground truth set or sequence
:param prediction: the predicted set or sequence
:return: the value of the metric
"""
... | 2a2b72a3dbe5897239143c1fae47988beda3797b | 649,762 |
def get_cpe_version(cpe: str):
"""Return the version entry of the given CPE"""
split_cpe = cpe.split(":")
if len(split_cpe) > 4:
return split_cpe[4]
return "" | 11cfc2073e61294e30041619c87323e6d75b1223 | 649,763 |
import math
def round_to_significant(num, sig_figs):
"""Return (rounded_num, format_precision).
rounded_num is num rounded to sig_figs significant figures.
format_precision is the number of digits to format after the decimal.
"""
sig_digit = int(math.floor(math.log10(abs(num))))
sig_digit -= ... | 0d74e29e984a91c9a64625faa5dd586483b8aad4 | 649,764 |
def select_span(cropped_length, original_length, center_point):
"""
Given a span of original_length pixels, choose a starting point for a new span
of cropped_length with center_point as close to the center as possible.
In this example we have an original span of 50 and want to crop that to 40:
... | b6b51833512bcbd31076b45581a805574961235e | 649,765 |
def shift_box(box: list,
x: float,
y: float) -> tuple:
"""
Shift original box by coordinates.
:param box: Original box.
:param x: X shift value.
:param y: Y shift value.
:return: Shifted box
"""
return box[0] - x, box[1] - y, box[2], box[3] | 1ac92038a4e79ae6b9ef6c6bccdaaec5be3ff6d2 | 649,767 |
import time
def datetime_to_timestamp_in_milliseconds(d):
"""convert a naive datetime object to milliseconds since Epoch.
"""
return int(time.mktime(d.timetuple()) * 1000) | 87cdabee20d40f399311a846444cc98d1b878fe4 | 649,769 |
def cubic_farthest_fit_inside(p0, p1, p2, p3, tolerance):
"""Returns True if the cubic Bezier p entirely lies within a distance
tolerance of origin, False otherwise. Assumes that p0 and p3 do fit
within tolerance of origin, and just checks the inside of the curve."""
# First check p2 then p1, as p2 ha... | 8ca693e036ef3740c55dcb49643b54852a395c5e | 649,770 |
def ncread_ts(ncvar, tidx_start=None, tidx_end=None):
"""Read in timeseries [ntime] from a netCDF variable.
:ncvar: (netCDF variable) input variable
:tidx_start: (int) starting index
:tidx_end: (int) ending index
:returns: (numpy array) timeseries data
"""
# read in profile
nsize = ncv... | e19eff9d60231f861cb842aac863cdcdd16efcc3 | 649,772 |
def _sort_dictionary(input: dict, reverse: bool = False) -> dict:
"""Rebuild a dictionary with the same keys and values but where the keys are inserted in sorted order. This can be useful for display purposes."""
sorted_keys = sorted(input, reverse=reverse)
return {k: input[k] for k in sorted_keys} | 251df6050e0b2624bbbc5360f800f5c597da9dfd | 649,773 |
import base64
def decode_authn_string(authn_string):
"""Decodes a hexadecimal authentication string into a MongoDB connnection URI"""
return base64.urlsafe_b64decode(authn_string.encode('utf-8')).decode('utf-8') | dbc4952a140882a621c82c5f639221e60a015f89 | 649,777 |
def get_application_instance_name(application):
"""
Return the name of the application instance.
"""
return "{}-{}".format(application.image.project.name, application.name) | e877677b831740f7bd156dc840593e69e185e411 | 649,778 |
def isiterable(target):
"""
Check if target object is iterable
:param target:
:return: true if target is iterable. Otherwise, return false
"""
try:
iter(target)
except:
return False
else:
return True | c091597444c929fef99d5491f969e617526071db | 649,780 |
def false_positive(y_true, y_pred):
"""
Function to calculate False Positives
:param y_true: list of true values
:param y_pred: list of predicted values
:return: number of false positives
"""
# initialize
fp = 0
for yt, yp in zip(y_true, y_pred):
if yt == 0 and yp == 1:
... | fd66ca4d12c8c2896bc74b0fd45f3bcd689ab3cc | 649,783 |
def edits1(word):
"""
Return all strings that are one edit away
from the input word.
"""
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def splits(word):
"""
Return a list of all possible (first, rest) pairs
that the input word is made of.
"""
return [(word[:i]... | f37960f233bf9c4e6a6ca1d6e217104e3b4ba481 | 649,786 |
def CheckEnforcedChanges(input_api, output_api, committing, enforced):
"""Enforces changes based on the provided rules.
|enforced| is a list of 2-tuples, where each entry is a list of file
names relative to the repository root. If all of the files in
the first list have been changed, then all of the files in t... | 4e693c9aeaed7238bf20f612732105666149f5aa | 649,789 |
def list_concat(*lists):
"""
joins multiple lists into a single list. Always returns a copy.
"""
# base python: lists are concatenated with "+"
ret = list()
for l in lists:
ret.extend(l)
return ret | 10df69a98751341780b019c365bf882adf5236bc | 649,790 |
def _accept_html(accept):
"""
Returns True if the request asked for HTML
"""
return hasattr(accept, 'accept_html') and accept.accept_html() | 754da225788de57cbb2220a3f8590012bd182eb0 | 649,791 |
def _calculate_interconnected_value(vij, vik, vil, vkj, vkk, vkl, vlj, vlk, vll):
"""Calculate an interconnected S-parameter value
Note:
The interconnect algorithm is based on equation 6 in the paper below::
Filipsson, Gunnar. "A new general computer algorithm for S-matrix calculation
... | a40a2c8b49bcf475d8b8ac206fd7a93abe5545a6 | 649,801 |
import cmath
def rotate_by(z: complex, angle: float) -> complex:
"""Rotate z around the origin by an angle"""
return z * cmath.rect(1,angle) | 14952cefcf85674c659de5a8fff3970f12e26696 | 649,803 |
def mapToDict(dictShape, x):
"""
Make a dict over two lists.
Parameters
----------
dictShape : list of any
The labels of the returned dict.
x : list of any
The values of the returned dict.
Returns
-------
dict
Each key in dictShape corresponds to the value i... | 13f01062e667a029c46eb104857f40473c502a20 | 649,804 |
def versiontuple(v):
"""Convert a string of package version in a tuple for future comparison.
:param v: string version, e.g "2.3.1".
:type v: str
:return: The return tuple, e.g. (2,3,1).
:rtype: tuple
:Example:
>>> versiontuple("2.3.1") > versiontuple("10.1.1")
>>> False
... | 4bcc9b368be4eb0d9f906e41797d2793a90c0de2 | 649,807 |
def check_uniqueness_in_rows(board: list):
"""
Check buildings of unique height in each row.
Return True if buildings in a row have unique length,
False otherwise.
"""
for row in board:
row = row[1:][:-1].replace("*", "")
for num in row:
if row.count(num) > 1:
... | c30ea2f1de9c2afe4018913cbec96fe72923e7a3 | 649,810 |
import re
def _clean_word_name(word):
"""Cleans the text for a word name, returns None if no match
Prevents us from adding entries that are just prefixes of suffixes, e.g.
-phobia.
"""
p = re.compile('(^[\w]+[\w-]*[\w]+)')
match = p.search(word)
if match is None:
#Make sure we are... | 0ecb9f43b026dd690f9656ab2c3c3ead262c3c94 | 649,811 |
def _gen_package(overlay, pkg, distro, preserve_existing, collector):
"""This is just a stub. We just add to the collector"""
collector.append(pkg)
# return new installer, name it.
return True, pkg | 81ee11c52a717f5d3b129c971ea9d1a2d4a83304 | 649,814 |
def expose(command=None, add_client=False):
"""
Decorator to expose a function. If add_client is True, the client
object will be added to the command list as first argument.
"""
def decorator(func):
func._toolkit_rpc = command or func.__name__
func._toolkit_rpc_param = (add_client,)
... | 2a5f7201530891816e6f87f6ddfde94208cace97 | 649,815 |
def get_title(title_raw):
"""
Extracts title from raw string
"""
return title_raw.replace('\xa0', ' ').split('\n')[0].split('## ')[1] | 15d4463e506a1f4b7e849ffa43aefeef9c2b9b3b | 649,817 |
from typing import Optional
def _truncate_doc(
doc: str,
max_len: Optional[int] = None,
) -> str:
"""
Truncate a document to max_len by the rough number of tokens
"""
if not max_len:
return doc
if len(doc.split()) > max_len:
doc = " ".join(doc.split()[:max_len])
ret... | e0fe82ece4e206f0023cdf25dbb74a4da8df77ed | 649,821 |
def _maybe_get_and_apply(dictionary, key, apply_fn):
"""Returns the result of apply_fn on the value of the key if not None."""
if key not in dictionary:
return None
return apply_fn(dictionary[key]) | 35407e8a2a64fd32969fff39703075e0f062ecdc | 649,822 |
import torch
from typing import List
import random
def get_indices(targets: torch.Tensor, per_class: bool = True,
count: int = 4, seed: int = 0) -> List[int]:
"""Samples indices to visualize
:param targets: ground truths
:type targets: torch.Tensor
:param per_class: whether count mean... | 9b7aa4420669c1a5f44f16af93fd0f220bb22a05 | 649,831 |
import torch
def NB_log_prob(x, mu, theta, eps=1e-8):
"""
Adapted from https://github.com/YosefLab/scVI/blob/master/scvi/models/log_likelihood.py
"""
log_theta_mu_eps = torch.log(theta + mu + eps)
res = (
theta * (torch.log(theta + eps) - log_theta_mu_eps)
+ x * (torch.log(mu + e... | f105cca7bf095cae8678aceab7fb88d1644aa418 | 649,834 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.