content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def cal_bn_l1_loss(bn_weights, penalties, rho):
"""Calculate l1 loss."""
# print(len(bn_weights), len(penalties)) # The length degrades with training. (some are removed)
assert len(bn_weights) == len(penalties)
loss = 0.0
for weight, penal in zip(bn_weights, penalties):
loss += rho * penal ... | f459eb10c6b2597044be13426348d95d97f0731b | 675,778 |
def create_draft_files_bp(app):
"""Create draft files blueprint."""
ext = app.extensions["invenio-rdm-records"]
return ext.draft_files_resource.as_blueprint() | 9d55a6dc1b1ff1678d3a72c6757245e68d7240db | 675,779 |
import torch
def moving_average(input_tensor: torch.Tensor, window_size: int, dimension: int):
"""
Parameters
----------
input_tensor: torch.Tensor of shape (B, L, D)
window_size: sliding windows size
dimension: dimension we want to apply sliding window
Returns
-------
"""
... | 9f1007b05f394118bee41cadbb6f0fc242f3f7e5 | 675,780 |
def list_pairs(validation_dates):
"""
For a set of ndates dates, return a list of indexes and IDs for all possible unique pairs.
For example, for ndates=3 -> [(0, 1), (0,2), (1,2)]
"""
ndates = len(validation_dates)
indexes = []
pair_ids = []
for k1 in range(ndates):
for k2 in r... | ab0826c43f5c85f40c3be7b63218bacc5225a503 | 675,781 |
import argparse
def parse_args():
"""parse_args"""
parser = argparse.ArgumentParser('MindSpore Refinet training')
# dataset
parser.add_argument('--data_file', type=str, default='', help='path and Name of one MindRecord file')
parser.add_argument('--batch_size', type=int, default=32, help='batch si... | a01c6185f837711fc1393332b192379f80f62fb8 | 675,782 |
def _right_child(node):
"""
Args:
node: index of a binary tree node
Returns:
index of node's right child
"""
return 2 * node + 2 | 183682b4218ac00f22c1e7f82c2606bbea4f91e1 | 675,783 |
import math
def get_board_size(game_board):
""" (str) -> int
Precondition: The length of the game_board must be a perfect square,
which is between 1 and 81 inclusive.
Return the length of each side of the given
tic-tac-toe game board.
>>> get_board_size('XXOO')
... | 2e0ac94e4ab5a1315c5698ce74a4c600064620a1 | 675,784 |
def VerificaSeAcabou(player_vida, inimigos):
"""
Verifica se o jogo acabou, observando a vida do player
e o número de inimigos
"""
#se a vida do player for < 0 ele perdeu
if player_vida <= 0:
print("Perdeu o jogo!")
return False
#se o número de inimigos for zero ele venceu
... | 44e6d8a0183dee65d4e577c5638443416b38bd45 | 675,785 |
def have_program(c, name):
"""
Returns whether connected user has program ``name`` in their ``$PATH``.
"""
return c.run("which {}".format(name), hide=True, warn=True) | a1b1bcb446aebef3cad9c530b557eb0c9b41e527 | 675,786 |
def has_remote(repo, remote_name):
"""Returns true if the given repository already has the named remote.
Args:
repo: The git.Repo object representing the repository.
remote_name: The remote name to be looked for.
"""
return remote_name in [x.name for x in repo.remotes] | 4e64ed34d6bdb699dbffe35c77a33c187e86394c | 675,787 |
def count_format_specifiers(format_string):
"""Return the number of format specifiers in string format_string.
>>> count_format_specifiers("foo bar foo")
0
>>> count_format_specifiers("foo %d bar foo")
1
>>> count_format_specifiers("foo %d bar %i foo")
2
>>> count_format_specifiers("foo... | f958d96b24ddebc8d90ea5a3d5678cbcee1c9067 | 675,788 |
def to_ipv6_network(addr):
""" IPv6 addresses are eight groupings. The first three groupings (48 bits) comprise the network address. """
# Split by :: to identify omitted zeros
ipv6_prefix = addr.split('::')[0]
# Get the first three groups, or as many as are found + ::
found_groups = []
for gr... | 335750f76ec2ab182d9b56e0841455900c59622e | 675,789 |
def aloe_job_id():
"""Returns an Aloe Job identifier
"""
return 'd608e5d2-6a16-41b2-bbf5-fd848cbd70a3-007' | a254f2c5090ff4d5d9cf491e6efd5a172ac1e5b3 | 675,790 |
import functools
def cached_property(fun):
"""A memoize decorator for class properties.
Adapted from: http://code.activestate.com/recipes/576563-cached-property/
"""
@functools.wraps(fun)
def get(self):
try:
return self._cache[fun]
except AttributeError:
se... | a0fec3b0df310e0d74dd40d23f992749f2e52173 | 675,791 |
def at_filter(arg):
""" %s \t\t -- filter results by value has length """
if isinstance(arg.value, list):
return arg.value or None
return arg.value.strip() or None | 170f6073b7a0edb02be7b8571da57c70922a53dc | 675,792 |
def delete_product(client, resource_group_name, service_name, product_id):
"""Delete product. """
return client.delete(resource_group_name, service_name, product_id, delete_subscriptions='True', if_match='*') | 1abd9d217af46f30ed288f7b00bf8d1d83bc3fac | 675,793 |
def comparelistitem(item1, item2):
"""
Returns result of list comparison
"""
return item1 == item2 | f8d7ed9bb0352f97e6e15bf9b0ef94eed1c24cc4 | 675,794 |
import os
def _getFilesFromFolder(path) -> list:
"""
Function Description :
_getFilesFromFolder : provide us a collection of file name with each path
accept path location or folder that want to scan all data in those path
EXAMPLE ARGS (path = '/usr/name/')
... | dff7972e4e6d28b724b23305dbafb15856c529b2 | 675,795 |
def merge(source1, source2):
"""Merge two dicts, source2 could override existing keys based on source1"""
return {**source1, **source2} | bdb046ebd4e5c422667add9e342901fcffff1d7e | 675,796 |
from unittest.mock import Mock
def mock_release_workload_detail():
"""
release_workload_detail mock value
"""
mock_rep = Mock()
mock_rep.ok = True
mock_rep.json.return_value = {
"German": {
"anaconda": {
"Total": 1208,
"Translated": 1199,
... | 5168c8d80b6c4994ea5257a28860ee7c9b3b4d0f | 675,797 |
import itertools
def make_multidim(col, ndim):
"""Take a col with length=2 and make it N-d by repeating elements.
For the special case of ndim==1 just return the original.
The output has shape [3] * ndim. By using 3 we can be sure that repeating
the two input elements gives an output that is suffici... | 268598a1f02deb4b924724dae584cb1f7c7366de | 675,798 |
def RGB2Hex(rgb):
"""
把十进制rgb元组转化为html标签的十六进制color值
rgb(tuple,list):十进制颜色值
"""
strs = '#'
for i in rgb:
num = int(i)#将str转int
#将R、G、B分别转化为16进制拼接转换并大写
strs += str(hex(num))[-2:].replace('x','0').upper()
return strs | 626507eda366e36fc5d99f487a3f848c4e4f9d02 | 675,799 |
import struct
def int_to_mac(c):
"""Turn an int into a MAC address."""
return ":".join(('{:02x}',)*6).format(
*struct.unpack('BBBBBB', c.to_bytes(6, byteorder='big'))) | 715b95463e6f8e6c97d17a73946d42cf79b44827 | 675,800 |
def parse_virustotal(dyn_data: dict) -> dict:
"""
parses out virustotal information from dyn_data dictionary
Not used, just used for data analysis sake
Args:
dyn_data: dictionary read from dynamic data
Returns:
network_dict: dictionary parsing the network information extracted... | fc4551831bae67c5932b46d9c7e4a0fda874a2d0 | 675,801 |
import os
def testing_workdir(tmpdir, request):
""" Create a workdir in a safe temporary folder; cd into dir above before test, cd out after
:param tmpdir: py.test fixture, will be injected
:param request: py.test fixture-related, will be injected (see pytest docs)
"""
saved_path = os.getcwd()
... | caf3fdf609d305871acf5e173ca38b51f0c047cf | 675,802 |
import json
def insert_vertices(file_path, dict):
"""
Converts a python "Vertices" dictionary into a json file
Input: path to a new .json file OR a properly formatted "Vertices" python dict
Output: (written in JSON file)
"""
try:
with open(file_path, "w", encoding="utf-8") as json_fil... | e840fcc5431d778ff086c0a841e15a79e404fd24 | 675,803 |
import csv
def get_image_value_list(csv_file_name):
"""
Expects a csv file with header/structure:
filename, TE, mean_background
skips the first (header) line
returns a list of tuples with (filename, TE)
"""
image_value_list = []
with open(csv_file_name) as csvfile:
... | 7802ba5a0cd787e52c22e7cab267222539bf046c | 675,804 |
import json
def load_json_from_file(file_path):
"""Load json from a json file"""
with open(file_path) as json_data:
return json.load(json_data) | 0f800eba604245c3e907bcb42d58da7de3a7a9b0 | 675,805 |
async def in_voice_channel(ctx):
"""Checks that the command sender is in the same voice channel as the bot."""
voice = ctx.author.voice
bot_voice = ctx.guild.voice_client
if voice and bot_voice and voice.channel and bot_voice.channel and voice.channel == bot_voice.channel:
return True
else:
... | b1bd347db349ac3d6c35427ab41ef08231fb373c | 675,806 |
def place(cards, pos, card):
"""
Replaces the card at a given position in a list.
Example:
> place([1,4,7,10,12], 2, 9)
[1,4,9,10,12]
"""
result = cards[:]
result[pos] = card
return result | ee301ea71eb94cc3446736adf8124100aa756d72 | 675,807 |
def text_of_list(t):
"""
Convert a string list to multiline text.
"""
return '\n'.join(t) | 526ca23f6fbca6780238ae71ccf581290b92037b | 675,808 |
import os
import json
import yaml
def load_config(file_name):
"""
Load configuration file, either YAML or JSON.
:param file_name: Path to file
:return: Dict
"""
file_base = os.path.basename(file_name)
# Detect file extension
extension = file_base[file_base.rindex('.') + 1:].lower() if... | a5049b7c400cdb0545a28d2fd2b647763855384d | 675,809 |
def trapmf(x, a, b, c, d):
"""
Trapezoidal membership function generator.
Parameters
========
x : single element array like
abcd : 1d array, length 4
Four-element vector. Ensure a <= b <= c <= d.
Returns
========
y : 1d array
Trapezoidal membership function.
"""
... | 6a7a8a50cf83194d072055054d71db4b0398bb2d | 675,810 |
import math
def eulerToMatrix(euler): #double heading, double attitude, double bank
"""
code from 'http://www.euclideanspace.com/maths/geometry/rotations/conversions/'.
this conversion uses NASA standard aeroplane conventions as described on page:
'http://www.euclideanspace.com/maths/geometry/rotation... | 9090d2b8ea7358341e94309691a7bb57bd5c65b1 | 675,811 |
import pathlib
def load_fixture(filename) -> str:
"""Load a fixture."""
return (
pathlib.Path(__file__)
.parent.joinpath("fixtures", filename)
.read_text(encoding="utf8")
) | 1b1aff8e05b9dc63197a0c56c243c355760535d1 | 675,812 |
def itraceToList( trace ):
""" Converts an instruction trace into list """
traceList = []
for i in trace:
traceList.append(i[0])
return traceList | d5fcf91447bae1460c9b50f22742b79343d685d6 | 675,813 |
import os
def get_secrets():
"""
A method for accessing our secrets.
"""
secrets = [
'TUMBLR_CONSUMER_KEY',
'TUMBLR_OAUTH_TOKEN',
'TUMBLR_OAUTH_TOKEN_SECRET',
'TUMBLR_APP_SECRET',
'AWS_SECRET_ACCESS_KEY',
'AWS_ACCESS_KEY_ID'
]
secrets_dict = {}
... | 2b0f2dad261293a322a0041a58eb23ceb2aad228 | 675,814 |
import torch
def get_dropout_mask(dropout_probability, tensor_shape, device):
"""
once get, it is fixed all the time
"""
binary_mask = (torch.rand(tensor_shape) > dropout_probability)
# Scale mask by 1/keep_prob to preserve output statistics.
dropout_mask = binary_mask.float().to(device).div(1... | 32ac5f510576a4d75431c1e953246e4ab17480cd | 675,815 |
from typing import Set
def import_declarations(import_set: Set[str]) -> str:
"""
Generate the import declaration(s) given the import specs.
:param import_set: import specs
:return: Go import declaration
>>> import_declarations(set())
''
>>> import_declarations({'time'})
'import "tim... | 6cef7b84701caa59eef1fde4b23c0ba176596c53 | 675,816 |
def get_version(fname):
"""Reads PKG-INFO file generated by setuptools and extracts the Version
number."""
res = "UNK"
with open(fname, "r") as f:
for line in f.readlines():
line = line[:-1]
if line.startswith("Version:"):
res = line.replace("Version:", ""... | 503d28ba0bea43dbbd5164acd2f6804a8a7c479b | 675,817 |
from typing import List
def issorted(array: List[int]) -> bool:
"""Checks if an array is sorted\n
Param array is an array of numbers\n
Returns true if sorted, false if not
"""
for i in range(len(array) - 1):
if array[i + 1] < array[i]:
return False
return True | f8abd4b656bc919a5db42aa836d4e4071439c0c0 | 675,818 |
import requests
import re
def get(share_url) -> dict:
"""
title、videos
"""
data = {}
headers = {
'accept':
'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'accept-encoding':
'gzip, deflate, br',
'accept-language':
... | 19b2ecde6ab4eeed6c8551e9972e493dd39de611 | 675,819 |
def to_subscription_key(uid, event):
"""Build the Subscription primary key for the given guid and event"""
return u'{}_{}'.format(uid, event) | 55edbc3a6a8af5e68133e18170c682e7fb7995a3 | 675,820 |
def bytes_to_string_list(bytes):
"""
:param bytes:
:return:
>>> bytes_to_string_list('\x12\x34')
['\\x12', '4']
"""
li = []
li = map(lambda c: c, bytes)
return li | 1b544998a2aa509a46d417ec29283a0e601c4c20 | 675,821 |
def solid(material):
"""All one material."""
def f(point):
return material
return f | 51bec882efc226694a330180a2408f83fd9051de | 675,822 |
def removecomment(astr, cphrase):
"""
the comment is similar to that in python.
any charachter after the # is treated as a comment
until the end of the line
astr is the string to be de-commented
cphrase is the comment phrase"""
# linesep = mylib3.getlinesep(astr)
alist = astr.splitlines(... | 67d31ef992448f3c68e452c3ae2886e14e35b987 | 675,823 |
def format_pathname(
pathname,
max_length):
"""
Format a pathname
:param str pathname: Pathname to format
:param int max_length: Maximum length of result pathname (> 3)
:return: Formatted pathname
:rtype: str
:raises ValueError: If *max_length* is not larger than 3
This... | add9a4fa5e82e6f99821fc8d623a8417a5ad737b | 675,824 |
def _intersection(a, b):
"""
a.shape = (m, )
b.shape = (m, )
"""
count = 0
for i_a, i_b in zip(a, b):
if i_a == 1 and i_b == 1:
count += 1
return count | b899be8a9d6b42a7897cac28e6a3c0ca5c6dfe9e | 675,825 |
from pathlib import Path
from typing import List
import os
def search_dirs_in_path(
path: Path, search_dirname="specterext", return_without_extid=True
) -> List[Path]:
"""recursively walks the filesystem collecting directories which are called "specterext"
returns a list of PATH all ending with specterext... | dbd25bcafa1f8341f063ba112f4542a71d3d79e3 | 675,826 |
def split_searchfile(_file) -> list:
"""split the file and store different terms in a list and return the list. """
answer = []
dump = []
for i in _file:
#print(i)
term = i.split("\n")
#print("trimfile: {name}".format(name=term))
if len(dump) == 3:
text = term... | ea0b90e13e1e7f715f96d6ef5ee733bb55179c3d | 675,827 |
def encode_binary(x, width):
"""Convert integer x to binary with at least width digits."""
assert isinstance(x, int)
xb = bin(x)[2:]
if width == 0:
assert x == 0
return ''
else:
assert len(xb) <= width
pad = width - len(xb)
return '0' * pad + xb | 61a5c1e933f495f4347e0d89490a02b6e9630f6e | 675,828 |
import jinja2
def get_template():
"""
The get_template function returns a basic template for our
HTML report
:return: Jinja2 Template
"""
html_string = """
<html>\n<head>\n<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
... | 2c157556133d6c207dd5d91f89e4e4533e362e51 | 675,829 |
def unnest_json_property(i,nested_property):
"""This function takes each item of the nested list and returns as a
property in its own right, prefixed by an underscore '_' to mitigate
risk of name clash. For any nested items, the nested list name is
taken as a prefix and append to any child items.
... | 364f155c5392ba7478748352bea09f5422cfd0c6 | 675,830 |
def dist(pt1, pt2):
"""Distance between two points"""
return ((pt2[0] - pt1[0])**2 + (pt2[1] - pt1[1])**2 + (pt2[2] - pt1[2])**2)**0.5 | 7277c8984a4c1c10223fb0cd481b7ac7b4868f9d | 675,831 |
import re
def make_lexer(grammar):
"""create a lexer for a particular grammar"""
def lex(text):
"""generate a series of tokens from an input string"""
while text:
for rule in grammar:
match = re.match(rule.expression, text)
if match:
... | 07b28a2cac1394dd45020cef9621531155ccee1c | 675,832 |
def filter_by_bidder_id(bids, bidder_id):
"""
>>> bids = [
... {"bidder_id": "1", "amount": 100},
... {"bidder_id": "1", "amount": 200},
... {"bidder_id": "2", "amount": 101}
... ]
>>> filter_by_bidder_id(bids, "1")
[{'amount': 100, 'bidder_id': '1'}, {'amount': 200, 'bidder... | 887e44b2a8b71b4e9b37c50defea0eba37fc7afb | 675,833 |
def get_distance(pt1, pt2):
""" Finds the distance between two points. """
x1 = pt1[0]
y1 = pt1[1]
x2 = pt2[0]
y2 = pt2[1]
return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** (1 / 2) | 814a8904e17f4f2fd91738664f711d2bc0a98566 | 675,834 |
from typing import Optional
from typing import Callable
def docfill(
*args,
template: Optional[str] = None,
**kwargs
):
"""Format the decorated function's docstring using given args and kwargs
This is useful if some functions share many common inputs or if the
range of valid values for a para... | ae3ab484d18bfb41e232f191163955e2c2e829f4 | 675,836 |
def app_request_type_label(app, request_type) -> str:
"""Format a label based on the application name and request type."""
return f"{app}\n({request_type})" | 8f7545842b7c342d0d7cf18ab45afddb48297aee | 675,837 |
import torch
def scalar_mult(x, y):
"""A function that does complex scalar multiplication between two complex scalars, x and y.
:param x: A complex scalar. (x[0], x[1]) = (real part, imaginary part).
:type x: torch.doubleTensor
:param y: A complex scalar. (x[0], x[1]) = (real part, imaginary part).
... | 751ab77346995d339d037c62d533a47107b85f15 | 675,839 |
def compute_primary_air_flow_2(Firepower):
"""using new flame temperature assumption"""
cp_average = 1.044
Q_dot = Firepower
T_amb = 300 # K
T_h = 1274 # K
m_dot_primary_air = (Q_dot)/(cp_average*(T_h - T_amb)) #kg/s
mw_air = 0.018 #kg/mol
mol_dot_primary_air = m_dot_primary_air/mw_a... | 153849943725f33ae6797cfb82e68e244e4425ed | 675,840 |
import os
def _available(shared_lib):
"""Make sure the compiled library functions are available."""
return os.path.isfile(shared_lib) | 73adce1e8b69029d5e06c6aa1893437be771d2ce | 675,841 |
def decode_text(value):
"""
Decode a text-like value for display.
Unicode values are returned unchanged. Byte strings will be decoded
with a text-safe replacement for unrecognized characters.
"""
if isinstance(value, bytes):
return value.decode('ascii', 'replace')
else:
... | ba2f37b2b16d6810799f85ff8026228d9af9cd72 | 675,842 |
import subprocess
def _remote_head(url):
"""Returns a tuple containing the hash of a remote repo's head and an error string,
exactly one of which will be None."""
try:
output = subprocess.check_output(['git', 'ls-remote', url, 'HEAD'], cwd='/')
except subprocess.CalledProcessError as ex:
... | 10b5c01cfe5f472854cbb32de37ae4868871fed7 | 675,843 |
def get_extra_packages():
"""
Return extra packages
Plus any version tests and warnings
"""
extras_require = {}
return extras_require | 8793f01d65c9f1b62757de8723fbbe0d9719d901 | 675,844 |
def znes_colors(n=None):
"""Return dict with ZNES colors.
Examples
--------
>>> znes_colors().keys() # doctest: +ELLIPSIS
dict_keys(['darkblue', 'red', 'lightblue', 'orange', 'grey',...
Original author: @ckaldemeyer
"""
colors = {
'darkblue': '#00395B',
'red': '#B54036... | 16a5c06b898bc58bc046c8a1cd9137846b0d9097 | 675,845 |
def get_entities(run):
""" Get BIDS-entities from run object """
valid = ['number', 'session', 'subject', 'acquisition']
entities = {
r: v
for r, v in run.items()
if r in valid and v is not None
}
if 'number' in entities:
entities['run'] = entities.pop('number')
... | 325c712f2ea9ca37886ca1f54f25cdb19c741290 | 675,846 |
import sys
import re
def get_platform():
"""
Get OS of the particular platform the toolkit is being run on.
"""
plat = sys.platform
if re.search("darwin", plat):
return "macos"
elif re.search("linux", plat):
return "linux"
elif re.search("win", plat):
return "windo... | b6c80c9cb4171c0c60a70d82ca9e907453d29799 | 675,847 |
def dict_equal_on(d1, d2, keys):
"""
Return True iff both dicts have all the requested keys with the same
values.
>>> dict_equal_on({1: 'a', 2: 'b'}, {1: 'a', 2: 'c'}, [1, 2])
False
>>> dict_equal_on({'a': 1}, {'b': 2}, [])
True
"""
if not keys:
return True
return d1.get... | 503c47e37926bbfb3db059dde1b18b2365f8c51e | 675,848 |
def normalize_angles(angles):
"""Returns array-like of angles within 0 to 360 degrees"""
return type(angles)(map(lambda x: x % 360, angles)) | ef2d4da18c48e4650290f037c6b6dc3f5ac4c8e6 | 675,849 |
import random
def make_trans_cst_type_data():
"""根据客户自己的交易类型,建立字典"""
trans_cst_type = random.choice([
"000000", # 人民币-现钞-银行汇票
"000001", # 人民币-现钞-银行承兑汇票
"000002", # 人民币-现钞-商业承兑汇票
"000003", # 人民币-现钞-本票
"000004", # 人民币-现钞-支票
"000010", # 人民币-现钞-银行卡
"00... | 51646c415be7367b1e3bcc52a5954fe2de205da9 | 675,850 |
def get_tags_string(tags):
"""
Returns a comma-delimited k=v string
Args:
tags (dict): A dictionary of key/value pairs
Returns:
str
"""
return ','.join([f'{k}={v}' for k, v in tags.items()]) | 561876d35739de5032465536f667caac9eb0cc6f | 675,851 |
import os
def home_prefix(path):
"""
Appends the path to the user's home path.
:param path: Path to be appended.
:return: (str) ~/path
"""
home_path = os.path.expanduser('~')
return os.path.join(home_path, path) | b6d66bba5270ee04cfd31233a20f647010852e19 | 675,852 |
def get_common_interests(a, b):
"""Calculates score according to common interests between two users"""
total, found = 0, 0
for x in a.all():
total += 1
for y in b.all():
if y == x:
found += 1
break
return 100 * float(found) / float(total) | 300dcbd8050d3be7d99c9b9c3e7fe60e56180e59 | 675,854 |
def migrate_fk_to_m2m(product_type_related_field):
"""Migrate product types' foreign key to a M2M relation."""
def make_migration(apps, schema):
ProductType = apps.get_model("product", "ProductType")
for product_type in ProductType.objects.all():
m2m_field = getattr(product_type, p... | ee4dbb2066bee7deeed2e7711158b1e1635a527b | 675,855 |
def findGap(values, precision=1e-16):
"""
From a given set of eigenvalues, finds the first spectroscopic gap, bigger than PRECISION.
"""
for i in range(1, len(values)):
difference = values[i] - values[i-1]
if difference > precision:
return difference | 95c617fbaa65ea7018708d748429e65054256827 | 675,856 |
def is_dataset(dataset):
"""
Check if input is a hdf dataset
e.g. is_dataset(hdf_group.get(address))
"""
return hasattr(dataset, 'size') | e7eb6392c7347792fdd0371d5c7b057a193e8b1d | 675,857 |
import traceback
def log(target: str = "satyrus.log") -> str:
"""\
"""
trace: str = traceback.format_exc()
with open(target, "w", encoding="utf8") as file:
file.write(trace)
return trace | 50c3369f097f70b123128bd7e4b4f8852f4c33a8 | 675,858 |
def display_label(f_class, catalog):
"""
Predict the flower name with the topk most likely classes using a trained deep learning model.
Parameters:
image_path - path name of the flower image
model - our NN model
topk - the K most probable classes
Returns:
probability and id of the to... | d7b3f5efd43400422a801bd0bffb923fac866732 | 675,859 |
def from_fahrenheit_to_celcius(temperatureF):
"""
Convert the temperature from
Fahrenheit to Celcius
"""
return (temperatureF - 32) * 5.0 / 9.0 | 145494603e79f541fe5e9cbc751ed7bdcdac0d98 | 675,860 |
import re
def eliminate_frame_idx_and_ext_from_clip_name(clip_name):
"""
Examples
--------
>>> clip_name = 'dst_grad_tp_1920x1080_b-size_64_[0001-0024].png'
>>> eliminate_frame_idx_from_clip_name(clip_name)
eliminate_frame_idx_from_clip_name(clip_name)
"""
eliminated_name = re.sub('_\[... | a0da0adcbcd0a156bdc8aa42644badd4b8dc9e26 | 675,861 |
def hello_world_authenticated():
"""
Authenticated monitor endpoint
---
tags:
- ping_authenticated
responses:
200:
description: Hello, authenticated world!
"""
return 'Hello, authenticated world!' | 9b6a4c107df3293c3ebe4b89409aba8920aa2abe | 675,862 |
import re
import os
import platform
def extract_REM(seed):
"""
Construct the REM lines
Input: seed
Return: a dictionary of the REM information
"""
rem = {}
his = open(seed + '.history', 'r')
get_pspot = False
pspot = []
for line in his:
if ' Welcome to ' in line:
... | ab60552f5037b593af7fe504b9db0adf8cdb593d | 675,863 |
import random
def stupide(configuration, joueur=0):
""" Choisit un coup aléatoire (uniforme) pour le joueur 0 ou 1, et renvoit la configuration modifiée."""
# On choisit le coup à jouer : ligne random, nb d'allumette(s) random...
lignes_non_vides = [i for i, c in enumerate(configuration) if c > 0]
pos... | b26f1fc00234ce6bb89dd18d1cfbba18ce0df2f8 | 675,864 |
def get_last_completed_launch(fw):
"""
Given a Firework object returns the last completed launch
"""
return next((l for l in reversed(fw.archived_launches + fw.launches) if
l.state == 'COMPLETED'), None) | ec9c2f6c55a367451ca6df9a187c22111d227a68 | 675,865 |
def _check_value(item, allowed_values, item_name=None, extra=None):
"""
Check the value of a parameter against a list of valid options.
Parameters
----------
item : object
Item to check.
allowed_values : tuple of objects
Allowed values to be checked against.
item_name : str ... | 1cecf190d83a14573d93ca73de070f98dbf7c57f | 675,866 |
def play_tictactoe_turn(action, board_state, turn):
"""
Input:
action:
0-8
an index into the board array
board_state:
(0,1,0,None,None,None,None,None,None)
a tuple of the board's state
turn:
1/0
the player's who's turn i... | e50c0ed69bfcef45f72b763e7133935636f047b2 | 675,867 |
def filter_startswith_prefix(dataframe, prefix="TALON"):
"""Filter out rows where 'annot_gene_id' column value starts with prefix.
Args:
dataframe: pandas DataFrame
prefix: string
Returns:
pandas DataFrame
"""
not_starts_with_prefix = dataframe["annot_gene_id"].apply(
... | 9e8f61d4c603099da0a2adf5dce4b4d043925992 | 675,868 |
import json
def parse_foiaonline_metadata(metadata_file, tika_metadata):
""" This is a custom metadata parser that extracts metadata from
files, which come with the records. A user can choose to either
overwrite the Tika metadata or keep it."""
with open((metadata_file), 'r') as f:
metadata =... | 98763d31225858d8bfd1a77db0b5ead1bc0c2849 | 675,869 |
import os
def list_fits_files_recursive(directory):
"""Returns list of all files contained within a top level directory, including files
within subdirectories.
Args:
directory (str): Directory to examine.
"""
# Create a list of fits files within the directory of interest
files_in_direc... | e75b9ff159bdfc89f90418d71504c13972d8a30a | 675,870 |
import os
import yaml
import time
def _git_repo_info(repo_path):
""" returns a string containing git branch, commit id and commit date """
result = None
if os.path.exists(repo_path):
# Check if the .git is a file. If it is a file, it means that we are in a submodule structure.
if os.path.i... | a8785f225ea208e3731b70317da329ace83f27cf | 675,871 |
def cercle(canv, x, y, r, color='black', fill=None):
"""tracé d'un cercle de centre (x,y) et de rayon r"""
return canv.create_oval(x - r, y - r, x + r, y + r, outline=color, fill=fill) | 9015e17138ccefdd278e8cd916ba622af620667e | 675,872 |
def combine_abs_error(poly_abs_err):
"""Returns a simplified expression for a given absolute error bound.
The input should be of the type [(Monomial, k, n)] where k's and n's are integers.
All k's should be at least 1.
This function returns two polynomials: one with monomials for which k == 1 and anoth... | 9a52dc9a78d33e4a328860d91b39096506b78f01 | 675,873 |
import yaml
def serializes(data_type):
"""Register decorated function as YAML representer for type."""
def decorator(func):
yaml.add_representer(data_type, func)
return func
return decorator | eb2092041e42c91202526201c4c00ad05e2e6342 | 675,874 |
def flip(author):
""" Last, F -> F~Last
"""
lc = author.find(',')
if lc < 0:
print("%% BAD author malformed: %s" % author)
return author
tmp = author[lc+1:]
if len(tmp) > 0:
if tmp[0] == '~':
tmp = tmp[1:]
return tmp + '~' + author[:lc]
else... | 5f07cec5783c5048bb2df04f186cb615c5f058c8 | 675,875 |
def int_to_varint_hex(int_value):
"""
VARINT
<= 0xfc example: 12
<= 0xffff example: fd1234
Prefix is fd and the next 2 bytes are the VarInt (in little-endian).
<= 0xffffffff example: fe12345678
Prefix is fe and the next 4 bytes are the VarI... | 7b0aa099987097effc922a78e1100eaac0686cbf | 675,876 |
from typing import Any
from typing import List
def validate_entry_context(entry_context: Any, keys: List[str], unpack_nested_elements: bool):
""" Validate entry context structure is valid, should be:
- For unpack_nested_elements==False:
1. List[Dict[str, str/bool/int/float]]
2. Lis... | 49e1f0a8a5b57066cf6bacdb564883600193f38c | 675,877 |
def cli(ctx, workflow_id):
"""Exports a workflow.
Output:
Dictionary representing the requested workflow
"""
return ctx.gi.workflows.export_workflow_dict(workflow_id) | afea211b979f0d323e7a565b22f9e27f63652fa2 | 675,880 |
def progessbar(new, tot):
"""Builds progressbar
Args:
new: current progress
tot: total length of the download
Returns:
progressbar as a string of length 20
"""
length = 20
progress = int(round(length * new / float(tot)))
percent = round(new/float(tot) * 100.0, 1)
... | 119cec7121167c5bcb23571cab4f33e4a816e521 | 675,881 |
def p1_for(input_list):
"""Compute some of numbers in list with for loop."""
out = 0
for i in input_list:
out += i
return out | 7691bc14e10eab3a7fbda46091dcb62773704f1a | 675,882 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.