content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def clique_ring(n_cluster=3, n_in_cluster=5):
"""Get adjacency matrix for cluster domain used by Schapiro et al 2013.
Args:
n_cluster: number of clusters, connected in a ring.
n_in_cluster: number of nodes in each cluster. Each node is connected to all
other nodes in cluster, except the edge connecti... | 2b8dad4b52e456a933c66af7198b6363eb839c41 | 10,033 |
def get_halfnormal_mean_from_scale(scale: float) -> float:
"""Returns the mean of the half-normal distribition."""
# https://en.wikipedia.org/wiki/Half-normal_distribution
return scale * np.sqrt(2) / np.sqrt(np.pi) | d5d0ac1e460d30ad544982a5f0bb7f463c64ede9 | 10,034 |
def cal_pr(y_hat, y_score):
"""
calculate the precision and recall curve
:param y_hat: ground-truth label, [n_sample]
:param y_score: predicted similarity score, [n_sample]
:return: [n_sample]
"""
thresholds = np.arange(1, -0.001, -0.001)
fps, tps = cal_binary_cls_curve(y_hat, y_score, t... | a64e38a51b5e8c8bdb6bbc26f4c99ae3746dfc64 | 10,035 |
def alert_source_create(context, values):
"""Create an alert source."""
return IMPL.alert_source_create(context, values) | 7d55eed069b644c718ffb55f27d22a56c7483f73 | 10,036 |
def sanitise_utf8(s):
"""Ensure an 8-bit string is utf-8.
s -- 8-bit string (or None)
Returns the sanitised string. If the string was already valid utf-8, returns
the same object.
This replaces bad characters with ascii question marks (I don't want to use
a unicode replacement character, beca... | 11b864ade1c36e2b42ffbdd76ee2851f01ca7803 | 10,037 |
def trans_r2xy(r, phi, r_e, phi_e):
"""r,phi -> x,y """
x = np.array(r) * np.cos(phi)
y = np.array(r) * np.sin(phi)
err = np.array(
[polar_err(i, j, k, l) for i, j, k, l in zip(r, phi, r_e, phi_e)]
)
return x, y, err[:, 0], err[:, 1] | dcc9e1433bb40dd76d41b1031420600cdab96d67 | 10,038 |
def ldpc_bp_decode(llr_vec, ldpc_code_params, decoder_algorithm, n_iters):
"""
LDPC Decoder using Belief Propagation (BP).
Parameters
----------
llr_vec : 1D array of float
Received codeword LLR values from the channel.
ldpc_code_params : dictionary
Parameters of the LDPC code.... | c9bd44c386ead2f9b968eb3a8c211d7af5e26a25 | 10,039 |
def edit_style_formats(style_format_id, **kwargs):
"""Create or edit styles formats.
:param style_format_id: identifier of a specific style format
"""
if request.method == "POST":
args = request.get_json()
errors = StyleFormatsSchema().validate(args)
if err... | a9c0cc004fb840ffcf2b9c0b45f43dc3535ea103 | 10,040 |
def volume_to_vtk(volelement, origin=(0.0, 0.0, 0.0)):
"""Convert the volume element to a VTK data object.
Args:
volelement (:class:`omf.volume.VolumeElement`): The volume element to
convert
"""
output = volume_grid_geom_to_vtk(volelement.geometry, origin=origin)
shp = get_volu... | 710152ebdb56592a1485fa0c451bf135679cc949 | 10,042 |
def _in_delta(value, target_value, delta) -> bool:
"""
Check if value is equal to target value within delta
"""
return abs(value - target_value) < delta | 92ab62a381fc1cfc6bbb82635f196ec4498babf4 | 10,043 |
def getpar(key, file='DATA/Par_file', sep='=', cast=str):
""" Reads parameter from SPECFEM parfile
"""
val = None
with open(file, 'r') as f:
# read line by line
for line in f:
if find(line, key) == 0:
# read key
key, val = _split(line, sep)
... | 05a2cf904dd1c5cdb71dd302e2a74c3397a6d1e2 | 10,044 |
from typing import Dict
def create_ok_response() -> flask.Response:
"""Creates a 200 OK response.
:return: flask.Response.
"""
ok_body: Dict[str, str] = {"status": "OK"}
return make_response(jsonify(ok_body), HTTP_200_OK) | 4b60c712a1b123c8daa976239cf5abd813e50221 | 10,046 |
import time
def format_timestamp(timestamp):
"""Formats an UTC timestamp into a date string.
>>> format_timestamp("2014-04-08T12:41:34+0100")
'Tue, 08 Apr 2014 12:41:34'
"""
t = iso8601.parse_date(timestamp).timetuple()
return time.strftime("%a, %d %b %Y %H:%M:%S", t) | f551c5bb984ad9d23d0c1d21103f340e6e4b104b | 10,049 |
def _flat(xvals):
"""
Function for flat surface y=0, with boundary conditions
Parameters
----------
xvals : np.array
x-values of the surface.
Returns
-------
yvals : np.array
y-Values of the initialized surface.
"""
yvals = np.zeros_like(xvals)
return yvals | 632ad5fa9acc30e7fae07942890dd9060ab6c859 | 10,050 |
import torch
def regularized_laplacian(weights, labels, alpha):
"""Uses the laplacian graph to smooth the labels matrix by "propagating" labels
Args:
weights: Tensor of shape (batch, n, n)
labels: Tensor of shape (batch, n, n_classes)
alpha: Scaler, acts as a smoothing factor
... | 12725881a121a3fb3455c0905d8db1a90b08dc4d | 10,051 |
def weight_variable_glorot(input_dim, output_dim, name=""):
"""Create a weight variable with Glorot & Bengio (AISTATS 2010)
initialization.
"""
init_range = np.sqrt(6.0 / (input_dim + output_dim))
initial = tf.random_uniform([input_dim, output_dim], minval=-init_range,
... | 85b7ba1f46d0e154425cc884202021faf621bc0e | 10,052 |
from typing import Tuple
def pareto_plot(column: pd.Series,
use_given_index: bool = False,
figsize: Tuple[int, int] = (12, 8),
return_freq_df: bool = False):
"""
Draw Pareto plot for categorical variable
Arguments:
----------
column: pd.Series
... | 8bf2f098a93076356ae00e702a05e4b831811609 | 10,053 |
from typing import Optional
from typing import Dict
import json
def remove_external_id(
role_name: str,
dir_path: Optional[str],
session=None,
client=None,
backup_policy: Optional[str] = "",
bucket: Optional[str] = None,
) -> Dict:
"""The remove_external_id method takes a role_name as a st... | 711fbe0bf12206688b3d372d97fe0e10f1aa59e1 | 10,056 |
def find_binaries(fw_path):
"""
Gets a list of possible binaries within a firmare sample.
The list might contain false positives, angr will ignore them.
:param fw_path: firmware path
:return: a list of binaries
"""
cmd = "find \""+ fw_path + "\""
cmd += " -executable -type f... | 53d4a8f8a9abcc9404392a1ba317fde2e583bc93 | 10,057 |
def get_core_count():
"""
Find out how many CPU cores this system has.
"""
try:
cores = str(compat.enum_cpus()) # 3.4 and up
except NotImplementedError:
cores = "1" # 3.2-3.3
else:
if compat.enum_cpus() is None:
cores = "1"
return cores | 2bd49d6189ba4f6ee92ae3e54cb629a8fb70e440 | 10,058 |
def vec2str(vec):
""" transform the vector to captcha str"""
_str = ""
for i in range(4):
v = vec[i*43: (i+1)*43]
_str += chr(np.argwhere(v == 1)[0][0] + ord('0'))
return _str | 9f927b9b084b2aeff26686a0066bdbfb9ad4e3f3 | 10,060 |
def mnist(path=None, batchsize=20, xpreptrain=None, ypreptrain=None, dataset="train", **kwargs):
"""
Legacy MNIST loader.
:type path: str
:param path: Path to MNIST pickle file.
:type batchsize: int
:param batchsize: Batch size (no shit sherlock)
:type xpreptrain: prepkit.preptrain
:p... | 65ab0c0ad529f5b9b6803585d00fb044a82db2a5 | 10,061 |
def rand_pad(ctvol):
"""Introduce random padding between 0 and 15 pixels on each of the 6 sides
of the <ctvol>"""
randpad = np.random.randint(low=0,high=15,size=(6))
ctvol = np.pad(ctvol, pad_width = ((randpad[0],randpad[1]), (randpad[2],randpad[3]), (randpad[4], randpad[5])),
m... | 83dd1de5c9914127c1d7fcc8d5e5068aa9f2864c | 10,062 |
from typing import Tuple
def _improve(tour: np.ndarray, matrix: np.ndarray, neighbours: np.ndarray, dlb: np.ndarray,
it1: int, t1: int, solutions: set, k: int) -> Tuple[float, np.ndarray]:
""" Последовательный 2-opt для эвристики Лина-Кернига
tour: список городов
matrix: матрица весов
nei... | 982a575fcde8e78186259f1970dc18850fd3b93e | 10,063 |
def plot_step_with_errorbar(lefts, widths, y_coords, y_errs,
errors_enabled=True, use_errorrects_for_legend=False, **kwargs):
"""Makes a step plot with error bars."""
lefts.append(lefts[-1] + widths[-1])
y_coords.append(y_coords[-1])
# prevent that we have labels for the step... | e532e71ada503474e5d52b24a1bf2a7fb2418e82 | 10,064 |
def intensity_modification(x):
""" Intensity modification
Parameters
x: Tensor
Returns
x: Tensor
"""
x = x + tf.random.uniform(shape=[], minval=-0.05, maxval=0.05, dtype=tf.dtypes.float32)
return x | c2ad13b6b123b3f053b88373ecfe7f4adfec87a3 | 10,065 |
def FormIdProperty(expression, **kwargs):
"""
Create a StringProperty that references a form ID. This is necessary because
form IDs change when apps are copied so we need to make sure we update
any references to the them.
:param expression: jsonpath expression that can be used to find the field
... | 5ac621dbd69df060de5280e8d893149ecb715b6f | 10,066 |
import secrets
def do_roll(dice: int, sides: int, _: int):
"""Given an amount of dice and the number of sides per die, simulate a dice roll and return
a list of ints representing the outcome values.
Modifier is ignored.
"""
dice = dice or 1
sides = sides or 1
values = sorted(((secrets.ran... | 2073a37e5b76a85182e8cf786707ed18ca3f2474 | 10,067 |
def compute_logp_independent_block(X, alpha=None):
"""Compute the analytical log likelihood of a matrix under the
assumption of independence.
"""
if alpha is None: alpha = np.ones(X.shape[1])
logp_ib = gammaln(alpha.sum()) - (gammaln(alpha)).sum()
logp_ib += gammaln(X.sum(0) + alpha).sum() - gam... | 831cdc63f8e131d3dfb797e054dfcd421f939ed5 | 10,068 |
def check_validity_label(labels):
"""
Check to see whether it makes a valid tuple
Parameters:
-----------
labels: A tuple of labels (Object_1, Object_2, Object_3,
Return:
-------
"""
# Event is None -> All other values are None
if labels[3] == 0:
for... | c5a3d75813ab521b1e56789d64e7f14861075fb0 | 10,069 |
def flat_proj(v1, v2):
""" Returns the flat projection of direction unit vector, v1 onto v2 """
temp1 = np.cross(v1, v2)
temp2 = np.cross(temp1, v1)
return proj(temp2, v2) | 8a75dc118940cad6735f361ae3214358d78881e9 | 10,070 |
import torch
from typing import Optional
from typing import Tuple
from typing import List
def marching_cubes_naive(
volume_data_batch: torch.Tensor,
isolevel: Optional[float] = None,
spacing: int = 1,
return_local_coords: bool = True,
) -> Tuple[List[torch.Tensor], List[torch.Tensor]]:
"""
Run... | a7a4ac4a08bbc270091acc2ddd6a84eb4ee0ba37 | 10,071 |
def gc_resnet101(num_classes):
"""Constructs a ResNet-101 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(GCBottleneck, [3, 4, 23, 3], num_classes=num_classes)
model.avgpool = nn.AdaptiveAvgPool2d(1)
return model | e6bb2e5e97fcf81d6abba34a2ee6c0638d39edf8 | 10,073 |
def compute_seatable_votes(votes, votetypes):
"""Compute the seatable votes.
Parameters
----------
votes: pandas.DataFrame
the votes of the seatable votes.
votetypes: dict
the information of the different types of vote variables.
Returns
-------
seatable_votes: numpy.nd... | 1f8a32589918236e00d1c702cb23ecbc19d0cccb | 10,075 |
from typing import Optional
async def read_cookie(refresh_token: Optional[str] = Cookie(None)) -> JSONResponse:
"""Reads a cookie.
Args:
refresh_token: Name of the cookie.
Returns:
JSONResponse:
Returns the value of the cookie as a json blurb.
"""
if refresh_token:
... | f7e4e20f138b24a6d1beda76b2c2e565f28e513c | 10,076 |
def readAirfoilFile(fileName, bluntTe=False, bluntTaperRange=0.1, bluntThickness=0.002):
"""Load the airfoil file"""
f = open(fileName)
line = f.readline() # Read (and ignore) the first line
r = []
try:
r.append([float(s) for s in line.split()])
except Exception:
pass
while... | 3b3da70ff36dc3a4ab2a186ee9712978f2658294 | 10,077 |
import re
def depListToArtifactList(depList):
"""Convert the maven GAV to a URL relative path"""
regexComment = re.compile('#.*$')
#regexLog = re.compile('^\[\w*\]')
artifactList = []
for nextLine in depList:
nextLine = regexComment.sub('', nextLine)
nextLine = nextLine.strip()
... | 52d27c3310a4fd17df857df4725079a4d93faa76 | 10,079 |
def configure_plugins_plugin_install_to_version(request, pk, version):
"""
View rendering for the install to version modal interface
:param request: Request
:param pk: The primary key for the plugin
:param version: The version to install
:return: a renderer
"""
plugin = get_object_or_40... | 96e1076bdb84d6e0758d5ba03777a6576889cfdc | 10,080 |
def _parameters_to_vector(parameters):
"""
This fix is required for pytorch >= 1.6.0, due to the change
in memory format promotion rule.
For more info, check:
* https://github.com/pytorch/pytorch/pull/37968
* https://github.com/pytorch/pytorch/releases/tag/v1.6.0
and search "Note: BC-break... | f3b7d4cb8262cbbcbe2e5abace6e8e8162fb3a57 | 10,081 |
from utils.snowflake.id_worker import IdWorker
from utils.limiter import limiter as lmt
from utils.logging import create_logger
from utils.converters import register_converters
from redis.sentinel import Sentinel
from rediscluster import StrictRedisCluster
from models import db
from .resources.user import user_bp
from ... | 1284a53c24d7fc4bf2ce0a0f00d6a3defea642d6 | 10,082 |
def select_variables(expr):
"""When called on an expression, will yield selectors to the variable.
A selector will either return the variable (or equivalent fragment) in
an expression, or will return an entirely new expression with the
fragment replaced with the value of `swap`.
e.g.
>>> from ... | a147b1f1fc66373597b98085b13ffd326baf72e1 | 10,083 |
from typing import Callable
from typing import Optional
import glob
def get_login(name_p: str, pass_p: str, auth_error: bytes = b'') -> Callable:
"""Decorator to ensure a player's login information is correct."""
# NOTE: this function does NOT verify whether the arguments have
# been passed into the conne... | 3b3a1eb36d92de373eab9414abef6dd44bf14502 | 10,084 |
import math
def map_visualize(df: gpd.GeoDataFrame,
lyrs='s',
scale=0.5,
figsize = (12,9),
color = "red",
ax = None,
fig=None,
*args, **kwargs):
"""Draw the geodataframe with the sa... | f59c72079f789e63ad7910e5c4ee62d93e5015e9 | 10,085 |
def unorm_to_byte(x):
"""float x in [0, 1] to an integer [0, 255]"""
return min(int(256 * x), 255) | a6870a339b9b0d5466962a9129c717876d8d0a50 | 10,086 |
def eigh(a, largest: bool = False):
"""
Get eigenvalues / eigenvectors of hermitian matrix a.
Args:
a: square hermitian float matrix
largest: if True, return order is based on descending eigenvalues, otherwise
ascending.
Returns:
w: [m] eigenvalues
v: [m, m]... | 254f243bd5c70f606cc67111df03626a0eae25b0 | 10,087 |
def lowpass(x, dt, fc, order=5):
"""
Low pass filter data signal x at cut off frequency fc, blocking harmonic content above fc.
Parameters
----------
x : array_like
Signal
dt : float
Signal sampling rate (s)
fc : float
Cut off frequency (Hz)
order : int, opti... | fd3cd4f7ccca9c2244c82420a560199633d082ab | 10,088 |
def doRunFixPlanets(msName):
"""Generate code for running fixplanets on fields with (0,0) coordinates"""
print('\n*** doRunFixPlanets ***')
fieldIds = sfsdr.getFieldsForFixPlanets(msName)
if len(fieldIds) != 0:
casaCmd = ''
mytb = aU.createCasaTool(tbtool)
mytb.open(msName+'/... | 2656505e91eeea545c1c91c169b183ac5dd5413a | 10,089 |
def add_name_suffix(
suffix, obj_names=None, filter_type=None, add_underscore=False, search_hierarchy=False,
selection_only=True, **kwargs):
"""
Add prefix to node name
:param suffix: str, string to add to the end of the current node
:param obj_names: str or list(str), name of list of no... | c9355a5030c430d6efa6d8abc6b6d9128f77cb8e | 10,090 |
def checksum(hdpgroup: list,
algorithm: str = 'CRC32',
chktag: str = '\'α') -> list:
"""List of checksums-like for detection of Non-intentional data corruption
See https://en.wikipedia.org/wiki/Cksum
See https://en.wikipedia.org/wiki/Checksum
Args:
hdpgroup (list): li... | 66566fbef3c962d5bcdf56727ff66ddfdd8af9b7 | 10,091 |
def dsum(i0,i1,step = 1, box=[]):
""" for a range of fits files
compute the mean and dispersion from the mean
"""
for i in range(i0,i1+1,step):
ff = 'IMG%05d.FIT' % i
h1, d1 = getData(ff,box)
#very specific for 16 bit data, since we want to keep the data in uint16
bze... | 6e0048461e29a7de4f7c4322fa1e3213f8248e60 | 10,092 |
def _env_translate_obs(obs):
"""
This should only be used for the Tiger ENV.
Parameters
----------
obs : list or array-like
The observation to be translated.
Returns
-------
str
A representation of the observation in English.
"""
if obs[0] == 1:
return '... | 761ff3f3269e41b44bdab098d3682630d928cdc6 | 10,093 |
def voter(address):
"""
Returns voter credentials.
Parameters:
address: address
Returns:
list of three values addresss (str), is_voter (bool),
voted (bool).
"""
return contract.functions.voters(address).call() | 91fd7adca6f8ed2e02dbe60b6241eb92f34a81b6 | 10,094 |
def E_disp_z(m, N, j_star=3.):
"""Vertical displacement as a function of vertical wavenumber."""
num = E0*b**3*N0**2
den = 2*j_star*np.pi*N**2 * (1 + m/beta_star(N, j_star))**2
return num/den | 39e6b9b5d512d577c8109ecfb5657a0ef5a8ea42 | 10,095 |
def get_stereo_image():
"""Retrieve one stereo camera image
Returns:
(mat): cv2 image
"""
img = core.get_stereo_image()
if img is not None:
return img
else:
return None | 72e570672885e8ef8c14c9cd29d3f7c648f9abac | 10,096 |
import time
import requests
def request_set_arm_state(token: str, arm_state: str):
"""Request set arm state."""
headers = {
'Authorization': 'Bearer %s' % token,
'Content-Type': 'application/json'
}
payload = {
"Created": int(time.time()),
"AppVersion": APP_VERSION,
... | 28a8ad2a0d49305d80581c2257d3fb9495b3f680 | 10,097 |
def get_all_config(filename=None):
"""
Set default configuration options for configparse
Config with defaults settings if no file will be passed
Also with defaults sections and defaults keys for missing options in config
:param filename: options config file to read
:return: configparser object w... | 9a5bdcd272f49be5bd8374e06f5b6579da91d64a | 10,098 |
def check_for_end_or_abort(e):
"""Return a closure checking for END or ABORT notifications
Arguments:
e -- event to signal when the action is completed
(will be set when an END or ABORT occurs)
"""
def check(notification, e = e):
print("EVENT : " + \
Base_pb2.ActionEve... | 91809c705666f4fd3aae7273760d5845fa35eadb | 10,099 |
def check_vacancy_at_cell(house_map, cell):
"""
Return True if the given cell is vacant.
Vacancy is defined as a '0' in the house map at the given coordinates.
(i.e. there is no wall at that location)
"""
x = cell[0]
y = cell[1]
if not 0 <= x < MAP_WIDTH:
return False
... | 78a24b25a6954b6411aa686512066b25c6f4e1d5 | 10,100 |
from typing import Dict
def extract_text_and_vertices(x: Dict[str, str]):
"""Extracts all annotations and bounding box vertices from a single OCR
output from Google Cloud Vision API.
The first element is the full OCR. It's equivalent to the output of
`extract_full_text_annotation` for the same OC... | 6fde2bc71ceccfd580a6f5f0da7fa0b76e045bad | 10,101 |
def cspace3(obs, bot, theta_steps):
"""
Compute the 3D (x, y, yaw) configuration space obstacle for a lit of convex 2D obstacles given by [obs] and a convex 2D robot given by vertices in [bot] at a variety of theta values.
obs should be a 3D array of size (2, vertices_per_obstacle, num_obstacles)
bot ... | 723e1b885a19ae0416226856f7b03aecb045e139 | 10,102 |
from typing import Optional
def Graph(backend:Optional[str]=None) -> BaseGraph:
"""Returns an instance of an implementation of :class:`~pyzx.graph.base.BaseGraph`.
By default :class:`~pyzx.graph.graph_s.GraphS` is used.
Currently ``backend`` is allowed to be `simple` (for the default),
or 'graph_tool' and 'igra... | 9d2d759096016e0df770863448305b627df0ce73 | 10,103 |
from datetime import datetime
def get_carb_data(data, offset=0):
""" Load carb information from an issue report cached_carbs dictionary
Arguments:
data -- dictionary containing cached carb information
offset -- the offset from UTC in seconds
Output:
3 lists in (carb_values, carb_start_dates,... | cc2e54859f3f4635e9724260f277dd3c191c32ac | 10,104 |
def _discover_bounds(cdf, tol=1e-7):
"""
Uses scipy's general continuous distribution methods
which compute the ppf from the cdf, then use the ppf
to find the lower and upper limits of the distribution.
"""
class DistFromCDF(stats.distributions.rv_continuous):
def cdf(self, x):
... | bb882065ed74a34c61c60aa48481b2737a2496da | 10,105 |
def ml_app_instances_ml_app_instance_id_get(ml_app_instance_id): # noqa: E501
"""ml_app_instances_ml_app_instance_id_get
# noqa: E501
:param ml_app_instance_id: MLApp instance identifier
:type ml_app_instance_id: str
:rtype: None
"""
return 'do some magic!' | e702d106b6dd4999ed536f77347ca84675be3716 | 10,106 |
import random
def generate_name(style: str = 'underscore', seed: int = None) -> str:
"""Generate a random name."""
if seed is not None:
random.seed(seed)
return format_names(random_names(), style=style) | 2f74460f5492c3b4788800d6e33a44b856df91aa | 10,107 |
def argunique(a, b):
"""
找出a--b对应体中的唯一对应体,即保证最终输出的aa--bb没有重复元素,也没有多重对应
:param a:
:param b:
:return: aaa, bbb 使得aaa-bbb是唯一对
"""
# 先对a中元素进行逐个检查,如果第一次出现,那么添加到aa中,如果不是第一次,那么检查是否一致,不一致则设置成-1
# 设置成-1,代表a中当前元素i有过一对多纪录,剔除。同时-1也不会被再匹配到
seta = {}
for i, j in zip(a, b):
if i not in ... | e804436203496d5f3109511967a0d75eaca330da | 10,108 |
def move(obj, direction):
"""
Moves object by (dx, dy).
Returns true if move succeeded.
"""
goal = obj.pos + direction
if (goal.x < 0 or goal.y < 0 or
goal.x >= obj.current_map.width or
goal.y >= obj.current_map.height):
# try_ catches this for the player, but nee... | 23917e448ed953acb2bb864d7a14d01c72f07a85 | 10,109 |
def addMedicine(medicine: object):
"""Data required are "name", "description", "price", "quantity", "medicalId" """
return mr.makePostRequest(mr.API + "/medicine/", medicine) | f488ecd16d6e2986944ae26e5776ca9f9be7e170 | 10,110 |
from benchbuild.utils.db import create_run
from benchbuild.utils import schema as s
from benchbuild.settings import CFG
from datetime import datetime
def begin(command, project, ename, group):
"""
Begin a run in the database log.
Args:
command: The command that will be executed.
pname: Th... | a33a5e809b20b6d1f92545bd0df5de9fbc230f91 | 10,111 |
def fortran_library_item(lib_name,
sources,
**attrs
): #obsolete feature
""" Helper function for creating fortran_libraries items. """
build_info = {'sources':sources}
known_attrs = ['module_files','module_dirs',
... | 720802933b9ebcaab566f3deeb063341b85dba7e | 10,112 |
def copy_generator(generator):
"""Copy an existing numpy (random number) generator.
Parameters
----------
generator : numpy.random.Generator or numpy.random.RandomState
The generator to copy.
Returns
-------
numpy.random.Generator or numpy.random.RandomState
In numpy <=1.16... | 57f5c3b9ad934330b1eedb6460943204f97b9436 | 10,113 |
def test_pages_kingdom_successful(args, protein_gen_success, cazy_home_url, monkeypatch):
"""Test parse_family_by_kingdom() when all is successful."""
test_fam = Family("famName", "CAZyClass", "http://www.cazy.org/GH14.html")
def mock_get_pag(*args, **kwargs):
return ["http://www.cazy.org/GH14_all... | b5fdbeac6a4a54170c17a98689ae5cc6bbca9542 | 10,116 |
def _truncate_and_pad_token_ids(token_ids, max_length):
"""Truncates or pads the token id list to max length."""
token_ids = token_ids[:max_length]
padding_size = max_length - len(token_ids)
if padding_size > 0:
token_ids += [0] * padding_size
return token_ids | a8f29fdbc99c3dcac42b9275037d3a3c39c22e12 | 10,117 |
def build_bundletoperfectsensor_pipeline(pan_img, ms_img):
"""
This function builds the a pipeline that performs P+XS pansharpening
:param pan_img: Path to the panchromatic image
:type pan_img: string
:param ms_img: Path to the multispectral image
:type ms_img: string
:returns: resample_ima... | f40aa0828ef50ef8f81f901f93dbaf8690a14d4f | 10,118 |
def get_argparser_ctor_args():
"""
This method returns a dict containing the kwargs for constructing an
argparse.ArgumentParser (either directly or as a subparser).
"""
return {
'prog': 'CodeChecker store',
'formatter_class': arg.RawDescriptionDefaultHelpFormatter,
# Descri... | 9debf6233652052782295aeb5b630ee2b4b3b19e | 10,119 |
def castep_geom_count(dot_castep):
"""Count the number of geom cycles"""
count = 0
with open(dot_castep) as fhandle:
for line in fhandle:
if 'starting iteration' in line:
count += 1
return count | 6a619b5853a02a8c118af1fc19da0d803941c84f | 10,120 |
def nav_login(request, text="Login", button=False):
"""Navigation login button
Args:
request (Request): Request object submitted by template
text (str, optional): Text to be shown in button. Defaults to "Login".
button (bool, optional): Is this to be styled as a button or as a link. Def... | ddbc3de38c47425ec9f095577d178c068cce74c2 | 10,121 |
def parse_adapter(name: str, raw: dict) -> dict:
"""Parse a single adapter."""
parsed = {
"name": strip_right(obj=name, fix="_adapter"),
"name_raw": name,
"name_plugin": raw["unique_plugin_name"],
"node_name": raw["node_name"],
"node_id": raw["node_id"],
"status":... | 085b8a38561d6ffda12ca27d2f2089759b34e1ed | 10,122 |
def export_phones(ucm_axl):
"""
Export Phones
"""
try:
phone_list = ucm_axl.get_phones(
tagfilter={
"name": "",
"description": "",
"product": "",
"model": "",
"class": "",
"protocol": "",
... | 1487cef48c5666224da57173b968e9988f587a57 | 10,123 |
def is_various_artists(name, mbid):
"""Check if given name or mbid represents 'Various Artists'."""
return name and VA_PAT.match(name) or mbid == VA_MBID | 084f1d88b99ec7f5b6eac0774a05e901bd701603 | 10,124 |
def validate_ruletype(t):
"""Validate *bounds rule types."""
if t not in ["typebounds"]:
raise exception.InvalidBoundsType("{0} is not a valid *bounds rule type.".format(t))
return t | a8ae173f768837cdc35d1a8f6429614b58a74988 | 10,125 |
def decode_section_flags(sflags: str) -> int:
"""Map readelf's representation of section flags to ELF flag values."""
d = {
'W': elftools.elf.constants.SH_FLAGS.SHF_WRITE,
'A': elftools.elf.constants.SH_FLAGS.SHF_ALLOC,
'X': elftools.elf.constants.SH_FLAGS.SHF_EXECINSTR,
'M': elf... | e007f1f370f6203bafe92a1a6422100f2d9626ae | 10,127 |
def nCr(n,r):
"""
Implements multiplicative formula:
https://en.wikipedia.org/wiki/Binomial_coefficient#Multiplicative_formula
"""
if r < 0 or r > n:
return 0
if r == 0 or r == n:
return 1
c = 1
for i in xrange(min(r, n - r)):
c = c * (n - i) // (i + 1)
return c | 8c0dc30b4cdab47c99bf98459e435147ac0b92fd | 10,128 |
import inspect
def _get_init_arguments(cls, *args, **kwargs):
"""Returns an OrderedDict of args passed to cls.__init__ given [kw]args."""
init_args = inspect.signature(cls.__init__)
bound_args = init_args.bind(None, *args, **kwargs)
bound_args.apply_defaults()
arg_dict = bound_args.arguments
d... | 116c01f9edb838e4b392fa624a454fdf4c455f1a | 10,130 |
def MatchCapture(nfa: NFA, id: CaptureGroup) -> NFA:
"""Handles: (?<id>A)"""
captures = {(s, i): {id} for (s, i) in nfa.transitions if i != Move.EMPTY}
return NFA(nfa.start, nfa.end, nfa.transitions, merge_trans(nfa.captures, captures)) | 08805d01be73480cfea4d627c6a67969290c1d11 | 10,131 |
def get_all_state_events(log):
""" Returns a list of tuples of event id, state_change_id, block_number and events"""
return [
(InternalEvent(res[0], res[1], res[2], log.serializer.deserialize(res[3])))
for res in get_db_state_changes(log.storage, 'state_events')
] | c75307c930add3e142996e19c441c84fd663e36a | 10,133 |
def iff(a: NNF, b: NNF) -> Or[And[NNF]]:
"""``a`` is true if and only if ``b`` is true."""
return (a & b) | (a.negate() & b.negate()) | 82ea5bfe9c4e1f79361319b2d8455cba898e77ec | 10,134 |
def redact_access_token(e: Exception) -> Exception:
"""Remove access token from exception message."""
if not isinstance(e, FacebookError):
return e
e.args = (redact_access_token_from_str(str(e.args[0])),)
return e | 63d7a7422cb7315866e9c25552fa96b403673261 | 10,135 |
def _get_ext_comm_subtype(type_high):
"""
Returns a ByteEnumField with the right sub-types dict for a given community.
http://www.iana.org/assignments/bgp-extended-communities/bgp-extended-communities.xhtml
"""
return _ext_comm_subtypes_classes.get(type_high, {}) | 5b5782659f1d261162d8f9d5becfe65b852f3bdc | 10,136 |
import click
def _filter_classes(classes, filters, names_only, iq):
"""
Filter a list of classes for the qualifiers defined by the
qualifier_filter parameter where this parameter is a list of tuples.
each tuple contains the qualifier name and a dictionary with qualifier
name as key and tuple con... | eecee9f5a1ccf6c793000faf11cd0f666a0c0f7b | 10,137 |
def template2():
"""load_cep_homo"""
script = """
## (Store,figure)
<< host = chemml
<< function = SavePlot
<< kwargs = {'normed':True}
<< output_directory = plots
<< filename = amwVSdensity
... | 2d6dfbab0ef3093645b67da756491fd1b1639649 | 10,138 |
from typing import Tuple
from typing import Any
def get_target_and_encoder_gpu(train: GpuDataset) -> Tuple[Any, type]:
"""Get target encoder and target based on dataset.
Args:
train: Dataset.
Returns:
(Target values, Target encoder).
"""
target = train.target
if isinstance(... | 64cfee3ec9c58bf07d9eb28977b4e5cb7ebadc80 | 10,139 |
import functools
def once(f):
"""Cache result of a function first call"""
@functools.wraps(f)
def wrapper(*args, **kwargs):
rv = getattr(f, 'rv', MISSING)
if rv is MISSING:
f.rv = f(*args, **kwargs)
return f.rv
return wrapper | 25d096f76d156c7a8a26f8f159b65b9b31c8d927 | 10,141 |
import torch
def setup(args):
"""
Create configs and perform basic setups.
"""
cfg = get_cfg()
add_config(args, cfg)
cfg.merge_from_file(args.config_file)
cfg.merge_from_list(args.opts)
cfg.MODEL.BUA.EXTRACTOR.MODE = 1
default_setup(cfg, args)
cfg.MODEL.DEVICE = 'cuda:0' if tor... | 76a8a21714a1fed96fe7b6f33cb948aee30bffcf | 10,142 |
def build_audit_stub(obj):
"""Returns a stub of audit model to which assessment is related to."""
audit_id = obj.audit_id
if audit_id is None:
return None
return {
'type': 'Audit',
'id': audit_id,
'context_id': obj.context_id,
'href': '/api/audits/%d' % audit_id,
'issue_tracker... | 705f066975bf9dae8704944c71eeb3e313cf445f | 10,143 |
def calculate_widths(threshold_img, landmarks):
"""
Calcula a largura dos vasos sanguíneos nos pontos de potenciais
bifurcação. Esse cálculo é feito pegando a menor distância percorrida
a partir do ponto em cada uma das direções (8 direções são utilizadas).
A função retorna o que ser... | 304ce6bec19faba0a0520b63435fcbf66f8989f0 | 10,144 |
from typing import Optional
def smi_to_fp(smi: str, fingerprint: str,
radius: int = 2, length: int = 2048) -> Optional[np.ndarray]:
"""fingerprint functions must be wrapped in a static function
so that they may be pickled for parallel processing
Parameters
----------
smi : s... | fa768c5b53a4a1b637b1928127ef85506d375fd7 | 10,145 |
def f(x, t):
"""function to learn."""
return tf.square(tf.cast(t, tf.float32) / FLAGS.tm) * (tf.math.sin(5 * x) + 1) | 9138b7a2acf43a1c62d5da8157725ff10e6f7f78 | 10,146 |
def render_cells(cells, width=80, col_spacing=2):
"""Given a list of short (~10 char) strings, display these aligned in
columns.
Example output::
Something like this can be
used to neatly arrange long
sequences of values in ... | 714b915430be84980c3a9b74f3c5b2cb89b6acba | 10,147 |
def separate_types(data):
"""Separate out the points from the linestrings."""
if data['type'] != 'FeatureCollection':
raise TypeError('expected a FeatureCollection, not ' + data['type'])
points = []
linestrings = []
for thing in data['features']:
if thing['type'] != 'Feature':
... | 28ab8eb7e2cdf1206f4908a15506a9b9af1aa428 | 10,148 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.