content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def remove_multiedges(E):
"""Returns ``(s, d, w)`` with unique ``(s, d)`` values and `w` minimized.
:param E: a set of edges
:type E: [(int, int, float)]
:return: a subset of edges `E`
:rtype: [(int, int, float), ...]
"""
result = []
exclusion = set()
for... | e6156259ee8f5714bfef0fab8a92aed117c6149c | 688,695 |
import six
import importlib
def load_class(requested_class):
"""
Check if requested_class is a string, if so attempt to load
class from module, otherwise return requested_class as is
"""
if isinstance(requested_class, six.string_types):
module_name, class_name = requested_class.rsplit(".",... | ae3c212d84b0cbe409babfc2f77e7c6b2dc62b12 | 688,699 |
def calc_tristimulus_array_length(data_array):
"""
calcurate the array length of tristimulus ndarray.
Parameters
----------
data_array : ndarray
tristimulus values
Returns
-------
int
length of the tristimulus array.
Examples
--------
>>> data_1 = np.ones((... | a301bb3e0f048fdc62c73f45a5b764f948ad0f0c | 688,703 |
def extend_position_embedding(model, max_position):
"""This function extends the position embedding weights of a model loaded from a checkpoint.
It assumes the new max position is bigger than the original max length.
Arguments:
model: required: a transformer model
max_position: required: an... | ed9ca2979295ee8b2c219655e63de362108066e6 | 688,704 |
import json
def read_user_ips(file):
"""Read in the JSON file of the user-IP address mapping."""
with open(file, 'r') as file:
return json.loads(file.read()) | a00171d82edc59bbea902e6bd356543093d1a05e | 688,708 |
import re
def get_read_group(list_of_names):
"""Extracts the correct group name for the group containing the read_id"""
for name in list_of_names:
if re.search(r'Read_\d+$', name):
return name | 44f8aa6ddd05f03760a114dcb911063033e3e5d8 | 688,709 |
def reloc_exit_patch(patch_data, relocs, start_address):
"""Relocate a piece of 6502 code to a given starting address."""
patch_data = bytearray(patch_data)
for i in relocs:
address = patch_data[i] + (patch_data[i + 1] << 8) + start_address
patch_data[i] = address & 0xFF
patch_data[i... | 24ef61eeb5db23c41e4cea99e47826462775551c | 688,713 |
def fingerprints_as_string(fingerprints):
"""
Method to formatting fingerprints list to human readable string value
:param fingerprints: fingerprints set as list
:type fingerprints: list
:return: fingerprints set as string
:rtype: str
"""
all_fingerprints_string = []
# loop all fin... | 1ed23026b4a930110a86fc2922543f62794e4427 | 688,715 |
import math
def haversine(lat1,lon1,lat2,lon2,radius=6371000.0):
"""
Haversine function, used to calculate the distance between two points on the surface of a sphere. Good approximation
for distances between two points on the surface of the Earth if the correct local curvature is used and the points are
... | 58125250e0d1a01bcc7a48e2d2a015e4610ed7be | 688,716 |
def no_blending(rgba, norm_intensities):
"""Just returns the intensities. Use in hill_shade to just view the calculated intensities"""
assert norm_intensities.ndim == 2, "norm_intensities must be 2 dimensional"
return norm_intensities | 350c2f8c235de6552165f4eb482aee1600fcabdf | 688,719 |
def feature_fixture(request):
"""Return an entity wrapper from given fixture name."""
return request.getfixturevalue(request.param) | 2f5b9164e34a9efc2a80ecea36cff226d04b5b7a | 688,722 |
def _filter_cols(dataset, seed):
"""Mapping function.
Filter columns for batch.
Args:
dataset: tf.data.Dataset with several columns.
seed: int
Returns:
dataset: tf.data.Dataset with two columns (X, Y).
"""
col_y = f'image/sim_{seed}_y/value'
return dataset['image/encoded'], dataset[col_y] | 29831bbd4231d35cd666e45350140d7b763f47ea | 688,726 |
def find_sum(inputs, target):
"""
given a list of input integers, find the (first) two numbers
which sum to the given target, and return them as a 2-tuple.
Return None if the sum could not be made.
"""
for i in inputs:
if i < target // 2 + 1:
if target - i in inputs:
... | 8961cb6dd02ef65afa14c1ac46280055960ed6a0 | 688,729 |
import inspect
def is_static_method(klass, name: str) -> bool:
"""
Check if the attribute of the passed `klass`
is a `@staticmethod`.
Arguments:
klass: Class object or instance to check for the attribute on.
name: Name of the attribute to check for.
Returns:
`True` if the... | 5ee84883d6ad52b6c0dd69f7123f80fd553313ea | 688,732 |
from typing import Union
def astuple(i, argname: Union[str, None]) -> tuple:
"""
Converts iterables (except strings) into a tuple.
:param argname:
If string, it's used in the exception raised when `i` not an iterable.
If `None`, wraps non-iterables in a single-item tuple, and no exception... | 6bf251b32223e80400e24f3658daebb0872159e2 | 688,737 |
def ms_to_hours(ms):
"""Convert milliseconds to hours"""
return round(ms / 60.0 / 60.0 / 1000.0, 2) | 0df04200eb35e44fbbc3050a61de8ac00e67d89e | 688,739 |
def org_add_payload(org_default_payload):
"""Provide an organization payload for adding a member."""
add_payload = org_default_payload
add_payload["action"] = "member_added"
return add_payload | 37def98da4c7fe3389177f3ef65ac1dc146def23 | 688,741 |
def cchunkify(lines, lang='', limit=2000):
"""
Creates code block chunks from the given lines.
Parameters
----------
lines : `list` of `str`
Lines of text to be chunkified.
lang : `str`, Optional
Language prefix of the code-block.
limit : `int`, Optional
The maxi... | 68db7bfa9e781240ddde86dba559f1da84112ee8 | 688,747 |
def exist_unchecked_leafs(G):
"""Helper function for hierachical hill climbing. The function determines
whether any of the leaf nodes of the graph have the attribute checked set
to False. It returns number of leafs for which this is the case.
Args:
G (nx.DirectedGraph): The directed graph to be... | 513fe0f7c1b61ee1063eda82d2b4720434cd7ae3 | 688,748 |
def num_edges(graph):
"""Returns the number of edges in a ProgramGraph."""
return len(graph.edges) | 3ae188a25570fe9b0df1650e011efcfaa5d75080 | 688,750 |
import tempfile
def simple_net_file(num_output):
"""Make a simple net prototxt, based on test_net.cpp, returning the name
of the (temporary) file."""
f = tempfile.NamedTemporaryFile(mode='w+', delete=False)
f.write("""name: 'testnet' force_backward: true
layer { type: 'DummyData' name: 'data' top... | 6d8107f638b0eff583c19bd691210e119520b4f9 | 688,759 |
import re
def get_fortfloat(key, txt, be_case_sensitive=True):
"""
Matches a fortran compatible specification of a float behind a defined key in a string.
:param key: The key to look for
:param txt: The string where to search for the key
:param be_case_sensitive: An optional boolean whether to sea... | c0171ab82196f9cffc0b66dfeeb7a766ff73dfe9 | 688,764 |
def option_namespace(name):
"""ArgumentParser options namespace (prefix of all options)."""
return name + "-" | 0b79edea508216e61afe06750d5fbf7727546932 | 688,765 |
def is_verb(tok):
"""
Is this token a verb
"""
return tok.tag_.startswith('V') | a42e92596de719d55810bbe8012f7418cc7d9be8 | 688,772 |
def get_fuel_required(module_mass: float) -> float:
"""Get the fuel required for a module.
Args:
module_mass: module mass
Returns:
fueld required to take off
"""
return int(module_mass / 3.0) - 2.0 | 2dc7f2840e681fb1f74d4ef1f280a7727f14ccfd | 688,773 |
def uniq(xs):
"""Remove duplicates in given list with its order kept.
>>> uniq([])
[]
>>> uniq([1, 4, 5, 1, 2, 3, 5, 10])
[1, 4, 5, 2, 3, 10]
"""
acc = xs[:1]
for x in xs[1:]:
if x not in acc:
acc += [x]
return acc | d0c7b87970d25c29127676f6a78d2e2cd961deac | 688,777 |
def lang(name, comment_symbol, multistart=None, multiend=None):
"""
Generate a language entry dictionary, given a name and comment symbol and
optional start/end strings for multiline comments.
"""
result = {
"name": name,
"comment_symbol": comment_symbol
}
if multistart is no... | e1e89caf4bb595e61a94df1ee70d33c39e75f486 | 688,778 |
def listify(item) -> list:
"""
If given a non-list, encapsulate in a single-element list.
"""
return item if isinstance(item, list) else [item] | 0f836bae02f59e659704360dffa8ebf22a45a0f9 | 688,779 |
import copy
def copy_original_exchange_id(data):
"""Copy each exchange id to the field ``original id`` for use in writing
ecospold2 files later."""
for ds in data:
for exc in ds['exchanges']:
exc['original id'] = copy.copy(exc['id'])
return data | c8f9634762feb91fc173e080d585fbdfef86b9fb | 688,780 |
def _strip_wmic_response(wmic_resp):
"""Strip and remove header row (if attribute) or call log (if method)."""
return [line.strip() for line in wmic_resp.split('\n') if line.strip() != ''][1:] | 7b235993aaa3bade533730e5698611163263740e | 688,781 |
import sympy
def render(expr, lhs=""):
"""
Puts $ at the beginning and end of a latex expression.
lhs : if we want to render something like: $x = 3 + 5$, set the left hand
side here
"""
left = "$$"
if lhs:
left = "$$%s =" % lhs
return ''.join([left, sympy.latex(expr), "$$... | 64190fe4358b212f15972d29873504317899c685 | 688,785 |
def compress_name(champion_name):
"""To ensure champion names can be searched for and compared,
the names need to be reduced.
The process is to remove any characters not in the alphabet
(apostrophe, space, etc) and then convert everything to lowercase.
Note that reversing this is non-trivial, ther... | de76dfd48436ae1ec66dc7e42357e6c52f15719a | 688,787 |
def createDatas(*models):
"""Call createData() on each Model or GeometryModel in input and return the results in a tuple.
If one of the models is None, the corresponding data object in the result is also None.
"""
return tuple([None if model is None else model.createData() for model in models]) | c4dd5231ac8e7a3efd16e33bd793cb8d60ea9292 | 688,789 |
def _create_source_file(source, tmp_path):
"""Create a file with the source code."""
directory = tmp_path / "models"
directory.mkdir()
source_file = directory / "models.py"
source_file.write_text(source)
return source_file | 872bc917f8cae340ae8c098a7fdf96ebd5725ba2 | 688,790 |
def __top_frond_left(dfs_data):
"""Returns the frond at the top of the LF stack."""
return dfs_data['LF'][-1] | 6a7870bf1dd2d165410a2e187240cf548a4e3cdb | 688,791 |
def link_cmd(path, link):
"""Returns link creation command."""
return ['ln', '-sfn', path, link] | a7c0477fd643b6eebc028fdfbd890922ac4ceb09 | 688,794 |
import ntpath
import posixpath
def as_posixpath(location):
"""
Return a posix-like path using posix path separators (slash or "/") for a
`location` path. This converts Windows paths to look like posix paths that
Python accepts gracefully on Windows for path handling.
"""
return location.replac... | 0a0e4f9c4dbff17781cbe980820ebf3f545fda21 | 688,799 |
def flag_greens_on_set(func):
"""Decorator to signal Green's functions are now out of date."""
def setter_wrapper(obj, value):
retval = func(obj, value)
obj._uptodate = False
return retval
return setter_wrapper | 030808f24f1a1b978e55e2f318849d8d029d1e75 | 688,800 |
def _auth_header(module):
"""Generate an authentication header from a token."""
token = module.params.get('auth')['access_token']
auth_header = {
'Authorization': 'Bearer {}'.format(token)
}
return auth_header | 187b232c36c2ec453821e0a07c2976322e5f8dc2 | 688,802 |
import uuid
def _replace_substrings(code, first_char, last_char):
"""Replace the substrings between first_char and last_char
with a unique id.
Return the replaced string and a list of replacement
tuples: (unique_id, original_substring)
"""
substrings = []
level = 0
start = -1
for i... | 4a4b877df5aa6ce889a62f6e3ed9b784e37ad41c | 688,805 |
import re
def get_set(srr_rar_block):
"""
An SRR file can contain re-creation data of different RAR sets.
This function tries to pick the basename of such a set.
"""
n = srr_rar_block.file_name[:-4]
match = re.match("(.*)\.part\d*$", n, re.I)
if match:
return match.group(1)
else:
return n | 2dc166e40d410beaf31d450ca4d932ab79e50292 | 688,807 |
def intersect2D(segment, point):
"""
Calculates if a ray of x->inf from "point" intersects with the segment
segment = [(x1, y1), (x2, y2)]
"""
x, y = point
#print(segment)
x1, y1 = segment[0]
x2, y2 = segment[1]
if (y1<=y and y<y2) or (y2<=y and y<y1):
x3 = x2*(y1-y)/(y1... | 403bf09794036572d4eb198951e89379634825c8 | 688,809 |
def _get_reserved_field(field_id, reserved_fields):
"""Returns the desired reserved field.
Args:
field_id: str. The id of the field to retrieve.
reserved_fields: list(fields). The reserved fields to search.
Returns:
The reserved field with the given `field_id`.
Raises:
ValueError: `field_id` ... | b32e4b183682c2bd482cb244956cc23865c85921 | 688,817 |
import math
def sigmoid(x):
"""Sigmoid function f(x)=1/(1+e^(-x))
Args:
x: float, input of sigmoid function
Returns:
y: float, function value
"""
# for x which is to large, the sigmoid returns 1
if x > 100:
return 1.0
# for x which is very small, the sigmoid r... | c65624784c34422ca41f14d118e3690990a05b47 | 688,818 |
def connect_the_dots(pts):
"""given a list of tag pts, convert the point observations to
poly-lines. If there is only one pt, return None, otherwise connect
the dots by copying the points and offseting by 1, producing N-1 line
segments.
Arguments: - `pts`: a list of point observations of the
f... | 9d678a1033acc75631c2391884df6d3ea46f013b | 688,820 |
from typing import List
def dict_to_generic_object_format(args: dict) -> List[dict]:
"""
Converts args dict into a list, please see GenericObjectGenerator Class in Pymisp.
Args:
args: dictionary describes MISP object
Returns:
list: list containing dicts that GenericObjectGenerator can... | 42118e4ffc053ef2758a9ebe69c0f7a212ea8091 | 688,822 |
import base64
def encode_photo(filepath):
"""
encode photo to text
:param filepath: file encoded
:return: encoded text
"""
with open(filepath, mode="rb") as f:
return base64.encodebytes(f.read()).decode("utf-8") | 7cfe4b8f3ba32b6a7fa1dbfe9277e6ae15ab21dc | 688,823 |
def rotate_list(l):
"""
Rotate a list of lists
:param l: list of lists to rotate
:return:
"""
return list(map(list, zip(*l))) | b4ae24f2f0dcadaf7b33ec6c0b231cbf01c71c5d | 688,828 |
def segwit_scriptpubkey(witver, witprog):
"""Create a segwit locking script for a given witness program (P2WPKH and P2WSH)."""
return bytes([witver + 0x50 if witver else 0, len(witprog)] + witprog) | 64969e52d2f665c511f9f24855a474dbad7d61da | 688,833 |
from typing import Union
from typing import List
def parse_setup(options: Union[List, str]) -> str:
"""Convert potentially a list of commands into a single string.
This creates a single string with newlines between each element of the list
so that they will all run after each other in a bash script.
... | 24ed9ddde7933c19d3196775229f214f82eff3e0 | 688,835 |
import unicodedata
def is_printable(char: str) -> bool:
"""
Determines if a chode point is printable/visible when printed.
Args:
char (str): Input code point.
Returns:
True if printable, False otherwise.
"""
letters = ('LC', 'Ll', 'Lm', 'Lo', 'Lt', 'Lu')
numbers =... | 7cd5b07b2d1400dd93633ec26a1ca80acb67231a | 688,842 |
def convert_secret_hex_to_bytes(secret):
"""
Convert a string secret to bytes.
"""
return int(secret, 16).to_bytes(32, byteorder="big") | 93b7b1973d32cb2dc1c48ae53fbd5ef8231737d3 | 688,843 |
from typing import Counter
def count_items(column_list):
"""
Function count the users.
Args:
column_list: The data list that is doing to be iterable.
Returns:
A list with the item types and another list with the count values.
"""
item_types = []
count_items = []
... | 5800a93d2747348705b8b3e96b594f49e160e5ef | 688,844 |
def get_brief_description(description):
"""Get brief description from paragraphs of command description."""
if description:
return description[0]
else:
return 'No description available.' | eb41a9dc6dd6145defb81f73f63b604312020f6d | 688,845 |
def needs_reversal(chain):
"""
Determine if the chain needs to be reversed.
This is to set the chains such that they are in a canonical ordering
Parameters
----------
chain : tuple
A tuple of elements to treat as a chain
Returns
-------
needs_flip : bool
Whether or... | b5ef8841fe01b9608b16b6823f103de56e654fa6 | 688,847 |
def bulleted_list(items, max_count=None, indent=2):
"""Format a bulleted list of values."""
if max_count is not None and len(items) > max_count:
item_list = list(items)
items = item_list[: max_count - 1]
items.append("...")
items.append(item_list[-1])
line_template = (" " * ... | f62ec763348488dcc96880c02843baa509cf873f | 688,850 |
def _maybe_list_replace(lst, sublist, replacement):
"""Replace first occurrence of sublist in lst with replacement."""
new_list = []
idx = 0
replaced = False
while idx < len(lst):
if not replaced and lst[idx:idx + len(sublist)] == sublist:
new_list.append(replacement)
replaced = True
idx... | 3f75099928108190999d88bd79d488e735ce74bb | 688,856 |
def PrintHtml(log):
"""Prints a log as HTML.
Args:
log: a Log namedtuple.
"""
def Tag(tag, cls, value):
return '<%s class="%s">%s</%s>' % (tag, cls, value, tag)
classes = ['filename', 'date', 'log']
line = ' '.join([Tag('span', cls, value) for cls, value in zip(classes, log)])
print(Tag('div', 'l... | df0836e13c090e058c49d73a2b6ee86b720588c9 | 688,858 |
def get_max_offset_supported(atten):
"""Get maximum supported offset for given attenuation"""
if atten >= 0.1:
return (-8, +8)
else:
return (-2, +2) | 9c246203e62823132ba68d56b7a6ab4e4da942cc | 688,861 |
def log_likelihood_from(*, chi_squared: float, noise_normalization: float) -> float:
"""
Returns the log likelihood of each model data point's fit to the dataset, where:
Log Likelihood = -0.5*[Chi_Squared_Term + Noise_Term] (see functions above for these definitions)
Parameters
----------
chi_... | 87dc243546ca17eedaed0534a3a1d2dd8171e435 | 688,862 |
def rename_fields(columns, data):
"""Replace any column names using a dict of 'old column name': 'new column name' """
return data.rename(columns=columns) | 59d569faaf51759b96824fe869fdacb5d5240c94 | 688,863 |
def _user_is_admin_for(user, org):
"""
Whether this user is an administrator for the given org
"""
return org.administrators.filter(pk=user.pk).exists() | 32c4f74a6d1ca8afdd783ea9197ee86100d0366b | 688,865 |
def drive_list(service, parent_id):
"""
List resources in parent_id
"""
query = "trashed=false and '%s' in parents" % parent_id
response = service.files().list(q=query).execute()
if response and 'items' in response and response['items']:
return response['items']
return [] | d901b69b39908c9b68dc05576c981e834d07a8b7 | 688,868 |
def _new_or_old_field_property(prop, new_field, old_field, old_priority):
"""
Get the given property on the old field or the new field, with priority given
to a field of the user's choosing.
Arguments:
prop -- a string of the requested property name
old_field -- the old field as a Field instance
new_fiel... | 4deef6347ae6077552fa5784f347ff0e07fa1c5e | 688,869 |
import re
def sanitize(
word: str,
chars=['.', ",", "-", "/", "#"],
check_mongoengine=True) -> str:
"""Sanitize a word by removing unwanted characters and lowercase it.
Args:
word (str): the word to sanitize
chars (list): a list of characters to remove
check_mo... | 28554008cd124fd4503c68153e97ccee0ad906f7 | 688,870 |
def add_space_to_parentheses(string: str):
"""
:param string: Must be a string
:return: string with space before '(' and after ')'
"""
return string.replace('(', ' (').replace(')', ') ') | cc0bea2f82a2328bdf3a907f77a3ea992e729939 | 688,871 |
def cast_type(cls, val, default):
"""Convert val to cls or return default."""
try:
val = cls(val)
except Exception:
val = default
return val | 131ceceb42d053125d1a4fc19e9dea8eaf231d4a | 688,875 |
def is_insertion(row):
"""Encodes if the indel is an insertion or deletion.
Args:
row (pandas.Series): reference seq (str) at index 'ref'
Returns:
is_insertion (int): 0 if insertion, 1 if deletion
"""
is_insertion = 0
if row["ref"] == "-":
is_insertion = 1
ret... | a358233643b4a4cf7ffe2a96828a3355e7d5ae3d | 688,879 |
import textwrap
def unindent(text: str) -> str:
"""Remove indentation from text"""
return textwrap.dedent(text).strip() | 035c46a9921a328902f84d71316707f854bf5201 | 688,881 |
def get_error_res(eval_id):
"""Creates a default error response based on the policy_evaluation_result structure
Parameters:
eval_id (String): Unique identifier for evaluation policy
Returns:
PolicyEvalResultStructure object: with the error state with the given id
"""
return {
... | ebb80435b6f0c590dc30a9095559cbbbd1da5662 | 688,883 |
import string
import random
def gen_random_string(n=24):
"""Returns a random n-length string, suitable for a password or random secret"""
# RFC 3986 section 2.3. unreserved characters (no special escapes required)
char_set = string.ascii_letters + string.digits + "-._~"
return "".join(random.choices(... | b3bd49ed5b89d886aefa7431b62d85b6f5ff1c60 | 688,889 |
def query_adapter(interface, request, context=None, view=None, name=''):
"""Registry adapter lookup helper
If view is provided, this function is trying to find a multi-adapter to given interface
for request, context and view; if not found, the lookup is done for request and context,
and finally only fo... | 81c164ab122717cb31d001f3cf632da49183da87 | 688,891 |
from typing import Optional
def _rename_list(
list1: list[str], method: str, list2: Optional[list[str]] = None
) -> list[str]:
"""Renames multiple list items following different methods.
Method can be "consecutive" to rename identical consecutive items
with increasing number or "fuse" to fuse with th... | df3385abef1c19a3a9056397c7f2549d615f9d8e | 688,894 |
def ping(request):
"""
Simple resource to check that server is up.
"""
return 'pong' | 957c7f4a0733a99292d8a04562e179317da63fb6 | 688,900 |
def null_count(df):
"""This functions returns the number of null values in a Dataframe"""
NullSum = df.isnull().sum().sum()
return NullSum | e2d0126d5ac6f275234263c87b6e80637b7b91d9 | 688,902 |
def type_factor(NT, NP, SC=30.0):
"""
NT - Number of planet types in area
NP - Number of planets in area
SC - a number used to scale how bad it is to differ from the
optimal number of planet types. Lower number means less bad
Returns a number between 0.0 and 1.0 indicating how good the rati... | 8b79f29b17e07528233754bebc996b8701f10e77 | 688,903 |
def compute_long_chain(number):
"""Compute a long chain
Arguments:
number {int} -- Requested number for which to compute the cube
Returns:
int -- Value of the cube/long chain for the given number
"""
return number * number * number | 62a214cac43409104d95ff4ca1f8b59beaf534c7 | 688,906 |
def get_markers_to_contigs(marker_sets, contigs):
"""Get marker to contig mapping
:param marker_sets: Marker sets from CheckM
:type marker_sets: set
:param contigs: Contig to marker mapping
:type contigs: dict
:return: Marker to contigs list mapping
:rtype: dict
"""
marker2contigs =... | 2ed01846d8e6e0c5fd60ec8152e098d1c91d87ab | 688,908 |
def _IsAnomalyInRef(change_point, ref_change_points):
"""Checks if anomalies are detected in both ref and non ref build.
Args:
change_point: A find_change_points.ChangePoint object to check.
ref_change_points: List of find_change_points.ChangePoint objects
found for a ref build series.
Returns:
... | d36686a342be43e786f067e55c10df5612d1c500 | 688,909 |
def _sum(op1, op2):
"""Sum of two operators, allowing for one of them to be None."""
if op1 is None:
return op2
elif op2 is None:
return op1
else:
return op1 + op2 | 6ae3c149af620446dba02ac89b4d7d93a7d1e76d | 688,911 |
def eyr_valid(passport):
""" Check that eyr is valid
eyr (Expiration Year) - four digits; at least 2020 and at most 2030.
:param passport: passport
:return: boolean
"""
return len(passport['eyr']) == 4 and 2020 <= int(passport['eyr']) <= 2030 | 47fe44bcde03c2bf99796fd14da9ad4bbb6b7e0e | 688,913 |
def ParseWorkflow(args):
"""Get and validate workflow from the args."""
return args.CONCEPTS.workflow.Parse() | 0794d6ab478f975a55c773d5a653bd8dccc35a00 | 688,915 |
def file_to_ints(input_file):
"""
Input: A file containing one number per line
Output: An int iterable
Blank lines and lines starting with '#' are ignored
"""
ints = []
with open(input_file) as f:
for line in f.readlines():
line = line.strip()
if line and not ... | cb091f3d48a6770dc2f37529b9243038dbd44411 | 688,916 |
def feature_to_tpm_dict(feature_to_read_count, feature_to_feature_length):
"""Calculate TPM values for feature
feature_to_read_count: dictionary linking features to read counts (float)
feature_to_feature_length: dictionary linking features to feature lengths (float)
Return value: dictionary linking fe... | 553a0375d9aec8dc29c47e88064e9f777a3c7614 | 688,920 |
def remove_stopwords(texts, stop_words):
"""
Parameters:
- `texts`
a list of documents
- `stop_words`
a list of words to be removed from each document in `texts`
Returns: a list of documents that does not contain any element of `stop_words`
"""
return [[w... | b70828b328abe1e0e59698307adc8ececeac368e | 688,922 |
def get_mapping_pfts(mapping):
"""Get all PFT names from the mapping."""
pft_names = set()
for value in mapping.values():
pft_names.update(value["pfts"])
return sorted(pft_names) | 40fc5d5cbd537db203a240e44a0ef6c0358a7019 | 688,923 |
def encode(token):
"""Escape special characters in a token for path representation.
:param str token: The token to encode
:return: The encoded string
:rtype: str
"""
return token.replace('\\', '\\\\').replace('/', '\\/') | 30db00dc30b267618e1b85905bce3c3436878c95 | 688,924 |
def build_window_title(paused: bool, current_file) -> str:
"""
Returns a neatly formatted window title.
:param bool paused: whether the VM is currently paused
:param current_file: the name of the file to display
:return str: a neatly formatted window title
"""
return f"EightDAD {'(PAUSED)' ... | 736bacb63a5d720b91e15b5812f14c73a1e5dc22 | 688,926 |
def mph_to_kph(mph):
"""Convert mph to kph."""
return mph * 1.609 | 133e54672582deaa9585560592e2d158b4335803 | 688,929 |
def sort_hand(hand, deck):
"""Returns a hand of cards sorted in the index order of the given deck"""
sorted_hand = []
for i in deck:
for card in hand:
if i == card:
sorted_hand.append(card)
return sorted_hand | 79033c383b28dca746d8c113209f85d3ae749ea1 | 688,930 |
def get_read_count_type(line):
"""
Return the count number and read type from the log line
"""
data = line.rstrip().split(":")
count = data[-1].strip()
type = data[-3].lstrip().rstrip()
return count, type | ae60a9952118bfd66b4ff3af7446f2a3b2c5d0a9 | 688,935 |
def read_text_file(path_to_file):
"""
Read a text file and import each line as an item in a list.
* path_to_file: the path to a text file.
"""
with open(path_to_file) as f:
lines = [line.rstrip() for line in f]
return lines | 0265631258341d29c72e2416a273d6595029f93b | 688,937 |
import requests
def load_text_lines_from_url(url):
"""Load lines of text from `url`."""
try:
response = requests.get(url)
response.raise_for_status()
content = response.text.split("\n")
return [x.strip() for x in content if len(x.strip()) > 0]
except requests.RequestExcepti... | 8e9c991af8b34e6c25a5d5b95f05a9b983972943 | 688,938 |
def x10(S: str, n: int):
"""change float to int by *10**n
Args:
S (str): float
n (int, optional): n of float(S)*10**n (number of shift).
Returns:
int: S*10**n
"""
if "." not in S:
return int(S) * 10**n
return int("".join([S.replace(".", ""), "0" * (n - S[::-1].f... | b2ea4a56580739d04cff44f185196ab27f92b67a | 688,939 |
def inverter_elementos(iteravel):
"""
Inverte os elementos dentro de um tuplo.
:param iteravel: tuplo
:return: tuplo
Exemplo:
>>> tpl = ("a1", "b3")
>>> inverter_elementos(tpl)
("1a", "3b")
"""
res = ()
for e in iteravel:
res += (e[::-1],)
return res | 5561c0885291bdcf697e5f315b139b66c4a97bda | 688,942 |
def scrapeints(string):
"""Extract a series of integers from a string. Slow but robust.
readints('[124, 56|abcdsfad4589.2]')
will return:
[124, 56, 4589, 2]
"""
# 2012-08-28 16:19 IJMC: Created
numbers = []
nchar = len(string)
thisnumber = ''
for n, char in enumerate(string)... | d6918e8a260f434f4b126244c505fbc4b1c48bbf | 688,943 |
def vm_ready_based_on_state(state):
"""Return True if the state is one where we can communicate with it (scp/ssh, etc.)
"""
if state in ["started", "powered on", "running", "unpaused"]:
return True
return False | f1a31e63d4a527fddd26b403828b2c305c72a086 | 688,944 |
def get_utm_zone(lat,lon):
"""A function to grab the UTM zone number for any lat/lon location
"""
zone_str = str(int((lon + 180)/6) + 1)
if ((lat>=56.) & (lat<64.) & (lon >=3.) & (lon <12.)):
zone_str = '32'
elif ((lat >= 72.) & (lat <84.)):
if ((lon >=0.) & (lon<9.)):
z... | 37887dda8e155f6207a2554732f39e0da0150192 | 688,945 |
def counters(stats):
""" Count all_sentences all_questions all_questions_with_ans & all_corrects
:param stats: list(quintet)
:rtype int, int, int, int
:return: all_sentences, all_questions, all_questions_with_ans, all_corrects
"""
# Initialization of counters.
all_sentences = 0
all_que... | d6edc124e6254b11316a429c84664db1a223b352 | 688,946 |
import torch
def define_device(device_name):
"""
Define the device to use during training and inference.
If auto it will detect automatically whether to use cuda or cpu
Parameters
----------
device_name : str
Either "auto", "cpu" or "cuda"
Returns
-------
str
Eith... | ab1fcf9a4d8907016085935684238d18d3800ddd | 688,947 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.