content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def format_readonly_node_type(node_id: str):
"""The anonymous node type for readonly node provider nodes."""
return "node_{}".format(node_id) | aacf6779a2a0fdb02b3d5bf3052cce8a630f63ce | 656,571 |
def is_junk(c):
"""
Return True if string `c` is a junk copyright that cannot be resolved
otherwise by the parsing.
It would be best not to have to resort to this, but this is practical.
"""
junk = set([
'copyrighted by their authors',
'copyrighted by their authors.',
'co... | d4c50d484c68a48b932c229bc405142b5d70f46f | 656,573 |
def item_extract(soup, root):
"""
:param soup:上层html数据的soup
:param root:上层解析器xml的结点
:return: 根据解析器抽取的items
"""
items = {}
for child in root:
if child.tag != 'parse':
continue
if child.attrib['type'] == 'soup':
sub_cssselector = child.attrib['cssselecto... | 6bc1fbe5d8e7b4e687b67a23eb7f0fbbdfa1c28f | 656,574 |
def lift_snd(f):
"""Lift a function f onto the second element of a 2-tuple.
>>> lift_snd(list)(('abc', 'def'))
('abc', ['d', 'e', 'f'])
"""
return lambda pair: (pair[0], f(pair[1])) | 55339663e86eb924a46c6bdaa9efa763f3b30960 | 656,576 |
def buildcheck(c):
"""Check if builds are OK"""
return c.run("twine check dist/*") | 146468b5375cee22e3b0e3b86b4f9143a20c6b19 | 656,577 |
def readval(file, ty):
"""Reads a line from file with an item of type ty
:param file: input stream, for example sys.stdin
:param ty: a type, for example int
:returns: an element of type ty
"""
return ty(file.readline()) | c7b6c649cf92f1ba110dd79fd7296ea8a4487c38 | 656,578 |
def create_updater(node_map, from_ver, to_ver):
"""Create an updater to update json loaded data.
Parameters
----------
node_map : Map[str, Function]
Map from type_key to updating function
from_ver : str
Prefix of version that we can accept,
to_ver : str
The target vers... | dc716ee8cb02ae651c902da19e069d615fe0255f | 656,580 |
from datetime import datetime
def default_format_mapping():
"""
Default values to use in formatting template strings.
"""
now = datetime.now()
def_map = {
"date": now.strftime ("%Y%m%d"),
"time": now.strftime ("%H%M%S"),
"datetime": now.strftime ("%Y%m%dT%H%M%S"),
}
return def_map | 868c766e84664109fefdbb14fb05ec7fe6e7a682 | 656,581 |
def condense_font_weight(css: str) -> str:
"""Condense multiple font weights into shorter integer equals.
"""
return css.replace('font-weight:normal;', 'font-weight:400;').replace('font-weight:bold;', 'font-weight:700;') | 45d3fb410bdddb40f55532c6ec12199222d1b659 | 656,582 |
import jinja2
def render_template(template_body: str, **template_vars) -> str:
"""render a template with jinja"""
if template_vars:
template_body = jinja2.Template(template_body).render(**template_vars)
return template_body | 26f4975a10f7aff5bdf5f3ce38a107b76e2816bd | 656,583 |
def alter_tables(rdb):
"""
CREATE tables for numeric and categorical data and necessary indexes.
"""
# Alters in database
create_table_apple_watch_numeric = """CREATE TABLE applewatch_numeric AS
SELECT "type","Name","unit","Date",("Value"::double precisio... | cf916c624d4ae870af206ea9619c60209e5c9058 | 656,584 |
import random
def evolution_search_compare_case2(search_space,
num_init=10,
k=10,
population_size=30,
total_queries=100,
candidate_num=100,
... | 8e826c5d32449047a3fdc5050eaf39a065d1f5ac | 656,585 |
def formatter_str(formatstr):
"""
Creates a formatter function from format string, i.e. '%s, %s' etc
:param formatstr: The formatting string
:return: Formatter function using formatstr
"""
return lambda item: formatstr % item | 817d5bd7f21be932a7ca9419fe87918316e229f3 | 656,586 |
import requests
import hashlib
def get_hash(resource_url):
""" Access the URL provided and calculate an MD5 hash of whatever is returned.
Throw an exception, if the URL is not accessible.
"""
req = requests.get(resource_url, stream=True)
m = hashlib.md5()
for chunk in req.iter_content(chunk_si... | 4cd8f79f5e34bbd5992fb6522b130b8461ce82cf | 656,587 |
def line_strip(line):
"""
Remove comments and replace commas from input text
for a free formatted modflow input file
Parameters
----------
line : str
a line of text from a modflow input file
Returns
-------
str : line with comments removed and commas replaced
... | 0c643b37c377c3ba65b25852316a3bae3f45b13e | 656,588 |
def split(string, sep):
"""Return the string split by sep.
Example usage: {{ value|split:"/" }}
"""
return string.split(sep) | fa403d4a7a4a6cbe4da11609f58c68459875c13f | 656,589 |
import torch
def conv_constitutive_constraint_nonlinear(input, output, sobel_filter, beta1, beta2):
"""Nonlinear extension of Darcy's law
- K * grad_u = sigma + beta1 * sqrt(K) * sigma ** 2 + beta2 * K * sigma ** 3
Args:
input: K
output: u, sigma1, sigma2
"""
K_u_h = - input *... | 9494835703de513ce321528f7f3aed0a77d33124 | 656,590 |
import numpy
def init_uniform_ttable(wordlist):
"""
Initialize (normalized) theta uniformly
"""
n = len(wordlist)
return numpy.ones((n, n + 1)) * (1 / n) | 4619975220e4790ba56f4b177464fe3bcab053be | 656,591 |
def _merge(left, right):
"""
Function merges left and right parts
Args:
left: left part of array
right: right part of array
Returns:
Sorted and merged left + right parts
"""
merge_result = []
i = 0
j = 0
while i < len(left) and j < len(right):
if lef... | db112a9ae55605ecfd7a4ebcc293c48732850889 | 656,592 |
import argparse
def get_parser() -> argparse.ArgumentParser:
"""
parse command line arguments
returns:
parser - ArgumentParser object
"""
parser = argparse.ArgumentParser(description="BBC Pidgin Scraper")
parser.add_argument(
"--output_file_name",
type=str,
d... | 2bee68bc39f7169c7ffdc98061a3ea56f22b8607 | 656,593 |
def _get_input_output_names(onnx_model):
"""
Return input and output names of the ONNX graph.
"""
input_names = [input.name for input in onnx_model.graph.input]
output_names = [output.name for output in onnx_model.graph.output]
assert len(input_names) >= 1, "number of inputs should be at least 1... | 50b40334d69cb4fdaf7afdcd29809cbac675f27a | 656,594 |
def url_param_dict_to_list(url_items_dict):
"""Turn this dictionary into a param list for the URL"""
params_list = ""
for key, value in url_items_dict:
if key != "page":
params_list += "&%s=%s" % (key, value)
return params_list | 23a17e05ff16c7f936f0d0a35e4c6a67fe37dc87 | 656,595 |
def read_lines(file_path):
""" read file as a list of lines """
with open(file_path) as f:
return [l.strip() for l in f.readlines()] | 4127653af7b17d10f770d1302d5ac10a12111de6 | 656,596 |
import torch
from typing import Optional
from typing import cast
def pad_mask(lengths: torch.Tensor,
max_length: Optional[int] = None,
device='cpu'):
"""lengths is a torch tensor
"""
if max_length is None:
max_length = cast(int, torch.max(lengths).item())
max_length =... | e966bfbbd8861738ab594257140baf86860ff9e7 | 656,597 |
def footer_creator(original_msg, slack_user, time_stamp, footer_type):
"""
Take orignal message and add a footer with correct
message and icon based on type
"""
footer_img_urls = {
"0": "",
"1": "https://emojipedia-us.s3.amazonaws.com/thumbs/120/microsoft/106/heavy-check-mark_2714.pn... | f0583b56db192b3b7866443b11e169bcfbc2d473 | 656,598 |
def convert_red(string):
"""Return red text"""
return f"{string}" | 4b05b32c50ebeb062d6504544885fadd68626081 | 656,599 |
import torch
def dice_loss_with_logits(logit: torch.Tensor, target: torch.Tensor):
"""
References
----------
`Dice Loss <https://arxiv.org/abs/1606.04797>`_
"""
if not (target.size() == logit.size()):
raise ValueError("Target size ({}) must be the same as logit size ({})".format(target... | c234b26ff9eb1a06d3ab5e89f749d846486b077a | 656,601 |
def _h_3ab(P):
"""Define the boundary between Region 3a-3b, h=f(P)
>>> "%.6f" % _h_3ab(25)
'2095.936454'
"""
return 0.201464004206875e4+3.74696550136983*P-0.0219921901054187*P**2+0.875131686009950e-4*P**3 | 68e8974cbcbeb873ac06fc1f61b32058b34899a3 | 656,602 |
import os
def get_subj(path, user_filter=None):
"""
Gets all folder names (i.e., subjects) in a directory (of subjects).
Removes hidden folders.
user_filter option can be used to return only the subjects that contain
the given string.
Warning: Returns a list in python2 and a generator in pyt... | 1eef420f580e42aea49e9c36cd5639490db500b5 | 656,603 |
import functools
def memorize(func):
"""Decorator to memorize and return the latest result
of a function.
"""
cache = {}
@functools.wraps(func)
def memorized_func_wrapper(*args, **kwargs):
if func not in cache:
cache[func] = func(*args, **kwargs)
return cache[func]... | 6bedebffb9643042be8ea61874406ed095d216ec | 656,604 |
def csr_ctype(field_data):
""" The type passed to, or returned from, the assembler instruction.
"""
if "width" in field_data:
width=str(field_data["width"])
if width.find("xlen") > 0:
return "uint_xlen_t"
else:
return "uint_csr" + str(width) + "_t"
return ... | 99d211a78b67a3dd8102081415a91edcd4624ecb | 656,605 |
import re
def sanitize_input(raw_data):
"""Removes special characters from raw data.
Keyword arguments:
raw_data -- raw file or URL text
"""
replace = {ord("\f"): " ", ord("\t"): " ", ord("\n"): " ", ord("\r"): None}
# remove formfeeds, tabs and carriage returns
content = raw_dat... | e10d58bc90c0899cea660cf0df746452fb74d774 | 656,607 |
def fnorm(f, normalization):
""" Normalize the frequency spectrum."""
return f / normalization | 453fba23dd9a07a7e82ead88f787ff9b6f47743d | 656,608 |
def neighbours( x, y, world ):
"""
Získá počet sousedů dané buňky.
Parametry:
x (int) X-ová souřadnice
y (int) Y-ová souřadnice
world (list) 2D pole s aktuálním stavem.
Vrací:
int Počet sousedů buňky na souřadnicích [x;y]
"""
# Počet sousedů
... | d780d79d31b99d1b753ed4a19bc3593e15a5af82 | 656,609 |
def make_word_groups(vocab_words):
"""
Add predixes to word groups
:param vocab_words: list of vocabulary words with a prefix.
:return: str of prefix followed by vocabulary words with
prefix applied, separated by ' :: '.
This function takes a `vocab_words` list and returns a string
... | 26cb7c52491acea62d411020d414afa8e57cc50c | 656,610 |
from typing import List
from typing import Dict
def remap_list(target_list: List[int], mapping: Dict[int, int]) -> List[int]:
"""
Take a list of atom indices and remap them using the given mapping.
"""
return [mapping[x] for x in target_list] | 8672f531490fbee6442eaca72b53df10c8844a14 | 656,611 |
def same_line(index, list_):
"""
return corner on the same line
:param index:
:param list_:
:return:
"""
for c in list_:
if c.i == index:
return c | e66b25c6a6a3123d9b11be59bcb0a0243ae058bd | 656,613 |
def binary_search(sequence, value, low, high):
"""Implements binary search, recursively. It operates on smaller and
smaller sections of the given array."""
mid = low + (high - low) // 2
if low == mid and mid == high:
if sequence[mid] != value:
return -1
if value < sequence[mi... | a9fd0673a17d5a5030a9587ddbd597369b8bfeae | 656,614 |
def get_answer():
"""something"""
return True | ab168508c7a759771ac0a0c84af67d5102e68038 | 656,615 |
import ast
from typing import Optional
from typing import List
def read_object_name(node: ast.AST, name: Optional[List[str]] = None) -> str:
"""Parse the object's (class or function) name from the right-hand size of an
assignement nameession.
The parsing is done recursively to recover the full import pat... | 0d0e9f32b14c5e121271d29a3f14151264c9cc5a | 656,616 |
import base64
import pickle
def bp(data):
"""Base64-Pickle."""
return base64.b64encode(pickle.dumps(data, protocol=2)) | 7017bcf8c3e19b5013375a7c0d837e4be01f8a49 | 656,617 |
def length(requests_mean):
"""
Arbitry choices to associate number of requests with length
"""
if requests_mean<=5.:
return 'short';
elif requests_mean<=10:
return 'medium';
else:
return 'long'; | f08051ac49d1a92a04f42d290ed2c6d7d25f1894 | 656,618 |
def pdbatom_formated_str(in_str):
"""
Returns a formatted ATOM record string
"""
pdb_fmt = {
"type": "{:6s}",
"serial": "{:5d}",
"space": "{:1s}",
"name": "{:4s}",
"altLoc": "{:1s}",
"resName": "{:3s}",
"chainID": "{:1s}",
"resSeq": "{:4d}... | 5bdc3fd87b44ec40804edd03450100d28f8791fa | 656,619 |
def name_value(obj):
"""
Convert (key, value) pairs to HAR format.
"""
return [{"name": k, "value": v} for k, v in obj.items()] | d9a5bef186b259401302f3b489033325e32af1f5 | 656,620 |
def keymap(fn, d):
"""returns {fn(k): v for k, v in d.items()}"""
return {fn(k): v for k, v in d.items()} | e7a2aed23e30a35973ed9f534be340553c7d3052 | 656,622 |
def nullValue(value):
"""nullValue.
Args:
value:
"""
returnValue = None
if value and value.strip():
returnValue = value.strip()
return returnValue | 2a1c30c5c7bffd2c2cc4d3633813940fba62c5e3 | 656,623 |
import re
def get_one_match(expr, lines):
"""
Must be only one match, otherwise result is None.
When there is a match, strip leading "[" and trailing "]"
"""
# member names in the ld_headers output are between square brackets
expr = rf'\[({expr})\]'
matches = list(filter(None, (re.search(e... | 02be5aff39c90c7555618e9e87cb3f2d19e845ed | 656,624 |
import json
def _get_synset_labels(filepath: str) -> dict:
"""
Gets synsets from json file in a dict
Args:
filepath: json file path
Returns:
Dict having the following structure:
{str id : (int synset_ID, str label_name )}
"""
with open(filepath, "r") as f:
ra... | bc119f8930dcbe5b5f1a67521e0ff82d4b8aa925 | 656,625 |
def pickPort(loc,PortList):
"""
Evaluates availability of an input (xport) against PortList.
Returns xport once it is verified to be available.
"""
#from locationcode import Loccode
while True:
try:
xport = int(input('Pick the next available port number (>=33) on mod '
... | 762eee09e7f4f3389e99427b399176c7696edbe2 | 656,626 |
def rotation(s,i):
""" Right rotation operator on strings
"""
n = len(s)
return "".join([ s[(n-(i-l))%n] for l in range(n) ]) | 334646fc6c2d252e0af7bb35543426b527d8aaa8 | 656,627 |
def DxxxTID_to_YOtrID(DxxxTID):
""" convert DxxxTID to YOtrID """
return("YOtr" + DxxxTID[1:3].upper() + DxxxTID[-6:]) | fd72db3dcf18b9cff83d79f1f5b9da6836df8a98 | 656,628 |
def is_cap(word: str) -> bool:
"""Return True if the word is capitalized, i.e. starts with an
uppercase character and is otherwise lowercase"""
return word[0].isupper() and (len(word) == 1 or word[1:].islower()) | 78787ca4ed8a4c70b0b19a0c92aa6ae9d72ee2f1 | 656,629 |
def mag(mag_star, mag_ref=0):
"""Calculates the brightness difference based on magnitudes
Parameters
----------
mag_star : float
Magnitude of input star
mag_ref : float
magnitude of reference star"""
return 10**(0.4*((mag_ref)-(mag_star))) | 7bdeb79b44d1b01c582fce394f6497e426e6c939 | 656,630 |
def get_depth(od):
"""Function to determine the depth of a nested dictionary.
Parameters:
od (dict): dictionary or dictionary-like object
Returns:
int: max depth of dictionary
"""
if isinstance(od, dict):
return 1 + (max(map(get_depth, od.values())) if od else 0)
return... | d0b84853e4fb38e3f0e4329a36e4d48d2658df2f | 656,631 |
def next_permutation(t: tuple) -> tuple:
"""
Prints the permutation of the input element t immediately following t in lexicographic order
:param t:
:return:
"""
assert isinstance(t, tuple)
for elem in t:
assert isinstance(elem, int)
assert len(t) == len(set(t))
RIGHT = -1
... | 73847f186c364f4674d601fc74a6f40a25008a95 | 656,632 |
def add_dicts_by_key(in_dict1, in_dict2):
"""
Combines two dictionaries and adds the values for those keys that are shared
"""
both = {}
for key1 in in_dict1:
for key2 in in_dict2:
if key1 == key2:
both[key1] = in_dict1[key1] + in_dict2[key2]
return both | 9061e1abf09899e2f8a93c9c02899e2f8ba769a9 | 656,634 |
from pathlib import Path
def get_output_stem(attributes):
"""Get output file stem, specific to HYPE."""
short_to_stem = dict(tas="Tobs",
tasmin="TMINobs",
tasmax="TMAXobs",
pr="Pobs")
shortname = attributes["short_name"]
if sh... | 5bc226f157b7cca2b72bb70bcb77a61fbabd9416 | 656,635 |
import os
def _get_suffix(path):
"""
Return suffix from `path`.
``/home/xex/somefile.txt`` --> ``txt``.
Args:
path (str): Full file path.
Returns:
str: Suffix.
Raises:
UserWarning: When ``/`` is detected in suffix.
"""
suffix = os.path.basename(path).split("... | 93533010df607200eaecfacc0dfff230ecadd530 | 656,636 |
from typing import Collection
from typing import Optional
def max_offset(offsets: "Collection[Optional[str]]") -> "Optional[str]":
"""
Return the most "recent" offset from a collection of offsets.
:param offsets: A collection of offsets to examine.
:return: The largest offset, or ``None`` if unknown.... | e34c64be7d52e99a9d4cc4aeb49c6e4d7587d93a | 656,638 |
def calculate_distance(P1, P2):
"""Calculates the distance of given points (1D to infinity-D)."""
if len(P1) != len(P2):
raise ValueError('Different dimension of given points.')
square_sum = 0
for i in range(len(P1)):
square_sum += (P1[i] - P2[i])**2
return square_sum**(1 / 2) | 079820b5e90dd485813e00e467b841d47d2f0fc7 | 656,639 |
def chunk_it(seq, num):
"""Split a sequence in a 'num' sequence of ~same size
"""
avg = len(seq) / float(num)
out = []
last = 0.0
while last < len(seq):
out.append(seq[int(last):int(last + avg)])
last += avg
return sorted(out, reverse=True) | 22273e199f0c02cb15b3c4efffb87d55eb173c5d | 656,640 |
def ball_to_int(ball):
"""CHANGE BALL TO INT FROM FLOAT"""
if ball is None:
return None
return (int(ball[0][0]), int(ball[0][1])), int(ball[1]) | 5698b92ccc8c0cdc24027d2d72d5ad8df7d9122a | 656,641 |
def not_below_absolute_zero(temperature):
"""Temperature not below absolute zero"""
return temperature._kelvin >= 0 | 669054c42aae8303840a97dddb0319d4e2c87910 | 656,642 |
def _ensure_unix_line_endings(path):
"""Replace windows line endings with Unix. Return path to modified file."""
out_path = path + "_unix"
with open(path) as inputfile:
with open(out_path, "w") as outputfile:
for line in inputfile:
outputfile.write(line.replace("\r\n", "... | c811eed0860f92dc58b2a184ec6d2a866ef6ee46 | 656,643 |
import math
def calculate_grid_dimensions(area):
"""
:param area:
:return:
"""
return round(math.sqrt(area), 0) | 691ff5850139f4bc584a9aee9e6152e8edc01d16 | 656,644 |
def ext_gcd(a, b):
"""
calculate the greatest common denominator or return integers if
b is 0 or a is an integer multiple of b.
"""
if b == 0:
return 1, 0
elif a % b == 0:
return 0, 1
else:
x, y = ext_gcd(b, a % b)
return y, x - y * (a // b) | d16a25ff3d8f40974132f25aac3ec199a580c5d8 | 656,645 |
import locale
def kilostr_to_int(money,times=1):
"""
Return the int value of the kilo float string.
@param money|string: the string to be converted
@param times|int: how many times to be multiplied by
"""
locale.setlocale(locale.LC_NUMERIC, 'English_US')
to = locale.atof(... | bd0cddabb04d880b6cd8279694006537e71bbe4b | 656,646 |
def cut_off_ringing(k, P, ir_cutoff=5e-5, uv_cutoff=1e2):
"""
Cut off ringing tail at high and low k
Parameters
----------
k: 1d numpy array
Note does not need to be ln-space
P: 1d numpy array
Function evaluated at corresponding k
"""
if ir_cutoff < k.min(): ir_cutoff = k.min()
if uv_cutoff > k.max(): uv_... | 50e343db69fd8ec53f2c632ae2b84eac8b7f3726 | 656,647 |
import tempfile
import subprocess
def convert_and_trim(audio_filepath, freq, dur):
"""
Uses ffmpeg to convert an audio file to a temporary wav file for use
in finding offset.
Args
:audio: path to the audiofile to convert (string)
:freq: Samples / second in the output wav (int)
... | 1c6bad6f3c93b94b66ee1d2678e86370541ecada | 656,648 |
def convert_to_unknown_type(value):
"""
Convert value to it's real type by probing conversions.
"""
if value is not None:
# Attempt to convert to logical
if value.upper() in ["TRUE", "FALSE"]:
return value.upper() == "TRUE"
# Attempt to convert to integer
tr... | 4b5ebf8fd02dbdf24148bf24cd72684816965f34 | 656,649 |
import numpy
def _patches_to_image(patches, image_shape):
"""Reshapes a numpy array of patches to a single image.
Args:
patches: Numpy array of shape (num_patches, patch_width, patch_width, 1).
image_shape: Tuple of integers, the height and width of assembled image.
Returns:
The whole assembled ... | 8bf77822b5ff76672d595323b4643f03634177f0 | 656,650 |
def grab_value_from_file(filename):
"""
Return the value from the first line of a file.
"""
return open(filename, 'r').readline().strip().split()[0] | 02fcf33e04fd5acae9f0e3ea7d4d19b753b8657e | 656,651 |
import ipaddress
def is_ipv4_address(ip_address):
"""
Checks if given ip is ipv4
:param ip_address: str ipv4
:return: bool
"""
try:
ipaddress.IPv4Address(ip_address)
return True
except ipaddress.AddressValueError as err:
return False | d225f7627655265959976fe6451903b06ef393d9 | 656,652 |
def is_dunder(name: str) -> bool:
"""Check if ``name`` is wrapped in double underscores.
>>> is_dunder("__some_dunder__")
True
>>> is_dunder("_some_not_dunder")
False
:param name:
:return:
"""
return len(name) > 5 and (name[:2] == name[-2:] == "__") | 9400b531a93b0c9179ea4a8e911344f319ac9dad | 656,653 |
def _is_kanji(char):
""" Check if given character is a Kanji. """
return ord("\u4e00") < ord(char) < ord("\u9fff") | 6c785eca322002b80ff20212d1a914e538d684ab | 656,654 |
def multiline_input(prompt):
"""Prompt for multiline input"""
lines=[]
print(prompt+" (input will end after entering a blank line) : >")
while True:
line=input()
if not line.strip():
break
else:
lines.append(line)
return "\n".join(lines) | e2841d59b249cda46b47f9690de4ff04efdc29ff | 656,655 |
def fatorial(numero=1, show=False):
"""
-> Calcula o Fatorial de um número.
:param numero: O número a ser calculado.
:param show: (opcional) Mostrar ou não a conta.
:return: O valor do Fatorial de um número n.
"""
fat = 1
ext = ''
for i in range(numero, 0, -1):
... | d83804f839ef36a20fdf8af69d85a9d5a2f9fdfc | 656,658 |
def test_add_to_registry(
CallableRegistry, # noqa: N803
PropertyRegistry,
CachedPropertyRegistry,
CallableParamRegistry,
PropertyParamRegistry,
CachedPropertyParamRegistry,
):
"""A member can be added to registries and accessed as per registry settings."""
@CallableRegistry.registry()... | 5396b034dbe81d04d8b6b1e6d9ae805dc5e86ffe | 656,660 |
def loss(y, ybar, sparm):
"""Loss is 1 if the labels are different, 0 if they are the same."""
return 100.0*int(y != ybar) | 2e6e8d1c13117839c4cb2432e5d92fcdf2bcc8f8 | 656,661 |
def flat_correct(ccd, flat, min_value=None, norm_value=None):
"""Correct the image for flat fielding.
The flat field image is normalized by its mean or a user-supplied value
before flat correcting.
Parameters
----------
ccd : `~astropy.nddata.CCDData`
Data to be transformed.
flat ... | abcd91b54f0664ae05b294fcc64b42f04dfdccef | 656,662 |
def topmon_ready(job):
"""Check if the keywords in the topmon have been replaced correctly."""
job.doc.topmon_ready = False
file_name = job.ws + "/topmon.inp"
if not job.isfile("topmon.inp"):
return False
if job.sp.cutoff_style == "shift":
a = False
with open(file_name) as my... | eaa3d3eb23b201dea20489d4ebbea9ea915e9bec | 656,663 |
def _pretty_str(value):
"""
Return a value of width bits as a pretty string.
"""
if value is None:
return 'Undefined'
return str(value) | 575ca79b7de3af208fb686af4cb92cc81166695d | 656,664 |
import os
def find_juju_ssh_keys():
"""Find the Juju ssh keys."""
paths = []
paths.append(os.path.expanduser("~/.local/share/juju/ssh"))
for path in paths:
if os.path.exists(path):
private = os.path.expanduser("{}/juju_id_rsa".format(path))
public = os.path.expanduser... | 3830338c452d55ce820604cb1a39280e94867db3 | 656,665 |
def format_response_data(sparkl_response):
"""
Builds easy-access object from response data sent back by SPARKL.
"""
# Get name of response/reply and list of output fields
try:
response_name = sparkl_response['attr']['name']
fields_data_list = sparkl_response['content']
# Retur... | bb952b9eb4cb54b0079887e1d9d7d5c76db1ae7f | 656,667 |
def to_cast(f):
"""
Decorator to easily use a function as casting argument.
Example:
from decouple import config
from decouple_plus.casting import to_cast
@to_cast
def to_tuple(value, delimiter=','):
# do stuff
...
# TEAMS_TREE == pepe,carl,jos... | aa00badcf86ae70b3056162d4c4bea52c44dee01 | 656,668 |
def coding_problem_12(budget, choices):
"""
There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a
function that returns the number of unique ways you can climb the staircase. The order of the steps matters.
For example, if N is 4, then there are 5 un... | 034dc1ece7c03bd1ebfbc4614c291166448a6a57 | 656,669 |
def get_cannabis_data_ok():
"""Get cannabis data from Oklahoma."""
return {} | b7687d7667df59b7885d48ad30c63e91a6850f55 | 656,670 |
def solve(n, ar):
"""
Return the absolute sum of the nxn matrix defined by ar.
"""
# Initialize the sum of the diagonals 1 and 2.
d1sum = 0
d2sum = 0
# Iterate through the list of n-sized lists, one row at a time and use
# enumerate() to generate the current index value which we'll use ... | 2a63345fff4f9914a33924b7fccf972b23840912 | 656,671 |
def vacation_wp (db, wpid) :
""" Allow creation of vacation wp for other user
"""
wp = db.time_wp.getnode (wpid)
tp = db.time_project.getnode (wp.project)
if tp.is_public_holiday :
return True
return False | e79896a199a716cba71dc393feeb9e2a1266d8c9 | 656,673 |
import time
def ofoc_year_zero():
"""Get Jan 1 2001 in seconds"""
str_zone = time.strftime("%z")
int_zone = ((int(str_zone[:3]) * 3600) + (int(str_zone[3:]) * 60))
return int(time.mktime(time.strptime("1 Jan 01", "%d %b %y")) + int_zone) | 5a5a2139f4dccd8f960bea371fddb3c45113c434 | 656,674 |
from typing import Sequence
from functools import reduce
from operator import mul
def prod(digits: Sequence[str]) -> int:
"""
Returns the product of a string of digits.
"""
return reduce(mul, map(int, digits)) | 016e29bd6a9da420883157c4f4e38f353ad71e86 | 656,675 |
def truncate_term_rankings( orig_rankings, top ):
"""
Truncate a list of multiple term rankings to the specified length.
"""
if top < 1:
return orig_rankings
trunc_rankings = []
for ranking in orig_rankings:
trunc_rankings.append( ranking[0:min(len(ranking),top)] )
return trunc_rankings | bd2724e83311b0f1ac35188087a9ec329e3955ac | 656,676 |
def EjemploRetorno2(n1, n2):
"""Función con parametros y retorno"""
s = n1 + n2
return s | b9d23e3863dc8c091516073987354e06963044e9 | 656,677 |
import math
def calculate_sin(x):
"""
Return the sine of x (measured in radians).
"""
return math.sin(x) | c86ead20f04ffd4ada1fd40ad45a79d5186da3b4 | 656,678 |
import struct
import socket
def inet_ntoa(i):
"""Like `socket.inet_nota()` but accepts an int."""
packed = struct.pack('!I', i)
return socket.inet_ntoa(packed) | 143bbf3652633b57b66d8398dae5058b3de92314 | 656,679 |
def format_sec_to_dhm(sec):
"""Format seconds to days, hours, minutes.
Args:
sec: float or int
Number of seconds in a period of time.
Returns: str
Period of time represented as a string on the form ``0d\:00h\:00m``.
"""
rem_int, s_int = divmod(int(sec), 60)
rem_int, m_int,... | 0dff0fb83f904465f5177cf7d38368ac1f44e8e4 | 656,680 |
def _common_dir(dirs):
"""
dirs: List[String]
"""
if not dirs:
return ""
if len(dirs) == 1:
return dirs[0]
split_dirs = [dir.split("/") for dir in dirs]
shortest = min(split_dirs)
longest = max(split_dirs)
for i, piece in enumerate(shortest):
# if the next... | 316757e16c79b2501e08977b95516b287f970f47 | 656,681 |
import subprocess
def _play_game(binary, map_width, map_height, bot_commands):
"""
Plays one game considering the specified bots and the game and map constraints.
:param binary: The halite binary
:param map_width: The map width
:param map_height: The map height
:param bot_commands: The command... | f79fc9b82441dcf321ebdf09b3eeada3bf2c334d | 656,682 |
from typing import Sequence
import os
def filelist(root) -> Sequence[str]:
"""Return a fully-qualified list of filenames under root directory; sort names alphabetically."""
allfiles = []
for path, subdirs, files in os.walk(root):
for name in files:
allfiles.append(os.path.join(path, na... | c547809875e1cdc24806ffc65437b3d0e7160b52 | 656,683 |
def get_qiime2_reserved_words():
"""Returns a list of the current reserved words in qiime2
Returns
-------
set: str
The reserved words
"""
qiime2_reserved_column_names = ['feature id', 'feature-id', 'featureid',
'id', 'sample id', 'sample-id', 'sample... | 71cc7672ff64a70d92979dae026ee432f8935e42 | 656,684 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.