content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def is_identity_matrix(L):
"""
Returns True if the input matrix is an identity matrix, False otherwise.
"""
result = len(L) == len(L[0])
for i in range(len(L)):
for j in range(len(L)):
if i == j:
result *= (L[i][j] == 1)
else:
result *=... | be042d8d342f0961a77c6a4ddc1b5b10234a7b08 | 676,223 |
def has_value(value):
"""
We want values like 0 and False to be considered values, but values like
None or blank strings to not be considered values
"""
return value or value == 0 or value is False | 1ffabaed22b2a1b83b89eb4d551c6e776a8e13c0 | 676,224 |
import os
import json
def get_version(path) -> str:
"""
Reads the version field from a package file
:param path: the path to a valid package.json file
:return: the version string or "unknown"
"""
if path and os.path.exists(path):
with open(path) as pkg:
package_dic... | cbd954542536fb7df7dde8f29dbbdf5324c50aea | 676,225 |
def create_container(swift_connection, name, storage_policy=None):
"""
Create a container with an optional storage policy.
:param swift_connection: connection to Swift
:type swift_connection: :py:class:`swiftclient.client.Connection`
:param name: container name
:type name: string
:param sto... | d7813a6cd3dc1f8548c76753ab0b679499dc179a | 676,226 |
import json
def load_students(file_name):
"""
Загрузить всех работников из файла JSON
"""
with open(file_name, "r", encoding="utf-8") as fin:
return json.load(fin) | 7f9b6f5209c582bcbb3327dd7fc5545e85eb7019 | 676,227 |
def filter_none_grads(grads_and_vars):
"""Filter None grads."""
return [(grads, vs) for (grads, vs) in grads_and_vars if grads is not None] | 4b2fd05522bf1ea7faada864c613e29073f8045c | 676,228 |
import pprint
def block_indent(text, spaces=4):
"""
Given a multi-line string, indent every line of it by the given number of spaces.
If `text` is not a string it is formatted using pprint.pformat.
"""
return '\n'.join([(' ' * spaces) + l for l in pprint.pformat(text).splitlines()]) | 1b0bad804ffb22e792c1da9b156fdc139d231af9 | 676,229 |
def get_single_company_identifiers(data: dict, identifier: str) -> dict:
"""Retrieves the three identifiers (CIK, ticker, title) of a single company.
:param data: The dictionary mapping CIKs with tickers and title from the SEC.
:type data: dict.
:param identifier: The identifier passed by the user when... | f96ffdb1f97e02e907bebc100a73b320ab231e6d | 676,230 |
def remove_overlap(ranges):
""" Simplify a list of ranges; I got it from https://codereview.stackexchange.com/questions/21307/consolidate-list-of-ranges-that-overlap """
result = []
current_start = -1
current_stop = -1
for start, stop in sorted(ranges):
if start > current_stop:
# this segment starts after t... | 913a1e899ddf456b1273463ac81ba28a226fd1eb | 676,231 |
def get_supported_os(scheduler):
"""
Return a tuple of the os supported by parallelcluster for the specific scheduler.
:param scheduler: the scheduler for which we want to know the supported os
:return: a tuple of strings of the supported os
"""
return "alinux" if scheduler == "awsbatch" else "... | 0ca06c8c5b5259f7916f04569c057db137d6dbfb | 676,232 |
def get_strand(read):
"""Get the strand of the mapped read"""
if read.is_reverse:
return '-'
return '+' | daaa9358dfdb031b7329af9bbeef9d77a5c5bce1 | 676,234 |
from typing import Tuple
from typing import List
def get_home_and_node_id_from_device_id(device_id: Tuple[str, str]) -> List[str]:
"""
Get home ID and node ID for Z-Wave device registry entry.
Returns [home_id, node_id]
"""
return device_id[1].split("-") | e50aeb886e483955cebc93d9e07d671f46c8ca21 | 676,235 |
def get_tag(td, tag, o1, o2):
"""Return the tag between offsets o1 and o2 if there is one, return None if
there is no such tag."""
tags = td.tags.find_tags(tag)
for t in tags:
if t.begin == o1 and t.end == o2:
return t
return None | c3d89631e24abb20ea5df2e9c99d61c477d57291 | 676,236 |
def enum(*values, **kwargs):
"""Generates an enum function that only accepts particular values. Other
values will raise a ValueError.
Parameters
----------
values : list
These are the acceptable values.
type : type
The acceptable types of values. Values will be converted befor... | a1832cff58dd52a2c811228cbf781a054ac8ea7b | 676,237 |
import os
def parse_timit_entry(dirpath, file):
"""Summary.
Parameters
----------
dirpath : TYPE
Description
file : TYPE
Description
Returns
-------
name : TYPE
Description
"""
path = os.path.join(dirpath, file)
phnfile = os.path.join(dirpath, file... | 600a95dd9699a18fa8fe16fa5ab71bd0e8384e76 | 676,238 |
import re
def validateEmail(email):
"""
验证 电子邮件
:param email: 电子邮件
:return: bool
这是一个简单的例子:
Example
-------
>>> validator.validateEmail("jackhu@gmail.com")
True
"""
email_pattern = re.compile(r'^[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\.[com,cn,net]{1,3}$')
if email_pattern.match... | ea7a1d210251d616246016f95212c05cdfa34d9d | 676,239 |
import codecs
import yaml
def load_yaml_file(file_path: str):
"""Load a YAML file from path"""
with codecs.open(file_path, 'r') as f:
return yaml.safe_load(f) | 4c5ba2a85e2b03772a369619e213bed18ce1c229 | 676,240 |
def remove_underscores(value):
"""
Removes the underscores from a given string
"""
return value.replace("_", " ").title() | cb8d64e486ed83859f40d103385083b31954f69e | 676,241 |
def _getView(syn, view_id, clause=None):
"""
Based on a user-defined query calls to synapse's tableQuery function and returns the entity-view generator object.
:param syn: A Synapse object: syn = synapseclient.login(username, password) - Must be logged into synapse
:param view_id: A Synapse ID of... | c61f2b1b674b7e31bbdbbdb9d4cda629400a3e03 | 676,242 |
def decline_weak_feminine_noun(ns: str, gs: str, np: str):
"""
Gives the full declension of weak feminine nouns.
>>> decline_weak_feminine_noun("saga", "sögu", "sögur")
[['saga', 'sögu', 'sögu', 'sögu'], ['sögur', 'sögur', 'sögum', 'sagna']]
>>> decline_weak_feminine_noun("kona", "konu", "konur")
... | 2011a0a76e9a7372100ecae5fa29f7783ff70d9b | 676,245 |
def _dms2dd(d: float, m: float, s: float) -> float:
"""
Converts a DMS coordinate to DD
:param d: degrees
:param m: minutes
:param s: seconds
:return: equivalent in decimal degrees
"""
return d + m / 60 + s / 3600 | 4d021f6d9287f5b0b5922053b6b7c7a9b590a80e | 676,246 |
import struct
import socket
def _ConvertMaskToCIDR(mask):
"""Convert a netmask like 255.255.255.0 to a CIDR length like /24."""
bits = int(struct.unpack('!I', socket.inet_pton(socket.AF_INET, mask))[0])
found_one_bit = False
maskbits = 0
for i in range(32):
if (bits >> i) & 1 == 1:
found_one_bit =... | bf2903f11b44943353fee5c398816f42ccfa65de | 676,247 |
import jinja2
def invite_form(event, context):
"""Get response for invite code page. Invoked by AWS Lambda."""
template = jinja2.Environment(
loader=jinja2.FileSystemLoader('./')
).get_template('public/tmpl/enter_invite.html')
return {
"statusCode": 200,
"headers": {"Content-Ty... | 8ea22ba166e4469b85aa8897b688f302608302c7 | 676,248 |
def post_args_from_form(form):
"""
Take a table of form data or other sort of dictionary and turn it into a
regular 1D list to be passed as args
"""
res = list()
for item in form:
res.append(item)
res.append(form[item].value)
return res | 5a0dc433a99e45745a56fbfcd17d7934f184112f | 676,249 |
import os
import subprocess
import shlex
def run_spades(input_arguments, cmd_args, working_dir):
"""
Runs SPAdes
:param input_arguments: string with properly formatted input arguments
:param flags: additional SPAdes flags
:param working_dir: working directory
:return: path to results
"""
... | 012fc318824656b0298af6611f86364601582796 | 676,250 |
def mean(iterable):
"""Returns the average of the list of items."""
return sum(iterable) / len(iterable) | 0292e6fa35f13e6652606c621c3cf93b81f1ef77 | 676,251 |
def strip_prefix(prefix, string):
"""Strip prefix from a string if it exists.
:param prefix: The prefix to strip.
:param string: The string to process.
"""
if string.startswith(prefix):
return string[len(prefix):]
return string | 07dd3cc154dde290d77bfbf4028e8be34179a128 | 676,253 |
def parse_problems(lines):
""" Given a list of lines, parses them and returns a list of problems. """
res = [list(map(int, ln.split(" "))) for ln in lines]
return res | 4e5c62ad2028e9ed441a5aa86276d059e0d118a3 | 676,254 |
def skip_names(mol_list):
"""
Check if a list of molecules contains nomenclature that suggests
it can be skipped.
i.e. lignin implies polymeric species.
"""
# lignin - a polymeric species that can form under oxidative
# polymerisation
# many forms exist. HRP produces some.
... | 39ff61bf257a7822402f5fdb4a68f6cae95288fa | 676,255 |
def get_morsel_cookie(info, name, default=None):
"""Gets the value of the cookie with the given name, else default."""
if info.cookies is not None and name in info.cookies:
return info.cookies[name].value
return default | 7a6ac4536a669869cdc17ab1e0d36078190666b4 | 676,256 |
def my_bleu_v1(candidate_token, reference_token):
"""
:description:
最简单的计算方法是看candidate_sentence 中有多少单词出现在参考翻译中, 重复的也需要计算.
计算出的数量作为分子,分母是candidate中的单词数量
:return: 候选句子单词在reference中出现的次数/candidate单词数量
"""
# 分母是候选句子中单词在参考句子中出现的次数 重复出现也要计算进去
count = 0
for token in candidate_token:
... | df27b057404e21052c3da8ab727bc2b543dd786e | 676,257 |
from typing import List
from pathlib import Path
import os
def _read_input() -> List[str]:
"""Read the input file. Every line represents an integer value."""
password_list = []
current_path = Path(os.path.dirname(os.path.realpath(__file__)))
image_path = current_path / "resources" / "day2_puzzle_input... | ab6bf78ea7a6e634d1c82c77171132d9f2a60b26 | 676,258 |
def calculate_total(row, rowNumber):
"""Returns total votes for a given row."""
try:
number = int(float(row[rowNumber]))
except ValueError:
number = 0
return number | 112aa82fedb6c5ef34095018b89dd0065d6474c8 | 676,259 |
def readId2Name(fin):
"""
Reconstruct a global id=>username dictionary from an open csv file
Reads the globalId2Name file (or equivalent) and constructs an id=>username
dictionary. Input is an open csv.reader file such as the one constructed
by the main method of this module. Returns a dictiona... | e8874e275fc894818467d8c032bdf58bb0314789 | 676,260 |
def seznam_kljucev(slovar):
"""funkcija da kljuce slovarja v seznam, ki ga lahko uporabimo za poimenovanje
stolpcev v csv filu"""
sez = []
for key in slovar.keys():
sez.append(key)
return sez | 270ea3ae746e1eea47ad7a0819f6f26dd05d21e2 | 676,263 |
from typing import List
def get_filetypes(format: str = 'json') -> List[str]:
"""Get filetypes based on specified format."""
return ['yml', 'yaml'] if format == 'yaml' else [format] | 4e9eb09f69bb727f267e48694b043f94b14bdadd | 676,264 |
import numpy as np
def DM_voltage_to_map(v):
"""
Reshape the 52-long vector v into 2D matrix representing the actual DM aperture.
Corners of the matrix are set to None for plotting.
Parameters:
v - double array of length 52
Returns:
output: 8x8 ndarray of doubles.
-------
Auth... | 08c8740057f8bb1ac6b563573a214d75c3ffc344 | 676,265 |
def min_x_pt(pt_dict):
"""Returns the key of the point at minimum x
(with minimum y) in the XY plane (Z is ignored)
pt_dict is a collection of 'pt_ID: (x, y, z)'
key-value pairs"""
nmin = (9.9E12, 9.9E12)
the_node = None
for k,v in pt_dict.items():
if v[0] == nmin[0]:
if... | 86c624b5dc9247b9513a9b7a6a5f1d83cadeff85 | 676,266 |
from pathlib import Path
import random
def get_wav_files(data_dir: Path):
"""
Get all *.wav files in the data directory.
"""
files = sorted(data_dir.glob("*.wav"))
random.Random(42).shuffle(files)
return files | 4d57de98c19af017bf9029c51c507545b8888644 | 676,267 |
def get_z_prop(p, pi, n):
"""
Function to get the Z value (standard deviations number under or over the average)
correspondent of the x value (parameter) in the standard normal distribution.
Applied in proportions.
Parameters:
--------------------------
p : double, float
"Succes... | e6e6911fefc76a0188c169275f2e160870abf94e | 676,268 |
def compress_indexes(indexes):
"""Compress a list of indexes. The list is assumed to be sorted in ascending
order, and this function will remove the all the consecutives numbers and
only keep the first and the number of the consecutives in a dict.
eg : [0, 1, 2, 3, 4, 7, 8, 9, 10, 11, 12, 13, 18, 19, 2... | 8863e14ba117bb8367bce7358f25caf719efea04 | 676,269 |
def map_1d_to_2d(index, N, M):
"""
Function: map_1d_to_2d\n
Parameter: index -> index which needs to be mapped to the 2D coordinates, N -> number of rows in the grid, M -> number of columns in the grid\n
Return: the location of the mapped index\n
"""
x = index // (N - 1)
y = index % M
re... | 30855926fbe995d5b4dd35f7cbc614016d6c0f9a | 676,270 |
def get_relatives_models(mat):
"""
Return tuple (model, parent1_model, parent2_model) in 'OR_AND_2D' format
"""
if mat.model is not None:
model = mat.model + '-' + str(mat.layer.dimensionality) + 'D'
model = model.replace('-', '_')
else:
model = None
parent1_model = None... | aa69f13ed124d806e69ce0ab4d4a8ed9ca86cdae | 676,271 |
def R2_a(FQmax, MYmax, qF, qM, ra, mu_Tmin):
"""
R2 Determining the required minimum clamp load Fkerf
(Section 5.4.1)
The required minimum clamp load Fkerf is determined
while taking into account the following requirements:
a) Friction grip to transmit a transverse load FQ
and... | 043a12b12d1c2fc32c44341a1c6e0e60e4fb7ed8 | 676,272 |
def check_argument_type(dtype, kernel_argument):
"""check if the numpy.dtype matches the type used in the code"""
types_map = {
"uint8": ["uchar", "unsigned char", "uint8_t"],
"int8": ["char", "int8_t"],
"uint16": ["ushort", "unsigned short", "uint16_t"],
"int16": ["short", "int1... | d05f010591554d9d22b8b24438a442bff5b4ba88 | 676,273 |
def qs1 (al):
""" Algo quicksort for a list
"""
if not al:
return []
return (qs1([x for x in al if x < al[0]])
+ [x for x in al if x == al[0]]
+ qs1([x for x in al if x > al[0]])) | 7fb90f8aa411573e87aedfc6299cb598f87023c0 | 676,274 |
import sys
def read_sdp_service_record():
"""
Read and return SDP record from a file
:return: (string) SDP record
"""
print('Reading service record')
try:
fh = open("sdp_record.xml", 'r')
except OSError:
sys.exit('Could not open the sdp record. Exiting...')
return fh.r... | c363d1816b9ba2f82b86f3aaa89e88a4fb4d1570 | 676,275 |
import os
import sys
def collect_test_cases():
"""Collect the list of monitors and test cases from the monitors/
directory. Returns (monitors, test_cases) where monitors is a list of
monitor names and test_cases is a list of
(mon_name, test_case_name, exec_list) where exec_list is a list of
monito... | 6c617a798c442b445d008e4bc4f13ef41a6395de | 676,276 |
def e_direcao(arg):
"""
e_direcao: universal --> logico
e_direcao(arg) tem o valor verdadeiro se arg for do tipo direcao e falso
caso contrario.
"""
return arg in ('N', 'S', 'E', 'W', 'NE', 'NW', 'SE', 'SW') | 244f86cea7d0123a7a177e275a07a0d475e6a7df | 676,277 |
import re
def parse_wbgene_string(string):
"""
Receives a string that contains WBGene indices. Parses the string into a set of WBGene indices. \
The format of a WBGene index is 'WBGene' and exactly 8 digits.
:type string: str
:param string: The string to be parsed. Can be any format of string.
... | 7cf59b47514948c9ab23c0cdeb775ec516bd2d54 | 676,278 |
import math
def rotate(vec, degrees):
"""
Rotates a 2D vector x, y counter-clockwise by degrees degrees
"""
x, y = vec
sin = math.sin(math.radians(degrees))
cos = math.cos(math.radians(degrees))
rot_x = cos * x + -sin * y
rot_y = sin * x + cos * y
return rot_x, rot_y | ec73f11ba9fc43621d4215982d58c6dc7057698e | 676,279 |
def extract_labels_single_format(featureset):
"""
[0,1,1,1,0,0...] instead of [[1,0], [1,0], [0,1]...]
:param featureset:
:return:
"""
def extract(label): return 1 if label == [1,0] else 0
y = lambda label: extract(label), featureset['Labels']
return y | 313cff099633b831b3171d23963c7d2d03580c0c | 676,280 |
import torch
def topk_accuracy(k, logits: torch.Tensor, labels: torch.Tensor, unk_id=None, pad_id=None):
"""
Averaged per sample:
1, if one of the k predictions with highest confidence was the correct one for all sub tokens
0, else
if `unk_id` is given, the best non <unk> prediction will b... | 3a689ded604649dcf6fc1a79bb6971a77f7b3d90 | 676,281 |
import re
def _parse_host(id):
"""
This helper function parses the host from `id` in scope nodes.
Returns the host name if it is a host, else return None.
"""
host_name = None
r = re.match(r"^(.*);<host>$", id)
if r:
host_name = r.group(1)
return host_name | d0186816abff3918def96e52c3ed68e512267728 | 676,282 |
import os
def ex_compile_and_link(env, dag, src, objs):
"""Return the exe name - used for the examples"""
basename = os.path.basename(src)
exe = env.build_dir_join(env.resuffix(basename, env['EXEEXT']))
all_obj = []
# first_example_lib and last_example_lib are for supporting
# compilations usin... | 0ae95eae102c882b7d1ec963291d08ca41aba23d | 676,283 |
def adjacency_list_(graph):
"""Get graph adjacency_list."""
adjacency_list = {}
graph = graph.get_vertices()
for vertex in graph:
vertex_adjacent_list = graph[vertex].get_vertex_adjacent_list()
adjacency_list[vertex] = vertex_adjacent_list
return adjacency_list | 86d7ff1943d00a3ea8ed061ea67e68bf60c618b1 | 676,284 |
def is_int(value):
""" Is value integer
args:
value (str): string
returns:
bool
"""
try:
int(str(value))
return True
except (ValueError, TypeError):
pass
return False | 1a41ee5e18b6994559effe31d025675a389f2f3d | 676,285 |
import warnings
def _set_coord_info(mg, xul, yul, xll, yll, rotation):
"""
Parameters
----------
mg : fp.discretization.Grid object
xul : float
upper left x-coordinate location
yul : float
upper left y-coordinate location
xll : float
lower left x-coordinate locati... | 19fe833a4fd57386c334675195232d67ab6140b2 | 676,286 |
def retrieve_row_values(row, field_names, index_dict):
"""This function will take a given list of field names, cursor row, and an index dictionary provide
a tuple of passed row values.
:param - row - cursor row
:param - field_names -list of fields and their order to retrieve
:param - index_dict - cu... | 9663a4c6d8588f74732af65de1421a1fbccaddde | 676,287 |
from typing import Dict
from typing import Union
from typing import Any
from typing import List
def hash_dict(
item_dict: Dict[str, Union[Dict[str, Any], List[Any], str]]
) -> Dict[str, Any]:
"""
Hash dictionary values.
Parameters
----------
item_dict : Dict[str, Union[Dict[str, Any], List[An... | df38e51c2caaccb7580ced127816eafc4b12c449 | 676,288 |
import difflib
def check_similarity(query, interactions_list):
"""
This function takes a query object and a list of Pairwise interaction objects,
Returns the interaction list with the attribute "originalChain" updated for each chain of
the pairwise interactions.
First it tries to check if the s... | da61ae6dd48ead0a258f9926328060482089f30c | 676,289 |
def varintdecode(data):
""" Varint decoding
"""
shift = 0
result = 0
for c in data:
b = ord(c)
result |= ((b & 0x7f) << shift)
if not (b & 0x80):
break
shift += 7
return result | e8e82a4e2fb8da8ba6962248e2797b040b6bcbb6 | 676,290 |
import socket
def receive_connection():
"""Wait for and then return a connected socket..
Opens a TCP connection on port 8080, and waits for a single client.
"""
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind... | 22e4317a6cf1f544dcd5b58d7a156d6ab2b715b9 | 676,291 |
def ant_2_containing_baslines(ant, antennas):
"""
Given antenna returns list of all baselines among given list with that
antenna.
"""
baselines = list()
for antenna in antennas:
if antenna < ant:
baselines.append(256 * antenna + ant)
elif antenna > ant:
b... | 7795e948152866dd75e254d58fb71cb5762cdb4c | 676,292 |
def count_commas(s: str) -> int:
"""
count commas:
- english comma [,](\u002c)
- Chinese full-width comma [,](\uff0c)
- Chinese seperator / Japanese comma [、](\u3001)
"""
count = 0
for c in s:
if c in "\u002c\uff0c\u3001":
count += 1
return count | 3c317cccaa9d784447734a0930ea0b50a47401bf | 676,293 |
import sys
import os
def FixPath(path):
"""Convert to msys paths on windows."""
if sys.platform != 'win32':
return path
drive, path = os.path.splitdrive(path)
# Replace X:\... with /x/....
# Msys does not like x:\ style paths (especially with mixed slashes).
if drive:
drive = '/' + drive.lower()[0... | e2d83c61103fc6774de38f143fc4918af43b6786 | 676,294 |
def list_to_dict(node_list: list):
"""
Convert the list to a dictionary,
Create a dictionary, key is a element in the list,
value is a element which next the key, if no exists, the value is None.
Args:
node_list (list): normal, list of node
Returns:
schema (dict): a dictionary
... | 804e71d28c1963fea35def5816cf0901daa1d926 | 676,295 |
def time(self):
"""Check Server Time
Test connectivity to the Rest API and get the current server time.
GET /api/v3/time
https://binance-docs.github.io/apidocs/spot/en/#check-server-time
"""
url_path = "/api/v3/time"
return self.query(url_path) | 592cc2502f2861d29ab52243192a763e57566973 | 676,296 |
def clipAlpha(aj, H, L):
"""
调整aj的值,使L<=aj<=H
Args:
aj 目标值
H 最大值
L 最小值
Returns:
aj 目标值
"""
aj = min(aj, H)
aj = max(L, aj)
return aj | 6b83c38e51bd1d00aa39a5d538c30b01c7e3b958 | 676,297 |
from typing import Callable
from typing import Any
from typing import Iterable
from typing import Tuple
def star_filter(function: Callable[[Any], bool], *iterables: Iterable[Any]) -> Iterable[Tuple[Any]]:
"""
A general filter function, that takes n argument iterator, a predicate that returns true/false,
a... | 1e4c10e8756607b8fbf3b6400ddc9b9e3b56c5d3 | 676,298 |
def safe_cast(val, to_type, default=None):
"""A helper for safe casts between types"""
try:
return to_type(val)
except (ValueError, TypeError):
return default | 19f74a0e3e75716486bb1903e784485d9cbdcb03 | 676,299 |
import re
def _replace_labels(html: str) -> str:
"""
Replace Django's question-level labels with legend elements
"""
return re.sub(
"<fieldset><label [^>]+>(.*?)</label>",
lambda m: f'<fieldset><legend class="tdp-question-legend">{m[1]}</legend>', # noqa: B950
html,
) | d69e23cf51fd00b4cec6201b12a2766a8f50a236 | 676,300 |
import math
def tanh(value):
"""
This function calculates the hyperbolic tangent function.
"""
return math.tanh(value) | e3fbb127c5ce2e7cf7fe13884c513c22b96ecf20 | 676,301 |
import warnings
def center_roi_around(center_rc, size_hw):
"""
Return a rectangular region of interest (ROI) of size `size_hw` around the
given center coordinates. The returned ROI is defined as
(start_row, start_column, end_row, end_column)
where the start_row/column are ment to be *include... | daddb578cf5b107d64a1d84df38ddbd3a671f988 | 676,302 |
def conv_lin(a, b=1.0, c=0.0, inverse=False):
"""Simple linear transform
will I think store parameters against each sensor then they are handy
>>> conv_lin(4,2,3)
11
>>> conv_lin(11,2,3.0,True)
4.0
>>>"""
if inverse is False:
return a * b + c
else:
... | a41d3254c933f59a5fb24253dcebc684a4211108 | 676,303 |
async def check_flat_lamp(command):
"""Check the flat lamp status"""
flat_lamp_cmd = await (await command.actor.send_command("lvmnps", "status"))
if flat_lamp_cmd.status.did_fail:
return False
else:
replies = flat_lamp_cmd.replies
check_lamp = {
"625NM": replies[-2]... | 0d93a1ad3777654f8e375ab38fe5c42e51a1b3de | 676,304 |
import numpy
def angle_between(v1, v2, v3):
"""Returns angle v2-v1-v3 i.e betweeen v1-v2 and v1-v3."""
# vector product between v1 and v2
px = v1[1] * v2[2] - v1[2] * v2[1]
py = v1[2] * v2[0] - v1[0] * v2[2]
pz = v1[0] * v2[1] - v1[1] * v2[0]
# vector product between v1 and v3
qx = v1[1] *... | b1a716a5b1864808600e0c9f6b2386f1835fa765 | 676,305 |
def get_param_dict(self):
"""Get the parameters dict for the ELUT of PMSM at the operationnal temperature and frequency
Parameters
----------
self : ELUT
an ELUT_PMSM object
Returns
----------
param_dict : dict
a Dict object
"""
# getting parameters of the abstract ... | 28da77a0bdc35af4920719972d2c528bcccc1510 | 676,307 |
import argparse
def _get_parser():
"""Return command-line argument parser."""
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("infile",
help="Neuroimaging volume to compute statistics on.")
p.add_argument("-V", "--Volume", action="store_true", required=False,
... | f210f5312910856c8b23180c19a4f3c82af74891 | 676,308 |
def train_batch(model, x, target, optimizer, criterion):
"""Train a model for one iteration
Args:
model (torch.nn.Module): model to train
x (torch.Tensor): input sample
target (torch.Tensor): output target
optimizer (torch.optim.Optimizer): parameter optimizer
criterion (... | ba9b3160e033af2cf62ab86f9c992acb75efe9b6 | 676,309 |
def patch_init(mocker):
"""
Makes patching a class' constructor slightly easier
"""
def patch_init(*args, **kwargs):
for item in args:
mocker.patch.object(item, '__init__', return_value=None, **kwargs)
return patch_init | b09733feccfc0f443de26f12fd53e1d290f5e26a | 676,310 |
def min_sample_filter(table, min_samples):
"""remove observations not present in more than a minimum number of samples"""
zeroes_per_column = (table > 0).sum(axis=0)
return table.loc[:, zeroes_per_column > min_samples] | 8c2c56b95a126eb3ab4a44d2397b904173752b25 | 676,311 |
from typing import List
import os
def get_files_recursive(dir: str, files: List[str]) -> List[str]:
"""
Recursively find files in subdirectories of dir
:param dir: The directory to search in
:param files: The list of detected files. Should be initialized as an empty list
:return: A list of files ... | 5315185ee469191d8b8a3fe90b8bd7dc7608d472 | 676,312 |
import json
def getCommandsFromLog(inFile,filterList,coverage):
"""
Get commands from a log
Parameters
----------
inFile : str
path to pyrpipe log file.
filterList : str
list of commands to ignore.
coverage : char
type of commands to report all, passed or failed: a... | e9e961f05a263405bb5f7eb4a4f75ad9011bc276 | 676,313 |
def get_panel_groups_at_depth(group, depth=0):
"""Return a list of the panel groups at a certain depth below the node group"""
assert depth >= 0
if depth == 0:
return [group]
else:
assert group.is_group()
return [
p
for gp in group.children()
f... | 1bbd8b94f39d738587262995953c4d7cd5f34dbe | 676,314 |
def longest_valid_parentheses2(s):
"""
Solution 2
"""
max_len = 0
start = 0
stack = []
for i in range(len(s)):
if s[i] == "(":
stack.append(i)
else:
if len(stack) == 0:
start = i + 1
else:
stack.pop()
... | e14208a21b5d324671611daaee7720f2838f596b | 676,315 |
def get_formatted_decimal_string(i, n):
"""
@param i: index
@param n: total number of indicies
@return: str(i) with correct number of padding zeros
"""
n_digits = len(str(n))
format_string = '{{:0>{}}}'.format(n_digits)
return format_string.format(i) | 92dfc912212a87173025e6f31de0c2c2f9d6f3fd | 676,316 |
def get_class(name, defmod=None):
"""Finds a class.
Search a class from its fully qualified name, e.g.
'pyconstruct.domains.predefined.Class'. If the class name is not fully
qualified, e.g. 'Class', it is searched inside the default module.
Parameters
----------
name : str
The ful... | 107aa231aeeae666fa3b6deab67a738fca6f3767 | 676,317 |
import os
def format_as_wiki(func):
"""
Decoratate a function that reads lines from a file. Put some wiki
formatting around each line of the file and add a header, and
footer.
Examples
--------
>>> from __future__ import print_function
>>> import os
>>> from standard_names.utiliti... | d6f77784aed7e4ad8351529da18507b7bf21f954 | 676,318 |
def rectsqr():
"""This function calculates the area of a rectangle"""
length = float(input("Enter the length: "))
widht = float(input("Enter the widht: "))
reactarea = length * widht
return reactarea | c15bbfc69136aaa391d5099f4c9e3b927d8c099a | 676,319 |
def max_endtime(graph):
"""
A method to calculate the maximum endtime of a network.
Parameter(s):
-------------
graph : TemporalDiGraph
A directed, temporal graph.
Returns:
--------
maxEndtime : int
the maximum endtime of a networ... | 6654e32674b309c8034ff94e88e1d040c9b09b74 | 676,320 |
import requests
def get_jobdesc_config(job):
"""Function for extracting job description config file."""
job_desc_url = '%s/job_description.json' % job['job_url']
r = requests.get(job_desc_url, verify=False)
r.raise_for_status()
return job_desc_url | 33d03c0267f8d55a61c25163c586c138e302fee2 | 676,321 |
def ReadableSize(num):
"""Get a human-readable size."""
for unit in ['B', 'KB', 'MB', 'GB']:
if abs(num) <= 1024.0:
return '%3.2f%s' % (num, unit)
num /= 1024.0
return '%.1f TB' % (num,) | 6dfc713a70e36e9fd7fb91c443cf14c139702259 | 676,322 |
from typing import Union
from typing import List
from typing import Tuple
from typing import Callable
import argparse
def in_sequence_ints(sequence: Union[List[int], Tuple[int]],
show_on_invalid: bool = False) -> Callable:
"""
excepts an int value that is in the sequence
show_on_inva... | c696c7c4206931d97fa48f4b06fb406129172bcb | 676,323 |
import requests
import json
def authenticate_with_ome(ip_address, user_name, password):
""" X-auth session creation """
auth_success = False
session_url = "https://%s/api/SessionService/Sessions" % (ip_address)
user_details = {'UserName': user_name,
'Password': password,
... | 2f4f9c8b13d8c24fc04765c19dcf482d45fe352b | 676,324 |
def convert_to_tuples(examples):
"""
Convert a list of Example objects to tuples of the form:
(source, translation, language, author, reference).
"""
convert1 = lambda e: e.to_simple_tuple()
return list(filter(bool, map(convert1, examples))) | 20e44c985b00791cd6c8e57c47e483be1c6e57e7 | 676,325 |
def prop_get_nyquistsampling(wf, lamx = 0.0):
"""Funtion determines the Nyquist sampling interval for the current beam,
which is focal_ratio * wavelength / 2.
Parameters
----------
wf : obj
Wavefront class object
lamx : float
Wavelength to use for computing sampling... | a0f4a0fd21a1e8a5d53da664cd780f28f2aedff7 | 676,326 |
def get_params_description(doc):
"""Get the parameters description from the docstring"""
params_description = {}
if doc is not None:
doc = doc.split('\n')
for line in doc:
if ':' in line:
line = line.split(':')
line[0] = line[0].strip()
... | c81fb0fe3d2cbccc3af5c31702ece68fbe704fbc | 676,327 |
import torch
def calc_vos_simple(poses):
"""
calculate the VOs, from a list of consecutive poses
:param poses: N x T x 7
:return: N x (T-1) x 7
"""
vos = []
for p in poses:
pvos = [p[i+1].unsqueeze(0) - p[i].unsqueeze(0)
for i in range(len(p)-1)]
vos.append(... | 53a3fdf9242044aa334952bab4005f370b83ea3f | 676,328 |
def _count_words(words):
"""
helper method for word_count() method, return length of given words
"""
try:
return len(words.split())
except:
return 0 | 526bbcccb0d0ee57b60fe2822bd5342142e01e32 | 676,329 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.