content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def parse_args():
"""parse args for binlog2sql"""
parser = argparse.ArgumentParser(description='Parse MySQL binlog to SQL you want', add_help=False)
connect_setting = parser.add_argument_group('connect setting')
connect_setting.add_argument('-h', '--host', dest='host', type=str,
... | 5,338,600 |
def split(meta_attribute, files, dest, search_dir):
"""split the subtree files into fragments"""
for file in files:
with open(file, "r") as fragment_content:
content = fragment_content.read()
for fragment in content.split("[id"):
if not fragment.strip():
... | 5,338,601 |
def lnLikelihoodDouble(parameters, values, errors, weights=None):
"""
Calculates the total log-likelihood of an ensemble of values, with
uncertainties, for a double Gaussian distribution (two means and
two dispersions).
INPUTS
parameters : model parameters (see below)
value... | 5,338,602 |
def init_routes():
"""Register RESTFul API routes"""
# health page API
api.add_resource(HealthResource, "/", "/health")
# system time API
api.add_resource(CurrentTimeResource, "/api/currenttime")
# APIs for template library
api.add_resource(TemplateResource, "/api/template") # query, crea... | 5,338,603 |
def clear_dir(path):
"""Empty out the image directory."""
for f in os.listdir(path):
f_path = os.path.join(path, f)
if os.path.isfile(f_path) or os.path.islink(f_path):
os.unlink(f_path) | 5,338,604 |
def assert_processor_available(processor: str) -> None:
"""
Assert that a specific PDF processor is available.
Args:
processor: a PDF processor type from :class:`Processors`
Raises:
AssertionError: if bad ``processor``
RuntimeError: if requested processor is unavailable
"""... | 5,338,605 |
def moleculeEntry(request, adjlist):
"""
Returns an html page which includes the image of the molecule
and its corresponding adjacency list/SMILES/InChI, as well
as molecular weight info and a button to retrieve thermo data.
Basically works as an equivalent of the molecule search function.
"""
... | 5,338,606 |
def has_user_id(id: int):
"""Checks if the Command Author's ID is the same as the ID passed into the function"""
def predicate(ctx) -> bool:
if ctx.author.id == id:
return True
raise MissingID(id, "Author")
return commands.check(predicate) | 5,338,607 |
def _polar_gbps(out, in_args, params, per_iter=False):
""" `speed_function` for `benchmark` estimating the effective bandwidth
of a polar decomposition in GB/s. The number of elements is estimated as
2 * the size of the input.
For a matrix multiplication of dimensions `m, n, k` that
took `dt` seconds, we defi... | 5,338,608 |
def is_FreeMonoid(x):
"""
Return True if `x` is a free monoid.
EXAMPLES::
sage: from sage.monoids.free_monoid import is_FreeMonoid
sage: is_FreeMonoid(5)
False
sage: is_FreeMonoid(FreeMonoid(7,'a'))
True
sage: is_FreeMonoid(FreeAbelianMonoid(7,'a'))
... | 5,338,609 |
def saveItemImage(item):
"""Saves the image for the item to disk. """
itemName = item['data']['name']
console('Getting image for: {}'.format(itemName))
fullImgUrl = '{}{}.jpg'.format(mfc_img_base, item['data']['id'])
req = urllib.request.Request(fullImgUrl, \
headers... | 5,338,610 |
def valida_data(data_ida, data_volta, data_pesquisa, lista_erro):
"""Valida se a data de ida é maior que a data de volta e a data de ida é menor que a data atual"""
if data_ida > data_volta:
lista_erro['data_volta'] = 'Data de volta não pode ser maior que a data de ida'
if data_ida < data_pesquisa:
... | 5,338,611 |
def install_hook() -> None:
"""
Installs the remote debugger as standard debugging method and calls
it when using the builtin `breakpoint()`
"""
_previous_breakpoint_hook = sys.breakpointhook
sys.breakpointhook = set_trace | 5,338,612 |
def get_institutes(url):
"""Get institutes objects and add them to data"""
driver.get(url)
institutes = driver.find_elements_by_class_name('item')
for institute in institutes:
obj = {}
obj["initials"] = institute.find_element_by_tag_name('a').text.split(
'\n')[0]
obj... | 5,338,613 |
def get_quote_data(ticker):
"""Inputs: @ticker
Returns a dictionary containing over 70 elements corresponding to the
input ticker, including company name, book value, moving average data,
pre-market / post-market price (when applicable), and more."""
site = "https://query1.finance.yahoo.com/v7/finan... | 5,338,614 |
def preprocess(network_path, network_dynamics_file = None, number_cores = 1, special_nodes = None):
""" computes the preprocessed travel time tables for all different travel time files
creates the travel time tables "tt_matrix" and "dis_matrix" and stores them
in the network-folder
:param network_path: ... | 5,338,615 |
def print_parameter_summary(model) -> None:
"""
Prints the number of trainable and non-trainable parameters in the model.
"""
# Note: use model.summary() for a detailed summary of layers.
trainable_count = np.sum([K.count_params(w) for w in
model.trainable_weights])
non_trainabl... | 5,338,616 |
def _import_stack_component(
component_type: StackComponentType, component_config: Dict[str, str]
) -> str:
"""import a single stack component with given type/config"""
component_type = StackComponentType(component_type)
component_name = component_config.pop("name")
component_flavor = component_conf... | 5,338,617 |
def show(*images):
"""Display images on screen.
"""
import matplotlib.pyplot as plt
L = len(images)
for i in range(L):
plt.subplot(1, L, i + 1)
plt.imshow(images[i], cmap=plt.cm.gray, interpolation='nearest')
plt.show() | 5,338,618 |
def unpack_range(a_range):
"""Extract chromosome, start, end from a string or tuple.
Examples::
"chr1" -> ("chr1", None, None)
"chr1:100-123" -> ("chr1", 99, 123)
("chr1", 100, 123) -> ("chr1", 100, 123)
"""
if not a_range:
return Region(None, None, None)
if isinsta... | 5,338,619 |
def _old_extract_roles(x, roles):
"""
x is [N, B, R, *shape]
roles is [N, B]
"""
N, B, R, *shape = x.shape
assert roles.shape == (N, B)
parts = []
for n in range(N):
parts.append(x[n:n+1, range(B), roles[n]])
return torch.cat(parts, dim=0) | 5,338,620 |
def read_cam_intr(file_path):
"""Reading camera intrinsic.
Args:
file_path (str): File path.
Return:
k (numpy.array): Camera intrinsic matrix, dim = (3, 3).
"""
assert os.path.exists(file_path), '{}: file not found'.format(file_path)
f = open(file_path, 'r')
k_str = f.readlines()[0].strip()... | 5,338,621 |
def setup(i):
"""
See "install" API with skip_process=yes
"""
i['skip_process']='yes'
return install(i) | 5,338,622 |
def post_merge_request(profile, payload):
"""Do a POST request to Github's API to merge.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect ... | 5,338,623 |
def is_valid_table_name(cur, table_name):
"""
Checks whether a name is for a table in the database.
Note: Copied from utils.database for use in testing, to avoid
a circular dependency between tests and implementation.
Args:
cur: sqlite3 database cursor object
table_name (str): name t... | 5,338,624 |
def create_mssql_pyodbc(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a mssql database using pyodbc.
"""
return create_engine(
_create_mssql_pyodbc(username, password, host, port, database),
**kwargs
) | 5,338,625 |
def write_idl(length_y, file_obj, plot_name, boxes, scores = None):
"""
Function that writes bounding boxes into an idl file.
Inputs:
length_y: (int) length of the Y direction of the image (needed to convert coordinate system origin)
file_obj: (file obj) file object of the idl file
plot_na... | 5,338,626 |
def _wait_for_multiple(driver,
locator_type,
locator,
timeout,
wait_for_n,
visible=False):
"""Waits until `wait_for_n` matching elements to be present (or visible).
Returns located elements when fo... | 5,338,627 |
def relu(x):
"""
x -- Output of the linear layer, of any shape
Returns:
Vec -- Post-activation parameter, of the same shape as Z
cash -- for computing the backward pass efficiently
"""
Vec = np.maximum(0, x)
assert(Vec.shape == x.shape)
cash = x
return Vec, cash | 5,338,628 |
def _declare_swiftdoc(
*,
actions,
arch,
label_name,
output_discriminator,
swiftdoc):
"""Declares the swiftdoc for this Swift framework.
Args:
actions: The actions provider from `ctx.actions`.
arch: The cpu architecture that the generated swiftdoc... | 5,338,629 |
def threshold_image(gray_image, name_bw, threshold):
"""
This computes the binary image of the input image using a threshold
:param gray_image: input image
:param threshold: input threshold
:param name_bw: name of the binary image
:return: BW image
"""
# perform Gaussian blur... | 5,338,630 |
def kalman_update(
states,
upper_chols,
loadings,
control_params,
meas_sd,
measurements,
controls,
log_mixture_weights,
debug,
):
"""Perform a Kalman update with likelihood evaluation.
Args:
states (jax.numpy.array): Array of shape (n_obs, n_mixtures, n_states) with
... | 5,338,631 |
def pkg_lpk(shp):
"""Example:
\b
> pkg_lpk in.shp
creates file in.lpk
wildcards allowed:
\b
> pkg_lpk *.shp
"""
for shp in glob.glob(shp):
create_lpk(shp, shp.replace('.shp', '.lpk')) | 5,338,632 |
def sub_repeatedly(pattern, repl, term):
"""apply sub() repeatedly until no change"""
while True:
new_term = re.sub(pattern, repl, term)
if new_term == term:
return term
term = new_term | 5,338,633 |
def _dtw(distance_matrix: np.ndarray, gully: float = 1., additive_penalty: float = 0.,
multiplicative_penalty: float = 1.) -> Tuple[np.ndarray, np.ndarray, float]:
"""
Compute the dynamic time warping distance between two sequences given a distance matrix.
DTW score of lowest cost path through the ... | 5,338,634 |
def display_plot(phase: ndarray, magnitude: ndarray, model: Tuple[ndarray, ndarray] = None) -> None:
"""
Display a phased light curve.
Parameters
----------
phase : ndarray
An array which stores a phase vector.
magnitude : ndarray
An array which represents a magnitude vector.
... | 5,338,635 |
def test_kgdm_parse_total_proteins_error_first_pag(fam_url, fam_template, args):
"""Test parse_total_proteins_error() when it's the first failure for the pagination page."""
errors = {
"url": fam_url,
"format": "error message",
}
family, failed_scrapes, sql_failures, format_failures = ... | 5,338,636 |
async def _ensure_meadowgrid_security_groups() -> str:
"""
Creates the meadowgrid coordinator security group and meadowgrid agent security
group if they doesn't exist. The coordinator security group allows meadowgrid agents
and the current ip to access the coordinator, as well as allowing the current ip... | 5,338,637 |
def _create_pairs_numba(
to_match, indexer, first_stage_cum_probs, group_codes_per_individual, seed
):
"""
Args:
to_match (np.ndarry): 2d boolean array with one row per individual
and one column sub-contact model.
indexer (numba.List): Numba list that maps id of county to a numpy... | 5,338,638 |
def test_set_attr():
"""
Tests that generate_schema returns a schema that has the ability to
set instance variables based on keys of different format in the
dictionary provided in schema.load(d)
"""
class TestObject(object):
def __init__(self):
super().__init__()
... | 5,338,639 |
def filter_known_bad(orbit_points):
"""
Filter some commands that are known to be incorrect.
"""
ops = orbit_points
bad = np.zeros(len(orbit_points), dtype=bool)
bad |= (ops['name'] == 'OORMPEN') & (ops['date'] == '2002:253:10:08:52.239')
bad |= (ops['name'] == 'OORMPEN') & (ops['date'] == '... | 5,338,640 |
def test_user_validation_shared(shared_zone_test_context):
"""
Confirm that test users cannot add/edit/delete records in non-test zones (via shared access)
"""
client = shared_zone_test_context.ok_vinyldns_client
batch_change_input = {
"changes": [
get_change_A_AAAA_json("add-tes... | 5,338,641 |
def create_lexicon(word_tags):
"""
Create a lexicon in the right format for nltk.CFG.fromString() from
a list with tuples with words and their tag.
"""
# dictionary to filter the double tags
word_dict = {}
for word, tag in word_tags:
if tag not in word_dict:
word_dict[ta... | 5,338,642 |
def process_datasets_metadata(input_file=None, dryrun=True, staging=True, sample=0, report=False, memory='4g', rmlstreamer_run=False):
"""Read a RDF metadata file with infos about datasets, check if the dataset exist in the project SPARQL endpoint
Download the data if new"""
# If no metadata file provided,... | 5,338,643 |
def get_voltage(directory, calculation="relax", functional=None):
"""
Calculate the voltage of a battery consisting of a cathode specified by the
directory versus a metallic Li anode.
Args:
directory:
calculation:
functional:
"""
raise NotImplementedError | 5,338,644 |
def update_fn(model, data_dict: dict, optimizers: dict, losses=None,
):
"""
Function which handles prediction from batch, logging, loss calculation
and optimizer step
Parameters
----------
model : torch.nn.Module
model to forward data through
data_dict : dict
dic... | 5,338,645 |
def display_time(seconds, granularity=2):
"""Display time as a nicely formatted string"""
result = []
if seconds == 0:
return "0 second"
for name, count in intervals:
value = seconds // count
if value:
seconds -= value * count
if value == 1:
... | 5,338,646 |
def reciprocal(x):
"""
Returns the reciprocal of x.
Args:
x (TensorOp): A tensor.
Returns:
TensorOp: The reciprocal of x.
"""
return ReciprocalOp(x) | 5,338,647 |
def get_protocol(remote_debugging_url: str, request_json: Callable[[str], Iterable]):
""" The current devtools protocol, as JSON """
return request_json(f"{remote_debugging_url}/json/protocol") | 5,338,648 |
def csv_saver_parser():
"""
Csv saver parser. Returns tuple with args as dictionary
and sufix that needs to be removed.
:return: tuple
"""
csv_saver_parser = ArgumentParser(description='Parser for saving data into CSV files.')
csv_saver_parser.add_argument('--F-csvsave',
... | 5,338,649 |
def get_var(expr: Expression) -> Var:
"""
Warning: this in only true for expressions captured by a match statement.
Don't call it from anywhere else
"""
assert isinstance(expr, NameExpr)
node = expr.node
assert isinstance(node, Var)
return node | 5,338,650 |
def sight(unit_type: int):
"""Return the sight range of a unit, given its unit type ID
:param unit_type: the unit type ID, according to :mod:`pysc2.lib.stats`
:type unit_type: int
:return: the unit's sight range
:rtype: float
"""
return __data['Sight'][unit_type] | 5,338,651 |
def decode_jwt(encoded_jwt):
"""
解码jwt
"""
global key
# 注意当载荷里面申明了 aud 受众的时候,解码时需要说明
decoded_jwt = jwt.decode(encoded_jwt, key, audience='dev', algorithms=["HS256"])
return decoded_jwt | 5,338,652 |
async def bulkget(ip, community, scalar_oids, repeating_oids, max_list_size=1,
port=161, timeout=DEFAULT_TIMEOUT):
# type: (str, str, List[str], List[str], int, int, int) -> BulkResult
"""
Delegates to :py:func:`~puresnmp.aio.api.raw.bulkget` but returns simple
Python types.
See t... | 5,338,653 |
def repo_version_db_key() -> bytes:
"""The db formated key which version information can be accessed at
Returns
-------
bytes
db formatted key to use to get/set the repository software version.
"""
db_key = c.K_VERSION.encode()
return db_key | 5,338,654 |
def generate_blob_sentiment_database(company_name, client_address):
"""
Calculate the textblob sentiment scores and put them into the database.
:param company_name: the name of the company. Used as the entry in the database.
:param client_address: the address of the database.
"""
client = Mong... | 5,338,655 |
def set_torch_rand_seed(seed: Union[int, str]):
"""Set rand seed for torch on both cpu, cuda and cudnn
Args:
seed (Union[int, str]): int seed or str, which will be hashed to get int seed
"""
if isinstance(seed, str):
seed = hash(seed)
elif not isinstance(int(seed), int):
rai... | 5,338,656 |
def _message(string):
"""Print an informative message to the console."""
sys.stdout.write("clant: %s\n" % string)
sys.stdout.flush() | 5,338,657 |
def retrieve_psd_cdf(path):
"""interact with hdf5 file format for marginal CDFs for a set of PSDs"""
with h5py.File(path, 'r') as obj:
group = obj['PSD_CDF']
Npsd = group.attrs['num_psds']
freqs = group['frequencies'][...]
data = group['CDFs'][...]
vals = data[:,0,:]
cdf... | 5,338,658 |
def main():
"""
Main function
"""
dblp_path = "dblp2.xml"
save_path = "dblp.json"
dblp = DBLP()
dblp.parse_all(dblp_path, save_path) | 5,338,659 |
def test_broadcastables():
""" Test the "broadcastables" argument when printing symbol-like objects. """
# No restrictions on shape
for s in [x, f_t]:
for bc in [(), (False,), (True,), (False, False), (True, False)]:
assert aesara_code_(s, broadcastables={s: bc}).broadcastable == bc
... | 5,338,660 |
def draw_box(box, color, text=None):
"""
Draw a bounding box using pyplot, optionally with a text box label.
Inputs:
- box: Tensor or list with 4 elements: [x0, y0, x1, y1] in [0, W] x [0, H]
coordinate system.
- color: pyplot color to use for the box.
- text: (Optional) String; if provided then d... | 5,338,661 |
def get(context: mgp.ProcCtx) -> mgp.Record(tracks=list):
"""Returns a list of track_ids of trendy songs.
Calculates recently popular tracks by comparing the
popularity of songs using the `followers`, `created_at`,
and proximity to other popular songs (pagerank).
Example usage:
CALL trendy_... | 5,338,662 |
def ip_only(value):
"""
Returns only the IP address string of the value provided. The value could be either an IP address,
and IP network or and IP interface as defined by the ipaddress module.
Parameters
----------
value : str
The value to use
Returns
-------
str
... | 5,338,663 |
def GetAuth1Token():
"""Returns an Auth1Token for use with server authentication."""
if AUTH1_TOKEN:
return AUTH1_TOKEN
if not OBJC_OK:
logging.error('Objective-C bindings not available.')
return None
pref_value = Foundation.CFPreferencesCopyAppValue(
'AdditionalHttpHeaders', 'ManagedInstall... | 5,338,664 |
def test_post_request_wrong_token_null_token(mock_app):
"""test receiving a post request with Auth headers and wrong scheme"""
headers = copy.deepcopy(HEADERS)
headers["Authorization"] = "Bearer "
# When a POST request Authorization="" is sent
response = mock_app.test_client().post("/apiv1.0/query... | 5,338,665 |
def TemplateInputFilename(context):
"""Build template file name from config."""
if args.templatedir:
filename = config_lib.CONFIG.Get("PyInstaller.template_filename",
context=context)
return os.path.join(args.templatedir, filename)
return None | 5,338,666 |
def get_data_by_isin(isin: str, dates: Tuple[datetime.date], is_etf: bool) -> Tuple[Optional[np.ndarray], str]:
"""Retrieves stock/ETF prices in EUR by ISIN for the given dates. Cached to make sure this is only queried once for
a given currency & date-range."""
from_date = dates[0].strftime("%d/%m/%Y")
... | 5,338,667 |
def get_result_qiskit() -> Dict[str, Dict[str, Any]]:
"""Fixture for returning sample experiment result
Returns
-------
Dict[str, Dict[str, Any]]
A dictionary of results for physics simulation and perfect gates
A result dictionary which looks something like::
{
... | 5,338,668 |
async def test_get_with_no_precision_loss_small_granularity(
min_level,
max_level,
date_from,
date_to,
expected,
):
"""Test query with interval granularity not smaller than the mininum layer level.
In this case we don't have any precision loss.
"""
indexer = MemoryIndexer(min_level... | 5,338,669 |
def all_budgets_for_student(user_id):
"""Returns a queryset for all budgets that a student can view/edit
i.e. is the submitter, president, or treasurer for any of the organization's budgets"""
query = Q(budget__submitter=user_id) | Q(budget__president_crsid=user_id) | Q(budget__treasurer_crsid=user_id)
... | 5,338,670 |
def exec_process(cmdline, silent=True, catch_enoent=True, input=None, **kwargs):
"""Execute a subprocess and returns the returncode, stdout buffer and stderr buffer.
Optionally prints stdout and stderr while running."""
try:
sub = subprocess.Popen(args=cmdline, stdin=subprocess.PIPE, stdout=subproce... | 5,338,671 |
def uniform_weights(x, x_mask):
"""Return uniform weights over non-masked x (a sequence of vectors).
Args:
x: batch * len * hdim
x_mask: batch * len (1 for padding, 0 for true)
Output:
x_avg: batch * hdim
"""
alpha = Variable(torch.ones(x.size(0), x.size(1)))
if x.data.i... | 5,338,672 |
def mixed_estimator_2(T1, T2, verbose=False):
"""
Based on the Lavancier and Rochet (2016) article.
The method combines two series of estimates of the same quantity taking into account their correlations. The individual measureements are assumed independent. The current implementation works only for point ... | 5,338,673 |
def test_coincident_indices_0():
"""Simple test with one coincident time."""
list0, list1 = setup_0()
solution = {5: 5}
assert coincident_indices(list0, list1, delta) == solution | 5,338,674 |
def main(api_key, token, board_id):
"""List out the board lists for our client"""
trello_client = TrelloClient(
api_key=api_key,
token=token,
)
board = Board(client=trello_client, board_id=board_id)
print('Lists')
print('-----')
print('Name: Id')
for card_list in board.al... | 5,338,675 |
def e_add_const(pub, a, n):
"""Add constant n to an encrypted integer"""
return a * modpow(pub.g, n, pub.n_sq) % pub.n_sq | 5,338,676 |
def area_triangle(base, height):
"""
"""
return (base * height) / 2.0 | 5,338,677 |
def _getAtomInvariantsWithRadius(mol, radius):
""" Helper function to calculate the atom invariants for each atom
with a given radius
Arguments:
- mol: the molecule of interest
- radius: the radius for the Morgan fingerprint
Return: list of atom invariants
"""
inv = []
for i ... | 5,338,678 |
def build_argparser():
"""Construct an argument parser for the ``translate_header.py`` script.
Returns
-------
argparser : `argparse.ArgumentParser`
The argument parser that defines the ``translate_header.py``
command-line interface.
"""
parser = argparse.ArgumentParser(descrip... | 5,338,679 |
def radcool(temp, zmetal):
""" Cooling Function
This version redefines Lambda_sd
(rho/m_p)^2 Lambda(T,z) is the cooling in erg/cm^3 s
Args:
temp : temperature in the unit of K
zmetal: metallicity in the unit of solar metallicity
Return:
in the unit of erg*s*cm^3
"""
... | 5,338,680 |
def L_model_forward(X, parameters):
"""
Implement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation
Arguments:
X -- data, numpy array of shape (input size, number of examples)
parameters -- output of initialize_parameters_deep()
Returns:
AL -- last post-... | 5,338,681 |
def linalg_multiply(a):
"""
Multiple all elements in vector or matrix
Parameters:
* a (array or matrix): The input to multiply
Return (number): The product of all elements
"""
return np.prod(a) | 5,338,682 |
def async_parser(word, rules, skip=False, **kwargs):
""" Asynchronously parses the pipe content
Args:
word (str): The string to transform
rules (List[obj]): the parsed rules (Objectify instances).
skip (bool): Don't parse the content
kwargs (dict): Keyword arguments
Kwargs:... | 5,338,683 |
def lambda_handler(event, context):
"""
This method selects 10% of the input manifest as validation and creates an s3 file containing the validation objects.
"""
label_attribute_name = event['LabelAttributeName']
meta_data = event['meta_data']
s3_input_uri = meta_data['IntermediateManifestS3Uri'... | 5,338,684 |
def run_remove_entry_via_id( id_to_remove ):
""" Removes id from solr.
Triggered by utils.reindex_all_support.run_enqueue_all_index_updates(). """
indexer = Indexer()
indexer.remove_index_entry( inscription_id=id_to_remove )
return | 5,338,685 |
def get_table_6():
"""表 6 蓄熱の採用の可否
Args:
Returns:
list: 表 6 蓄熱の採用の可否
"""
table_6 = [
('不可', '不可', '可', '可', '可'),
('不可', '不可', '可', '可', '可'),
('不可', '不可', '可', '可', '可'),
('不可', '不可', '可', '可', '可'),
('不可', '不可', '可', '可', '可'),
('不可', '不可',... | 5,338,686 |
def test_get_filename_not_found(fs: Mock, cwd: Mock) -> None:
"""It raises `SystemExit` when file is not found."""
with pytest.raises(SystemExit):
assert file_handler.get_filenames(".", "*.pdf") | 5,338,687 |
def is_prime(number, num_trials=200):
"""Determines whether a number is prime.
Runs the Miller-Rabin probabilistic primality test many times on the given number.
Args:
number (int): Number to perform primality test on.
num_trials (int): Number of times to perform the Miller-Rabin test.
... | 5,338,688 |
def extract_labels(filenames):
"""
Extract class labels of the images from image path list.
# Arguments
filenames: List of paths to image file.
# Returns
List of image labels.
"""
return LabelEncoder().fit_transform([extract_label(filename) for filename in filenames]) | 5,338,689 |
def reverseList(head):
"""
:type head: ListNode
:rtype: ListNode
"""
current = head;
# temp is first
counter = 0;
flag = 'Y';
while current is not None and flag != 'N':
# store the current element
# print(f"Current: {current... | 5,338,690 |
def test_solver(m=20, n=10, k=5):
"""Test lstsq._tikhonov.solve()."""
A = np.random.random((m, n))
B = np.random.random((m, k))
regularizers = 5 + np.random.random(k)
Ps = [5 + np.random.random((n, n)) for _ in range(k)]
Ps_diag = [5 + np.random.random(n) for _ in range(k)]
# Bad number of ... | 5,338,691 |
def test_verify_password_reset_token_invalid():
"""It should return None if the token is invalid"""
token = "wrong"
result = verify_password_reset_token(token)
assert result is None | 5,338,692 |
def validate(data: BuildParams):
"""
Makes sure a valid combination of params have been provided.
"""
git_repo = bool(data.source.git_repo)
dockerfile = bool(data.source.dockerfile)
build_context = bool(data.source.build_context)
git_valid = git_repo and not dockerfile and not build_context
... | 5,338,693 |
def load_model(filepath=FILEPATH) -> TrainingParams:
"""
Load
:param filepath:
:return:
"""
with open(filepath, "rb") as handler:
model = pickle.load(handler)
return model | 5,338,694 |
def test_add_vertex_data_prop_columns(df_type):
"""
add_vertex_data() on "merchants" table, subset of properties.
"""
from cugraph.experimental import PropertyGraph
merchants = dataset1["merchants"]
merchants_df = df_type(columns=merchants[0],
data=merchants[1])
e... | 5,338,695 |
def entry_point():
"""
Get station information and departures from public transport operators, and update
a departure board with departure information for a station.
""" | 5,338,696 |
def is_symmetric(m):
"""Check if a sparse matrix is symmetric
https://mail.python.org/pipermail/scipy-dev/2014-October/020117.html
Parameters
----------
m : sparse matrix
Returns
-------
check : bool
"""
if m.shape[0] != m.shape[1]:
raise Valu... | 5,338,697 |
def get_proj_libdirs(proj_dir: Path) -> List[str]:
"""
This function finds the library directories
"""
proj_libdir = os.environ.get("PROJ_LIBDIR")
libdirs = []
if proj_libdir is None:
libdir_search_paths = (proj_dir / "lib", proj_dir / "lib64")
for libdir_search_path in libdir_se... | 5,338,698 |
def render_raster_map(bounds, scale, basemap_image, aoi_image, id, path, colors):
"""Render raster dataset map based on bounds. Merge this over basemap image
and under aoi_image.
Parameters
----------
bounds : list-like of [xmin, ymin, xmax, ymax]
bounds of map
scale : dict
map... | 5,338,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.