content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def right_index_iter(shape):
"""Iterator for the right boundary indices of a structured grid."""
return range(shape[1] - 1, shape[0] * shape[1], shape[1]) | 8765df17e28aeb4520b1f528fb78bad118e47dcf | 600,505 |
def remove_punctuations(text: str) -> str:
"""Remove non-space, non-alphanumeric characters from `text`
Arguments:
text {str} -- ex: 'It\'s 4:00am, you say?'
Returns:
str -- ex: 'Its 400am you say'
"""
unpunct = ''.join(t for t in text if t.isalnum() or t.isspace())
return unp... | d78e1680b8f92424df674f26e08cd996bcff23dd | 600,513 |
def summed_objective_func(inputs, module):
"""Function that sums the fprop output of a module."""
inputs = inputs.reshape(module.imsize)
return module.fprop(inputs).sum() | 79ce038115e3d5036bcacab15bad04a354e57574 | 600,514 |
from pathlib import Path
def traverse_path(path, split_idx):
"""
Generates a dictionary of the path to each country.
Input:
path: str. The path to the root directory
split_idx: int. split point to capture country name. I.e. -2 splits one directory up.
"""
pathlist = Path(path).gl... | ba4bbcc370ce6e4538088414acfac051a1c59693 | 600,515 |
def get_crop_margins(page, crop_percent, side='both'):
""" Get the margins to remove from all sides using the crop_percent """
width, height = page.mediaBox.upperRight
w_diff, h_diff = float(width) * (crop_percent / 2), float(height) * (crop_percent / 2)
scale = (width / (width - w_diff * 2))
if sid... | a2b4ecd86b9bf4922c33f856f3f7eb4d242a0d9f | 600,517 |
def facet_plot_dimensions(n_activities):
"""Returns dimension N of a N x N facet plot that fits n_activities.
Args:
n_activities (int): Number of activities to be plotted.
Returns:
int: The number of rows and columns to be used.
"""
return min(i for i in range(100) if i**2 >= n_act... | bea1bf6f504e3a8156562f65a243823b7e9c64e3 | 600,518 |
def iscomplex(pscale):
""" Returns whether pscale is an instance of a complex number """
return isinstance(pscale, complex) | 23aa3f67ac7de7aa4629de3d232f83ba916c7e20 | 600,519 |
def _get_word_weight(word, word_freq_map, a=1e-3):
"""
Computes SIF weight (Arora et al. 2017)
:param word: input word
:param word_freq_map: dict containing word: word freq.
:param a: weight parameter
:return: SIF weight for the word
"""
word_freq = word_freq_map.get(word, 0.0)
retur... | 5d65acb7dd3854ec6f6f8f1b6a87b7cd53f23fb3 | 600,520 |
def render_text(content):
""" a simple renderer for text documents: replace new lines with <br> """
return "<br>".join(content.splitlines()) | 75684286a1b1576120105b0438104b0d6157e0d7 | 600,522 |
def NeededPaddingForAlignment(value, alignment=8):
"""Returns the padding necessary to align value with the given alignment."""
if value % alignment:
return alignment - (value % alignment)
return 0 | e7e9cb58fc43b4c249758acf54a49a344c3d8034 | 600,523 |
def _detect_faces_helper(face_client, image_url):
"""Detect Faces Helper.
This will detect the faces found in the image with url image_url using the provided FaceClient instance and return the faces identified in an image.
"""
detected_faces = face_client.face.detect_with_url(url=image_url)
if not... | 614ce4d4030a7b5205f1d905bbc1e7cff8b5fb89 | 600,526 |
def as_int(text, default=None, base=10):
"""Parse the specified value as an integer."""
try:
return int(text, base)
except (ValueError, TypeError):
return default | 6efc665f97f8e6006342c12b79925d5bc16cc013 | 600,531 |
def get_prop_cen_z_offset(class_str):
"""Get the proposal z centroid offset depending on the class.
"""
if class_str == 'Car':
offset = 2.17799973487854
elif class_str == 'Pedestrian':
offset = 0.351921409368515
elif class_str == 'Cyclist':
offset = 0.8944902420043945
el... | c12d02328e30b51acc64dca2e4f5cb5bfa278199 | 600,533 |
def merge(new_items, into_list):
"""
Appends items from `new_items` into `into_list`, only if they are not already there.
:param new_items:
:param into_list:
:return:
"""
at_least_one_added = False
for item in new_items:
if item not in into_list:
into_list.append(item... | 63800c1f42fe6de4c4b816e348ec5ceabcdc914e | 600,536 |
import re
def LoopTemplate(s, ctx):
"""Minute templating language: use like str.format,
so LoopTemplate("{one}", dict(one="1")) => "1",
but also supports {loop people}{name}{endloop} which
loops over an iterable in the context and processes the
inside as a subtemplate with the next ite... | 5bdc4390413cb87798610750c57bc0e654b391e6 | 600,538 |
def count_consonants(string: str) -> int:
"""
Counts the number of consonants in the given string
:param string: String to count
:return: int
Example:
>>> count_consonants("Hello World")
>>> 7
"""
return sum(1 for char in string if char.lower() in 'bcdfghjklmnpqrstvwxyz') | 85f293199e71406bfbec1ff4f10db62568f6bd97 | 600,545 |
import torch
def set_intersection(tensor1, tensor2):
"""Intersection of elements present in tensor1 and tensor2.
Note: it only works if elements are unique in each tensor.
"""
aux = torch.cat((tensor1, tensor2), dim=0)
aux = aux.sort()[0]
return aux[:-1][(aux[1:] == aux[:-1]).detach()] | 9bab721cb508fb4fa8921a1f6f3f722efc522cbd | 600,549 |
import decimal
def integer_squareroot(value: int) -> int:
"""
Return the integer square root of ``value``.
Uses Python's decimal module to compute the square root of ``value`` with
a precision of 128-bits. The value 128 is chosen since the largest square
root of a 256-bit integer is a 128-bit inte... | 72d1eb5c65b50b54cf3461734e228bbc734334ed | 600,550 |
def sparseFeature(feat, feat_num, embed_dim=4):
"""
create dictionary for sparse feature
:param feat: feature name
:param feat_num: the total number of sparse features that do not repeat
:param embed_dim: embedding dimension
:return:
"""
return {'feat': feat, 'feat_num': feat_num, 'embed... | ffe53e988e20a2f23db1c63f3a471ff04650f592 | 600,552 |
def parse_test_names(test_name_args):
"""Returns a dictionary mapping test case names to a list of test functions
:param test_name_args: The parsed value of the ``--test`` or ``--skip``
arguments
:return: None if ``test_name_args`` is None, otherwise return a dictionary
mapping test case n... | a1c5aed647f9b77289c1c23b16b3703b722cb432 | 600,554 |
def tibetan_month(date):
"""Return 'month' element of a Tibetan date, date."""
return date[1] | 74d2d198e9a81eeff369c0a4bd433c0036942e3c | 600,564 |
import torch
def make_circle_masks(n, h, w):
"""
Create circle mask on a grid of size (h, w).
Center and radius chosen randomly from [-0.5, 0.5] and [0.1, 0.4] respectively (for grid scale of [-1, 1]).
Parameters
----------
n: int
Number of channels to create mask for.
h: int
... | a6943667e343ee06567c51a26392b3320378c22d | 600,567 |
def DFS(graph, source=None, key=None):
"""
An Impelemetaion of depth-first-search for tranversing a
graph of getting a node.
Parameters
----------
source:int, str, float, optional
Value of the node to start the tranverse. if ommited the method
uses the first node in the graph as... | a81ce4170eae7327aff0fb32960edb14c51d3d04 | 600,568 |
def ord_val(lex_id: str) -> int:
"""Parse the ordinal value of a lexical id.
The ordinal value is the position in the sequence,
from repeated calls to next_id.
>>> ord_val("0098")
98
>>> ord_val("0099")
99
>>> ord_val("0100")
100
>>> ord_val("11000")
1000
>>> ord_val("1... | 054ae2f8af3a08f774d002cd7f64c9634713d6c7 | 600,569 |
def ndim(x):
"""
returns number of dimensions for tensor
"""
return len(x.get_shape()) | 7db9839c47dd700eec0b42857ea8af1774b1a608 | 600,575 |
def remove_s_mean(data, mean):
"""Remove the spatial mean of a time series matrix
"""
n = min(data.shape[0],data.shape[1])
for i in range(0, n):
if data.shape[0]==n:
data[i] -= mean[i]
else :
data[:,i] -= mean[i]
return data | f73bb40177ce82a1696e780726e34f8527485fd0 | 600,576 |
def get_default_order(view):
"""
Get default sort order from model view.
Returns (field, desc) tuple.
:param view:
View instance
"""
if view.column_default_sort:
if isinstance(view.column_default_sort, tuple):
return view.column_default_sort
... | 0a8db65f535ea94e8f6543c0de75cfedd122aeac | 600,579 |
def is_collection(value) -> bool:
"""
Check if value is a collection
"""
return any([isinstance(value, list), isinstance(value, set), isinstance(value, tuple)]) | d5e3a5a92b4ccfc9e30a7de444546a7bd4974b09 | 600,583 |
def find_nearest_index(vertices, x_from, y_from, vertice_count):
"""
Find the index of the vertex that is the closest to specified
coordinate (x_from, y_from).
"""
min_distance_squared = 1000000
nearest_index = 0
x_from *= 1000
y_from *= 1000
for index, vertice in enumerate(vert... | 65867ab47c9632dae4b90c7402799846faf2937f | 600,584 |
def total_time(boutlist):
"""Takes list of times of bouts in seconds, returns it's last item representing the total trial time."""
total_time = boutlist[-1]
return total_time | ef330f460522fad513acd37c115fbcd8eaf0dad6 | 600,589 |
def coc_accepted(post, config):
"""
Verifies that the user is in the Redis set "accepted_CoC".
:param post: the Comment object containing the claim.
:param config: the global config dict.
:return: True if the user has accepted the Code of Conduct, False if they
haven't.
"""
return c... | 9843461da6f4d0221203c7057b40c3505fad40b8 | 600,597 |
def parse_file(file_name):
"""
Parses file generated by the filtering script
:param file_name:
:return: nested list of all counts, nested list of gene IDs/symbols, list of sample names
"""
all_counts = []
gene_names = []
with open(file_name, "r") as file:
header = next(file)
... | 4c05867e5d61894b23f6ec06b5a48b47e3a34c47 | 600,598 |
def scale_to_total(value):
"""\
Convert a mapping of distinct quantities to a mapping of proportions of the
total quantity.
"""
total = float(sum(value.values()))
return {k: (v / total) for k, v in value.items()} | 4ac2be24fa668b9b194749def3649253a413545a | 600,600 |
def _get_num_annos(id2gos):
"""Return the number of annotations found in id2gos"""
num = 0
for gos in id2gos.values():
num += len(gos)
return num | 47a7360b8cb51118920f84e418fbe7fca5b2630c | 600,603 |
def key_values_to_dict(kvs):
"""
Given a list with key values in form `Key=Value` it creates a dict from it.
"""
my_dict = {}
for kv in kvs:
k, v = kv.split("=")
my_dict[k] = v
return my_dict | 76033dcc3907e9c7e31510223f2384ddc370ddb1 | 600,604 |
def bin_centers(bin_edges):
"""Return array of bin centers given an array of bin edges"""
return (bin_edges[1:] + bin_edges[:-1]) / 2.0 | 7582a0983e809d1305657004df0b2a02a8b267e2 | 600,605 |
def lines_get_first_line(lines: str) -> str:
"""Return the first non-empty line in lines."""
return lines.strip().splitlines()[0] | 47f8aabb56731f4652578ae616b7e14319620baf | 600,610 |
def class_is_abstract(node):
"""return true if the given class node should be considered as an abstract
class
"""
for method in node.methods():
if method.parent.frame() is node:
if method.is_abstract(pass_is_abstract=False):
return True
return False | aad9f9a15df4be2792699cb788ea8f34a7f55169 | 600,611 |
def guess_spatial_dimensions(image):
"""Make an educated guess about whether an image has a channels dimension.
Parameters
----------
image : ndarray
The input image.
Returns
-------
spatial_dims : int or None
The number of spatial dimensions of `image`. If ambiguous, the v... | b95c78d6e122638340e92c1cd61312f327c81897 | 600,612 |
def exponenciacao(base, expoente):
"""
Implementação de um algoritmo de exponenciação.
Argumentos:
base: int. Base da operação
expoente: int. Expoente da operação.
Retorna o resultado da operação de exponenciação
"""
result = base
for _ in range(0, expoente - 1):
re... | f15fbb000586ae3e5d1761ab28a273dc1719ded7 | 600,613 |
def pdb_names2list(pdb_files_textfile):
"""
Convert a file that contains names in each line into an element of a list
Args:
pdb_files_testfile (str) : Full / relative path to the text file
Returns:
A List where the i^(th) element is the i^(th) line in the test file
"""
... | 18a274802fdf416709e40f797954028e24e209ff | 600,616 |
def inc(x):
"""
Increments the value of x
>>> inc(4)
5
"""
return x + 1 | 79159342dd7ab241e7f513192fc29d14b5bcd314 | 600,617 |
def title_case(sentence):
"""
Convert a string to title case.
Parameters
----------
sentence : str
String to be converted to title case
Returns
-------
title : str
Sentence converted to title case
Example
-------
>>> title_case("string to be coNverted")
'String To Be Converted'
"""
words = sen... | ee2091a69b34d8d01144535e8e01cf6ce30bdc50 | 600,621 |
def create_lm_inputs_labels(dataset, vocab):
"""Create inputs and labels for language modelling."""
decode_id = vocab.decode_id
end_id = vocab.end_id
inputs = [[decode_id] + vocab.lookup(seq) for seq in dataset]
labels = [vocab.lookup(seq) + [end_id] for seq in dataset]
return inputs, labels | eda6d5a07b01df1721526cd6de96c1c36a39e4c5 | 600,624 |
import re
def is_valid_username(username):
"""A username is valid if it fulfills the following conditions:
- Contains at least 8 characters and at most 12 characters
- Only contains letters from A to Z, a to z and digits from 0 to 9
- Contains at least one digit
- Must start with a capital letter
... | f01a297f61b3c3740ece4ec131ec0441076032d1 | 600,627 |
import torch
import pickle
def load_model_training(path, epoch, ac, ac_targ, pi_optimizer, q_optimizer):
"""Load the model and all things necessary for continueing the training.
Args:
path (str): Path to the directory of checkpoints to save
epoch (int): Current epoch number
ac: A... | 534d4bafb6a9dfe6717dc33626afc7a7940bdfa5 | 600,628 |
from typing import List
from typing import Any
def shard_list(alist: List[Any], shard_count: int) -> List[List[Any]]:
"""Breaks the list up into roughly-equally sized shards.
Args:
alist: A list of things.
shard_count (int): The total number of shards.
Returns:
List[List[Any]]: T... | d5f5188514db968882c154c0118dff64dbc174fa | 600,629 |
from typing import Union
from typing import List
from typing import Any
from typing import Dict
def _textfsm_to_dict(
structured_output: Union[List[Any], Dict[str, Any]], header: List[str]
) -> Union[List[Any], Dict[str, Any]]:
"""
Create list of dicts from textfsm output and header
Args:
str... | abdce8d28e9f05c6f06c3349be26039a1560a965 | 600,635 |
def create_task_options_doc(task_options):
"""Generate the 'Options' section for a given tasks documentation"""
doc = []
for option in task_options:
usage_str = option.get("usage")
if usage_str:
doc.append(f"\n``{usage_str}``")
if option.get("required"):
doc.... | ef5de2598c802a006f46d8328048401b7f457de9 | 600,637 |
def _serializeExclude_eval(parentUnit, priv):
"""
Always decide not to serialize obj
:param priv: private data for this function first unit of this class
:return: tuple (do serialize this object, next priv, replacement unit)
"""
# do not use this :class:`hwt.synthesizer.unit.Unit` instance and... | 0fe664636d35fa0400a0a9e0244f0c2edecef8fb | 600,638 |
from typing import Tuple
def parse(args: Tuple[str, str, str]) -> Tuple[str]:
"""Parser for single register instructions."""
return (args[2],) | c9e5af48745ec03c1665af9490b0628a00d31d35 | 600,639 |
def fractional_part(numerator, denominator):
"""The fractional_part function divides the numerator by the denominator, and
returns just the fractional part (a number between 0 and 1)."""
if denominator != 0:
return (numerator % denominator) / denominator
return 0 | c03037b4e3f56c55b26dfe1ec76641ab21b9175c | 600,642 |
def _get_content(filepath):
"""Return contents of filepath"""
return open(filepath, 'r').read() | 98eae04f4492ce14bfe0f360fe4fb40c283367aa | 600,646 |
def size_of_varint_1(value):
""" Number of bytes needed to encode an integer in variable-length format.
"""
value = (value << 1) ^ (value >> 63)
res = 0
while True:
res += 1
value = value >> 7
if value == 0:
break
return res | c7640c81d7af9e10c90e6924237cfe0437659e9a | 600,647 |
from typing import List
from typing import Union
from typing import Dict
def _result_values_to_dict(treeview_headers: List[str],
result_values: List[Union[int, str, float]]) -> Dict[str, Union[int, str, float]]:
"""
Turn value list into a dict according to the keys based on treeview... | 41e9c3dba5cdcf299a0a00b86861d2deb73ff6d5 | 600,648 |
def allslots(cls: type):
""" Get slots tuple for all the MRO of class `cls' in right («super-to-sub») order. """
return tuple(j for i in cls.mro()[::-1] if hasattr(i, '__slots__') for j in i.__slots__) | 64191f85765a3d64fb7971cea4a66f55e87c5568 | 600,652 |
def trim_suffix(text, suffix):
"""Strip a suffix from text, if it appears (otherwise return text unchanged)"""
if not text.endswith(suffix):
return text
return text[: len(text) - len(suffix)] | 8a6cb8f80a62be17897b16770e1a0fc68c16faef | 600,661 |
def initialize_distribution(states, actions):
"""
initialize a distribution memory
:param states: a list of states
:param actions: a list of actions
:return: a dictionary to record values
"""
dist = {}
for i in states:
dist[i] = {}
for j in actions:
dist[i][j... | d99ff9485d209590b0fa5f8fa772ebe2c1c2303d | 600,666 |
def first_not_none(iterable):
"""Select the first item from an iterable that is not None.
The idea is that you can use this to specify a list of fall-backs to use
for configuration options.
"""
for item in iterable:
if item is not None:
return item
return None | 800c55e5f427cf0a707e19e71dbac8065019d639 | 600,668 |
def splitdate(yyyymmddhh):
"""
yyyy,mm,dd,hh = splitdate(yyyymmddhh)
give an date string (yyyymmddhh) return integers yyyy,mm,dd,hh.
"""
yyyy = int(yyyymmddhh[0:4])
mm = int(yyyymmddhh[4:6])
dd = int(yyyymmddhh[6:8])
hh = int(yyyymmddhh[8:10])
return yyyy,mm,dd,hh | 30b6394bf679d22a6ee33dab94f5943ba8f38d77 | 600,670 |
def humanize_time(secs):
"""
Convert seconds to hh:mm:ss format.
"""
secs = int(secs)
mins, secs = divmod(secs, 60)
hours, mins = divmod(mins, 60)
return '{h:02d}:{m:02d}:{s:02d} (hh:mm:ss)'.format(h=hours, m=mins, s=secs) | a821502bb0cbc6e45bc5f0c851ef04b6d36a8d09 | 600,671 |
def Horner(betas, t):
"""Use Horner's method to evaluate a polynomial.
betas: coefficients in decreasing order of power.
t: where to evaluate
"""
total = 0
for beta in betas:
total = total * t + beta
return total | b3895e399087ee52779582b978a93508f8036dc2 | 600,672 |
import functools
def returns_true_or_raises(f):
"""A safety net.
Decorator for functions that are only allowed to return True or raise
an exception.
Args:
f: A function whose only expected return value is True.
Returns:
A wrapped functions whose guaranteed only return value is T... | 6fd2de70d4c1058211915f3d8492c51ac81564b1 | 600,674 |
def get_accuracy(true_positives, true_negatives, false_positives, false_negatives):
"""
The accuracy is the ability to correctly predict the class of an observation.
Args:
true_positives: amount of items that have correctly been identifies as positives
true_negatives: amount of items that h... | d0b3287eab44dedf33033fe90b554dd62479dacd | 600,679 |
import pickle
def load_pickle_files(path='Data'):
"""
Loads the pickle files with the prepared Data
:param path: path to the pickle files
:return: np.arrays of the prepared data
"""
with open(f'{path}/champion.pickle', 'rb') as file_champion, open(f'{path}/enemy.pickle', 'rb') as file_enemies,... | 280b2d4eac31746836726c6ccfabadeebcfcf0e6 | 600,685 |
def _FlagIsExplicitlySet(args, flag):
"""Return True if --flag is explicitly passed by the user."""
return hasattr(args, flag) and args.IsSpecified(flag) | 7f82a73112c51f63194f391affc70afe0634a0df | 600,686 |
import torch
def to_4D_image(image: torch.Tensor) -> torch.Tensor:
"""Convert `image` to 4D tensors (b, c, h, w)
Args:
image (torch.Tensor): 2/3/4D image tensor
2D: (h, w)
3D: (c, h, w)
4D: (b, c, h, w)
Returns:
torch.Tensor: 4D image tensor
"""
ndims = len(image.shape)
asser... | 56c7638e9dbc78205478678180beda730d5b5e36 | 600,687 |
def replace_periods(dict_val, replace_with='_'):
"""
Recursively replace "." fonud in keys in the given dict with the value
of replace_with
"""
facts = dict()
for k, v in dict_val.items():
if '.' in k:
if replace_with:
k = k.replace('.', '_')
if is... | 1a5aba1c55195b088d61caa050f0ff84147e3c5d | 600,688 |
def format_amount(amount: float = 0.00) -> str:
"""
Convert to number with 2 decimal (string type) e.g.
- 10.23 => "10.23"
- 10 => "10.00"
- 1337.1337 => "1337.13"
- 1337.1387 => "1337.14"
:param amount:
:return:
"""
result = "{0:.2f}".format(amount)
return result | da0bda52712cdc6482b1c20458796fc360e6dd26 | 600,689 |
def pstrip(s, prefix):
"""Prefix strip
>>> pstrip('foo_oof', 'foo_')
'oof'
>>> pstrip('baroof', 'foo_')
'baroof'
"""
i = len(prefix)
if s[:i] == prefix:
return s[i:]
return s | 17612292b7c16da32a6cb8b2ea4fd1660b8280ee | 600,694 |
def update_email(email):
"""Make email addresses, upper-case."""
return email.upper() | e3a586aedf7035203c76bab73452474c15a30583 | 600,695 |
import math
def kl_divergence(ps, qs):
""" Calculates the relative entropy of distribution of ps to qs
"""
rel_entropy = 0.0
for (p,q) in zip(ps, qs):
if p > 0:
rel_entropy += p*math.log(p/q, 2)
return rel_entropy | ba766606a14639d65357ef7468ee2dbadece8261 | 600,696 |
def frequency_bands(f,Y):
"""Process to obtain the values for each frequency band.
Parameters
----------
f : list
Frequency bins for given FFT parameters.
Y : ndarray
Array of values from which we divide into frequency bands.
Returns
-------
delta : array
Ar... | ea8d41ff6cf7e4531dd6c2b5c22e7d8e6e78e4e6 | 600,698 |
import struct
def _replace_header_size(raw_header: bytes, header_size: int) -> bytes:
"""Replace the 'header_size' field in a raw header."""
header_size_bytes = struct.pack("<I", header_size)
return raw_header[: 8 + 4] + header_size_bytes + raw_header[8 + 4 + 4 :] | b51e54452cfb284d92075a09bd738474928a7e00 | 600,699 |
def get_r_env(A_env, A_A):
"""床面積の合計に対する外皮の部位の面積の合計の比 (7)
Args:
A_env(float): 外皮の部位の面積の合計 (m2)
A_A(float): 床面積の合計 (m2)
Returns:
float: 床面積の合計に対する外皮の部位の面積の合計の比
"""
return A_env / A_A | eb01ff8f3478e082d5649316445db34524c7735d | 600,701 |
def transpose(matrix):
"""
IMPORTANT: You should only use list comprehension for this question.
Follow the syntax guidelines in the writeup.
Takes in a list of lists representation of a matrix and
returns its transpose, also as a list of lists.
>>> arr1 = transpose([[1,2,3],[4,5,6],[7,8,9]])
... | 651e2e004bffecf112fb2de78db73e4c6bd7520e | 600,703 |
import torch
def make_features(batch, side, data_type='text'):
"""
Args:
batch (Tensor): a batch of source or target data.
side (str): for source or for target.
data_type (str): type of the source input.
Options are [text|img|audio].
Returns:
A sequence of src/t... | 617892884d0fe3a783c17ad185b1996784399a63 | 600,705 |
def check(plays, winning_numbers):
"""Check if the given plays match any of the winning numbers:
* plays is a list of powerball play tuples.
* winning_numbers is a powerball play tuple.
A powerball play tuple contains a list of 5 numbers followed by a
powerball number. e.g. ([6, 20, 21, 52, 55], 2... | 0e1671cc29e7836e9fdd08220a5d41d3b3620298 | 600,706 |
def compute_metrics(qids_to_relevant_documentids, qids_to_ranked_candidate_documents, exclude_qids):
"""Compute MRR metric
Args:
p_qids_to_relevant_documentids (dict): dictionary of query-document mapping
Dict as read in with load_reference or load_reference_from_stream
p_qids_to_ranked_cand... | d9d3f21247522bdae9b5a357b37bc68d73a98dc5 | 600,708 |
def prepare_data(*, data, x_name, y_name):
"""Change format from {"algo": ..., "algo_name": ..., "metrics": dict} to (algo, instance, x, y)."""
res = []
for met in data:
res.append(
(
met["algo"],
met["algo_name"],
met["metrics"][x_name],
... | 8d4769f4a5e6fdd222f2dd54b10d144d45e9207a | 600,711 |
def findAnEven(l):
"""
Assumes l is a list of ints
Returns the first even num in l
Raises ValueError if l doesn't contain an even num
"""
first_even_n = 0
for num in l:
if num % 2 == 0:
first_even_n = num
break
if first_even_n == 0:
raise ValueError("l doesn't contain an eve... | 8386c598bf62d4edfc22911bf9326835dc23490f | 600,713 |
from typing import List
def levenshtein_distance(s1: str, s2: str) -> int:
"""Return the Levenshtein distance between two strings,
using the Wagner-Fischer iterative algorithm.
This function is based on code from https://github.com/toastdriven/pylev:
Copyright (c) 2012, Daniel Lindsley
All right... | 6b4b4ab2e1453e9ed8b2b5ee1aacc477d1571ceb | 600,715 |
import hashlib
def md5(file_path, save_md5=True, md5_path=None):
"""
It generates the MD5 code of the input file.
It saves the code into a file if it save_md5 is True.
It saves the code into the text file of 'md5_path'.
If md5_path is None, the name of the file is the same as the input file
wi... | e3fe873d6f754431ca5a6460554c0de21b2d8df8 | 600,716 |
def count_text_lines(txt_file):
"""Get number of lines in a text file
Args:
txt_file: txt file to count
Return:
int, the number of lines in the input file
"""
f = open(txt_file, "r")
lines = f.readlines()
f.close()
return len(lines) | 3b140849c2a081499990ee343da2b93bc147b06b | 600,717 |
import math
def combined_rank(R_k):
"""Compute the combined habitats ranks as described in equation (3)
Inputs:
- R_k: the list of ranks
Output:
- R_hab as decribed in the user guide's equation 3."""
R = 4.8 -0.5 *math.sqrt( (1.5 *max(5-R_k))**2 + \
... | af4c0a4a61475b2a0260ad959d025cd8443f183c | 600,719 |
def count(sequence, condition=None):
"""
Returns number of item in a sequence satisfying given condition.
Args:
sequence: iterable
Sequence of items to go through.
condition: callable or None
Condition to test.
Returns:
int
N... | 0828259724189be0e76a52ae2683525b0fe8e4fb | 600,720 |
def isc_1km_to_250m ( i_sc_1km ) :
"""
return the 250m grid index cross track of a 1km pixel
"""
return 4. * i_sc_1km | b9fa5bcad88de7daeb2b876cf4a1afc966f5aa20 | 600,723 |
def get_row(csr, row):
"""returns row from csr matrix: indices and values."""
start = csr.indptr[row]
end = csr.indptr[row + 1]
return csr.indices[start:end], csr.data[start:end] | 979eed806e19ce59cc4614ae5e264eba07f814d7 | 600,725 |
def get_zone_id(route53, domain):
"""Return the hostid for a domainname."""
# return jsondata['HostedZones'][]
response = route53.list_hosted_zones()
search_domain = domain + "."
for i in range(len(response['HostedZones'])):
if response['HostedZones'][i]['Name'] == search_domain:
... | 940d183bf3df5819252edb65f75660b37cdf45e1 | 600,729 |
import ipaddress
def is_valid_ip(ip_address):
""" Check Validity of an IP address """
try:
ip = ipaddress.ip_address(u'' + ip_address)
return True
except ValueError as e:
return False | c6b5011610249af389fc0e16c282cdaab245faeb | 600,732 |
from networkx.readwrite import json_graph
import json
def load_graph(json_name):
"""
Args:
json_name: json file name
Returns:
networkx graph
"""
with open(json_name, 'r') as f:
data = json.load(f)
f.close()
graph = json_graph.node_link_graph(data)
print('Loade... | 09882c9ac5368b78d7a4c7b3cd6395102070d046 | 600,735 |
def is_even(x):
""" Determines if x is even """
return x % 2 == 0 | efce3a9804891a8db1daa506186e06e7d9e4b465 | 600,736 |
def _get_frozen_unfrozen(tensorstore_metadata):
"""Returns two lists with the names of axes that are frozen and unfrozen."""
frozen = []
unfrozen = []
for axis_name in tensorstore_metadata['axes']:
if axis_name in tensorstore_metadata['axesWrap']:
wrapped_axes = tensorstore_metadata['axesWrap'][axis_n... | 2184997db689ab648bbd5459797b20cd130c7ee2 | 600,737 |
def crc8(b, crc):
"""
Updates a CRC8 value with a new byte.
"""
b2 = b
if (b < 0):
b2 = b + 256
for i in range(8):
odd = ((b2 ^ crc) & 1) == 1
crc >>= 1
b2 >>= 1
if (odd):
crc ^= 0x8C
return crc | 6658b34ca45b1335cbc480d114da18f487e4eba3 | 600,738 |
def get_feature_type(
feature_text: str) -> str:
"""
Args:
feature_text: endswith '\n'
For example:
' CDS complement(12..2189)
' /gene="rIIA"
' /locus_tag="T4p001"
' ... | 6218e625a339f028968060d45c13542dd2569ee2 | 600,739 |
def is_iterable( x ):
"""Check if x is an iterable object"""
return hasattr( x, '__iter__' ) | 7a098c997f06f931d7a7822a13db7626ba07beda | 600,740 |
def compare_overlaps(context, synsets_signatures,
nbest=False, keepscore=False, normalizescore=False):
"""
Calculates overlaps between the context sentence and the synset_signture
and returns a ranked list of synsets from highest overlap to lowest.
"""
overlaplen_synsets = [] # ... | 8b666e02dfe7ef6a938ffac63b94fefe0f956889 | 600,741 |
from typing import Any
def ignore_if_not_confirmed(answers: dict[str, Any]) -> bool:
"""Ignore if not confirmed question."""
return not answers["confirmation"] | db30fe363f054e0bc7a7c64ff3fd50a8bfa58e9b | 600,742 |
def strip_extra_spaces(input_string):
"""
Removes extra spaces from input string
>>> strip_extra_spaces("I have no cats")
'I have no cats'
"""
while " " in input_string:
input_string = input_string.replace(" ", " ")
return input_string | e42df55a20a6d581f03f7bc5aeef545deb041cca | 600,745 |
from typing import Union
from typing import Type
from typing import Any
import inspect
def is_method(item: Union[object, Type[Any]], attribute: Any) -> bool:
"""Returns if 'attribute' is a method of 'item'."""
if isinstance(attribute, str):
try:
attribute = getattr(item, attribute)
... | c4c4267b1ca5c49df44983009c4df1eb2454339b | 600,746 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.