content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import math
def visibility(nov, nol, a):
"""Compute visibility using height-correlated GGX.
Heitz 2014, "Understanding the Masking-Shadowing Function in Microfacet-Based
BRDFs"
Args:
nov: Normal dot view direction.
nol: Normal dot light direction.
a: Linear roughness.
Returns:
The geometr... | 04fb867d55622951fee64c7edb22d042f890ae74 | 676,061 |
def flip(res):
"""flips 'x', 'o' or 'draw'."""
if res == 'x':
return 'o'
elif res == 'o':
return 'x'
elif res == 'draw':
return 'draw'
else:
raise RuntimeError("Invalid res: %s" % str(res)) | 22438c63ae9cc456c2d090b2462e6277a6146d6e | 676,062 |
import math
def calculate_tail_correction(box_legth, n_particles, cutoff):
"""
Calculates the tail correction
Parameters
----------
box_legth : float
The distance between the particles in reduced units.
n_particles : int
The number of particles.
cutoff : float
... | 16ea67d6423cf4a466313a2766aa9c9c4d7c0f15 | 676,065 |
def getPdbCifLink(pdb_code):
"""Returns the html path to the cif file on the pdb server
"""
file_name = pdb_code + '.cif'
pdb_loc = 'https://files.rcsb.org/download/' + file_name
return file_name, pdb_loc | ff8eebf8eb5559088e8f37be67b9b032383b2541 | 676,066 |
def prep_sub_id(sub_id_input):
"""Processes subscription ID
Args:
sub_id_input: raw subscription id
Returns:
Processed subscription id
"""
if not isinstance(sub_id_input, str):
return ""
if len(sub_id_input) == 0:
return ""
return "{" + sub_id_input.strip... | 719693c2a11d1e8611fceec80b34b07a157e91ad | 676,067 |
def nth_eol(src, lineno):
"""
Compute the ending index of the n-th line (before the newline,
where n is 1-indexed)
>>> nth_eol("aaa\\nbb\\nc", 2)
6
"""
assert lineno >= 1
pos = -1
for _ in range(lineno):
pos = src.find('\n', pos + 1)
if pos == -1:
return ... | d0a77d3541874d054297a78bd1307bc18ec220af | 676,070 |
import requests
def get_online_person(params=None, **kwargs) -> bytes:
"""Get a picture of a fictional person from the ThisPersonDoesNotExist webpage.
:param params: params dictionary used by requests.get
:param kwargs: kwargs used by requests.get
:return: the image as bytes
"""
r = requests.g... | 1b492fcf4d67f1431d8883af1761135d4d52cd97 | 676,071 |
def cols_to_count(df, group, columns):
"""Count the number of column values when grouping by another column and return new columns in original dataframe.
Args:
df: Pandas DataFrame.
group: Column name to groupby
columns: Columns to count.
Returns:
Original DataFrame with ne... | d9bdb0e6a87805a02a21d7f19505e84206264d66 | 676,074 |
import math
def calcVector(p1,p2):
"""
calculate a line vector in polar form from two points. The return
is the length of the line and the slope in degrees
"""
dx = p2[0]-p1[0]
dy = p2[1]-p1[1]
mag = math.sqrt(dx * dx + dy * dy)
theta = math.atan2(dy,dx) * 180.0 / math.pi + 90.0
re... | bb89a5332aba097f6178d679accc8786b3e07d51 | 676,079 |
def striplines(text):
""" Remove all leading/trailing whitespaces from lines and blank lines. """
return "\n".join(
line.strip() for line in text.splitlines() if len(line.strip())
) | d0122580daa2e0bff8be323b2eeb1f7966b86cf0 | 676,080 |
from datetime import datetime
def ms_since_epoch(dt):
"""
Get the milliseconds since epoch until specific a date and time.
Args:
dt (datetime): date and time limit.
Returns:
int: number of milliseconds.
"""
return (dt - datetime(1970, 1, 1)).total_seconds() * 1000 | 3a7630c0930949f06573292729156c2e881107bd | 676,086 |
import re
def slugify(s):
"""
Simplifies ugly strings into something URL-friendly.
>>> print slugify("[Some] _ Article's Title--")
some-articles-title
"""
# "[Some] _ Article's Title--"
# "[some] _ article's title--"
s = s.lower()
# "[some] _ article's_title--"
# "[some]___ar... | fb403a0e8ff10e4c672f2fb3835da8b25877da46 | 676,090 |
import linecache
def get_title(notes_path, file_stem):
""" Get the title by reading the second line of the .md file """
title = linecache.getline(notes_path + file_stem + '.md', 2)
title = title.replace('\n', '')
title = title.replace('title: ', '')
return title | 990047acbdcbf3e8d04c8167c59b985938829867 | 676,103 |
from typing import List
from typing import Dict
from typing import Any
def sew_messages_and_reactions(
messages: List[Dict[str, Any]], reactions: List[Dict[str, Any]]
) -> List[Dict[str, Any]]:
"""Given a iterable of messages and reactions stitch reactions
into messages.
"""
# Add all messages wit... | 01824e078fb7a44af6af80f49ff00b5ca5fcd3a6 | 676,104 |
def get_timing(line: str) -> str:
"""
Returns the stimulus timing from a line of text grabbed from a .vmrk file.
"""
return line.split(",")[2] | 299d0e0cd9c84ee926c1a69828c4db966c09fff1 | 676,105 |
def empty_string_check(string, raise_exception=True):
"""
Simple check to see if the string provided by parameter string is empty. False indicates the string is NOT empty.
Parameter raise_exception determines if a ValueError exception should be raised if the string is empty.
If raise_exception is False and the str... | 37b3ea789d31b9aec3c184e35026ad4b4f608d26 | 676,106 |
def get_public_key_from_x509cert_obj(x509cert) -> bytes:
""" returns a RSA public key object from a x509 certificate object """
return x509cert.public_key() | 896411f57781ae0b3537d2678345f0a69311b1e4 | 676,107 |
import re
def cap_case_str(s):
"""
Translate a string like "foo_Bar-baz whee" and return "FooBarBazWhee".
"""
return re.sub(r'(?:[^a-z0-9]+|^)(.)', lambda m: m.group(1).upper(), s, flags=re.IGNORECASE) | a6941c994280eb1564a1d2029d05c43e05925ca7 | 676,112 |
def transfer_mac(mac):
"""Transfer MAC address format from xxxx.xxxx.xxxx to xx:xx:xx:xx:xx:xx"""
mac = ''.join(mac.split('.'))
rslt = ':'.join([mac[e:e + 2] for e in range(0, 11, 2)])
return rslt | 09cf5e33f24c6052cb3c45c8a8c26431f17abb5c | 676,117 |
def make_name(key):
"""Return a string suitable for use as a python identifer from an environment key."""
return key.replace('PLATFORM_', '').lower() | 9b7167025a60958b20939c17cc7ad18084e4d4ee | 676,119 |
def get_crowd_selection_counts(input_id, task_runs_json_object):
"""
Figure out how many times the crowd selected each option
:param input_id: the id for a given task
:type input_id: int
:param task_runs_json_object: all of the input task_runs from json.load(open('task_run.json'))
:type task_r... | 83fc32c0426aaa20055924337048bbac35f9f00d | 676,120 |
def _GetSupportedApiVersions(versions, runtime):
"""Returns the runtime-specific or general list of supported runtimes.
The provided 'versions' dict contains a field called 'api_versions'
which is the list of default versions supported. This dict may also
contain a 'supported_api_versions' dict which lists ap... | a6136ae1cc2ecf6e7068b80c9f6d968dfbcddf2d | 676,121 |
def build_hugo_links(links: list) -> list:
"""
Extens the passed wiki links list by adding a dict key for the hugo link.
"""
for link in links:
link['hugo_link'] = f'[{link["text"]}]({{{{< ref "{link["link"]}" >}}}})'
return links | 98bad831be77545505a2dba92ba84548d91378a2 | 676,125 |
def _is_digit_power_sum(number: int, power: int) -> bool:
""" Returns whether a number is equal to the sum of its digits to the given power """
return number == sum(d ** power for d in map(int, str(number))) | 82b7347c4886a8133a9f50809214f61d8f56f40e | 676,128 |
def get_achievement(dist):
"""Получить поздравления за пройденную дистанцию."""
# В уроке «Строки» вы описали логику
# вывода сообщений о достижении в зависимости
# от пройденной дистанции.
# Перенесите этот код сюда и замените print() на return.
if dist >= 6.5:
return 'Отличный результа... | c71a804806322e24dd0c4ac4ab6524ac15dd9552 | 676,129 |
def support(node):
"""Get support value of a node.
Parameters
----------
node : skbio.TreeNode
node to get support value of
Returns
-------
float or None
support value of the node, or None if not available
Notes
-----
A "support value" is defined as the numeric... | 788814d06d02cdbfdf5803e231dd0bb56e4ea06e | 676,131 |
def merge_sort(sorted_l1, sorted_l2):
""" Merge sorting two sorted array """
result = []
i = 0
j = 0
while i < len(sorted_l1) and j < len(sorted_l2):
if sorted_l1[i] < sorted_l2[j]:
result.append(sorted_l1[i])
i += 1
else:
result.append(sorted_l2[... | 4ffc22f57f70dc23f4e12cb359f4b3b3fc4fd65b | 676,133 |
def construct_html(search_term, results):
"""
Given a list of results, construct the HTML page.
"""
link_format = '<a href="{0.img_url}"><img src="{0.thumb_url}" alt="{0.name}" title="{0.name}"></a>'
html_links = '\n'.join([link_format.format(result) for result in results])
html_output = (
... | 8e77abdf3d18fc8eeb9795847d5565c951762e24 | 676,137 |
def split_by_comma(s):
""" Split a string by comma, trim each resultant string element, and remove falsy-values.
:param s: str to split by comma
:return: list of provided string split by comma
"""
return [i.strip() for i in s.split(",") if i] | eb8a5dd0353addeae55cd85e30e5b0e18c661a8d | 676,139 |
def compute_resource_attributes(decos, compute_deco, resource_defaults):
"""
Compute resource values taking into account defaults, the values specified
in the compute decorator (like @batch or @kubernetes) directly, and
resources specified via @resources decorator.
Returns a dictionary of resource ... | bbc02bfb4dab6bc4825b326f166b2a4d63bfc69d | 676,142 |
import glob
def get_file_list(file_type):
"""
Returns a list of all files to be processed
:param file_type: string - The type to be used: crash, charges, person, primaryperson, unit
:return: array
"""
return glob.glob("/data/extract_*_%s_*.csv" % file_type) | f8d4d63348b1abc61e566698fa70b04da63fab89 | 676,144 |
def _ns(obj, search):
"""Makes searching via namespace slightly easier."""
return obj.xpath(search, namespaces={'aws':'http://www.aws.com/aws'}) | 488f1bf232b9acc5aa3ee801721776ca824e0930 | 676,145 |
def clustering(cloud, tol, min_size, max_size):
"""
Input parameters:
cloud: Input cloud
tol: tolerance
min_size: minimal number of points to form a cluster
max_size: maximal number of points that a cluster allows
Output:
cluster_indices: a list of list. Each element ... | dc12cee3a359eb6dda07ab3f5888d74d21182150 | 676,146 |
def findInEdges(nodeNum, edges, att=None):
"""
Find the specified node index in either node_i or node_j columns of input edges df.
Parameters
----------
nodeNum : int
This is the node index not protein index.
edges : pandas dataframe
Dataframe in which to search for node.
R... | 83ffce762bf660c33787f58c0d132f8a38cf8db9 | 676,148 |
from functools import reduce
def deepGetAttr(obj, path):
"""
Resolves a dot-delimited path on an object. If path is not found
an `AttributeError` will be raised.
"""
return reduce(getattr, path.split('.'), obj) | 9029369c204e78184066032bd2b264d2af758da5 | 676,149 |
def tokenize(sent, bert_tok):
"""Return tokenized sentence"""
return ' '.join(bert_tok.tokenize(sent)) | c955114fb98a62e42e0b6d3fbef0822514dd30e6 | 676,153 |
def get_mask_from_lengths(memory, memory_lengths):
"""Get mask tensor from list of length
Args:
memory: (batch, max_time, dim)
memory_lengths: array like
"""
mask = memory.data.new(memory.size(0), memory.size(1)).byte().zero_()
for idx, l in enumerate(memory_lengths):
mask[id... | 129feda0dabdc5d3b264e82b4fb417723baba31c | 676,154 |
import math
def _get_burst_docids(dtd_matrix, burst_loc, burst_scale):
"""
Given a burst and width of an event burst, retrieve all documents published within that burst, regardless of
whether they actually concern any event.
:param dtd_matrix: document-to-day matrix
:param burst_loc: location of t... | f51c98678b6c6ffc38fa95f4fd721d19d634529e | 676,162 |
def split_by_commas(string):
"""Split a string by unenclosed commas.
Splits a string by commas that are not inside of:
- quotes
- brackets
Arguments:
string {String} -- String to be split. Usuall a function parameter
string
Examples:
>>> split_by_commas('foo, bar(ba... | 8f9c63a1bc4f491d2810b6c701d84bfe00941be8 | 676,163 |
def drop_null_values(df):
""" Drop records with NaN values. """
df = df.dropna()
return df | 2b695f39191267133d70be7c8f8b1b4c4f9307aa | 676,164 |
def run_checks(checks):
"""
Run a number of checks.
:param tuple checks: a tuple of tuples, with check name and parameters dict.
:returns: whether all checks succeeded, and the results of each check
:rtype: tuple of (bool, dict)
"""
results = {}
all_succeeded = True
for check, kwar... | 1a689676f291672112beee784a2440fbeb8db91c | 676,165 |
import pickle
def read_raw_results(results_file):
"""
Read the raw results from the pickle file.
Parameters:
- results_file: the path to the pickle file.
Return:
- results: a dictionary of objects.
"""
results = None
with open(results_file, 'rb') as f:
results = p... | 66ac92d22a77667c63c0598e917205a590df9ce6 | 676,167 |
import calendar
def totimestamp(value):
"""
convert a datetime into a float since epoch
"""
return int(calendar.timegm(value.timetuple()) * 1000 + value.microsecond / 1000) | 6e41f9f23098f3e12d9d7d906e965ae3ba6f0daa | 676,170 |
def error_format(search):
"""
:param search: inputted word
:return: bool.
Checking every element in the inputted word is in alphabet.
"""
for letter in search:
if letter.isalpha() is False:
return True | 3b6f6778cfe41e8a2e535f4fce71a7df602bced5 | 676,175 |
import re
def from_dms(dms_string):
"""
Converts a string from sexagesimal format to a numeric value, in the same
units as the major unit of the sexagesimal number (typically hours or degrees).
The value can have one, two, or three fields representing hours/degrees, minutes,
and seconds respective... | 88e43206d774327f1637431f044f13a1402d30e3 | 676,180 |
def qualify_name(name_or_qname, to_kind):
"""
Formats a name or qualified name (kind/name) into a qualified
name of the specified target kind.
:param name_or_qname: The name to transform
:param to_kind: The kind to apply
:return: A qualified name like: kind/name
"""
if '/' in name_or_qn... | 2d12ac771fcee2ba75cfbdd056daef0900ba43d8 | 676,181 |
import typing
def linear_search(arr: typing.List[int], target: int) -> int:
"""
Performs a linear search through arr. This is O(N) as worst case the last element in arr
will need to be checked
:param arr: The sequence of integers
:param target: The target number to retrieve the index of.
:ret... | f5cd7d779e38e36a07559c6ac9a27ac59451c568 | 676,184 |
import math
def distance(x0, y0, x1, y1):
"""Return the coordinate distance between 2 points"""
dist = math.hypot((x1-x0),(y1-y0))
return dist | ece17d5c5449df8c368e279cb0f7ff937c54343d | 676,187 |
def r_squared(measured, predicted):
"""Assumes measured a one-dimensional array of measured values
predicted a one-dimensional array of predicted values
Returns coefficient of determination"""
estimated_error = ((predicted - measured)**2).sum()
mean_of_measured = measured.sum()/len(m... | ae61d447502af92adb289f0e3229657b749833a8 | 676,189 |
def compute_gcvf(sdam: float, scdm: float) -> float:
"""
Compute the goodness of class variance fit (GCVF).
:param sdam: Sum of squared deviations for array mean (SDAM)
:param scdm: Sum of squared class devations from mean (SCDM)
:return: GCVF
Sources:
https://arxiv.org/abs/2005.01653
... | 9a0fba7b949593c14e6cd0a441facc6001f626bd | 676,191 |
def bind(func, *args):
"""
Returns a nullary function that calls func with the given arguments.
"""
def noarg_func():
return func(*args)
return noarg_func | 3d83c66de52b9493919a7d64a63bf9fe01889f23 | 676,192 |
def read_fasta(fasta):
"""
Read the protein sequences in a fasta file
Parameters
-----------
fasta : str
Filename of fasta file containing protein sequences
Returns
----------
(list_of_headers, list_of_sequences) : tuple
A tuple of corresponding lists of protein desc... | a7e3d3a5dda7d76c66d9ceda57bd53956b84b978 | 676,195 |
def get_service_at_index(asset, index):
"""Gets asset's service at index."""
matching_services = [s for s in asset.services if s.index == int(index)]
if not matching_services:
return None
return matching_services[0] | 2a8e89b63cf8ce3f97226d7c281c8c8318409567 | 676,199 |
def count(pets):
"""Return count from queryset."""
return pets.count() | c4e16693a7515765e09631a4f911a173906e21ac | 676,201 |
import math
def length (v):
""" Length of a vector in 2-space.
Params: v (2-tuple) vector in 2-space
Returns: (float) length
"""
# INSERT CODE HERE, replacing 'pass'
x,y = v[0],v[1]
return math.sqrt ((x**2) + (y**2)) | 07f51cf0e10d2e3567cbe0bb77cc6f3ddedc3b0f | 676,203 |
def descending_coin(coin):
"""Returns the next descending coin in order.
>>> descending_coin(25)
10
>>> descending_coin(10)
5
>>> descending_coin(5)
1
>>> descending_coin(2) # Other values return None
"""
if coin == 25:
return 10
elif coin == 10:
return 5
... | 72857bf5b41789f56862d4acb30a9cf7130761b6 | 676,205 |
def _ds_or_none(ds):
"""return none if ds is empty"""
if any(ds.coords) or any(ds.variables) or any(ds.attrs):
return ds
return None | d873815512527e5b58945ebec1e414864b5d2a19 | 676,207 |
from typing import Callable
from typing import Any
def assert_and_pass(func: Callable, arg: Any):
"""Call ``func``` with ``arg`` and return ``arg``. Additionally allow arg
to be ``None``.
Args:
func: Test function.
arg: Function argument.
Returns:
Result of ``func(arg)``... | fae696f07b1d567b648fa32b3f2291e79b8550c7 | 676,212 |
def type_name(obj):
"""Fetch the type name of an object.
This is a cosmetic shortcut. I find the normal method very ugly.
:param any obj: The object you want the type name of
:returns str: The type name
"""
return type(obj).__name__ | 080f4826de4af3c5f14e08973003416e37ae8dd0 | 676,214 |
from typing import Generic
from re import T
def filter_by_organization(model: Generic[T], organization_id: str) -> QuerySet: # type: ignore
"""
Filters active resources that belong to an organization.
Args:
model (Generic[T]): Model that is going to be queried.
organization_id (str): ID ... | a8c7f2144f451f3f0950c112744a853f099f1337 | 676,215 |
import torch
def pad_feature_map(feature_map: torch.Tensor, padding_size: int):
"""Zero-pad feature map by a constant padding margin.
Args:
feature_map: The map to extract features from.
padding_size: The padding size.
"""
return torch.nn.ConstantPad2d(padding_size, 0.0)(feature_map) | 0e5d08f31c958ac70ff219bf8fb6bf34ae3f9557 | 676,218 |
def is_identity_matrix(L):
"""
Returns True if the input matrix is an identity matrix, False otherwise.
"""
result = len(L) == len(L[0])
for i in range(len(L)):
for j in range(len(L)):
if i == j:
result *= (L[i][j] == 1)
else:
result *=... | be042d8d342f0961a77c6a4ddc1b5b10234a7b08 | 676,223 |
def has_value(value):
"""
We want values like 0 and False to be considered values, but values like
None or blank strings to not be considered values
"""
return value or value == 0 or value is False | 1ffabaed22b2a1b83b89eb4d551c6e776a8e13c0 | 676,224 |
def create_container(swift_connection, name, storage_policy=None):
"""
Create a container with an optional storage policy.
:param swift_connection: connection to Swift
:type swift_connection: :py:class:`swiftclient.client.Connection`
:param name: container name
:type name: string
:param sto... | d7813a6cd3dc1f8548c76753ab0b679499dc179a | 676,226 |
import pprint
def block_indent(text, spaces=4):
"""
Given a multi-line string, indent every line of it by the given number of spaces.
If `text` is not a string it is formatted using pprint.pformat.
"""
return '\n'.join([(' ' * spaces) + l for l in pprint.pformat(text).splitlines()]) | 1b0bad804ffb22e792c1da9b156fdc139d231af9 | 676,229 |
def get_single_company_identifiers(data: dict, identifier: str) -> dict:
"""Retrieves the three identifiers (CIK, ticker, title) of a single company.
:param data: The dictionary mapping CIKs with tickers and title from the SEC.
:type data: dict.
:param identifier: The identifier passed by the user when... | f96ffdb1f97e02e907bebc100a73b320ab231e6d | 676,230 |
def remove_overlap(ranges):
""" Simplify a list of ranges; I got it from https://codereview.stackexchange.com/questions/21307/consolidate-list-of-ranges-that-overlap """
result = []
current_start = -1
current_stop = -1
for start, stop in sorted(ranges):
if start > current_stop:
# this segment starts after t... | 913a1e899ddf456b1273463ac81ba28a226fd1eb | 676,231 |
def get_supported_os(scheduler):
"""
Return a tuple of the os supported by parallelcluster for the specific scheduler.
:param scheduler: the scheduler for which we want to know the supported os
:return: a tuple of strings of the supported os
"""
return "alinux" if scheduler == "awsbatch" else "... | 0ca06c8c5b5259f7916f04569c057db137d6dbfb | 676,232 |
def get_strand(read):
"""Get the strand of the mapped read"""
if read.is_reverse:
return '-'
return '+' | daaa9358dfdb031b7329af9bbeef9d77a5c5bce1 | 676,234 |
from typing import Tuple
from typing import List
def get_home_and_node_id_from_device_id(device_id: Tuple[str, str]) -> List[str]:
"""
Get home ID and node ID for Z-Wave device registry entry.
Returns [home_id, node_id]
"""
return device_id[1].split("-") | e50aeb886e483955cebc93d9e07d671f46c8ca21 | 676,235 |
def get_tag(td, tag, o1, o2):
"""Return the tag between offsets o1 and o2 if there is one, return None if
there is no such tag."""
tags = td.tags.find_tags(tag)
for t in tags:
if t.begin == o1 and t.end == o2:
return t
return None | c3d89631e24abb20ea5df2e9c99d61c477d57291 | 676,236 |
def enum(*values, **kwargs):
"""Generates an enum function that only accepts particular values. Other
values will raise a ValueError.
Parameters
----------
values : list
These are the acceptable values.
type : type
The acceptable types of values. Values will be converted befor... | a1832cff58dd52a2c811228cbf781a054ac8ea7b | 676,237 |
import codecs
import yaml
def load_yaml_file(file_path: str):
"""Load a YAML file from path"""
with codecs.open(file_path, 'r') as f:
return yaml.safe_load(f) | 4c5ba2a85e2b03772a369619e213bed18ce1c229 | 676,240 |
def remove_underscores(value):
"""
Removes the underscores from a given string
"""
return value.replace("_", " ").title() | cb8d64e486ed83859f40d103385083b31954f69e | 676,241 |
def _getView(syn, view_id, clause=None):
"""
Based on a user-defined query calls to synapse's tableQuery function and returns the entity-view generator object.
:param syn: A Synapse object: syn = synapseclient.login(username, password) - Must be logged into synapse
:param view_id: A Synapse ID of... | c61f2b1b674b7e31bbdbbdb9d4cda629400a3e03 | 676,242 |
def _dms2dd(d: float, m: float, s: float) -> float:
"""
Converts a DMS coordinate to DD
:param d: degrees
:param m: minutes
:param s: seconds
:return: equivalent in decimal degrees
"""
return d + m / 60 + s / 3600 | 4d021f6d9287f5b0b5922053b6b7c7a9b590a80e | 676,246 |
import struct
import socket
def _ConvertMaskToCIDR(mask):
"""Convert a netmask like 255.255.255.0 to a CIDR length like /24."""
bits = int(struct.unpack('!I', socket.inet_pton(socket.AF_INET, mask))[0])
found_one_bit = False
maskbits = 0
for i in range(32):
if (bits >> i) & 1 == 1:
found_one_bit =... | bf2903f11b44943353fee5c398816f42ccfa65de | 676,247 |
import jinja2
def invite_form(event, context):
"""Get response for invite code page. Invoked by AWS Lambda."""
template = jinja2.Environment(
loader=jinja2.FileSystemLoader('./')
).get_template('public/tmpl/enter_invite.html')
return {
"statusCode": 200,
"headers": {"Content-Ty... | 8ea22ba166e4469b85aa8897b688f302608302c7 | 676,248 |
def mean(iterable):
"""Returns the average of the list of items."""
return sum(iterable) / len(iterable) | 0292e6fa35f13e6652606c621c3cf93b81f1ef77 | 676,251 |
def strip_prefix(prefix, string):
"""Strip prefix from a string if it exists.
:param prefix: The prefix to strip.
:param string: The string to process.
"""
if string.startswith(prefix):
return string[len(prefix):]
return string | 07dd3cc154dde290d77bfbf4028e8be34179a128 | 676,253 |
def parse_problems(lines):
""" Given a list of lines, parses them and returns a list of problems. """
res = [list(map(int, ln.split(" "))) for ln in lines]
return res | 4e5c62ad2028e9ed441a5aa86276d059e0d118a3 | 676,254 |
def skip_names(mol_list):
"""
Check if a list of molecules contains nomenclature that suggests
it can be skipped.
i.e. lignin implies polymeric species.
"""
# lignin - a polymeric species that can form under oxidative
# polymerisation
# many forms exist. HRP produces some.
... | 39ff61bf257a7822402f5fdb4a68f6cae95288fa | 676,255 |
def get_morsel_cookie(info, name, default=None):
"""Gets the value of the cookie with the given name, else default."""
if info.cookies is not None and name in info.cookies:
return info.cookies[name].value
return default | 7a6ac4536a669869cdc17ab1e0d36078190666b4 | 676,256 |
def readId2Name(fin):
"""
Reconstruct a global id=>username dictionary from an open csv file
Reads the globalId2Name file (or equivalent) and constructs an id=>username
dictionary. Input is an open csv.reader file such as the one constructed
by the main method of this module. Returns a dictiona... | e8874e275fc894818467d8c032bdf58bb0314789 | 676,260 |
from typing import List
def get_filetypes(format: str = 'json') -> List[str]:
"""Get filetypes based on specified format."""
return ['yml', 'yaml'] if format == 'yaml' else [format] | 4e9eb09f69bb727f267e48694b043f94b14bdadd | 676,264 |
def min_x_pt(pt_dict):
"""Returns the key of the point at minimum x
(with minimum y) in the XY plane (Z is ignored)
pt_dict is a collection of 'pt_ID: (x, y, z)'
key-value pairs"""
nmin = (9.9E12, 9.9E12)
the_node = None
for k,v in pt_dict.items():
if v[0] == nmin[0]:
if... | 86c624b5dc9247b9513a9b7a6a5f1d83cadeff85 | 676,266 |
from pathlib import Path
import random
def get_wav_files(data_dir: Path):
"""
Get all *.wav files in the data directory.
"""
files = sorted(data_dir.glob("*.wav"))
random.Random(42).shuffle(files)
return files | 4d57de98c19af017bf9029c51c507545b8888644 | 676,267 |
def get_z_prop(p, pi, n):
"""
Function to get the Z value (standard deviations number under or over the average)
correspondent of the x value (parameter) in the standard normal distribution.
Applied in proportions.
Parameters:
--------------------------
p : double, float
"Succes... | e6e6911fefc76a0188c169275f2e160870abf94e | 676,268 |
def compress_indexes(indexes):
"""Compress a list of indexes. The list is assumed to be sorted in ascending
order, and this function will remove the all the consecutives numbers and
only keep the first and the number of the consecutives in a dict.
eg : [0, 1, 2, 3, 4, 7, 8, 9, 10, 11, 12, 13, 18, 19, 2... | 8863e14ba117bb8367bce7358f25caf719efea04 | 676,269 |
import re
def parse_wbgene_string(string):
"""
Receives a string that contains WBGene indices. Parses the string into a set of WBGene indices. \
The format of a WBGene index is 'WBGene' and exactly 8 digits.
:type string: str
:param string: The string to be parsed. Can be any format of string.
... | 7cf59b47514948c9ab23c0cdeb775ec516bd2d54 | 676,278 |
import math
def rotate(vec, degrees):
"""
Rotates a 2D vector x, y counter-clockwise by degrees degrees
"""
x, y = vec
sin = math.sin(math.radians(degrees))
cos = math.cos(math.radians(degrees))
rot_x = cos * x + -sin * y
rot_y = sin * x + cos * y
return rot_x, rot_y | ec73f11ba9fc43621d4215982d58c6dc7057698e | 676,279 |
import torch
def topk_accuracy(k, logits: torch.Tensor, labels: torch.Tensor, unk_id=None, pad_id=None):
"""
Averaged per sample:
1, if one of the k predictions with highest confidence was the correct one for all sub tokens
0, else
if `unk_id` is given, the best non <unk> prediction will b... | 3a689ded604649dcf6fc1a79bb6971a77f7b3d90 | 676,281 |
import re
def _parse_host(id):
"""
This helper function parses the host from `id` in scope nodes.
Returns the host name if it is a host, else return None.
"""
host_name = None
r = re.match(r"^(.*);<host>$", id)
if r:
host_name = r.group(1)
return host_name | d0186816abff3918def96e52c3ed68e512267728 | 676,282 |
def retrieve_row_values(row, field_names, index_dict):
"""This function will take a given list of field names, cursor row, and an index dictionary provide
a tuple of passed row values.
:param - row - cursor row
:param - field_names -list of fields and their order to retrieve
:param - index_dict - cu... | 9663a4c6d8588f74732af65de1421a1fbccaddde | 676,287 |
from typing import Dict
from typing import Union
from typing import Any
from typing import List
def hash_dict(
item_dict: Dict[str, Union[Dict[str, Any], List[Any], str]]
) -> Dict[str, Any]:
"""
Hash dictionary values.
Parameters
----------
item_dict : Dict[str, Union[Dict[str, Any], List[An... | df38e51c2caaccb7580ced127816eafc4b12c449 | 676,288 |
def ant_2_containing_baslines(ant, antennas):
"""
Given antenna returns list of all baselines among given list with that
antenna.
"""
baselines = list()
for antenna in antennas:
if antenna < ant:
baselines.append(256 * antenna + ant)
elif antenna > ant:
b... | 7795e948152866dd75e254d58fb71cb5762cdb4c | 676,292 |
def count_commas(s: str) -> int:
"""
count commas:
- english comma [,](\u002c)
- Chinese full-width comma [,](\uff0c)
- Chinese seperator / Japanese comma [、](\u3001)
"""
count = 0
for c in s:
if c in "\u002c\uff0c\u3001":
count += 1
return count | 3c317cccaa9d784447734a0930ea0b50a47401bf | 676,293 |
def list_to_dict(node_list: list):
"""
Convert the list to a dictionary,
Create a dictionary, key is a element in the list,
value is a element which next the key, if no exists, the value is None.
Args:
node_list (list): normal, list of node
Returns:
schema (dict): a dictionary
... | 804e71d28c1963fea35def5816cf0901daa1d926 | 676,295 |
def clipAlpha(aj, H, L):
"""
调整aj的值,使L<=aj<=H
Args:
aj 目标值
H 最大值
L 最小值
Returns:
aj 目标值
"""
aj = min(aj, H)
aj = max(L, aj)
return aj | 6b83c38e51bd1d00aa39a5d538c30b01c7e3b958 | 676,297 |
def safe_cast(val, to_type, default=None):
"""A helper for safe casts between types"""
try:
return to_type(val)
except (ValueError, TypeError):
return default | 19f74a0e3e75716486bb1903e784485d9cbdcb03 | 676,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.