content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def myst_extensions(no_md=False):
"""The allowed extensions for the myst format."""
if no_md:
return [".myst", ".mystnb", ".mnb"]
return [".md", ".myst", ".mystnb", ".mnb"] | 4a71ae74b57ed8a94d751489b6a1ed92818d4edc | 101,125 |
from pathlib import Path
def category_files(category: str) -> list:
"""Helper function to return all filenames in the category directory."""
files = [
x.stem
for x in list(Path(f"pandas_ta/{category}/").glob("*.py"))
if x.stem != "__init__"
]
return files | 37a06c5b2a6c36347666166f4ae86d49d750452e | 101,126 |
import pickle
def unit(name, attribute='gcost'):
"""
Returns Unit resource cost by Unit Name.
:param name: Unit Name
:param attribute: Attribute Value (gcost (default), rcost)
:return: Decoded attribute
"""
file = open('./battlefortune/data/units', 'rb')
output = pickle.load(file)[nam... | ef979053e5e839a0457b94feb5b033d5b324a5d5 | 101,130 |
from typing import Iterable
import itertools
def all_equal(seq: Iterable) -> bool:
"""Check that all elements of a sequence are equal."""
grouped = itertools.groupby(seq)
first = next(grouped, (None, grouped))
second = next(grouped, None)
return first and not second | 262ac0d5f13d838ddec136a5d3b7982d7499b6a7 | 101,132 |
def lcm(num1, num2):
"""Returns the lowest common multiple of two given integers."""
temp_num = num1
while (temp_num % num2) != 0:
temp_num += num1
return temp_num | bdb1c66c2e155fe930ffb84d2657e1536d2387dc | 101,134 |
def get_branch_name(ref: str, ref_prefix='refs/heads/', clean=True, max_len=15):
"""
Get and preprocess the branch name from the reference within a CodeCommit event.
:param ref: As obtained from the CodeCommit event
:param ref_prefix:
:param clean:
:param max_len: Maximal length of the resultin... | 48a12bacbdb2b7d51d61cfd941fa343c04073b97 | 101,136 |
import torch
def least_squares(a, b, rcond=None):
"""
A PyTorch implementation of NumPy's "linalg.lstsq" function
Parameters
----------
a : torch.Tensor
(m,n) "Coefficient" matrix
b : torch.Tensor
(m,) or (m,k) "dependent variable" values
rcond : float
Cutt-off rat... | 676703ff9e9407efe5a11476009dc90dba70db63 | 101,137 |
def _get_mobility_factor_counts_for_reasonable_r(results, method, lower_R=0.5, upper_R=1.5):
"""
Returns the count of mobility factors for which method resulted in an R value between `lower_R` and `upper_R`.
Args:
results (pd.DataFrame): Dataframe with rows as methods and corresponding simulation m... | d7f71cb9383967aae6720a23c4d25daf396487fe | 101,139 |
def create_clip_in_selected_slot(creator, song, clip_length=None):
"""
Create a new clip in the selected slot of if none exists, using a
given creator object. Fires it if the song is playing and
displays it in the detail view.
"""
selected_slot = song.view.highlighted_clip_slot
if creator a... | 675b793b346aa40744b36ea30f6828be06bd49be | 101,143 |
def rows_to_dicts(cur, rows):
"""
Converts cursor result to a list of dicts rather than list of tuples.
Args:
cur: sqlite3 database cursor object
rows (list<tuple>): output of cursor fetch
Returns:
List of dicts where each key is a column name
"""
cols = [col[0] for col i... | 8d6b7f4abbb1b72e3a4bd3340ce35ae5b1f5b4d7 | 101,147 |
def generate_access(metadata):
"""Generates access metadata section.
https://oarepo.github.io/publications-api/schemas/publication-dataset-v1.0.0.html#allOf_i0_allOf_i1_access
"""
return {
'record': 'restricted',
'files': 'restricted',
'owned_by': []
} | d34615e28f752ad77f5519e0f09c299523a60efb | 101,148 |
def with_metaclass(meta, *bases):
"""
Create a base class with a metaclass.
For example, if you have the metaclass
>>> class Meta(type):
... pass
Use this as the metaclass by doing
>>> from sympy.core.compatibility import with_metaclass
>>> class MyClass(with_metaclass(Meta, obje... | a4a9f7d096312f97c7c5af0e5f520bb80313524c | 101,150 |
def camel_to_snake(name):
"""
Converts camelCase to snake_case variable names
Used in the Fleur parser to convert attribute names from the xml files
"""
name = name.replace('-', '')
return ''.join(['_' + c.lower() if c.isupper() else c for c in name]).lstrip('_') | 4ce20f914fefb33a41ca0a0a5fcba27f0b3a84ba | 101,153 |
def get_all_sell_orders(market_datas):
"""
Get all sell orders from the returned market data
:param market_datas: the market data dictionary
:return: list of sell orders
"""
sell_orders = []
for _, market_data in market_datas.items():
for order in market_data:
if not orde... | 47fe504b72d9028d4d2e999ee4b748d9dae7f6ee | 101,156 |
def update_infer_params(
model_configs,
beam_size=None,
maximum_labels_length=None,
length_penalty=None):
""" Resets inference-specific parameters.
Args:
model_configs: A dictionary of all model configurations.
beam_size: The beam width, if provided, pass it to `... | 85c96f32160bc5900f7442f5c1949cd6039bec6c | 101,159 |
def _evaluate_features(features_name: list, features_index: list, config_features_available: bool):
"""
This ensures that (1) if feature names are provided in the config file, one and only one of the
arguments, `features_name` or `features_index`, might be given, and (2) if feature names are
NOT provide... | d2fc9589e007866ea7e5809aceb9998c16d41b81 | 101,161 |
def dataToComponent(data, component):
"""Converts data to the desired component.
Parameters
----------
data : `dict`, `object`
Data from which the component will be constructed. This can be an
dictionary with keys that are exact match for parameters required
by component, or a s... | dd5f58d5ee5a4cb2c81a71940ebd0a8f5af6dd92 | 101,164 |
def _get_certificate(client, vault_base_url, certificate_name):
""" Download a certificate from a KeyVault. """
cert = client.get_certificate(vault_base_url, certificate_name, '')
return cert | 2367367cb0bb7131934d13731dab15ddcdce525b | 101,165 |
def layer_architecture(model):
"""Get a Keras model config as a dictionary.
Strip all info like layer names that are not essential to the definition of
the model.
Parameters
----------
model : dict or keras.engine.training.Model
A Keras model or a dict representing the config of the m... | 59bea7504b7a84e68eae051d0963f9d8cd2ed088 | 101,168 |
import math
def deg2rad(degrees):
"""
Converts degrees to radians.
Args:
degrees: A degree value.
Returns:
The equivalent value in radians.
"""
return math.pi*degrees/180.0 | 28b4088f48b02f979c97e9ee3aae52bab793e73a | 101,171 |
import re
def from_camelcase(inStr):
"""Converts a string from camelCase to snake_case
>>> from_camelcase('convertToPythonicCase')
'convert_to_pythonic_case'
Args:
inStr (str): String to convert
Returns:
String formatted as snake_case
"""
return re.sub('[A-Z]', lambda x:... | 73b876e2eab1361c97acd5b4828db2de384a30c1 | 101,174 |
def flatten_nested_dict(x,
join_str = '/',
prefix = ''):
"""Transforms nested dictionary into a flat dictionary."""
assert isinstance(x, dict)
result = {}
for k, v in x.items():
key = prefix + join_str + k
if isinstance(v, dict):
result.update(flatte... | 44ebd4f88b5c0024ea37aa76de2a065cefb293c4 | 101,177 |
def flip_keypoints(keypoints):
"""
Flipped keypoints horizontally (x = -x)
"""
for i, k in enumerate(keypoints):
keypoints[i, 0] = -keypoints[i, 0]
return keypoints | 2da5e0b3fc2fde35a49b8615fd3fbe8f63fec3f3 | 101,178 |
import fnmatch
def refineGitignore(contents, files):
"""
Ignore only those files which are present in the repository
"""
refinedContents = ""
for exp in contents.split('\n'):
for file in files:
if fnmatch.fnmatch(file, exp):
refinedContents += exp + '\n'
... | 14af785ab70d9970baa6d3ca5c9e578a612389ba | 101,179 |
def dictadd(dict_a, dict_b):
"""
Returns a dictionary consisting of the keys in `a` and `b`.
If they share a key, the value from b is used.
>>> dictadd({1: 0, 2: 0}, {2: 1, 3: 1})
{1: 0, 2: 1, 3: 1}
"""
result = dict(dict_a)
result.update(dict_b)
return result | 59935c5a79280678818926789663f21e13ee4728 | 101,180 |
import json
def json_points(points):
"""
Returns a list of points [(lat, lng)...] as a JSON formatted list of
strings.
>>> json_points([(1,2), (3,4)])
'["1,2", "3,4"]'
"""
return json.dumps(["{0},{1}".format(point[0], point[1]) for point in points]) | 812de51e1e593d7f15054a389cd823fe32a96174 | 101,181 |
import math
def haversine_distance(lat1, lat2, long1, long2):
"""
:param lat1: Point 1's latitude
:param lat2: Point 2's latitude
:param long1: Point 1's longitude
:param long2: Point 2's longitude
Description:
The function returns the haversine (big circle) distances from the two points on earth. Does... | 1c6a6345aad7a5404cf3534c5d16f4574de68d03 | 101,184 |
def iterable(arg):
"""
Make an argument iterable
:param arg: an argument to make iterable
:type: list
:return: iterable argument
"""
if not isinstance(arg, (list, tuple)):
return [arg]
else:
return arg | 96bb2433f8c577ede6b2460829f3ba006f9515ef | 101,187 |
def path_replace(path, path_replacements):
"""Replaces path key/value pairs from path_replacements in path"""
for key in path_replacements:
path = path.replace(key,path_replacements[key])
return path | bceecaf9e8e48fdbcd948d784c9a7e521fdbc31c | 101,195 |
def transfer_result(fut, errors_only=False, process=None):
"""
Return a ``done_callback`` that transfers the result, errors or cancellation
to the provided future.
If errors_only is ``True`` then it will not transfer a successful result
to the provided future.
.. code-block:: python
f... | f8d22a71cd66e1486c2e5e4d8ca93d7047fe1e26 | 101,198 |
def calculate_coverage(filename):
"""
Calculate translation coverage for a .po file
"""
with open(filename, 'r') as f:
lines = f.readlines()
lines_count = 0
lines_covered = 0
lines_uncovered = 0
for line in lines:
if line.startswith("msgid "):
lines_count ... | 706db8b1e65e4f218cd97d98897ce99cbac7b207 | 101,203 |
def create_spreadsheet(service, title):
"""
Create a new spreadsheet.
:param service: Google service object
:param title: Spreadsheet title
:return: Newly created spreadsheet ID
"""
spreadsheet = {
'properties': {
'title': title
}
}
spreadsheet = service.... | 91dd784ffe4cb37087c1f69085824cb616c264bd | 101,205 |
def normalize_baseuri(baseuri: str) -> str:
"""Normalize a baseuri
If it doesn't end in a slash, add one.
"""
if baseuri[-1] != "/":
return baseuri + "/"
return baseuri | 9e3938b84e99b49512d85f54bef6f26b3e8796e9 | 101,208 |
import time
def print_test(method):
"""
Utility method for print verbalizing test suite, prints out
time taken for test and functions name, and status
"""
def run(*args, **kw):
ts = time.time()
print('\ttesting function %r' % method.__name__)
method(*args, **kw)
te... | d92e81c22f7aab9a1227381c9e7f4064ed1ce9cd | 101,210 |
def _make_length_filter_fn(length_name, max_length):
"""Returns a predicate function which takes in data sample
and returns a bool indicating whether to filter by length.
"""
def _filter_fn(data):
return data[length_name] <= max_length
return _filter_fn | 6e16f62f2b0001930321f94e6ac4c316b8bebeed | 101,213 |
def is_disabled(context, name):
"""Whether a specific pattern is disabled.
The context object might define an inclusion list (includes) or an exclusion list (excludes)
A pattern is considered disabled if it's found in the exclusion list or
it's not found in the inclusion list and the inclusion list is ... | a1842b6addf0759ca408718af5584494a5ed6637 | 101,216 |
import heapq
def subtree_nodes_with_edge_length(tree, leaf_y, n):
""" Returns list of length n of leaves closest to sister taxon (minimizing edge weights)
Parameters
----------
tree : treeswift tree object
leaf_y : treeswift node for closest sister taxon
n = number of taxa contained in su... | 131445433a8254e6acecd72561ee1abca8fc3286 | 101,221 |
import codecs
def serializer_with_encoder_constructor(serialization_func, encoder_type='utf-8', encoder_error_mode='strict'):
"""
Wrap a serialization function with string encoding. This is important for JSON, as it serializes objects into
strings (potentially unicode), NOT bytestreams. An extra encoding ... | 602962b13837dcd11255a731cac48ba0e6dd520f | 101,224 |
def get_resolved_fact_keys(conversation):
"""
Returns a list of all the resolved facts for a conversation as string keys
:param conversation: The current conversation
:return: List of all resolved fact names as strings
"""
return [fact_entity_row.fact.name for fact_entity_row in conversation.fac... | e29cc1178cf72d5168411e036449a3cf0f2c3451 | 101,226 |
def rensure(items, count):
"""Make sure there are `count` number of items in the list otherwise
just fill in `None` from the beginning until it reaches `count` items."""
fills = count - len(items)
if fills >= 1:
return [None] * fills + items
return items | d1e9784019f65934227fc657ee99f567ac65e776 | 101,230 |
def num_ancestors(p):
"""
Returns the number of known ancestors of p
Does not include p, so the answer might be 0.
Parameter p: The initial family member
Precondition: p is a Person (and not None)
"""
# Work on small data (BASE CASE)
if p.mom == None and p.dad == None:
retur... | 52f9a9fe32caa03391eae374351b2888edbdbc70 | 101,234 |
def get_types(mol):
"""Returns an array of atomic numbers from an rdkit mol."""
return [mol.GetAtomWithIdx(i).GetAtomicNum() for i in range(mol.GetNumAtoms())] | 27f379c4d54ff0d2bb9d9f59de274fb4bfb412c4 | 101,235 |
def as_list(tup_list):
"""
Turns a tuple-list into a list of the first element of the tuple
@param tup_list is the tuple-list you are converting
@returns the created list
"""
res = []
for elem in tup_list:
res.append(elem[0])
return res | 770f5f4e302e1796f6945507c7f314cf157cc77a | 101,236 |
import torch
def infer(model, inputs):
"""
Using a model to infer outputs from inputs.
Args:
model (Model): a PyTorch model.
inputs (Tensor): inputs to the model.
Returns:
outputs (Tensor): results inferred by the model from inputs.
"""
# switch to evaluate mode
m... | 883bcd3cc4ef9167203afe5d34d08286ea6d8cbe | 101,239 |
def union(list1, list2):
"""
Returns the union of two lists
:param list1: first list
:param list2: second list
:return: A list containing the union over list1 and list2
"""
ret = list1[:]
for i in list2:
if i not in ret:
ret.append(i)
return ret | 14e6dffee90f51f9fb17560b914a0bbcb760a87f | 101,240 |
def column_to_list(data, index):
"""
Função que retorna a coluna de uma lista de listas como uma lista
Argumentos:
data: lista de listas
index: posição (coluna) à ser acessada e retornada
Retorna:
Uma lista com os valores da coluna definida através do ar... | 6fee91ff0130c6c3c1e8f90fb024537a04cce36c | 101,242 |
def reg_tap_cim_to_gld(step, step_voltage_increment):
"""
:param step: CIM setting of voltage regulator, which is a
multiplier of nominal voltage, e.g. 1.0125.
:param step_voltage_increment: voltage step as multiplier of nominal
voltage, e.g. 0.625
... | b0cef47b6f10d7930587a531d06221e126a63304 | 101,246 |
import timeit
def measure_time(func):
"""
Decorator that measures time
"""
def timer(*args, **kwargs):
start = timeit.default_timer()
ret = func(*args, **kwargs)
end = timeit.default_timer()
print("Time[{}] : {}".format(func.__name__, end-start))
return ret
... | 38506dddc4e37f7d68756f12dda860936e53c131 | 101,249 |
def comma_sep(value, precision=0):
"""Convert `int` to #,###.## notation as `str`"""
#https://stackoverflow.com/questions/36626017/format-a-number-with-comma-separators-and-round-to-2-decimal-places-in-python-2
return f"{value:,.{precision}f}" | 766821b2a735c923e32ce5cff6a4b01353e864e2 | 101,252 |
def get_region_id(region):
"""Return Pure region ID from region code.
Example:
- Hong Kong -> #1
- Singapore -> #2
- Shanghai/CN -> #4
"""
regions = {
'HK': 1,
'SG': 2,
'CN': 4,
}
assert region in regions, (
'Region "%s" does not exist.' %... | cfd993b7105e863f8e98d2930dae518d53d4d653 | 101,257 |
import torch
def response_preprocessing(responses: torch.Tensor) -> torch.Tensor:
"""Preprocesses responses
Args:
responses (Tensor): Response tensor.
Returns:
Tensor: Preprocessed responses
"""
# responses = normalize_tensor_by_standard_deviation_devision(responses)
return r... | 7266b76a406a558ecaf6489a3006e60678e05716 | 101,258 |
from typing import Any
def calendars_config_entity(
calendars_config_track: bool, calendars_config_ignore_availability: bool | None
) -> dict[str, Any]:
"""Fixture that creates an entity within the yaml configuration."""
entity = {
"device_id": "backyard_light",
"name": "Backyard Light",
... | b6872ab94695bd6e7f08fcdea5f9811bc65846d2 | 101,267 |
def zip_codes_to_go(target: list, zip_code: list) -> list:
"""finds the zip codes that haven't been used
Args:
target (list): the list of zip codes that you want
zip_code (list): the list of zip codes that you already have
Returns:
list: list of zip codes that you still need
""... | f35ab50d841012d40c1678faa735f63e5f9915f1 | 101,269 |
from sympy.printing.fortran import FCodePrinter
def fcode(expr, assign_to=None, **settings):
"""Converts an expr to a string of fortran code
Parameters
==========
expr : Expr
A SymPy expression to be converted.
assign_to : optional
When given, the argument is used as the name of ... | 8f504707ecc5c7a4951529fa2c45f118be6814db | 101,271 |
from functools import reduce
def getChunk(the_list: list, num: int):
"""
Example:
if the_list: ['a', 'b', 'c', 'd', 'e', 'f'] and num: 3
['a', 'b', 'c', 'd', 'e', 'f'] -> ['a b c', 'b c d', 'c d e', 'd e f']
:param the_list: ['a', 'b', 'c', 'd', 'e', 'f'].
:param num: the number of words in a... | 5f4f80e5b2a3dcf17adaa3ff05b63c7eaab16edf | 101,273 |
def import_dfg_from_rows(rows, parameters=None):
"""
Import a DFG (along with the start and end activities) from the rows of a .dfg file
Parameters
--------------
rows
Rows the DFG file
parameters
Possible parameters of the algorithm
Returns
--------------
dfg
... | 62216287a866ce4426cb1ba6b64ddbeab860d3d0 | 101,274 |
def get_opcode(instruction_bytes):
"""
Returns the 6-bit MIPS opcode from a 4 byte instruction.
"""
op = (instruction_bytes & 0xFC000000) >> (3 * 8 + 2)
return op | 85dab0a35b0e31a3f2f2b5c1f3d5323b1ccf3dae | 101,276 |
def slice_data(data, sub, block, subcond=None):
""" pull symmetric matrix from data block (4D or 5D)
Parameters
----------
data : numpy array
4D array (block, sub, nnode, nnode)
5D array (subcond, block, sub, nnode, nnode)
sub : int
int representing subject to index in d... | 294d10c2d6c681dbb801ccfe6d5e5a4dd259adf1 | 101,277 |
def A000290(n: int) -> int:
"""Squares numbers: a(n) = n^2."""
return n ** 2 | 97849016dd6ec2f24dc173e059a9e69f25652d4a | 101,278 |
def pad_gtin(app_identifier, value):
"""
Pad the value of any GTIN [ AI (01) or (02) ] to 14 digits
in the element string representation.
:param app_identifier: Application identifier.
:param value: The GTIN string - can be 8, 12 or 13 digits.
:return: GTIN string with zeros padded to the left,... | 5463e9ffd1b974b3d0376f481b7baf5862d431ed | 101,280 |
def create_url(event_id: int) -> str:
"""
Return the correct link to the event by its id
:param event_id: id of the event
:return: link to the event
"""
return f'https://olimpiada.ru/activity/{event_id}' | afa3443a158d00b9480adb358a16fc37125ec9de | 101,282 |
def oposto(a):
"""
Faz a negação do literal de acordo com os moldes do algoritmo.
:param a: literal
:return: negação do literal
"""
if a[0] == '~':
aux = a[1:]
else:
aux = ''.join(['~', a])
return aux | d32a6b428ea276d11f85d6df5a17f7bef280327e | 101,290 |
def read_requirements_file(filename):
"""Read pip-formatted requirements from a file."""
with open(filename, 'r') as f:
return [line.strip() for line in f.readlines()
if not line.startswith('#')] | 3e72cadf3dd2aa61de023861e4d7b6ec448b90b0 | 101,292 |
import base64
def uuid_to_b32(uuid_obj):
"""
Convert UUID object to a b32 string
:param uuid_obj: UUID object
:return: b32 string
"""
return base64.b32encode(uuid_obj.bytes).decode().replace("=", "").lower() | 8f4ae816b1cb08967470b2913cf5ee34e2a8e440 | 101,295 |
def compare(name, first, second, bfr):
"""Differentiate 'repeat..until' from '*..end' brackets."""
brackets = (bfr[first.begin:first.end], bfr[second.begin:second.end])
return (brackets[0] == "repeat") ^ (brackets[1] == "end") | 277aaf22e452c7d5c7292ccf233d08b21d3bb90e | 101,301 |
def _wrap_close_transport(channel, transport):
"""
Wrap a Channel or SFTPFile object so its close() method also closes
the underlying Transport.
"""
def close():
""" Close this object and the underlying Transport """
channel._orig_close() # pylint: disable=protected-access
... | 064c570e329fa2841cbdeffa941e83b9225a9fd3 | 101,306 |
def conv_output_length(input_length, filter_size, stride, pad=0):
"""Helper function to compute the output size of a convolution operation
This function computes the length along a single axis, which corresponds
to a 1D convolution. It can also be used for convolutions with higher
dimensionalities by us... | 43a563cf422e6ba4f7989f9b55a4d17ca9c5b215 | 101,308 |
import inspect
def get_functions(mod):
"""
Get a list of functions for the given module.
:param mod: The module to inspect for functions.
:type mod: types.ModuleType
:return: The list of functions.
:rtype: list[types.FunctionType]
"""
return [o[0] for o in inspect.getmembers(mod, insp... | 78a7807760086b65aefdc45be7c7c39d95e5ba9d | 101,316 |
def flatten_card(ast):
"""Flatten a card AST node into a string."""
string = ast.front_demarcator_token.text \
+ ast.front_text \
+ ast.back_demarcator_token.text \
+ ast.back_text
return string | 627d17de37313f12a7e65e8694ebfbcac83c8f0a | 101,317 |
import requests
def api_get_courses(srcdb):
"""
Return the API response for a search for all CU Boulder courses.
"""
url = "https://classes.colorado.edu/api/?page=fose&route=search"
data = {
"other": {
"srcdb": srcdb,
},
"criteria": []
}
resp = requests.... | 461899123c0f03674b66fef39063b7df9081e3c9 | 101,320 |
import glob
def find_files(pattern):
"""Find files matching pattern"""
return glob.iglob(pattern) | 3cd1ffedad56c98bdafd4aa1bdde4fd3a3f9a53b | 101,323 |
from typing import TextIO
from typing import List
def parse_tsv(file: TextIO) -> List[List[str]]:
"""Parse a TSV file into a list of lists of strings."""
return [
list(line.strip().split('\t'))
for line in file
] | ddfab5ab3fff3318f316f161855ee28d93d53c2a | 101,327 |
import random
def choose(argv):
"""Randomly choose one of multiple things. Usage: choose <thing1> <thing2> [thing3] ..."""
if len(argv) > 2:
return 'I choose ' + random.choice(argv[1:]) | 14c82ff4b740bdb1016f484aa32d46444b41484c | 101,333 |
import re
def normalize_hostname_to_rfc(mystr):
"""
Given a hostname, normalize to Nextdoor hostname standard
Args:
mystr (str): hostname to normalize
Returns:
normalized hostname
Details:
* lower everthing
* delete anything which is not alphanumeric
* compress mul... | ce6d6fd07ba12ac28f0d96bb4ee3dc0345e7bcd4 | 101,340 |
def is_aba(aba_str):
"""Returns true if 3 character string is of the form ABA"""
if len(aba_str) != 3:
raise Exception
return aba_str[0] == aba_str[2] and aba_str[0] != aba_str[1] | cbd5b463ae5af9816047811f1ebaae59c4e7cbe7 | 101,341 |
def _transitions(state, policies):
"""Returns a list of (action, prob) pairs from the specified state."""
if state.is_chance_node():
return state.chance_outcomes()
else:
pl = state.current_player()
return list(policies[pl].action_probabilities(state).items()) | cdbba6b2e7ea6d25e89d0132c326d9b7147d9788 | 101,344 |
import json
def load_json_file(filepath):
"""Load content of json-file from `filepath`"""
with open(filepath, 'r') as json_file:
return json.load(json_file) | 578575a6398c3e803613b8b4277043bcab08191c | 101,348 |
def echo(s):
"""repeats a string twice"""
return s + s | 534fbf0464261a35e929518c245dc3e32e09977a | 101,351 |
def build_transcript(transcript, build='37'):
"""Build a transcript object
These represents the transcripts that are parsed from the VCF, not
the transcript definitions that are collected from ensembl.
Args:
transcript(dict): Parsed transcript information
Returns:
... | 485a8f3bee6030c7a66f50be2fbd1a4c1acf424b | 101,352 |
def join_ensembles(ensemble_list):
"""Join several ensembles using a set theory union.
Parameters
----------
ensemble_list : list of :class:`.Ensemble`
list of ensembles to join
Returns
-------
:class:`.Ensemble`
union of all given ensembles
"""
ensemble = None
... | 04ec37bcb1c3013b86c25a379f91b88692600361 | 101,354 |
def fixStringLength(s, n, ctd='...', alignRight = True):
"""
Forces a string into a space of size `n`, using continuation
character `ctd` to indicate truncation
"""
try:
return ( s[:(n-len(ctd))] + ctd if len(s) > n
else s.rjust(n) if alignRight
else s.l... | dfb927f5b5861a5153279817fb14a4496bab2bbb | 101,356 |
def _base_model_from_kwargs(cls, kwargs):
"""Helper for BaseModel.__reduce__, expanding kwargs."""
return cls(**kwargs) | bd7a991c891172cac334541b9ccee82c5489f4ad | 101,362 |
def get_requires(filename):
""" Function used to read the required dependencies (e.g. in 'requirements.txt')
"""
requires = []
with open(filename, "rt") as req_file:
for line in req_file:
requires.append(line.rstrip())
return requires | 4c4df470846a2812e79fe5349371c287b3a5ea95 | 101,363 |
def _build_synset_lookup(imagenet_metadata_file):
"""Build lookup for synset to human-readable label.
Args:
imagenet_metadata_file: string, path to file containing mapping from
synset to human-readable label.
Assumes each line of the file looks like:
n02119247 black fox
n021193... | afa342c78cb0db96e3c8eafdda6ee12b19b9ed1f | 101,366 |
def get_seeds_from_cache(testdir, salt):
"""Run ``pytest --cache-show`` and parse the outcome to get cached seeds."""
result = testdir.runpytest("--cache-show")
fmt = "test_seed[{param}]:{salt} contains:"
ix_a = result.outlines.index(fmt.format(param="a", salt=salt))
seed_a = int(result.outlines[i... | 0dbbfdeb5bc3b279b7b587cbd84c035047159c7f | 101,370 |
def pk_verify(hashed, signature, public_key):
"""
Verify `hashed` based on `signature` and `public_key`.
hashed: string
A hash for the data that is signed.
signature: tuple
Value returned by :func:`pk_sign`.
public_key: :class:`Crypto.PublicKey.RSA`
Public portion of key p... | 95d0288d5ed85cb3501f87b4ab83650535c818b0 | 101,375 |
import textwrap
def shorten(text, width=70, placeholder='...'):
"""Shortens text to a max length.
Shortens text to a max length using some optional placeholder
with textwrap (if Python > 3.3) or a custom method.
:param text: The text to shorten
:type text: str
:param width: The max width, def... | 359ce44ece03e1eca9ac46ef71f77d6cdc241247 | 101,377 |
import yaml
def show(data):
"""
Works like yaml.dump(), but with output suited for doctests. Flow style
is always off, and there is no blank line at the end.
"""
return yaml.dump(data, default_flow_style=False).strip() | f8f7211c9721a7e030e2b8d934e92b4425735af6 | 101,380 |
def encontrar_estrenos(p1: dict, p2: dict, p3: dict, p4: dict, p5: dict, anio: int) -> str:
"""Busca entre las peliculas cuales tienen como anio de estreno una fecha estrictamente
posterior a la recibida por parametro.
Parametros:
p1 (dict): Diccionario que contiene la informacion de la pelicula ... | 26d300db18776d9e6fd12fce46e48296b5333186 | 101,386 |
def is_typed_dict(obj, typ):
"""Returns true if obj is a dict and has a field 'type'=typ.
"""
return (type(obj) is dict and obj.get('type', None) == typ) | f62c2707899f5e11549fbc10dbbf8f95e27bc8da | 101,390 |
import uuid
def CreateNewSessionID() -> str:
"""Create a new session ID.
Returns:
str: The session ID.
"""
return uuid.uuid4().hex[:6] | c39654d4aa2c2cafbf25ff5b3afcb5ccdc314ac2 | 101,393 |
def loadavg () :
""" Get load average from /proc/loadavg
The first three fields in this file are load average figures
giving the number of jobs in the run queue (state R) or
waiting for disk I/O (state D) averaged over 1, 5, and 15
minutes. They are the same as the load average numb... | fdc3e0a8e1b6d8b711b7b81e147700502b527a3a | 101,395 |
def _login_manager_user_loader(user_id):
"""
setup None user loader.
Without this, it will throw an error if it doesn't exist
"""
return None | e94f7dd2c86f42b575456bf1cfe7970861578cc3 | 101,397 |
import optparse
def CreateTestRunnerOptionParser(usage=None, default_timeout=60):
"""Returns a new OptionParser with arguments applicable to all tests."""
option_parser = optparse.OptionParser(usage=usage)
option_parser.add_option('-t', dest='timeout',
help='Timeout to wait for each t... | a98d8e3997df2604432dd051256399bea367fd30 | 101,400 |
def cudnn_lstm_parameter_size(input_size, hidden_size):
"""Number of parameters in a single CuDNN LSTM cell."""
biases = 8 * hidden_size
weights = 4 * (hidden_size * input_size) + 4 * (hidden_size * hidden_size)
return biases + weights | 1548e9ba8358939edb6d5fb1e7dcf5f4a3b2302e | 101,402 |
def get_indefinite_article(noun: str) -> str:
"""
>>> get_indefinite_article('Elephant')
'an'
>>> get_indefinite_article('lion')
'a'
>>> get_indefinite_article(' ant')
'an'
"""
normalised_noun = noun.lower().strip()
if not normalised_noun:
return 'a'
if normalised_... | bb77a18bb5e60e31a0d68eae921ea8aefb0ebf1b | 101,410 |
def clean_consecutive_duplicates(
move_data, subset=None, keep="first", inplace=False
):
"""
Removes consecutives duplicate rows of the Dataframe, optionally only
certaind columns can be consider.
Parameters
----------
move_data : dataframe
The input trajectory data
subset : Arr... | 7f1d4258810c7c5bc117d2b5b2d098abffd4b613 | 101,414 |
def is_number(number):
"""
Return True if an object is a number - can be converted into a float.
Parameters
----------
number : any
Returns
-------
bool
True if input is a float convertable (a number), False otherwise.
"""
try:
float(number)
return True... | 94116ce4f005f747222ced537168d2138944e325 | 101,417 |
def rotate_word(s, n):
"""
Rotate each char in a string by the given amount.
Wrap around to the beginning (if necessary).
"""
rotate = ''
for c in s:
start = ord('a')
num = ord(c) - start
r_num = (num + n) % 26 + start
r_c = chr(r_num)
rotate += r_c
re... | d2fd72d289b96693eb9e7a2697ab4a8a0a28a0be | 101,419 |
def sigma_eaton(es_norm, v_ratio, n):
"""
calculate effective pressure with the ratio of velocity and normal velocity
Notes
-----
.. math:: {\\sigma}={\\sigma}_{n}\\left(\\frac{V}{V_{n}}\\right)^{n}
"""
return es_norm * (v_ratio)**n | 708b59edebd6ea14dffbdb59d91d05ebfae0d8b2 | 101,420 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.