content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def abbreviation_in(abbreviations):
"""Constrain the course to given abbreviations."""
def _satisfies(course):
return course.abbreviation in abbreviations
return _satisfies | 708d98eb5af039504f3425b947d2918a42350428 | 636,497 |
import shutil
def center_text(message:str) -> str:
"""Takes a string and returns the centered result as a string.
Parameters
----------
message: (str)
The message to center
Examples
--------
Printing someones name centered in terminal.
```
from sdu.cli import center_text... | 9e5d4f1512f3fdc0af95093c0ff5222b5f41aa5f | 636,498 |
import base64
def serialize_bytes(b: bytes) -> str:
"""
Takes a bytes object and serialize it.
Must be reversible with `deserialize_string()`.
"""
return base64.b64encode(b).decode("utf-8") | ab153397125771647f75721e757a7a0daddee89a | 636,501 |
def _get_interval_result(result):
"""Parse the raw output of the REST API output and return the timestep
Args:
result (dict): the raw JSON output of the ESnet REST API
Returns:
int or None
"""
value = result.get('agg')
if value:
return int(value)
value = result.get... | a2f73870034863e034255a696e950ec53f67284d | 636,505 |
def _string_to_numbers(input_string) -> list:
"""Convert comma-separated floats in string form to relevant type.
Parameters
----------
input_string : string
Comma-separated floats values encoded as a string.
Returns
-------
list of numbers
Returns converted list of floats o... | 6c53ed2571251e872b30b8238e18ae6209523fdd | 636,510 |
def hits(origin, res):
"""
calculate the hit number of recommend result
:param origin: dict {user:[item,...]} the user click or behave items
:param res: dict {user:[item,...]} the algorithm recommend result
:return: int the number of res result in origin
"""
hitCount = {}
for user, items... | 6663c125a0c12692eaddac0cc6aeed5eab04b9d6 | 636,512 |
def gf_sub_ground(f, a, p, K):
"""
Compute ``f - a`` where ``f`` in ``GF(p)[x]`` and ``a`` in ``GF(p)``.
**Examples**
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.galoistools import gf_sub_ground
>>> gf_sub_ground([3, 2, 4], 2, 5, ZZ)
[3, 2, 2]
"""
if not f:
... | 998db6ebd121936012eaa2f9421f11b216e99482 | 636,523 |
def get_atari_filter(shape):
"""Get default model set for atari environments."""
shape = list(shape)
# (out_size, kernel, stride)
filters_84x84 = [
[16, 8, 4],
[32, 4, 2],
[256, 11, 1],
]
filters_42x42 = [
[16, 4, 2],
[32, 4, 2],
[256, 11, 1],
... | d22870fdd6df44fa2e02907dfbc1a7df878f42fe | 636,526 |
import torch
def interpolate_bilinear(grid,
query_points,
name='interpolate_bilinear',
indexing='ij'):
"""Similar to Matlab's interp2 function.
Finds values for query points on a grid using bilinear interpolation.
Args:
grid: a... | 5c3293b30bcc87ccc0ba4041001c9d5404295b79 | 636,528 |
from unittest.mock import call
def get_items(service,
function,
items='items',
throw_reasons=None,
retry_reasons=None,
**kwargs):
"""Gets a single page of items from a Google service function that is paged.
Args:
service: A Google servic... | a0788cccfba9ffb12f3ee8f52396ff16a912fdc0 | 636,530 |
import socket
def get_hostname_by_addr(addr):
"""return hostname for host at address"""
try:
(hostname, aliaslist, ipaddrlist) = socket.gethostbyaddr(
socket.gethostbyname(addr)
)
return hostname
except:
return addr | f71d8221faf757f22065dac1c33480c6a09447fa | 636,531 |
def img_normalize(img, val_range=None):
""" Normalize the tensor into (0, 1).
Args:
tensor (torch.Tensor): input tensor.
val_range (tuple): range in the form (min_val, max_val).
Returns:
torch.Tensor: normalized tensor
"""
t = img.clone()
if val_range:
mm, mx = v... | 199e22c7b2b0c1316205febd3238046a9f452bfb | 636,533 |
def vectorize(function):
"""
:param function: Function to be vectorized
:return: Vectorized function
Create new function y= vf(x), such that:
y = f(x)
/ map(f, x) if x is list
vf =
\ f(x) if x is not list
Example:
>>> import math
>>>
>>> sqrt... | 551daccbb1264da1bae31f0477a65d76d2d29035 | 636,534 |
from typing import List
def generate_pairs(number: int) -> List[List[int]]:
"""Generate all pairs of number sequence.
Args:
number: <int> the number
Returns: <list> a sequence
Examples:
>>> assert generate_pairs(1) == [[0, 0], [0, 1], [1, 1]]
"""
return [
[top, inner... | 1f711fca8774ce06dc291d45aff1d4ac3b1388e1 | 636,538 |
def deserialize_text(value):
"""
Deserialize a text value,
"""
return value | 560c1858710bcd2f2cdda5a12383a70b3f8e8296 | 636,540 |
def coq_param(name, type):
"""Coq parameter
Arguments:
- `name`: name of the variable
- `type`: type of the variable
"""
return "Parameter {0!s} : {1!s}.\n".format(name, type) | e674f2d93b2cb3b85b5ec7d487917b1035b464f4 | 636,542 |
from typing import Optional
import base64
def webex_id_to_uuid(webex_id: Optional[str]) -> Optional[str]:
"""
Convert a webex id as used by the public APIs to a UUID
:param webex_id: base 64 encoded id as used by public APIs
:type webex_id: str
:return: ID in uuid format
"""
return webex_... | d2fb6f5aa8c28d84d0f91a2713dfae4b8a507642 | 636,546 |
import itertools
def create_pairs(df, column_entity_list):
"""
df: Pandas dataframe
Find all pairs of entities in any list of entities
Returns list of paired tuples of the for [(A,B), (B,C)]
"""
# Join as lists
l = [''.join(row) for row in df[column_entity_list]]
# Tokenize string... | cb604aacee8dc70d07b70731b7ab169cb645c874 | 636,547 |
import base64
def to_base64(utf: str) -> str:
""" Convert a string to its base 64 encoded string. """
bs: bytes = base64.b64encode(utf.encode())
return bs.decode() | d3224aaecc87c07c9b2fe0ac0605eaa37a11a7dd | 636,548 |
import re
def replaceCaseInsensitive(a_string, to_replace, replacement):
"""assumes a_string is a string
assumes to_replace is a string
assumes replacement is a string
returns a new string, a_string with any instances of to_replace replased
with replacement. case insinsitive."""
pattern = re.c... | 75b7035ded2c6840e41817e0ad6b13ae896ed970 | 636,553 |
import hashlib
def gen_sha256_hash(msg):
"""Generate SHA 256 Hash of the message."""
hash_object = hashlib.sha256(msg.encode('utf-8'))
return hash_object.hexdigest() | 4de420ab6fa9878f8c03a17b78b5508a1fecde63 | 636,556 |
def getNeighFeat(data_rna, G, neighbors, norm = False):
"""
Function for getting neighbourhood features. Calculates the sum of logFC
across the different neighbours of the gene.
To normalize for number of neighbours with change in fold change (FC), the
norm parameter need to be True.
... | 9ee1df8c32c71f3431fdb93968a83812cbe5a47f | 636,558 |
def timestamp(pkt_hdr):
""" Returns the timestamp of the packet in epoch milliseconds. """
(epoch_secs, delta_micros) = pkt_hdr.getts()
epoch_micros = (epoch_secs * 1000000.0) + delta_micros
return epoch_micros | ff4e8acac6cc8b65f72db8740bd3e5b91a062013 | 636,559 |
def _qualname(obj):
"""
Return the (non-fully-)qualified name of the given object.
"""
return obj.__qualname__ | ceb8c09309822c633f9dcfd0e9d1f741633071c2 | 636,561 |
def delete_vertices(graph, dverts):
"""Delete the vertices indexed by dverts from graph; return the resulting graph."""
vertices, edges = graph
remverts = list(filter(lambda x: x not in dverts, range(len(vertices))))
vmap = {v: n for (n, v) in enumerate(remverts)}
nvertices = list(map(vertices.__get... | beed1a7e4c59fe842cd3a568c1bd3e75654f59cd | 636,563 |
def HasPackedMethodOrdinals(interface):
"""Returns whether all method ordinals are packed such that indexing into a
table would be efficient."""
max_ordinal = len(interface.methods) * 2
return all(method.ordinal < max_ordinal for method in interface.methods) | 6c52e6ca065664480f3f32ac79906f9a9906b57e | 636,564 |
import textwrap
def _format_doc(docstring, prefix):
"""Use textwrap to format a docstring for markdown."""
initial_indent = prefix
# subsequent_indent = " " * len(prefix)
subsequent_indent = " " * 2
block = docstring.split("\n")
fmt_block = []
for line in block:
line = textwrap.f... | 1bf2bf0ee35f9b6e345eb8c70355d0a86bf74290 | 636,567 |
import json
def PrepareGroupORM(r, obj, mapping, objname, request, mappingattr='mapping'):
"""Prepare data assign to orm
Examples::
try:
r = PrepareGroupORM(r, obj, mapping, obj__heads__, self.args.items())
except Exception as error:
return omitError(ErrorMsg=repr(erro... | 6a202d295771e6034011953d476cd1432d671f0b | 636,569 |
def oc_to_vlan_range(value):
"""
Converts an industry standard vlan range into a list that can be
interpreted by openconfig. For example:
["1", "2", "3..10"] -> "1, 2, 3-10"
"""
return ",".join(["{}".format(s).replace("..", "-") for s in value]) | 2556b41ae83a31e2e66466a157d208c09efec7d6 | 636,570 |
def get_inputs( filename ):
"""
The input notes consists of two lines.
Line 1 - estimate of earliest timestamp of departure
Line 2 - bus IDs in service, where 'x' = out of service
This function returns a dict with the time, buses in service and their offsets
"""
with open( filename, 'r' ) a... | e2991b7f454a89d3076c72362416e82526ef214f | 636,572 |
def F2K(T_F):
"""
Convert temperature in Fahrenheit to Kelvin
"""
return 5/9*(T_F+459.67) | dd7ed4866debef819ddc8cf3f298abfb23908c6c | 636,575 |
def convert_to_demisto_class(was_classified: str) -> int:
"""
Convert was_classified to demisto classification
:param was_classified:
:return:
"""
if was_classified == 'Yes':
demisto_class = 1
else:
demisto_class = 0
return demisto_class | 9c5f43224dae1f732bee779e5fee1093d6051273 | 636,577 |
def get_months_in_range(startdate, enddate):
"""Enumerates all months from startdate to enddate
Args:
startdate: start of the list of dates
enddate: end of the list of dates, likely today
Returns:
list of months in iso8601 format: yyyymm
"""
result = []
startmonth = [int... | 9805fb4848ee6395d9dd5db27022ab68de1b06cb | 636,584 |
def __rred(r_1, r_2):
"""
Calculate the reduced (effective) radius of two radii according to Hertzian
contact theory.
Parameters
----------
r_1: scalar
The first radius.
r_2: scalar
The second radius.
Returns
-------
r_red: scalar
The reduced (effective... | bdde676ddc3ec23693db98aee060e1894939226c | 636,585 |
import random
import json
def create_fake_community(faker):
"""Create fake communities for demo purposes."""
data_to_use = {
"access": {
"visibility": random.choice(["public", "restricted"]),
"member_policy": random.choice(["open", "closed"]),
"record_policy": rando... | 218657164f5acb7866bec8f3680be7df73151ea1 | 636,586 |
def negative_predictive_value(y_real, y_pred):
"""
Computes negative predictive value of a binary classification model: NPV = TN/(TN+FN).
Args:
y_real (np.array): Array of ground truth values
y_pred (np.array): Array of predicted values
Returns:
(float): The negative predictiv... | 2a0ca0feab7c53195e21eff0090b025b001d29af | 636,587 |
from functools import reduce
def dtype_element_count( dtype, name = None ):
"""Returns the number of values that compose a dtype.
If you need the number of elements of a specifically named
column, pass the root dtype in with the name.
Ie::
>>> a = numpy.dtype([
... ('position... | a5a7a8a2d0a5de04f38e3f6efe3361f59778e0b6 | 636,590 |
def kwargs_to_string(kwargs):
"""
Given a set of kwargs, turns them into a string which can then be passed to a command.
:param kwargs: kwargs from a function call.
:return: outstr: A string, which is '' if no kwargs were given, and the kwargs in string format otherwise.
"""
outstr = ''
for ... | cb0496e0695b84de3922c03d0a542cb5ad091334 | 636,591 |
def append_collection_links(request, response, link_dict):
"""
Convenience method to append to a response object document-level links.
"""
data = response.data
if not 'collection_links' in data:
data['collection_links'] = {}
for (link_relation_name, url) in link_dict.items():
... | 8f25910c182f68c46172354f1a3bf9b336154126 | 636,594 |
def sol_format(values, n):
"""
Formats the size of the n biggest SCCs using the format "A,B,C".
If the number of values is less than n, then the value 0 is used.
"""
res = [0]*n
# Get first n values
for i in range(min(len(values), n)):
res[i] = values[i][1]
# Format to string
... | 0cd5b89105b9acf52e26d76aea128b8fb0d252dc | 636,595 |
def fatorial(num = 1, show = False):
"""
-> Cálculo do fatorial de um número
:param num: O número a ser calculado
:param show: (Opcional) mostra o calculo se True
:return: Retorna o valor do fatorial do num.
"""
cal = 1
for c in range(num, 0, -1):
cal *= c
if show == True... | 975fd49631ea5b16f4a80102c9d9670d19f56c53 | 636,599 |
def rowswap(matlist, index1, index2, K):
"""
Returns the matrix with index1 row and index2 row swapped
"""
matlist[index1], matlist[index2] = matlist[index2], matlist[index1]
return matlist | e525d3a29345b7a47d080f431ff51a0fc0914ce3 | 636,600 |
def check_joystick_compatibility(pg_joystick):
"""
Check if passed joystick is compatible for this application.
Buttons, axes and hats number are checked to consider joystick as compatible or not.
:param pygame.joystick.Joystick pg_joystick: joystick
:return: True if :var pg_joystick: is compatible with current ... | ae1af75b06e85d56e4fc2de130358578df927518 | 636,602 |
import logging
def get_logger(name):
"""Gets logger for module by it's name.
:param str name: name of the module.
:rtype: logging.Logger
"""
name = name.split(".")[-1]
return logging.getLogger(name) | 8d39d901d403f2dcdb3d6fdce96cc3e10a8de921 | 636,604 |
def data_to_psychomotor(dic):
"""
Returns a dictionary of psychomotor details of each student
{name:{details}}
"""
final_dic = {} #will return to psychomotor
dic_psymo = dic["psychomotor"][0] #the relevant sheet
for key, value in dic_psymo.items():
del value["AGE"]
final_d... | a544b0ec8c8e3639ed9e5f82c5b0853c3e283a7e | 636,605 |
def horizontal_overlaps(rect, others, sorted=False):
"""Get rects that overlap horizontally with the
given rect."""
overlaps = []
for other in others:
# Note: can optimise to prevent
# going through the rest of the
# array when we hit a non match
if rect.overlaps_y(other)... | 856499aeb2507c5425de63fe95a129058193438f | 636,607 |
def perm2cycles_without_fixed(perm):
"""
Convert permutation in one-line notation to permutation in cycle notation without fixed points
:param perm: Permutation in one-line notation
:type perm: list
:return: Returns permutation in cycle notation without fixed points
:rtype: list
"""
cy... | 7e513b5a36f10dcadf3994996910ad9008ead2c5 | 636,608 |
def merge(line):
"""
Helper function that merges a single row or column in 2048.
"""
n_elements = len(line)
# Remove 0 entries and slide to the left
line = [value for value in line if value != 0]
index = 0
# Iterate while there are possible pairs
while index < len(line)-1:
# ... | 574d525461d1b0982ad5838db444d742d4d93f7e | 636,612 |
def makeseed(a=None):
"""Turn a hashable value into three seed values for whrandom.seed().
None or no argument returns (0, 0, 0), to seed from current time.
"""
if a is None:
return (0, 0, 0)
a = hash(a)
a, x = divmod(a, 256)
a, y = divmod(a, 256)
a, z = divmod(a, 256)
x = (x + a) % 256 or 1
y = (y + a) %... | 256baf066b12da64243f918ee32d87826d144f8f | 636,614 |
def try_cast_float(f):
"""Cast i to float, else return None if ValueError"""
try:
return float(f)
except ValueError:
return None | 8e2159174c4d67f83e20fb0b94661d33dec06291 | 636,619 |
def matrix_indices(vector_idx, matrix_size):
"""
Convert from vector index to matrix indices.
Args:
vector_idx (int): Vector index.
matrix_size (int): Size along one axis of the square matrix to output indices for.
Returns:
(int, int): Row index, column index.
"""
asse... | 0d088bdc52bc6dc9dc43966d5ec8a20f80716c8e | 636,620 |
def check_node_on_pos(graph, position, resolution=1e-4):
"""
Function checks, if at least one node of graph has position 'position'
Returns boolean value. 'position' attribute must be shapely Point object.
Parameters
----------
graph : nx.Graph
networkx graph object (nodes should have a... | eae92a44dad70c0b7ef7cbd8ea29ee7561e17802 | 636,621 |
import pickle
def load_pickle_file(path_to_file):
"""
Loads the data from a pickle file and returns that object
"""
## Look up: https://docs.python.org/3/library/pickle.html
## The code should look something like this:
# with open(path_to_file, 'rb') as f:
# obj = pickle....
## We wi... | 9c23ffeb74189d659b60cbdd4812fb6a573f2037 | 636,622 |
def expand_unknown_vocab(line, vocab):
"""
Treat the words that are in the "line" but not in the "vocab" as unknows,
and expand the characters in those words as individual words.
For example, the word "Spoon" is in "line" but not in "vocab", it will be
expanded as "<S> <p> <o> <o> <n>".
"""
... | 9c20267e7bf6a31f7f21411ec1db701e088268a1 | 636,625 |
def identity(df):
"""Verb: No-op."""
return df | 633835e460b3945fb8c3b634081a65045fc223d9 | 636,626 |
import requests
import logging
def _raise_for_status(response: requests.Response, logger: logging.Logger) -> requests.Response:
"""
Check the status code of the response. If the status code suggests an error, log the response as
JSON and then raise an exception. Otherwise, return the response for further ... | 787e514f128978d834df14ab7bda25b8e7acad35 | 636,629 |
def duration(first, last):
"""Evaluate duration
Parameters
----------
first : int
First timestamp
last : int
Last timestamp
Returns
-------
str
Formatted string
"""
ret = ''
diff = last - first
if diff <= 0:
return ''
mm = divmod(di... | d368f18cb574dadab3794e3816410c9d8dcb07ee | 636,643 |
def replace_ellipsis(n, index):
"""Replace ... with slices, :, : ,:
>>> replace_ellipsis(4, (3, Ellipsis, 2))
(3, slice(None, None, None), slice(None, None, None), 2)
>>> replace_ellipsis(2, (Ellipsis, None))
(slice(None, None, None), slice(None, None, None), None)
"""
# Careful about usin... | 774acac046947261af4e42920823015699d9e8f8 | 636,646 |
from typing import Callable
def max_length(length: int) -> Callable[[str], bool]:
"""
Create an MAX length validator (inclusive)
Args:
length (int): MAX length
Returns:
Callable[[str], bool]: a function with the name exact_length_{length}
"""
def v(_field):
return le... | 6093d934637ee0fe24e1ebf5a57ea59281f4644c | 636,656 |
def parse_field(field):
"""
Parse a non-meta key from the response attributes dict.
The non-meta keys correspond to (sub-)question titles ((s)qid).
If the field name contains no brackets ('[', ']'), a qid without
subquestions is meant. Otherwise one or two sqids are within the
brackets: two if ... | 8c06354f2a2982b8a507d0c1965602e22fa2c03c | 636,657 |
def replace_with_phrases(tokens, phrases):
"""Replace applicable tokens in semantically-ordered tokens
with their corresponding phrase.
Args:
tokens (list of str): A list of semantically-ordered tokens.
phrases (list of str): A list of phrases.
Returns:
list of str: A list o... | b0f3a3652870784c2fab74ac3d229434a58d01f3 | 636,660 |
def get_fasta_size_from_faifile(infile):
"""
Get chromosome size from .fai file
.fai format:
1 249250621 52 60 61
2 243199373 253404903 60 61
3 198022430 500657651 60 61
4 191154276 701980507 ... | 5c33a2eda39108b847fc3add99f45a84dc6b091e | 636,661 |
def add_vecs_to_vocab(vocab, vectors):
"""Add list of vector tuples to given vocab. All vectors need to have the
same length. Format: [("text", [1, 2, 3])]"""
length = len(vectors[0][1])
vocab.reset_vectors(width=length)
for word, vec in vectors:
vocab.set_vector(word, vector=vec)
return... | 72926407518161b5babb637006f190fdf9c5140e | 636,665 |
def int2str(value):
"""
int 转换为 str
"""
return str(value) | 64bf9bcf960263703aa1c3b98bf2cf9ed453c1cb | 636,667 |
def extract_page_id(full_file_name: str) -> str:
"""
Extract page id from file_name
Example:
Data-loss-94d44921-0a4c-4319-8f78-60ef45267d97.md -> 94d449210a4c43198f7860ef45267d97
"""
file_name, _ = full_file_name.rsplit('.', maxsplit=1)
parts = file_name.rsplit('-', maxsplit=5)
id_... | d66f338bb61845af949d94fb6f497c64f26af2c5 | 636,670 |
def _check_key_types(remote_values, local_values):
"""
Validates that the key types match regardless of the casing. E.g. 'RSA' == 'rsa'
:param list[str] remote_values:
:param list[str] local_values:
:rtype: bool
"""
copy = []
for val in local_values:
copy.append(val.upper())
... | 6e32ab9914bdce38a511afd00ff1f56d7c68434b | 636,675 |
def sorted_components(layout_area, row_height, comps):
"""
Sort the components by row
:param layout_area: a list [x, y] that stores the area of the layout
:param comps: a list of components that need to be sorted
:return: a list of rows, each containing a list of components in that row.
"""
... | bf320e9414405192752ccfcced360d8eb06ec0de | 636,682 |
def _sorted_facet_counts(solr_counts, field):
"""
Convert the raw solr facet data (counts, ranges, etc.) from a flat array
into a two-dimensional list sorted by the number of hits. The result will
look something like this: (('field1', count1), ('field2', count2), ...)
"""
raw = solr_counts.get(... | 01d093fd71e80c7651ec4ca9ceb7f66f414fad9e | 636,685 |
import re
def get_percent(line):
"""
Args:
line: A progress string containing percent complete
Return:
integer of current percent value if found, otherwise None
"""
m = re.search(r'\d+', line)
if m:
try:
return int(m.group())
except ValueE... | 0bcf59cdf833b9c29a510169061c1c58df6b7a9b | 636,689 |
def esc(string):
"""
Escape strings for SQLite queries
"""
return string.replace("'", "''") | 54b2faffaba7b5b9cdccc4b6ca31d289e542105f | 636,691 |
def min_length(minimum):
""" Return a function that tests if values are the specified minimum length """
def callback(value):
"""Accept a value to validate, return validation results"""
if len(value) >= minimum:
return True, None
return False, ('"' + str(value) + '" is not a ... | be01b938355c1c4e7bd0fc7c0f025419b8f1986d | 636,694 |
def get_tf_idf(doc_tf, idf_map):
"""
calculate the product of the term frequency and the idf
:param doc_tf: term frequency map of the string
:param idf_map: idf map of all the strings
:return: vector map of a document
"""
vector = {}
for word in doc_tf:
if word in idf_map:
... | 28122958d9464427bb984b3b4a37219b26d05ad8 | 636,695 |
def extract_server_arguments(namespace):
"""Given the output of .parse() on a ArgumentParser that had
add_server_arguments called with it, remove the resulting option in-place
from namespace and return them in a separate namespace."""
server_arguments = type(namespace)()
server_arguments.bind = nam... | c1aeb21fdd0f61b7a6b845cd5d3c815686747fff | 636,703 |
def _IsOutsideTimeRange(timestamp,
time_range = None):
"""Returns a boolean indicating whether a timestamp is in a given range."""
return time_range is not None and (timestamp < time_range[0] or
timestamp > time_range[1]) | 05b72d28607b74f0b71517381583ca88dde0efc5 | 636,704 |
def iloc(df, loc):
"""Get the specified dataframe row as a dict"""
return dict(sorted(df.iloc[loc].items())) | db3c12e0125713b09f005c05d0327f8f779d450a | 636,705 |
import re
def AuthorStart(s):
"""
To check if there is an author for the input text by performing a regex check to match the format of
first name, first name and last name, first name and middle name and last name, or mobile number
Parameters:
s (string): The string for which we need to perform r... | 65042e0ec21fe2d8d6ca48bd9634736e3eb5d386 | 636,707 |
def output_tensor(interpreter, i):
"""Gets a model's ith output tensor.
Args:
interpreter: The ``tf.lite.Interpreter`` holding the model.
i (int): The index position of an output tensor.
Returns:
The output tensor at the specified position.
"""
return interpreter.tensor(interpreter.get_output_det... | 4c4915ac4ee9337daa45eabbbc38e58d1b9fdec9 | 636,709 |
def IsFlag(token_name):
"""Returns whether the passed string is a flag.
Args:
token_name: the string to check.
Returns:
True if it's a flag, False otherwise.
"""
return token_name.startswith('-') | 35731409ac7fffe1917c29e0f4f9735b384d3a4c | 636,710 |
import torch
def L1_loss(pred, target):
"""
Calculate L1 loss
"""
return torch.mean(torch.abs(pred - target)) | dd34fe06502676cba62813e156da5246b5933cc5 | 636,711 |
def get_server_name(prefix, xid, wid):
"""Gets unique server name for each work unit in the experiment.
Args:
prefix: String, the prefix of the server.
xid: Integer, the experiment id.
wid: Integer, the work unit id.
Returns:
String.
"""
return f'{prefix}-{xid}-{wid}' | 6fdaa7c998ccf0f3fa38534b233a25e9fc1eb04a | 636,713 |
def get_build_list(json_data: dict) -> list:
"""Return a list of build IDs for a device"""
builds = []
for firmware in json_data["firmwares"]:
builds.append(firmware["buildid"])
return builds | a92d49cca68cc91a9a3c33aa224583ffcf65a36c | 636,720 |
def _get_fake_dataset_contents() -> str:
"""
Build a fake dataset file and write it to a temporary folder.
The dataset has "measurements" for 3 different channels 0, 8, and 12, with columns for two
numerical features NUM1, NUM2 and two categorical features CAT1, CAT".
Labels are attached to channel ... | 4f3677380fec74f56170ceace42dee1deae22727 | 636,723 |
import typing
def clamp(source: typing.Tuple[int, int, int]) -> typing.Tuple[int, ...]:
"""Helper for clamping rgb values
Args:
source (Tuple[int, int, int]): values to be clamped
Returns:
value (Tuple[int, int, int]): clamped values
"""
return tuple(max(0, min(value, 255)) for v... | 5daedc938cfe1d9930c537db1d46ee0fa676499d | 636,727 |
def _find_cells_with_tags(nb, tags):
"""
Find the first cell with any of the given tags, returns a dictionary
with 'cell' (cell object) and 'index', the cell index.
"""
tags_to_find = list(tags)
tags_found = {}
for index, cell in enumerate(nb['cells']):
for tag in cell['metadata'].g... | 7ff62fc853f5b196a1cd2f0e022867f8f8a8bf65 | 636,729 |
import itertools
def nwise(iterable, n=2):
"""
Iterates over iterable n items at a time
list(nwise('ABCDE', 3))
>>> ['ABC', 'BCD', 'CDE']
"""
iterables = itertools.tee(iterable, n)
[next(iterables[i]) for i in range(n) for j in range(i)]
return zip(*iterables) | 9556614f388747cee62ebf2501a281a0bcf4551b | 636,732 |
def serialize_device(device):
"""
Standard representation for a device as returned by various tasks::
{
'id': 'device_id'
'hostname': 'device_hostname',
'tags': [],
'locked': false,
'state': 'provisioning',
'ip_addresses': [
... | 4d74f43c7cdffed0f605756530aaa46a8796f952 | 636,733 |
from datetime import datetime
def validate_date(date_text):
"""Validates that the date is in ISO 8601 format: YYYY-MM-DD"""
try:
if date_text != datetime.strptime(date_text, "%Y-%m-%d").strftime('%Y-%m-%d'):
return False
return True
except ValueError:
return False | 2d7592edc150b9270403d01c849fd57097111107 | 636,734 |
import types
def _get_synthesizer_name(synthesizer):
"""Get the name of the synthesizer function or class.
If the given synthesizer is a function, return its name.
If it is a method, return the name of the class to which
the method belongs.
Args:
synthesizer (function or method):
... | 2a42e7d43b91b58cd8f8782c3f40950c60a93fbf | 636,738 |
def solution(n):
"""
Determines the maximal 'binary gap' in an integer
:param n: a positive integer (between 1 and 2147483647)
:return: a count of the longest sequence of zeros in the binary representation of the integer
"""
bin_limit = 2147483647
if not isinstance(n, int):
... | a62d7822cbd480f650c0f804e543c0b8f17dee15 | 636,741 |
import struct
def _parseMCCDHeader(header):
"""
Parse experimental metadata from MCCD header. Byte-offsets of
experimental parameters are based on this `reference
<http://www.sb.fsu.edu/~xray/Manuals/marCCD165header.html>`_
Parameters
----------
header : bytes
MCCD header
""... | 0ffd483a412ed79726c687fb4c8dd75e94a21410 | 636,743 |
def _add_solr_language_info(res, obj):
"""
:param res: Solr document, i.e. a dict to which new keys will be added.
:param obj: object which is searched for language information.
:return: mutated dict res
"""
if getattr(obj, 'language', None):
res['language_t'] = obj.language.name
... | e434932074afc8df7d8c6b9e6702e431eed69c32 | 636,748 |
from typing import Union
from typing import List
def sieve_of_eratosthenes(n: int = 2) -> Union[List[int], None]:
"""
Returns a list of prime numbers up to and including n.
For n<2 returns None.
>>> sieve_of_eratosthenes()
[2]
>>> sieve_of_eratosthenes(5)
[2, 3, 5]
>>> sieve_of_eratos... | b0425e13aa71c666593a846caff29d85d19aea42 | 636,749 |
def winner(player):
"""
Check if the player won (has no pieces left in his hand)
:param player: Player whose turn it is
:return: True, if Player won, otherwise False
"""
if len(player.hand) == 0:
return True
return False | 0c71441e43ee828aa7820e9f860ac9b97268b407 | 636,751 |
def is_prime(num):
"""
This function checks whether the input natural number larger than 1 is a prime number.
:param num:
:return: boolean
"""
i = 2
while i ** 2 <= num:
if num % i == 0:
return False
i += 1
return True | dacfb5919dfc52c38f5b364651c9e9d81bec9628 | 636,765 |
import torch
def np2tensor(array, device=None):
"""Convert form np.ndarray to torch.Tensor.
Args:
array (np.ndarray): A tensor of any sizes
Returns:
tensor (torch.Tensor):
"""
tensor = torch.from_numpy(array).to(device)
return tensor | a4f7a0f7e05d49699010877f1d6385eda3354bca | 636,767 |
from typing import Union
from pathlib import Path
def has_dicm_prefix(filename: Union[str, Path]) -> bool:
"""DICOM files have a 128 byte preamble followed by bytes 'DICM'."""
with open(filename, "rb") as f:
f.seek(128)
return f.read(4) == b"DICM" | cddbc4862d9f72695b46b8094e4c24696d6ad5f4 | 636,769 |
def get_sequencing_cell_id(dataset_uuid:str, barcode:str)->str:
"""Takes a dataset uuid and a barcode of a cell within that dataset to produce a unique cell ID"""
return "-".join([dataset_uuid, barcode]) | e0b8b33d192d2398ecedcef206da48c05160c3dd | 636,771 |
def splitlines(string_with_lines):
"""Return a ``list`` from a string with lines."""
return string_with_lines.splitlines() | daea6a35fd652eaab1cda5a022d8d0a85047bf03 | 636,772 |
def _gap_difference(seq_gaps: dict, union_gaps: dict) -> tuple:
"""
Parameters
----------
seq_gaps
{gap pos: length, } of a sequence used to generate the gap union
union_gaps
{gap pos: maximum length, ...} derived from the same seq aligned
to different sequences
Returns... | c52db6cf9557af7425b36ac0a590e8ee69ccf993 | 636,775 |
import random
def one_chance_in (n):
"""
Returns True with a 1/n chance.
"""
return (random.randint(1,n) == 1) | 61f9838139606b33e7f923c03f589571feec8bdc | 636,779 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.