content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def split_string(string: str, indices: list) -> list:
"""Splits string between indices.
Notes:
It is possible to skip characters from the beginning and end of the
string but not from the middle.
Examples:
>>> s = 'abcde'
>>> indices = [1, 2, 4]
>>> split_string(s, i... | 0850c4d0f18b70cbd75790e34580ea0567ddea05 | 18,308 |
def fact_iter(n):
"""
1. number of times around loop is n
2. number of operations inside loop is a constant
3. overall just O(n)
>>> fact_iter(5)
120
>>> fact_iter(12)
479001600
>>> fact_iter(10)
3628800
>>> fact_iter(16)
20922789888000
>>> fact_iter(4)
24
""... | 063abee825c8407b276f839543eb6985a90ac653 | 18,316 |
def execute(command, document):
"""Call obj as an command recursively while callable."""
while callable(command):
command = command(document)
return command | 46f34e8eb04a21aee303f3b13088d7bc4be1c16e | 18,322 |
def _model_field_values(model_instance) -> dict:
"""Return model fields values (with the proper type) as a dictionary."""
return model_instance.schema().dump(model_instance) | aeffb9cfc9304dec5672be6169c0909f2afbb3cb | 18,324 |
import re
def is_in_file(path, search_string):
"""
Determine whether a string is contained in a file.
Like ``grep``.
Parameters
----------
path : str
The path to a file.
search_string : str
The string to be located in the file.
"""
with open(path, 'r') as filep:
... | 9912db6a81551e6b930bbf9b3c11168a34b91fe5 | 18,325 |
def rc_one_hot_encoding(encoded_seq):
"""Reverse complements one hot encoding for one sequence."""
return(encoded_seq[::-1, ::-1]) | 7dbd65c384cdd89dbb76698fe792fa85b0ff4206 | 18,327 |
import uuid
def format_jsonrpc_msg(method, params=None, *, notification=False):
"""
Returns dictionary that contains JSON RPC message.
Parameters
----------
method: str
Method name
params: dict or list, optional
List of args or dictionary of kwargs.
notification: boolean
... | 23797940fb64efd7cc39da6871a377268ace57a7 | 18,331 |
import gzip
import base64
def decompress(data):
"""
Decodes a Base64 bytes (or string) input and decompresses it using Gzip
:param data: Base64 (bytes) data to be decoded
:return: Decompressed and decoded bytes
"""
if isinstance(data, bytes):
source = data
elif isinstance(data, st... | 30dff2aad4facbece190a2b2719fb96b840fd6ee | 18,334 |
from typing import Dict
def largest_valued_key(dic: Dict[str, set]) -> str:
"""Find the key with the largest value."""
biggest_size = -1
biggest_key = None
for key, value in dic.items():
length = len(value)
if length > biggest_size:
biggest_size = length
biggest... | 2d4312217b93560514fb717251028baaeee7a6fe | 18,335 |
def validate_entangler_map(entangler_map, num_qubits, allow_double_entanglement=False):
"""Validate a user supplied entangler map and converts entries to ints.
Args:
entangler_map (list[list]) : An entangler map, keys are source qubit index (int),
value is array
... | 5c329eadd1aa1775e0df403ad5c0fe728e8b2750 | 18,336 |
def keyName(*args):
"""Sort values in order and separate by hyphen - used as a unique key."""
a = [int(i) for i in [*args]] # make sure all ints
a = [str(i) for i in sorted(a)] # sort ints and then return strings
return '-'.join(a) | 4eea1461cc308e8e4491f9c970ee23473e48c5a7 | 18,339 |
def one_quarter_right_rotation_escalators(escalator):
"""
Return the escalator coordinates rotated by 1/4. This assumes the escalator is defined for a 4×4 board.
"""
return ((escalator[0][1], 4 - (escalator[0][0] + 1)), (escalator[1][1], 4 - (escalator[1][0] + 1))) | 22e4dfe3fc63f3cc1e81450b921e5c64c00e841e | 18,343 |
def _decorate_tree(t, series):
""" Attaches some default values on the tree for plotting.
Parameters
----------
t: skbio.TreeNode
Input tree
series: pd.Series
Input pandas series
"""
for i, n in enumerate(t.postorder()):
n.size = 30
if n.is_root():
... | 2e7a14c19882938a6b6132c8a09764ab641f2be2 | 18,346 |
def format_response(resp, body):
"""Format an http.client.HTTPResponse for logging."""
s = f'{resp.status} {resp.reason}\n'
s = s + '\n'.join(f'{name}: {value}' for name, value in resp.getheaders())
s = s + '\n\n' + body
return s | 5866723df307a66a710bb105dc31ed9662780d78 | 18,350 |
from typing import Tuple
def _should_include(key: str, split_range: Tuple[float, float]) -> bool:
"""
Hashes key to decimal between 0 and 1 and returns whether it falls
within the supplied range.
"""
max_precision_order = 10000
decimal_hash = (hash(key) % max_precision_order) / max_precision_o... | 28cb494f5ca4681d04d3568b0c5e74a1e4d28ee3 | 18,355 |
def extendedEuclideanAlgorimth(a, b):
"""
Compute the coefficients of the bezout's identity.
Bezout's identity: for integer a and b exist integers x and y such that
a * x + b * y = d, where d = gcd(a, b).
Parameters
----------
a: int
One of the numbers used for compute the coef... | 37f5cd45254e358bc0c0c267d2b1d77351d04711 | 18,356 |
def make_vlan_name(parent, vlan_id):
"""
Create a VLAN name.
Parameters
----------
parent : str
The parent interface.
vlan_id :
The vlan id.
Returns
-------
str
The VLAN name.
"""
return '{}.{}'.format(parent, vlan_id) | 52793977737792726066de674d3da854bd3cf129 | 18,358 |
def index_to_coord(index):
"""Returns relative chunk coodinates (x,y,z) given a chunk index.
Args:
index (int): Index of a chunk location.
"""
y = index // 256
z = (index - y * 256) // 16
x = index - y * 256 - z * 16
return x, y, z | 35c3aa7efdd9d820c1e8ca1e269d74a4b7d082ca | 18,359 |
import torch
def orthogonal_random_matrix_(rows, columns, device):
"""Generate a random matrix whose columns are orthogonal to each
other (in groups of size `rows`) and their norms is drawn from the
chi-square distribution with `rows` degrees of freedom
(namely the norm of a `rows`-dimensional vector ... | bfd40861fb78ecebe7cfceeaf5ab32044cf1a8dc | 18,361 |
def parse_pairs(pairs):
"""Parse lines like X=5,Y=56, and returns a dict."""
# ENST00000002501=0.1028238844578573,ENST00000006053=0.16846186988367085,
# the last elem is always ""
data = {x.split("=")[0]: x.split("=")[1] for x in pairs.split(",")[:-1]}
return data | f39c329e74ec0e749754386cbffbea186ba43a3c | 18,363 |
def drop_peaks(dataframe,data,cutoff):
"""
Filters out the peaks larger than a cut-off value in a dataseries
Parameters
----------
dataframe : pd.DataFrame
dataframe from which the peaks need to be removed
data : str
the name of the column to use for the removal of peak values
... | d645b8519a7da9d4dff588ccc1bbf50ecc801d34 | 18,366 |
def decap(df, neck, end_func=None):
"""
Separate the head from the body of a dataframe
"""
if end_func is None:
end_func = lambda h, b: len(b) - 1
head = df.iloc[:neck]
body = df.iloc[neck:]
end = end_func(head, body)
body = body[:end]
return head, body | 06da0736ce37308a2794722ddc502789fd9a0a5e | 18,368 |
def get_maximal_alignment(address):
"""
Calculate the maximal alignment of the provided memory location.
"""
alignment = 1
while address % alignment == 0 and alignment < 256:
alignment *= 2
return alignment | efd24a7030b968d9f7630390077b3a0642fd30a2 | 18,374 |
def intersection(iterableA, iterableB, key=lambda x: x):
"""Return the intersection of two iterables with respect to `key` function.
Used to compare to set of strings case insensitively.
"""
def unify(iterable):
d = {}
for item in iterable:
d.setdefault(key(item), []).append... | 1e38162dc7508e5621618b089d64be8ae4b57669 | 18,378 |
def get_location_from_action_name(action):
"""Return the location from the name of the action"""
if action.startswith('at_'):
location_name = action[len('at_'):]
elif action.startswith('go_to_'):
location_name = action[len('go_to_'):]
elif action.startswith('look_at_'):
location_... | c918630b03c4b233d6b976ebb31fd295a94dee2b | 18,380 |
import itertools
def subsequences(iterable, seq=2):
"""Return subsequences of an iterable
Each element in the generator will be a tuple of `seq` elements that were
ordered in the iterable.
"""
iters = itertools.tee(iterable, seq)
for i, itr in enumerate(iters):
for _ in range(i):
... | da436028d37f74729a2b5c2dfb74716da61efb2d | 18,382 |
def sign(x):
"""
Return 1 if x is positive, -1 if it's negative, and 0 if it's zero.
"""
if x > 0:
return 1
elif x < 0:
return -1
else:
return 0 | 7625903a16419c8914b92c2c1273c34bd646d9d2 | 18,383 |
def copy_metadata(nb_data):
"""Copy metadata of notebook
Args:
nb_data (JSON): a json data load from jupyter notebook
Returns:
dict: metadate copied from nb_data
"""
metadata = dict()
metadata["metadata"] = nb_data["metadata"]
metadata["nbformat"] = nb_data["nbformat"]
... | bfd0c0e53097b4a47150b5a2d7a35fabbcc03098 | 18,387 |
def get_html_name(form, name):
"""Return the name used in the html form for the given form instance and field name. """
return form.add_prefix(name) | 8ae42f5abbcf9e8131b0edb6868414e1af5a29d8 | 18,388 |
def to_lower_camel_case(string):
"""
Converts string to lower camel case.
Args:
string (str): input string in any case
Returns:
str: string converted to lower camel case
Example:
>>> to_lower_camel_case('snake_case_string')
'snakeCaseString'
"""
components ... | 6d8ba39e1de7fdc0453712d6bbc0221685163ad5 | 18,389 |
def ip_key(ip):
"""
Return an IP address as a tuple of ints.
This function is used to sort IP addresses properly.
"""
return tuple(int(part) for part in ip.split('.')) | 69082fe54aae5b060cbc95b5290d73fdb2bf275b | 18,392 |
def df_move_column(df, column_name, new_location):
"""Move a dataframe column to a new location based on integer index
"""
df = df.copy()
columns = df.columns.tolist()
columns.insert(new_location, columns.pop(columns.index(column_name)))
return df[columns] | 2b978af20f9cc8d89c91450e136e46947028f741 | 18,400 |
def beta2_mu(four_mass2_over_q2_):
"""Calculate β_μ^2"""
return 1.0 - four_mass2_over_q2_ | 64770e7e023fe6fff7a3391a8d6385f0cddd6dde | 18,402 |
import hashlib
def md5_for_file(filename, block_size=2**20):
"""
Calculates the MD5 of the given file. See `source <http://stackoverflow.com/questions/1131220/get-md5-hash-of-a-files-without-open-it-in-python>`_.
:param filename: The file to read in
:param block_size: How much of the file to r... | a972b43c7fc15e92c897101b9bff23e0392152be | 18,406 |
from pathlib import Path
def find_root_folder(start_file: Path):
"""
Find the root package folder from a file within the package
"""
# Get starting location
package_path = start_file if start_file.is_dir() else start_file.parent
# Check current location isn't a path
if not (package_path /... | c3e7e2af6d7ec40359ca30443b0323044314fe32 | 18,409 |
import importlib
def get_simulator_api(api, reload=False):
""" Get the BioSimulators API for a simulator
Args:
api (:obj:`str`): module which implements the API for the simulator
reload (:obj:`bool`, optional): whether to reload the API
Returns:
:obj:`types.ModuleType`
"""
... | 088b129ce31d246af4d85800d0192ee3cf44092e | 18,419 |
def list_intersection(lst1, lst2):
"""
Intersection of two lists.
From:
https://stackoverflow.com/questions/3697432/how-to-find-list-intersection
Using list comprehension for small lists and set() method with builtin
intersection for longer lists.
Parameters
----------
lst1, lst2 :... | bc9a416dd4fb4d143308c95407ef7f8b5ce52fc0 | 18,427 |
def longest_in_list( l:list ) ->str:
"""
Returns the longest item's string inside a list
"""
longest :str = ''
for i in range( len(l) ):
if len( str(l[i]) ) > len(longest):
longest = l[i]
return longest | 43de1bd7a237b336cdb5cb90eb7ecaa6663be2de | 18,433 |
import logging
def add_console_handler(formatter, level=logging.INFO):
"""Creates and returns a handler that streams to the console at the logging level specified"""
ch = logging.StreamHandler()
ch.setFormatter(formatter)
ch.setLevel(level)
return ch | 2bfdfe427ea32ed206f36f78a105437b98014f67 | 18,434 |
from typing import Dict
def create_query_string(query_dict: Dict[str, str]):
"""Create query string with dictionary"""
query_string = '?'
for key, item in query_dict.items():
query_string += '{}={}&'.format(key, item)
return query_string[:-1] | a83ded8a5cc516ea79547c161e84fc4caec4fe71 | 18,435 |
def pytest_ignore_collect(path, config):
""" Only load tests from feature definition file. """
if path.ext != ".toml":
return True
return False | 80d193ff28a7f2f903ec5d4dd09d13973e066dcf | 18,446 |
import math
def circle_touching_line(center, radius, start, end):
""" Return true if the given circle intersects the given segment. Note
that this checks for intersection with a line segment, and not an actual
line.
:param center: Center of the circle.
:type center: Vector
:param radius: R... | 51dd2c4d9f07bb68e326a7ea1d2c25e65fe93513 | 18,453 |
import functools
import operator
def prod(collection):
"""Product of all elements in the collection"""
return functools.reduce(operator.mul, collection) | 225c9d437e1ade873de26bb6ef6b157daa3545a0 | 18,457 |
def limit(self, start_or_stop=None, stop=None, step=None):
"""
Create a new table with fewer rows.
See also: Python's builtin :func:`slice`.
:param start_or_stop:
If the only argument, then how many rows to include, otherwise,
the index of the first row to include.
:param stop:
... | b101ed9eba1b5771b7acbd555ae41c4365cea1d3 | 18,471 |
def format_datetime_iso(obj):
"""Return datetime obj ISO formatted."""
return obj.strftime('%Y-%m-%dT%H:%M:%S') | 88d87a81d387f7dab906b2a9775208a1b82b3fce | 18,475 |
import json
import random
import time
from typing import Union
import pathlib
def save_json_file(json_file: Union[str, pathlib.Path], dictionary_to_save: dict, retries: int = 3) -> None:
"""
Writes a new JSON file to disk. If the file exists, it will be overwritten.
:param json_file: JSON file to write in... | 6145c3b8d68bcdeaa5db9ec7771eebcdb65461ab | 18,485 |
def convert_empty_value_to_none(event, key_name):
""" Changes an empty string of "" or " ", and empty list of [] or an empty dictionary of {} to None so it will be NULL in the database
:param event: A dictionary
:param key_name: The key for which to check for empty strings
:return: An altered dictionar... | 075b6fb14f22e201392539623454e0166b4c7448 | 18,490 |
def build_env_file(conf):
"""
Construct the key=val string from the data structurr.
Parameters
----------
conf : dict
The key value's
Returns
-------
str
The key=val strings.
"""
return "\n".join(['{}={}'.format(k, v) for k, v in conf.items()]) | aa6dca869becec055392fef010e504559f276bb7 | 18,492 |
import hashlib
def get_md5(str_):
"""
hash function --md5
:param str_:origin str
:return:hex digest
"""
md5 = hashlib.md5()
md5.update(str_.encode('utf-8'))
return md5.hexdigest() | fb905d673ac7407fcaa3f70a822620dd38dbb5e6 | 18,495 |
def stringify_value(value):
"""Convert any value to string.
"""
if value is None:
return u''
isoformat = getattr(value, 'isoformat', None)
if isoformat is not None:
value = isoformat()
return type(u'')(value) | 47c3939f06a667eb8e5f8951be827ea1dff325b7 | 18,497 |
def make_linear_function(p1,p2):
"""
Returns the linear function defined by two points, p1 and p2
For example make_linear_function((1,3), (2,5))
returns the function f(x) = 2x + 1.
"""
m = (p2[1]-p1[1])/(p2[0]-p1[0])
k = p1[1] - p1[0] * m
return lambda x: x * m + k | a358e1757cfa1cd8e7e0a729027659349ec22985 | 18,502 |
def time2mins(time_taken):
"""Convert time into minutes.
Parameters
----------
time_taken : float
Time in seconds
Returns
-------
float
Minutes
"""
return time_taken / 60. | 11877ff009e010f6fa633abf0aff87aabbd44ce0 | 18,509 |
import sympy
import six
def _coprime_density(value):
"""Returns float > 0; asymptotic density of integers coprime to `value`."""
factors = sympy.factorint(value)
density = 1.0
for prime in six.iterkeys(factors):
density *= 1 - 1 / prime
return density | 1017464c175a68e1ae510a8edf3d2f4ee4b74ba5 | 18,511 |
def get_binary_representation(n, num_digits):
"""
Helper function to get a binary representation of items to add to a subset,
which combinations() uses to construct and append another item to the powerset.
Parameters:
n and num_digits are non-negative ints
Returns:
a num_digit... | 2b2d1e8bc4f964d805e48a8dd0525ee19aa7ab4e | 18,514 |
def merge(list1, list2):
"""
Merge two sorted lists.
Returns a new sorted list containing those elements that are in
either list1 or list2.
Iterative, because recursive would generate too many calls for
reasonably sized lists.
"""
merged_list = []
copy_list1 = list(list1)
c... | c4398faf890337d10400f9c71b49f2de7376f826 | 18,521 |
def string_address(address):
"""Make a string representation of the address"""
if len(address) < 7:
return None
addr_string = ''
for i in range(5):
addr_string += (format(address[i], '02x') + ':')
addr_string += format(address[5], '02x') + ' '
if address[6]:
addr_strin... | 23995bca8ce57ae341113eb9273ab2fcca7fbe96 | 18,525 |
from typing import Callable
def combine_predicates(*predicates: Callable[..., bool]) -> Callable[..., bool]:
"""
Combine multiple predicates into a single one. The result is true only if all of the predicates are satisfied.
"""
def check_all(*args, **kwargs) -> bool:
return all(map(lambda f: ... | 5805c4bb884dc7c2797353d258bf29c35104b95d | 18,527 |
def getLineAndColumnFromSyntaxItem(syntaxItem):
"""
Returns a tupel of the line and the column of a tree node.
"""
line = False
column = False
while line is False and column is False and syntaxItem:
line = syntaxItem.get("line", False)
column = syntaxItem.get("column", False)
... | 9094b11865b7d8a477df7b5f480673c06c1981c7 | 18,530 |
import fnmatch
def fnmatch_mult(name,patterns):
"""
will return True if name matches any patterns
"""
return any(fnmatch.fnmatch(name,pat) for pat in patterns) | d2edf50c42405c4231d075f232b4b9ac7d3a180a | 18,533 |
def prepend_non_digit(string):
"""
Prepends non-digit-containing string.
Useful in combination with built-in slugify in order to create strings
from titles that can be used as HTML IDs, which cannot begin with digits.
"""
if string[:1].isdigit():
string = "go-to-{0}".format(string)
r... | 34594a7839a40477a986d284986b2f1eb1e1d994 | 18,534 |
def patch(attrs, updates):
"""Perform a set of updates to a attribute dictionary, return the original values."""
orig = {}
for attr, value in updates:
orig[attr] = attrs[attr]
attrs[attr] = value
return orig | ec8b8e4862afdc556512a848882a933214a747b4 | 18,535 |
def ge(x, y):
"""Implement `ge`."""
return x >= y | e1aa97783f3f4cc64c0f833fec053c85c506e1e1 | 18,536 |
def _sanitize_feature_name(feature_name: str) -> str:
"""Returns a sanitized feature name."""
return feature_name.replace('"', '') | 7f232680502819d5054ee6852ca4a824565839cc | 18,546 |
def sanitise_db_creds(creds):
"""Clean up certain values in the credentials to make sure that the DB driver
doesn't get confused.
"""
tmp = {}
for name, value in creds.items():
if name == 'port':
tmp[name] = int(value)
elif name == 'password':
tmp['passwd'] = ... | a5f3e8d4aab2f5959a8a03833f7c3be653234126 | 18,547 |
import pickle
def save_model(model, filepath="models/"):
"""Save a trained model to filepath (e.g. 'model/filename')
Args:
model (var): variable-held trained model (e.g. Linear_Regression)
filepath (str): path to save model (excluding file extension)
Returns:
msg (str): confirmat... | 3de1495e4e207998f251a1977e8e21d0af1b0402 | 18,561 |
def django_testdir_initial(django_testdir):
"""A django_testdir fixture which provides initial_data."""
django_testdir.project_root.join("tpkg/app/migrations").remove()
django_testdir.makefile(
".json",
initial_data="""
[{
"pk": 1,
"model": "app.item",
... | 1b99e811945bb10a3d74e3a1b2cfe5d52fb2a27b | 18,563 |
def find_brackets(smiles):
"""
Find indexes of the first matching brackets ( "(" and ")" ). It doesn't check if all brackets are valid, i.e. complete.
Parameters
----------
smiles
Returns
-------
list
Index of first and second matching bracket.
"""
indexes = []
n_b... | b1b8d40e6f04d7a903b55b85db98a35fb8eab10c | 18,568 |
def get_node_name_parts(obj_name):
"""
Breaks different Maya node name parts and returns them:
- objectName: a:a:grpA|a:a:grpB|a:b:pSphere1
- long_prefix: a:a:grpA|a:a:grpB
- namespace: 'a:b
- basename': 'pSphere1'
:param obj_name: str, name of Maya node
:return: tuple(st... | c3c0d47ff7ef791616b93bb0456cb503e4c80140 | 18,572 |
def invert_image(image):
"""
Inverts a binary image
Args:
image: a binary image (black and white only)
Returns:
An inverted version of the image passed as argument
"""
return 255 - image | eb466971c77fae2a57ad86a3b555884865ed404a | 18,574 |
def with_api(func):
"""Decorate a method to use the client() context manager."""
def wrapper(*args):
with args[0].client() as api:
return func(args[0], api, *args[1:])
return wrapper | 9ecbebc9c0599d83d178820ed88d0f6fa5c34ee1 | 18,576 |
import torch
def gelu_quick(x):
""" Approximation of gelu.
Examples:
>>> inputs = torch.rand(3, 2)
>>> assert torch.allclose(gelu_quick(inputs), F.gelu(inputs), atol=1e-2)
References: https://arxiv.org/pdf/1606.08415.pdf
"""
return x * torch.sigmoid(1.702 * x) | 1fc27f052ae9958cab53f499d906c612ef24f3a8 | 18,584 |
from pathlib import Path
def input_custom_variables(string: str, dmvio_folder: str):
""" Replace the following environment variables in the given string.
if ${EVALPATH} is inside string it is replaced with the path to the evaltools (the folder where this file is
located).
${DMVIO_PATH} is replaced wit... | 0766874154192a885e49f50f14b5ab9038788ced | 18,588 |
def _GetLines(line_strings):
"""Parses the start and end lines from a line string like 'start-end'.
Arguments:
line_strings: (array of string) A list of strings representing a line
range like 'start-end'.
Returns:
A list of tuples of the start and end line numbers.
Raises:
ValueError: If th... | d59fc282ef5f7dca251de8b3015eaebd18230f9f | 18,590 |
def match_includes_reaction_center(train_mode, match, atoms_core):
"""
Determindes whether a substructure match includes the full reaction center.
Parameters
----------
train_mode: Literal["single_reactant", "transition_state"]
Mode in which diagram was constructed.
match: tuple
... | 1da9d3c7304280d24918046ecc8e88ece078040f | 18,591 |
def _get_num_slices(op_slice_sizes):
"""Returns the number of slices in a list of OpSlice sizes.
Args:
op_slice_sizes: List of list of slice sizes, where the outer list has a list
per op and the inner list is the slice sizes of the op.
Returns:
Integer max number of slices in the list of ops.
""... | 55d7170d4e1318fdd72e8c4e6ab1da30d42640e9 | 18,592 |
def _explode_lines(shape):
"""
Return a list of LineStrings which make up the shape.
"""
if shape.geom_type == 'LineString':
return [shape]
elif shape.geom_type == 'MultiLineString':
return shape.geoms
elif shape.geom_type == 'GeometryCollection':
lines = []
fo... | 689deed3c3674fdc7d0cb12917004bbe9eca2227 | 18,593 |
import random
def packet_loss(P):
"""Adds a uniformly distributed packet loss, returns True if packet to be dropped"""
u = random.uniform(0, 1)
if u < P:
return True
return False | a5a7e3ce2a7b23937a4c23ce498cdd1aa5561841 | 18,594 |
def default_narrative(
end_yr,
value_by,
value_ey,
diffusion_choice='linear',
sig_midpoint=0,
sig_steepness=1,
base_yr=2015,
regional_specific=True,
fueltype_replace=0,
fueltype_new=0,
):
"""Create a default single narrative with a ... | 7076e19af13337d52241c4cd35a6ec3392678d3c | 18,596 |
def reshape_bboxes(bboxes):
"""
Convert bboxes from [x1, y1, x2, y2] to [y1, x1, y2, x2]
bboxes : [num_bboxes, 4]
"""
return [bboxes[:,[1, 0, 3, 2]]] | 23e1b59e77d282d0d9f8a67519bd0933e21c1998 | 18,598 |
import time
def datetime_to_millis(dt):
"""
Convert a ``datetime`` object to milliseconds since epoch.
"""
return int(time.mktime(dt.timetuple())) * 1000 | 91091c6a84a0001d1ee6847b9912b2590f1cc57f | 18,607 |
def ord_prio(prio):
"""Compute the ordinal number of a text priority
:param prio: string
:rtype: integer
"""
return { 'urgmust': 1,
'must' : 2,
'high' : 3,
'medium' : 4,
'low' : 5 }.get(prio, 5) | fb84a9c7d244bd3c2664bb97cb56f5ec23517671 | 18,612 |
def convert_string_to_tuple(creds_string):
"""Recreate a MAAS API credentials tuple from a colon-separated string."""
creds_tuple = tuple(creds_string.split(':'))
if len(creds_tuple) != 3:
raise ValueError(
"Malformed credentials string. Expected 3 colon-separated items, "
"... | a0f0553553733340d276bbb0f01d44d4ff842008 | 18,613 |
def _split_host_and_port(servers):
"""Convert python-memcached based server strings to pymemcache's one.
- python-memcached: ['127.0.0.1:11211', ...] or ['127.0.0.1', ...]
- pymemcache: [('127.0.0.1', 11211), ...]
"""
_host_and_port_list = []
for server in servers:
connection_info = ser... | 2f4544566bb00684b99cbbb796ca4a0246891f08 | 18,617 |
def get_lomb_signif_ratio(lomb_model, i):
"""
Get the ratio of the significances (in sigmas) of the ith and first
frequencies from a fitted Lomb-Scargle model.
"""
return (lomb_model['freq_fits'][i-1]['signif'] /
lomb_model['freq_fits'][0]['signif']) | e3f4d8db9a08926be49725c2a10696ede4e6d1b0 | 18,618 |
def validate(raw):
""" Checks the content of the data provided by the user.
Users provide tickers to the application by writing them into a file
that is loaded through the console interface with the <load filename>
command.
We expect the file to be filled with coma separated tickers :class:`string... | c69b5b4177e11fabc3f70c0388e3b50f56a201b7 | 18,620 |
def expand_qgrams_word_list(wlist, qsize, output, sep='~'):
"""Expands a list of words into a list of q-grams. It uses `sep` to join words"""
n = len(wlist)
for start in range(n - qsize + 1):
t = sep.join(wlist[start:start+qsize])
output.append(t)
return output | 0937f53fa12dded031dec21deb32282c85c904ac | 18,621 |
def convert_thrift_header(thrift_header):
""" returns a dictionary representation of a thrift transaction header """
return {
"actor": thrift_header.actor,
"block_id": thrift_header.block_id,
"business_unit": thrift_header.business_unit,
"create_ts": thrift_header.create_ts,
... | f0554da0c10c464633d19a001ca32a0180c42dd0 | 18,628 |
def _find_exclude_idx(ch_names, exclude):
"""Find the index of all channels to exclude.
If there are several channels called "A" and we want to exclude "A",
then add (the index of) all "A" channels to the exclusion list.
"""
return [idx for idx, ch in enumerate(ch_names) if ch in exclude] | db754d5e92af59563d6ee2004e5470bfe08a0fc1 | 18,629 |
import torch
def compute_jacobian_on_surface(u, v, forward_transform, eps=0.01):
"""
Computes the differentials:
[dX/dv, dY/dv, dX/dv, dX/du, dY/du, dX/du]
for the given projection function) using central differences. u and v are an orthogonal coordinate system on the surface and X, Y, Z are 3D Ca... | 3d0a7a749abeba834fe800365dac1c208e16a87a | 18,631 |
def compute_factorial(n: int) -> int:
"""
Compute n-factorial.
:param n: Number to compute factorial for
:return: n-factorial
"""
if (not isinstance(n, int)) or (n < 0):
raise ValueError("compute_factorial() only accepts non-negative integer values.")
factorial = 1
for i in range... | 75061c245376f09ec01e6bcf018d04e938f419c1 | 18,632 |
def linear_annealing(n, total, p_initial, p_final):
"""Linearly interpolates a probability between p_initial and p_final.
Current probability is based on the current step, n. Used to linearly anneal
the exploration probability of the RLTuner.
Args:
n: The current step.
total: The total number of steps... | 2f79b56efd11477a1f649e9b374891ff09632c7f | 18,633 |
def get_charging_status(battery_id):
"""
Check if the battery is currently charging
:param battery_id: Battery ID/Number e.g. BAT0
:return: bool, True is battery is charging
"""
with open(f'/sys/class/power_supply/{battery_id}/status') as f:
if 'Charging' in f.read():
return... | 18fa1cc07a4338ec526954342383f346f9cd057c | 18,634 |
def _convertToElementList(elements_list):
"""
Take a list of element node indexes deliminated by -1 and convert
it into a list element node indexes list.
"""
elements = []
current_element = []
for node_index in elements_list:
if node_index == -1:
elements.append(current_e... | 750a7a7780dc901b7e00cd8a36fdfd3638005322 | 18,637 |
def get_common_introduced(db_entry, arches):
"""Returns the common introduction API level or None.
If the symbol was introduced in the same API level for all architectures,
return that API level. If the symbol is not present in all architectures or
was introduced to them at different times, return None... | f71d5f91faa5a8553cd85cdbd248dea8052b2fab | 18,641 |
def kf_derivative_wrt_density(kf, n):
"""Computes the derivative of kf with respect to density
It is given by `kf / (3 * n)`
Parameters
----------
kf : array-like
The fermi momentum in fm^-1
n : array-like
The density in fm^-3
Returns
-------
d(kf)/d(n) : array-lik... | 76dd7581f0248a0f7c5f01706cf6f23fcf27f079 | 18,643 |
def extract_phone_number(num, replacement):
"""Takes in the phone number as string and replace_with arg as replacement, returns processed phone num or None"""
phone_num = "".join(i for i in num if i.isdigit())
if len(phone_num) != 10:
phone_num = replacement if replacement == "--blank--" else num
... | cf49aa0f2cea5974feb487385d76349430e3b5f7 | 18,644 |
def get_region_string(point, size=0.1):
"""
Construct a string of coordinates that create a box around the specified point.
Parameters
----------
point : list of float
Latitude and longitude of the specified point.
size : float, optional
Side length of the output square.
Re... | d39da98ebc14224817d4b093875e3fafce143441 | 18,648 |
def _nbits(n, correction = {
'0': 4, '1': 3, '2': 2, '3': 2,
'4': 1, '5': 1, '6': 1, '7': 1,
'8': 0, '9': 0, 'a': 0, 'b': 0,
'c': 0, 'd': 0, 'e': 0, 'f': 0}):
"""Number of bits in binary representation of the positive integer n,
or 0 if n == 0.
"""
if n < 0:
raise... | 11d6367e41273037108680634c63958de6e72730 | 18,649 |
def incrementFilename(filename, increment):
""" add count to filename """
fname = filename.split('.')
finalname= fname[0]+'_'+increment+'.'+fname[1]
return finalname | 972c6434a3746b801aff70190ec82c2fd3de1c20 | 18,652 |
def get_keys(dict):
""" extract the keys from a dictionary """
return dict.keys() | 7c12a9717a4ed57aec53366f60a15f3aa04f672d | 18,655 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.