content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def json_ld_rename_metadata_fields(db):
"""Change metadata field names from the JSON-LD `processes` to BW schema.
BW schema: https://wurst.readthedocs.io/#internal-data-format
"""
fields_new_old = [
("@id", "code"),
("category", "classifications"),
("@type", "type"),
(... | bf39df80384d02db9857ded5fa6440378c7848fd | 647,774 |
import re
def containChinese(content: str) -> bool:
""" 判断内容是否含有中文字符
Arguments:
content {string} -- 要检测的内容
Returns:
{bool} -- 是否包含中文
"""
zh_pattern = re.compile(
u'([\u4E00-\u9FA5]|[\u9FA6-\u9FEF]|[\u3400-\u4DB5]|[\U00020000-\U0002A6D6]|[\U0002A700-\U0002B734]|[\U0002B740... | 08788234fe323f154a1b962f740f1acacbca68b7 | 647,775 |
def crop_dfs(leap_df, emg_df):
"""Crops both DataFrames to start at the same time"""
i = 0
while (emg_df['ts'][i] < leap_df['Unix Time'][0]):
i += 1
i -= 1
j = len(emg_df) - 1
while (emg_df['ts'][j] > leap_df['Unix Time'][len(leap_df) - 1]):
j -= 1
j += 1
return (leap_df, emg_df[i:j].reset_index(drop=True)) | 492c81ec69af800d8eb1b74bc8e27d020014ea63 | 647,776 |
def api():
"""Provide an introspective view of the available APIs."""
return dict() | 30c7148c96151e7c675ce61ebe7493ad5325d889 | 647,777 |
import re
def _translate(pat):
"""Given a pattern, returns a regexp string for it."""
out = '^'
for c in pat:
if c == '*':
out += '.*'
else:
out += re.escape(c)
out += '$'
return out | ffec38a7b7cbe65b1da0fd67b389ff5d422fc2aa | 647,778 |
def _downsample_simple(arr, n):
"""
Skip n elements of a 1D array.
:param arr: 1D array.
:param n: integer which defines the skips.
:return: Downsampled 1D array.
"""
return arr[::n] | bd531cf5a5771966dfb3edba5136dd69ea2e2849 | 647,779 |
def mapping_original_units(df, map_units={}, **kwargs):
"""Map original units according to pre-defined dictionary."""
# make a list of units that are mapped
units_before = list(set(map_units.keys()) & set(df['Unit']))
units_after = list(map(map_units.get, units_before))
unmapped_units = list(set(df[... | 4d969e5efd36852ede67fa38a7aa08d727c6091e | 647,780 |
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
s = len(set(nums))
l = len(nums)
if l - s > 0 :
return True
else:
return False | 988d583902edc60ef0c38b2588145417809333db | 647,781 |
def genomic_dup3_abs_38(genomic_del3_dup3_loc):
"""Create test fixture absolute copy number variation"""
return {
"type": "AbsoluteCopyNumber",
"_id": "ga4gh:VAC.cQATJ6a1uGwXOHu-advv8lRsMgjNLKul",
"subject": genomic_del3_dup3_loc,
"copies": {"type": "Number", "value": 2}
} | a34c8abbbcc3e41e503eab74683e71a280c1919e | 647,782 |
def getWeightCode(weight,stds):
"""
Get the corresponding weight code as HYPOINVERSE
"""
if weight < stds[3]:
weightCode = 4
elif weight < stds[2]:
weightCode = 3
elif weight < stds[1]:
weightCode = 2
elif weight < stds[0]:
weightCode = 1
else:
wei... | e660576662d2aaf35b074f6d524a62904b591937 | 647,783 |
def substitution_costs(c1, c2):
"""defines the costs of substitutions for the alignment"""
if c1[-1] == c2[-1]:
return 2
else:
return -3 | 62df44a6d5afd047a79845043b7e0d3de51fca49 | 647,784 |
def get_extrapolated_flux(flux_ref, freq_ref, spectral_index):
"""
Computes the flux density at 843 MHz extrapolated from a higher/lower flux
density measurement & some assumed spectral index.
input:
------
flux_ref: float
Reference flux density, usually S400 or S1400 [mJy].
freq_re... | 27ab6d5416b3ecd2fcea970e2dacb5460a8185c6 | 647,785 |
def removeMissingTargetRows():
"""
Remove rows with missing target values
"""
return True | ff177510cf2232c4731c30af489ff5275bbc061c | 647,786 |
def flag(argument):
"""
Check for a valid flag option (no argument) and return ``None``.
(Directive option conversion function.)
Raise ``ValueError`` if an argument is found.
"""
if argument and argument.strip():
raise ValueError('no argument is allowed; "%s" supplied' % argument)
e... | 0f2ad5aab0cd0e440f711987cf10f9ec59a55ae5 | 647,787 |
def remove_double_blanks(lines):
""" Takes a list of lines and condenses multiple blank lines into a single
blank line.
"""
new_lines = []
prev_line = "" # empty line here will remove leading blank space
for line in lines:
if len(line.strip()) or len(prev_line.strip()):
new_... | a2c18a66f3cf06cdcf7a5f742168fd7b5b51b048 | 647,788 |
def interpolation(x0, y0, x1, y1, x):
"""
Performs interpolation.
Parameters
----------
x0 : float.
The coordinate of the first point on the x axis.
y0 : float.
The coordinate of the first point on the y axis.
x1 : float.
The coordinate of the second point on the x a... | 7e78c5f9cb697c58d6a7ef405cc8e37cff84641d | 647,789 |
def calc_commission_tc(trade_cnt, price):
"""
币类计算交易费用:只简单计算手续费,双向都使用流通币计算手续费,不涉及卖出使用币类的手续计算,
如需要更精确计算,请使用自定义计算费率,即在AbuCommission初始化中自定义计算手续费的方法
:param trade_cnt: 交易的币个数(int)
:param price: 每币的价格(人民币)
:return: 计算结果手续费
"""
cost = trade_cnt * price
# 双向都使用流通币计算手续费,千分之2
commission = ... | 953f19b2f56c69691882b0990bb9e88ca6ab7351 | 647,790 |
def wait():
"""Wait for completion of a child process, and return a tuple containing its pid
and exit status indication: a 16-bit number, whose low byte is the signal number
that killed the process, and whose high byte is the exit status (if the signal
number is zero); the high bit of the low b... | e75b6940129efc31ea00812d637ba29c418de580 | 647,791 |
def undecorated_test_function():
"""An undecorated Python function that simple passes with the following named formatters:
test_name: Name of undecorated function.
"""
py_file = \
"""
import pytest
def {test_name}():
pass
"""
return py_file | e13684a1892ff5d61eeebbe56fdb57257838fdf4 | 647,792 |
import sys
import argparse
def parse_args():
"""Parse input arguments
Use --help to see a pretty description of the arguments
"""
if 'ipykernel' in sys.argv[0]:
sys.argv = [sys.argv[0]]
parser = argparse.ArgumentParser()
parser.add_argument('--env_name', type=str, default='hanoi_opera... | 899fa350e294e3c992d4918d4b9d15f9a9183ca2 | 647,793 |
def make_component_header(component, header):
"""
Function that extracts information from components
and adds it to the data header. The input header is
expected to come from Data.coords.header by default.
Parameters
----------
component: glue Component
Glue component to extract info... | 8607303a43f7e1fe993b38da95c1d00f876fd9d0 | 647,794 |
def _get_screenshot_data(driver) -> None:
"""
Returns the screenshot as base64 encoded data.
"""
return driver.get_screenshot_as_png() | dda711072bf54ed1a87afec91c242f0099e7e337 | 647,795 |
def _take_n_bases(cds_seq, nbases, direction, row_list, row_index):
"""
Helper function to deal with shared codons in (sub-)exon boundaries.
"""
rows = []
while 0 <= row_index < len(row_list):
rows.append(row_list[row_index])
if direction == "next":
row_index += 1
... | 6b94cdb775c6d25d2f821e8e92458cd0807dd000 | 647,796 |
def get_index_first_line_with_white(mask):
"""
Récupère l'index de la première ligne comportant du blanc.
Args:
mask (ndarray): masque en noir et blanc (0-255).
Returns (int):
Index de la première ligne comportant du blanc.
"""
row_index_first_white = 0
lines_value = [sum(l... | 260acaeb0b3cfcf91ffc51e1b49a57fbc7fbd905 | 647,797 |
import sys
import traceback
def format_exc(frame=None):
"""
Format call-stack and display exception information (if availible)
"""
exc_info = sys.exc_info()
exc_desc = ""
callstack = traceback.extract_stack(frame)
callstack = callstack[:-1]
if exc_info[0] is not None:
excepti... | 6a06018651c27753fd8c250c961e59ce37412e91 | 647,798 |
def PyByteArray_Concat(space, w_left, w_right):
"""Concat bytearrays a and b and return a new bytearray with the result."""
return space.add(w_left, w_right) | 38131be8abfcfae5d59f9ad75db82de144f716ee | 647,800 |
def to_secs(delta):
"""Convert a :py:class:`datetime.timedelta` to a number of seconds.
(This is basically a backport of
:py:meth:`datetime.timedelta.total_seconds`.)
"""
return (delta.days * 86400.0 +
delta.seconds +
delta.microseconds / 1000000.0) | 1ff9c8b2a857f713d7bda2691b0b2cfe8a1611dc | 647,801 |
from typing import List
def alphabet() -> List[str]:
"""Retourne la liste des 26 lettres de l'alphabet.
"""
return [chr(i) for i in range(ord('a'), ord('z') + 1)] | 7627d3c444c1ef4bf61ea9dd60add5ff45c46f43 | 647,802 |
def print(*args, **kwargs):
"""
Currently no purpose.
"""
return __builtins__.print(*args, **kwargs) | 40a132293199790c2d4b0e1ef0fbbb2959d92129 | 647,803 |
def fst(l):
"""Returns the first item in any list
Parameters
---------
l : list
the list we want to extract the first item from
Returns
-------
first item in list
"""
if isinstance(l, list):
return fst(l[0])
else:
return l | 9b46e31fca7e5c18cf999ed071fa25a261bd3dc4 | 647,804 |
def get_max_profit(stock_prices):
"""
Time Complexity: O(n)
Space Complexity: O(1)
n: number of stocks (length of the list)
"""
if len(stock_prices) < 2:
raise ValueError('Getting a profit requires at least 2 prices')
min_price = stock_prices[0]
max_profit = stock_prices[1] - s... | a636037d9ba3d82fc7e262e3ef84ce29d6a034e8 | 647,806 |
def is_builtin_type(tp):
"""Checks if the given type is a builtin one.
"""
return hasattr(__builtins__, tp.__name__) and tp is getattr(__builtins__, tp.__name__) | 786a9928b45883df68608a45a0e6efa6d4dfe27e | 647,807 |
def accepted_extensions():
"""
Files accepted to be processed by deviot
"""
accepted = ['ino', 'pde', 'cpp', 'c', 'S', 'h']
return accepted | a43c5fdda0b38ab361ea0e953434233eb1ee2f58 | 647,808 |
def _prepare_hunk(hunk):
"""Drop all information but the username and patch"""
cleanhunk = []
for line in hunk.splitlines():
if line.startswith(b'# User') or not line.startswith(b'#'):
if line.startswith(b'@@'):
line = b'@@\n'
cleanhunk.append(line)
return... | 31a2e482c207b4dade2527d0852b7b99695e0eaa | 647,809 |
import torch
def is_fused_optimizer(optimizer: torch.optim.Optimizer):
"""
Checking if :attr:`optimizer` is a fused optimizer or not.
"""
return hasattr(optimizer, "_bagua_fused_optimizer") | e513aad065d0c64d044adc706b6192722382dcdf | 647,810 |
def odorant_distances(results, subject_id=None):
"""
Given the test results, returns a dictionary whose keys are odorant pairs
and whose values are psychometric distances between those pairs,
defined as the fraction of discriminations that were incorrect.
This can be limited to one subject indicated... | 9153057ac06ea0c2df8bb34b40bc1af7fd00625a | 647,811 |
def map_agent_to_domains(agent_label, lambda_tmp):
"""
Returns the domain(s) that an agent is allowed to explore.
:param agent_label: agent label
:param lambda_tmp: lambda value
:return: domain label
"""
assert agent_label in [1, 2, 3, 4], f'ERROR: Check agent label: {agent_label}'
asse... | 395e87a6f93d25b25fb55f405fd3084af7b170f0 | 647,812 |
import os
def isowner(st):
"""Return True if the stat object st is from the current user."""
return st.st_uid == os.getuid() | 23d3183954352b2bdccfa02a0becfeb5e3045abe | 647,813 |
def skinHasImage(image):
"""Returns True if the image file exists in the skin"""
return True | f6cd5fcb33575e835a73a184c9d1aebabb68a12c | 647,814 |
def get_fps_number(avg_fps_msg: str) -> float:
"""Decodes FPS number from given "Avg FPS" string output by Peeking Duck
in the format: "... Avg FPS over last n frames: x.xx ..."
Args:
avg_fps_msg (str): Peeking Duck's average FPS message string
Returns:
float: Frames per second number
... | c955e00d1f1235014ed02d9a2907815b2a5e7ad0 | 647,815 |
def newton_poly(coef, x_data, x):
"""
evaluate the Newton polynomial
at x
"""
n = len(x_data) - 1
p = coef[n]
for k in range(1,n+1):
p = coef[n-k] + (x -x_data[n-k])*p
return p | 9b1cec6428fc3b7a4cd424e5c9e1c6171e0b75b2 | 647,816 |
from typing import Union
from typing import Tuple
def endswith(text: str, expression: Union[str, Tuple[str, ...]]) -> bool:
"""Text ends with test"""
return text.endswith(expression) | 7f9416a35158ad7f643dfa29fe91eea084b6ad8d | 647,817 |
def someFunc(x):
"""y = |x| """
if x != 3 and x != -2:
return (x+3)/(x**2 -x -6)
#return (16-2*x)*(30-2*x)*x
#if x<=1:
# return .5*x -3
#else:
# return 4*x+3
#return x/ (x**2+4)
#return (x+3)/(x**2 - x -6)
#if x <= 2:
# return math.sqrt(4 - x**2) | 288eca6a57562bf6aa95fddc56c05083c5152e71 | 647,818 |
import sys
import os
def get_threads() -> int:
""" Returns the number of available threads on a posix/win based system """
if sys.platform == 'win32':
return (int)(os.environ['NUMBER_OF_PROCESSORS'])
else:
return (int)(os.popen('grep -c cores /proc/cpuinfo').read()) | dc73708fb5aaf25d79f080f521c2699aabea6482 | 647,819 |
import re
def get_info_float(lines, rege):
"""Get the infromation form contents based on the regular expression."""
cp = re.compile(rege)
energy = 1000
for line in lines:
match = cp.search(line)
if match:
energy = float(match.group(1))
return energy | 9e23b84312167e1b01ae8e7326e147311db22f3c | 647,820 |
import hashlib
def generate_edge_tablename(src_label, label, dst_label):
"""Generate a name for the edge table.
Because of the limit on table name length on PostgreSQL, we have
to truncate some of the longer names. To do this we concatenate
the first 2 characters of each word in each of the input arg... | afb1a146570eb4652a0409ad35acf0f9198efa88 | 647,821 |
def _get_intersection(cp1, cp2, s, e):
"""get intersection"""
dc = (cp1[0] - cp2[0], cp1[1] - cp2[1])
dp = (s[0] - e[0], s[1] - e[1])
n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]
n2 = s[0] * e[1] - s[1] * e[0]
n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])
return ((n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1]... | 71aef92cd0b00162e11a710c99e46c9f4ed9d8e7 | 647,822 |
from collections import deque
def calc_depth(vertex_count: int, graph):
"""Calculates depth of rooted tree.
Assumption:
The graph is connected.
Args:
vertex_count : The number of vertices in rooted tree.
graph : Rooted tree (0-indexed).
Returns:
depth : Depth ... | 4b69e133b72c3e721c6cbf40fbb82155de41aa06 | 647,823 |
def query_api_hist(conn, username):
"""
query API call details via hist
:param conn:
:param username:
:return:
"""
cursor = conn.cursor()
sql = "SELECT api_name, COUNT(api_name) FROM api WHERE 1=1"
if username is not None and username != '':
sql += " AND username='{0}'".forma... | 7ce16906a803e3f714591da97bd88e3e675b8fe7 | 647,824 |
def bbox_transform(bbox):
"""
[analog of SqueezeDet src/utils/util.py:bbox_transform()]
convert a bbox of form [cx, cy, w, h] to [xmin, ymin, xmax, ymax].
Works for numpy array or list of tensors.
"""
cx, cy, w, h = bbox
out_box = [[]]*4
out_box[0] = cx-w/2
out_box[1] = cy-h/2
out_box[2] = cx+w/... | 015ee040b745ccc0a21a3694a8b1d5239a50dd7c | 647,826 |
def group_races_by_closing_time(races):
"""
Group races into buckets based on closing time
"""
results = {}
for race in races:
if not results.get(race.poll_closing_time):
results[race.poll_closing_time] = []
results[race.poll_closing_time].append(race)
return sorte... | b120b3b539992e3ca95a05400ef6fd23dfe192dc | 647,827 |
def boost_node(n, label, next_label):
"""Returns code snippet for a leaf/boost node."""
return "%s: return %s;" % (label, n['score']) | e0cd5d42351d1dc4bea30e812b20f57d8dc82bb5 | 647,828 |
import re
def remove_agritrop_link(s):
"""
Removes the domain name of agritrop
:param s: String to remove
"""
s = re.sub("https://agritrop.cirad.fr/","",s)
return s | cc0d5de9f73a32b8cba2e34c61fa0d8e2107e87a | 647,829 |
def _Dij(A, i, j):
"""Sum of lower-left and upper-right blocks of contingency table."""
# See [2] bottom of page 309
return A[i+1:, :j].sum() + A[:i, j+1:].sum() | b57910ea124940d133e23321b0e970f30183b514 | 647,830 |
import torch
def onehot(targets, num_classes):
"""Origin: https://github.com/moskomule/mixup.pytorch
convert index tensor into onehot tensor
:param targets: index tensor
:param num_classes: number of classes
"""
assert isinstance(targets, torch.LongTensor)
return torch.zeros(targets.size()... | e1021c7d06fbe5152d3c27b1fd6a05c0fa418718 | 647,831 |
def hargreaves(tmin, tmax, tmean, et_rad):
"""
Estimate reference evapotranspiration over grass (ETo) using the Hargreaves
equation.
Generally, when solar radiation data, relative humidity data
and/or wind speed data are missing, it is better to estimate them using
the functions available in th... | efb925489b07edab35ce19d9a5f6a0eb7c4dbc77 | 647,832 |
def is_active(drone):
"""Check if the drone is in active state."""
return drone["State"]["Status"] == "Active" | dd91eb2d9e8dd23ae1debe9dd7302ed93990b396 | 647,835 |
def get_title(soup):
"""
Get a topic title.
Examples
--------
>>> title_tag = '<title>title</title>'
>>> soup = make_soup(title_tag)
>>> get_title(soup)
'title'
"""
return soup.find('title').text.split('|')[0].strip() | d5ae3581338940f7ac7ddc4949fc294ed16d197e | 647,836 |
import sqlite3
def db_connection():
"""creates a connection to the database."""
return sqlite3.connect("netflix.db") | b28c4c26e4805e47ee4805293986fe6c359414e5 | 647,837 |
def create_indicator_entry(
indicator_type,
value,
pkg_id,
ind_id,
timestamp,
source=None,
score=None,
):
"""Creating a JSON object of given args
Args:
indicator_type: (str) indicator type
value: (str) indicator value
pkg_id: (str)... | d64f00dad16eeb07f46ccd44acd012b3fef8a023 | 647,838 |
import torch
def get_random_weights(metainfo):
"""
random weight initialization
"""
parameters = []
for i in range(len(metainfo['dimensions'])):
size = metainfo['dimensions'][i]
if i == 0:
prev_size = metainfo['n_spaces']*3
else:
prev_size = metainfo['dimensions'][i-1]
biases = torch.randn(size,... | 10f623146be3cfc11cf4a067d86834faf10a3b0c | 647,839 |
import sqlite3
def get_data(path ='./graph.db', node = 9):
"""
1) connects to DB location
2) Get data from specific node number
3) extracts data for use in neural network
"""
conn = sqlite3.connect(path)
c = conn.cursor()
result = c.execute("SELECT * FROM Node_{}".format(node))
re... | 9582b86db8f6d7c8ae95994de072e0c991b05e96 | 647,840 |
def create_document1(args):
""" Creates document 1 -- an html document"""
return f"""
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body style="font-family:sans-serif;margin-left:2em;">
<h1 style="font-family: 'Trebuchet MS', Helvetica, sans-ser... | 9f75267e13440cfbf98b0bdc94bdc86f50ffda92 | 647,841 |
def _new_board(board_size):
"""Return a emprty tic-tac-toe board we can use for simulating a game.
Args:
board_size (int): The size of one side of the board, a board_size * board_size board is created
Returns:
board_size x board_size tuple of ints
"""
return tuple(tuple(0 for _ in ... | dda587b9d30f4ca30dbbacd37a5f7f12c7fdc5e8 | 647,843 |
import os
def _get():
"""Get the list of held cycle items."""
return os.environ.get('REDO_CYCLES', '').split(':') | d0295038ce471fb3d349c42816ccdf8290e83d01 | 647,844 |
def train_test_split(features, target, split_ts):
"""
Splits all provided TimeSeries instances into train and test sets according to the provided timestamp.
:param features: Feature TimeSeries instances to be split.
:param target: Target TimeSeries instance to be split.
:return: 4-tuple of the form... | f40ccedb24132aa4d03896290185aa5599456e07 | 647,845 |
import random
def group_random_crop(img_group, target_size):
"""
group_random_crop
"""
w, h = img_group[0].size
th, tw = target_size, target_size
assert (w >= target_size) and (h >= target_size), \
"image width({}) and height({}) should be larger than crop size".format(w, h)
ou... | 6e5c1ed1d9f4a614f13bf0cd142c368cdc0871b1 | 647,846 |
def get_item(config, section, key, *args):
"""
Return property value.
:param config: Configuration parser instance.
:param section: Section name in configuration with property to look for.
:param key: Name of the key to look for in section.
:param args: Can contains the default value (consi... | eed94329598da7a241e3b7ce1a4b23c05e898d2c | 647,848 |
def ndim(array, dims):
"""Return True IFF CRDS `array` object has number of dimensions `dims`.
>>> array = utils.Struct({"KIND":"IMAGE", "SHAPE" : (2048,2048), "TYPE": "float32"})
>>> ndim(array, 2)
True
>>> ndim(array, 3)
False
"""
return len(array.SHAPE) == dims | 281febc77629240e5993b39e12d8b491ae9e9911 | 647,849 |
import re
def extract_sb_ticket_id(ticket_url):
"""Extracts the supportbee ticket id from url"""
match = re.search(r'\/(\d+)', ticket_url)
return match.group(1) if match else None | 1cc51a6fb4e87c0e0455bc0733b58af85228131d | 647,850 |
def _convert_to_mbps(interface):
"""Convert Kbps to Mbps"""
interface['statistics']['tx-kbps'] = int(interface.get('statistics').get('tx-kbps')) / 1000
interface['statistics']['rx-kbps'] = int(interface.get('statistics').get('tx-kbps')) / 1000
if interface['oper-status'] == 'if-oper-state-ready':
... | b55b3a0f7a8cb348ee14fa498125d89f59c1c986 | 647,851 |
def Switch(c, x, y):
"""Implement `switch`."""
return x if c else y | 2ece666db3fb0ac7da549622e2edce875d1832bf | 647,852 |
def _out_bounce(x: float) -> float:
"""https://easings.net/#easeOutBounce"""
n, d = 7.5625, 2.75
if x < 1 / d:
return n * x * x
elif x < 2 / d:
x_ = x - 1.5 / d
return n * x_ * x_ + 0.75
elif x < 2.5 / d:
x_ = x - 2.25 / d
return n * x_ * x_ + 0.9375
else:... | 14174349b76d0280acaf962416cd0e819c9ec0eb | 647,853 |
import base64
def b64d(s):
"""b64d(s) -> str
Base64 decodes a string
Example:
>>> b64d('dGVzdA==')
'test'
"""
return base64.b64decode(s) | e174460759f0cf0c1ab2b2c6997dc4c351049891 | 647,854 |
import re
def remove_whitespaces_and_hyphens(value):
"""
Returns value without whitespaces or -
"""
if not value:
return value
return re.sub(r'[\s-]+', '', value) | ce83c37d66bd487b335e35e7e6e7a445cc4d1e5e | 647,855 |
def _e2o(hind, verif, metric=None):
"""Compare the ensemble mean forecast to the verification data for a
``HindcastEnsemble`` setup.
Args:
hind (xarray object): Hindcast with optional ``member`` dimension.
verif (xarray object): Verification data.
metric (Metric): needed for probabi... | 2168aba17940bca8ec355c43d1deeeece463c5b3 | 647,856 |
from numpy import array, tile
def offset_image(shape = (3000,4096)):
"""
"""
template = array([[0,1,2,3],[4,5,6,7],[8,9,10,11],[12,13,14,15]])
rows = shape[0]
cols = shape[1]
offset = tile(template,(int(rows/4),int(cols/4)))[:rows,:cols]
return offset | e74527b19947a7326313582832f7e12b1455b076 | 647,857 |
def double(x: int) -> int:
"""
Doubles a number.
"""
return 2 * x | bdacf4e2aee5e1d487454ca6bda85c578d5de60b | 647,858 |
from typing import Dict
import argparse
import json
def base_oas_file_type(value) -> Dict:
"""
Load base oas file
"""
try:
with open(value) as oas_file:
data = oas_file.read()
except OSError as error:
raise argparse.ArgumentTypeError(error) from error
return json.l... | 962500d4f20b6f8c04f31ef57d1988c079fc87d6 | 647,861 |
def _remove_plural(input):
"""
_remove_plural - function to remove plural forms
Inputs:
- input : str
Outputs:
- input : str
"""
# ending w/ 'es'
if input.endswith('es'):
return input[:-2]
# ending w/ ss -> skip
elif input.endswith('ss'):
pass
# ending w/ s only
elif input.endswith('s'):
return inp... | 6980b5ac8d3f35d3cf436453194ed4152b0cfb45 | 647,862 |
import pickle
def load_state(filename):
"""Load the annotation state stored in filename.
"""
with open(filename, 'rb') as input_state_file:
loaded_state = pickle.load(input_state_file)
return loaded_state | ee1fd8d5a703d6b830ea83b0d623bde4b6158039 | 647,863 |
def property_from_topic(mqtt_topic):
"""Extract the RuuviTag's property from the MQTT topic."""
return mqtt_topic.split("/")[3] | 59a1cb0b362c1d8908681c5701cd2b7785381a4d | 647,864 |
def predict_from_model(patch, model):
"""Predict which pixels are tumor.
"""
prediction = model.predict(patch.reshape(1, 256, 256, 3))
prediction = prediction[:, :, :, 1].reshape(256, 256)
return prediction | e367993c88239e3fc740c4628705b84a7207a116 | 647,865 |
def get_image_class_name(self, image_id):
""" Retrieves the image class name given an image id """
return self.image_infos[image_id]['class_name'] | fd2c3c4dcf1cd09779a8f31c3b96bee33738822f | 647,866 |
def __init_index(index, info, num_atoms):
"""
Initializes the index key for the info dict.
Args:
index (int):
Index of atom in the Atoms object.
info (dict):
Dictionary that stores the velocity, and groups.
num_atoms (int):
Number of atoms in th... | 52d2bda14c4e055bd21da90e44b9d36d31f6bb6d | 647,867 |
import re
def shorten_module(mod):
"""
Return a module name that is shorter but still useful, for
being displayed in logs
>>> shorten_module("civicboom/lib/helpers.py")
'lib.helpers'
"""
return re.sub("civicboom/(.*).py", "\\1", mod).replace("/", ".") | 9e5727a1ccb1b79fdc865fc758ab1ba50c25c149 | 647,868 |
def snapToEdge(arg1,arg2,arg3):
"""
:param arg1: coords of POINT to project
:param arg2: coords of START
:param arg3: coords of END
:return: resulting projection of POINT to line between START and END in form of vector
"""
vector1 = arg3 - arg2
vector2 = arg1 - arg2
# returnCoord=co... | 60a5f27814477ed1e483398764545f290134973b | 647,870 |
from typing import List
from typing import Tuple
def build_sorted_text_output(headline: str, content: List[Tuple[str, str, int]]) -> str:
"""
Takes a headline and a list of items and their respective descriptions,
sorts it and returns a nicely readable output
"""
content.sort()
output: str =... | b8fe12c8b05ed2fd55f0b05cbecb73c39d3d1eef | 647,871 |
import textwrap
def format_comment(s: str) -> str:
"""Formats a string to comment wrapped to an 80 character line width
Returns wrapped string including newline and // comment characters.
"""
comment = textwrap.wrap(s,
width=77,
initial_indent='... | 74bcc1a062e2646b2ce46765c393ddbb9b3b494d | 647,873 |
def get_rad_weekday(date):
"""
Returns numeric representation of a weekday according to RAD's data load
schedule.
:param date: date to return weekday for
:type value: datetime.date
"""
isoday = date.isoweekday()
if isoday == 7:
# Sunday
return 0
else:
return ... | d6c0bfd8a7dec7c969cdb73bbf4c11457d0b9894 | 647,874 |
import json
def json_pp(json_object):
""" Convenience method for pretty-printing JSON
"""
if isinstance(json_object, dict):
return json.dumps(json_object,
sort_keys=True,
indent=4,
separators=(',', ':')) + "\n"
elif... | a42c1f7a6c04ed45d197a458e8da9f19b2e65435 | 647,876 |
from pathlib import Path
import os
def log_dir() -> Path:
"""
Return the path to a directory which logs should be stored in.
"""
return Path(os.environ['DCOS_E2E_LOG_DIR']) | 4ef9a6d1182387142f228fa2bf886855eafe362e | 647,879 |
import os
def _GetBaseFileName(filenode):
"""Returns the base name for output files, given the filenode.
Examples:
'dev/ppb_find_dev.h' -> 'ppb_find_dev'
'trusted/ppb_buffer_trusted.h' -> 'ppb_buffer_trusted'
"""
path, name = os.path.split(filenode.GetProperty('NAME'))
name = os.path.splitext(name)... | 911b595f3649fe8147bddf157a37a26237590c3f | 647,880 |
def chunk_to_parameter(chunk):
"""
:param chunk: List of numbers.
:return: String of numbers, comma delimited, no spaces.
"""
numbers = ''
for number in chunk:
numbers += '%s,' % number
# Remove last comma.
numbers = numbers[:-1]
return numbers | da794c9a767e3e71b25821f97fce8a473c43959c | 647,881 |
def getLvl1ModelList():
"""Get the complete list of lvl1 models."""
# format: [filename, [model names]]
files = [
['FBL', ['FBL_L1', 'FBL_L2', 'FBL_Sc', 'FBL_LDA', 'FBL_LDA_L1']],
['FBL_delay100_skip20',
['FBL_delay_L1', 'FBL_delay_L2', 'FBL_delay_Sc', 'FBL_delay_LDA']]... | 5850af7987b1eb4ee3e71cc00880ac462003afae | 647,882 |
def blk_file_format(number: int) -> str:
"""
Increases by one the blk file name, for example:
blk000132.dat => blk000133.dat
:param current_blk_file: <String> Actual file (eg. 000001)
:return: <String> Next file (eg. 000002)
"""
return str(number).zfill(6) | 51b72c27f7c7ca793feda845850b4cacbaaa1120 | 647,883 |
import click
def _validate_repo_name(ctx, param, value):
"""Callback used to check if repository argument was given."""
if "/" not in value:
raise click.BadParameter('Expected format for REPOSITORY is '
'"<org_name>/<project_name>" (e.g "jcfr/sandbox")')
return val... | 4468081bea703c193c8417885a71d30b3fcd6f10 | 647,884 |
def sort_strategies(strategies):
"""Discover the number of sequences"""
nof_sequences = []
stg_names = []
for strategy in strategies:
nof = ''
nof = [nof + str(strategy[i])
for i in range(len(strategy)) if strategy[i].isnumeric()]
nof = int(''.join(nof))
if... | c82d2fc434b757241363dc8f7b42f96cc2cbe3ee | 647,885 |
def std_ver_minor_uninst_valueerr_decimal(request):
"""Return a decimal value that is not a valid value to represent a minor version number."""
return request.param | d2645ffe6197a828c6c6d8762755c34e34f5368e | 647,886 |
from typing import TextIO
def skip_header(reader: TextIO) -> str:
"""Skip the header in reader and return the first real piece of data.
>>> infile = StringIO('Example\\n# Comment\\n# Comment\\nData line\\n')
>>> skip_header(infile)
'Data line\\n'
"""
# Read the descript... | 89617cf0fca71822e4c3c54b2a6a8d7aeb05abfe | 647,887 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.