content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def matrix_zeros(m, n, **options):
""""Get a zeros matrix for a given format."""
format = options.get('format', 'sympy')
dtype = options.get('dtype', 'float64')
spmatrix = options.get('spmatrix', 'csr')
if format == 'sympy':
return zeros(m, n)
elif format == 'numpy':
return _nump... | e4c87a85dd6a37868704205b21732d82a4ffb2df | 3,900 |
def make_password(password, salt=None):
"""
Turn a plain-text password into a hash for database storage
Same as encode() but generate a new random salt. If password is None then
return a concatenation of UNUSABLE_PASSWORD_PREFIX and a random string,
which disallows logins. Additional random string ... | 6c39486c2eb88af278580cdf4b86b7b45489eef0 | 3,901 |
from typing import Optional
from typing import TextIO
from typing import Type
import csv
from pathlib import Path
import sys
def get_dialect(
filename: str, filehandle: Optional[TextIO] = None
) -> Type[csv.Dialect]:
"""Try to guess dialect based on file name or contents."""
dialect: Type[csv.Dialect] = c... | 91d21e5bb321e7deb1e4b8db445d5c51d8138456 | 3,902 |
from typing import Optional
from typing import Any
import os
def load_object(primary_path: str, file_name: Optional[str] = None, module: Optional[str] = "pickle") -> Any:
"""
This is a generic function to load any given
object using different `module`s, e.g. pickle,
dill, and yaml.
Note: See `get... | e6f8e423637ae8a26b623d754b9a7ae3699ef6f5 | 3,903 |
from typing import Union
from pathlib import Path
from typing import Tuple
import torch
from typing import Optional
from typing import Callable
from re import T
def compute_spectrogram(
audio: Union[Path, Tuple[torch.Tensor, int]],
n_fft: int,
win_length: Optional[int],
hop_length: int,
n_mels: in... | 918fc0c9273b2085ded2ca8d6dd5d4db758538f0 | 3,904 |
def decode_html_dir(new):
""" konvertiert bestimmte Spalte in HTML-Entities """
def decode(key):
return decode_html(unicode(new[key]))
if new.has_key('title') and new['title'].find('&') >= 0:
new['title'] = decode('title')
if new.has_key('sub_title') and new['sub_title'].find('&') >= 0:
new['sub_t... | 029483974a26befc2df8d92babf53f5a32be31f5 | 3,905 |
def apply_hash(h, key):
"""
Apply a hash function to the key.
This function is a wrapper for xxhash functions with initialized seeds.
Currently assume h is a xxhash.x32 object with initialized seed
If we change choice of hash function later, it will be easier to change
how we apply the hash (either through a func... | e79ce4fdbb6f6c09b6115b35e619894b67ce991a | 3,906 |
def dmsp_enz_deg(
c,
t,
alpha,
vmax,
vmax_32,
kappa_32,
k
):
"""
Function that computes dD32_dt and dD34_dt of DMSP
Parameters
----------
c: float.
Concentration of DMSP in nM.
t: int
Integration time in min.
alpha: float.
Alpha for cleavage by Ddd... | d5e4b77523ab469b61eec106a28e1e3143644bf7 | 3,907 |
def plot_holdings(returns, positions, legend_loc='best', ax=None, **kwargs):
"""Plots total amount of stocks with an active position, either short
or long.
Displays daily total, daily average per month, and all-time daily
average.
Parameters
----------
returns : pd.Series
Daily ret... | 5e375729aa48d0d3f8aada17268048a68a662421 | 3,908 |
import os
def get_systemd_run_args(available_memory):
"""
Figure out if we're on system with cgroups v2, or not, and return
appropriate systemd-run args.
If we don't have v2, we'll need to be root, unfortunately.
"""
args = [
"systemd-run",
"--uid",
str(os.geteuid()),
... | f872286bf6759e26e24a5331db108ccee8f89605 | 3,909 |
def concatenation_sum(n: int) -> int:
"""
Algo:
1. Find length of num (n), i.e. number of digits 'd'.
2. Determine largest number with 'd - 1' digits => L = 10^(d - 1) - 1
3. Find diff => f = n - L
4. Now, the sum => s1 = f * d, gives us the number of digits in the string formed ... | 644c994ee9b5af280feb233a40df51b519c4b9c6 | 3,910 |
def make_join_conditional(key_columns: KeyColumns, left_alias: str, right_alias: str) -> Composed:
"""
Turn a pair of aliases and a list of key columns into a SQL safe string containing
join conditionals ANDed together.
s.id1 is not distinct from d.id1 and s.id2 is not distinct from d.id2
"""
... | c0b239598f606f35d3af0cbf8c34168137e05b9c | 3,911 |
def home():
""" Home interface """
return '''<!doctype html>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<body style="margin:0;font-family:sans-serif;color:white">
<form method="POST" action="analyse" enctype="multipart/form-data">
<label style="text-align:center;position:fixe... | d8a9c3449ac56b04ee1514729342ce29469c5c2f | 3,912 |
def _enable_mixed_precision_graph_rewrite_base(opt, loss_scale,
use_v1_behavior):
"""Enables mixed precision. See `enable_mixed_precision_graph_rewrite`."""
opt = _wrap_optimizer(opt, loss_scale, use_v1_behavior=use_v1_behavior)
config.set_optimizer_experimental_opti... | 8601ae6d24575e2bf5a7057bc06992088d473179 | 3,913 |
import argparse
def get_args() -> ProgramArgs:
"""
utility method that handles the argument parsing via argparse
:return: the result of using argparse to parse the command line arguments
"""
parser = argparse.ArgumentParser(
description="simple assembler/compiler for making it easier to wr... | d47d0fd4da6fb263bbd12848d3888b435596c092 | 3,914 |
def selection_criteria_1(users, label_of_interest):
"""
Formula for Retirement/Selection score:
x = sum_i=1_to_n (r_i) — sum_j=1_to_m (r_j).
Where first summation contains reliability scores of users who have labeled it as the same
as the label of interest, second summation contains reliability scor... | 8255fd3645d5b50c43006d2124d06577e3ac8f2d | 3,915 |
import requests
from typing import cast
def get_default_product_not_found(product_category_id: str) -> str:
"""Get default product.
When invalid options are provided, the defualt product is returned. Which happens to be unflavoured whey at 2.2 lbs.
This is PRODUCT_INFORMATION.
"""
response = requ... | 4464a56de2ff514a71d5d06b1684f04a9ed8e564 | 3,916 |
import re
def book_number_from_path(book_path: str) -> float:
"""
Parses the book number from a directory string.
Novellas will have a floating point value like "1.1" which indicates that it was the first novella
to be published between book 1 and book 2.
:param book_path: path of the currently ... | 087cb0b8cd0c48c003175a05ed0d7bb14ad99ac3 | 3,917 |
def intervals_split_merge(list_lab_intervals):
"""
对界限列表进行融合
e.g.
如['(2,5]', '(5,7]'], 融合后输出为 '(2,7]'
Parameters:
----------
list_lab_intervals: list, 界限区间字符串列表
Returns:
-------
label_merge: 合并后的区间
"""
list_labels = []
# 遍历每个区间, 取得左值右值字符串组成列表
for lab in list_la... | a9e99ec6fc51efb78a4884206a72f7f4ad129dd4 | 3,918 |
def antique(bins, bin_method=BinMethod.category):
"""CARTOColors Antique qualitative scheme"""
return scheme('Antique', bins, bin_method) | 718ca4c2b9efede292bb5e8e1eb5128e6200a454 | 3,919 |
import json
def do_request(batch_no, req):
"""execute one request. tail the logs. wait for completion"""
tmp_src = _s3_split_url(req['input'])
cpy_dst = _s3_split_url(req['output'])
new_req = {
"src_bucket": tmp_src[0],
"src_key": tmp_src[1],
"dst_bucket": cpy_dst[0],
... | 6e4b8591abfe8a1c106a0ede1e6aa3f6712afd4a | 3,920 |
import sys
def bigwig_tss_targets(wig_file, tss_list, seq_coords, pool_width=1):
""" Read gene target values from a bigwig
Args:
wig_file: Bigwig filename
tss_list: list of TSS instances
seq_coords: list of (chrom,start,end) sequence coordinates
pool_width: average pool adjacent nucleotides of t... | 23e2ffb41e86ff4de72a239bd59841b37025a9ed | 3,921 |
def _robot_barcode(event: Message) -> str:
"""Extracts a robot barcode from an event message.
Args:
event (Message): The event
Returns:
str: robot barcode
"""
return str(
next(
subject["friendly_name"] # type: ignore
for subject in event.message["ev... | 5ffb6567ebb103fc534390d13876d9c1fa956169 | 3,922 |
def build_dist(srcdir, destdir='.', build_type='bdist_egg'):
"""
Builds a distribution using the specified source directory and places
it in the specified destination directory.
srcdir: str
Source directory for the distribution to be built.
destdir: str
Directory where ... | bd5ac5cbffb88a3ff0de3cf54f615ef6696273a8 | 3,923 |
from typing import List
from typing import Union
def check_thirteen_fd(fds: List[Union[BI, FakeBI]]) -> str:
"""识别十三段形态
:param fds: list
由远及近的十三段形态
:return: str
"""
v = Signals.Other.value
if len(fds) != 13:
return v
direction = fds[-1].direction
fd1, fd2, fd3, fd4, f... | 95c308c2560cc7a337e4a1719836c3df74ab1bbe | 3,924 |
from typing import List
def set_process_tracking(template: str, channels: List[str]) -> str:
"""This function replaces the template placeholder for the process tracking with the correct process tracking.
Args:
template: The template to be modified.
channels: The list of channels to be used.
... | 0cf720bd56a63939541a06e60492472f92c4e589 | 3,925 |
def solve(instance: Instance) -> InstanceSolution:
"""Solves the P||Cmax problem by using a genetic algorithm.
:param instance: valid problem instance
:return: generated solution of a given problem instance
"""
generations = 512
population_size = 128
best_specimens_number = 32
generator ... | f8a82a066de29e0c149c3c5f01821af080619764 | 3,926 |
def payee_transaction():
"""Last transaction for the given payee."""
entry = g.ledger.attributes.payee_transaction(request.args.get("payee"))
return serialise(entry) | 47a21c7921cae4be30b6eefbbde43bfdf5a38013 | 3,927 |
def represent(element: Element) -> str:
"""Represent the regular expression as a string pattern."""
return _Representer().visit(element) | dfd44499aa1f63248c1a6632131974b242fedf95 | 3,928 |
def read_dynamo_table(gc, name, read_throughput=None, splits=None):
"""
Reads a Dynamo table as a Glue DynamicFrame.
:param awsglue.context.GlueContext gc: The GlueContext
:param str name: The name of the Dynamo table
:param str read_throughput: Optional read throughput - supports values from "0.1"... | 5f789626cb3fc8004532cc59bdae128b744b111e | 3,929 |
import six
def convert_to_bytes(text):
"""
Converts `text` to bytes (if it's not already).
Used when generating tfrecords. More specifically, in function call `tf.train.BytesList(value=[<bytes1>, <bytes2>, ...])`
"""
if six.PY2:
return convert_to_str(text) # In python2, str is byte
el... | da10be9cb88a80f66becead41400b3a4eb6152a2 | 3,930 |
from typing import OrderedDict
def xreplace_constrained(exprs, make, rule=None, costmodel=lambda e: True, repeat=False):
"""
Unlike ``xreplace``, which replaces all objects specified in a mapper,
this function replaces all objects satisfying two criteria: ::
* The "matching rule" -- a function re... | f24f0bb1356c5613c012fe405691b1b493ffc6a2 | 3,931 |
import re
def get_comp_rules() -> str:
"""
Download the comp rules from Wizards site and return it
:return: Comp rules text
"""
response = download_from_wizards(COMP_RULES)
# Get the comp rules from the website (as it changes often)
# Also split up the regex find so we only have the URL
... | dbb48b391305199182a2bf66bed62dcd91dc0071 | 3,932 |
def delete_vpc(vpc_id):
"""Delete a VPC."""
client = get_client("ec2")
params = {}
params["VpcId"] = vpc_id
return client.delete_vpc(**params) | 5c1a043d837ff1bc0cab41ccdbe784688966a275 | 3,933 |
def test_network_xor(alpha = 0.1, iterations = 1000):
"""Creates and trains a network against the XOR/XNOR data"""
n, W, B = network_random_gaussian([2, 2, 2])
X, Y = xor_data()
return n.iterate_network(X, Y, alpha, iterations) | cb05f01f589d7e224d1a0a87f594a075228741fc | 3,934 |
from pathlib import Path
import shutil
def assemble_book(draft__dir: Path, work_dir: Path, text_dir: Path) -> Path:
"""Merge contents of draft book skeleton with test-specific files for
the book contents.
"""
book_dir = work_dir / "test-book"
# Copy skeleton from draft__dir
shutil.copytree(draft__dir, book_dir)... | 51ec6ed21760feeff3eeee6ee6fa802383b5afa3 | 3,935 |
def merid_advec_spharm(arr, v, radius):
"""Meridional advection using spherical harmonics."""
_, d_dy = horiz_gradient_spharm(arr, radius)
return v * d_dy | 7973f99b60ad9d94b6858d28d8877f5c814160c2 | 3,936 |
def run_win_pct(team_name, df):
"""
Function that calculates a teams winning percentage Year over Year (YoY)
Calculation:
Number of wins by the total number of competitions.
Then multiply by 100 = win percentage.
Number of loses by the total number of competitions.
Then multi... | 3fc071cd7e89f68216286b0b6422a95ce8f690f6 | 3,937 |
def get_container_info(pi_status):
"""
Expects a dictionary data structure that include keys and values of the
parameters that describe the containers running in a Raspberry Pi computer.
Returns the input dictionary populated with values measured from the current
status of one or more containers... | a488e7afa9c2e003edb3138c1d78e434921dbf3e | 3,938 |
import math
def formatSI(n: float) -> str:
"""Format the integer or float n to 3 significant digits + SI prefix."""
s = ''
if n < 0:
n = -n
s += '-'
if type(n) is int and n < 1000:
s = str(n) + ' '
elif n < 1e-22:
s = '0.00 '
else:
assert n < 9.99e26
... | ddbbb70e66d368253d29c3223eee7a5926518efd | 3,939 |
import scipy
def pemp(stat, stat0):
""" Computes empirical values identically to bioconductor/qvalue empPvals """
assert len(stat0) > 0
assert len(stat) > 0
stat = np.array(stat)
stat0 = np.array(stat0)
m = len(stat)
m0 = len(stat0)
statc = np.concatenate((stat, stat0))
v = np.... | 7d046666687ede0b671c00d5c691ac520179e11f | 3,940 |
def help_message() -> str:
"""
Return help message.
Returns
-------
str
Help message.
"""
msg = f"""neocities-sync
Sync local directories with neocities.org sites.
Usage:
neocities-sync options] [--dry-run] [-c CONFIG] [-s SITE1] [-s SITE2] ...
Options:
-C CONFIG_FIL... | 8c2d0c31513e36c1ef1c9f0b096d264449dafdee | 3,941 |
def fuzzyCompareDouble(p1, p2):
"""
compares 2 double as points
"""
return abs(p1 - p2) * 100000. <= min(abs(p1), abs(p2)) | e2a93a993147e8523da0717d08587250003f9269 | 3,942 |
def filter_date_df(date_time, df, var="date"):
"""Filtrar dataframe para uma dada lista de datas.
Parameters
----------
date_time: list
list with dates.
df: pandas.Dataframe
var: str
column to filter, default value is "date" but can be adaptable for other ones.
Returns
... | 6d3002917ef0786e8b128a2a02df3fabb9997aab | 3,943 |
import urllib
def pproxy_desired_access_log_line(url):
"""Return a desired pproxy log entry given a url."""
qe_url_parts = urllib.parse.urlparse(url)
protocol_port = '443' if qe_url_parts.scheme == 'https' else '80'
return 'http {}:{}'.format(qe_url_parts.hostname, protocol_port) | 4c056b1d2cc11a72cf63400734807b9b074f147c | 3,944 |
import socket
def unused_port() -> int:
"""Return a port that is unused on the current host."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1] | 26d72e1a529edd37b14ac746bcb4082c1d1b9061 | 3,945 |
def get_axioma_risk_free_rate(conn) :
"""
Get the USD risk free rate provided by Axioma and converted it into
a daily risk free rate assuming a 252 trading data calendar.
"""
query = """
select
data_date,
Risk_Free_Rate
from
axioma_... | 2c6c680ef36c247b67c481ff4dde685afc4bad4d | 3,946 |
def update_user_count_estimated(set_of_contributors, anonymous_coward_comments_counter):
"""
Total user count estimate update in the presence of anonymous users.
Currently we use a very simplistic model for estimating the full user count.
Inputs: - set_of_contributors: A python set of user ids.
... | 165160c8c0284743856c17aba90cffaa78f2ba11 | 3,947 |
import numbers
import time
import warnings
def _fit_and_score(estimator, X, y, scorer, train, test, verbose,
parameters, fit_params, return_train_score=False,
return_parameters=False, return_n_test_samples=False,
return_times=False, return_estimator=False,
... | 6330fb95709e74471b72b58297b3ce3c7d483449 | 3,948 |
from typing import Dict
from typing import List
def prettify_eval(set_: str, accuracy: float, correct: int, avg_loss: float, n_instances: int,
stats: Dict[str, List[int]]):
"""Returns string with prettified classification results"""
table = 'problem_type accuracy\n'
for k in sorted(stats... | 5e5ba8ffa62668e245daa2ada9fc09747b5b6dd2 | 3,949 |
def GetRecentRevisions(repository, project=None, num_revisions=20):
"""Get Recent Revisions.
Args:
repository: models.Repository, the repository whose revisions to get
we ought.
project: models.Project, restrict the query to a given project.
num_revisions: int, maximum number of revisions to fetc... | da775b43e0c4cee77006a12b5c1536a328f8a210 | 3,950 |
def load_location(doc_name):
"""Load a location from db by name."""
doc_ref = get_db().collection("locations").document(doc_name)
doc = doc_ref.get()
if not doc.exists:
return None
else:
return doc.to_dict() | 900450ec3a1c033a9c11baed611170457660754f | 3,951 |
def plotMultiROC(y_true, # list of true labels
y_scores, # array of scores for each class of shape [n_samples, n_classes]
title = 'Multiclass ROC Plot',
n_points=100, # reinterpolates to have exactly N points
labels = None, # list... | a8ca19b92f7f3539d8550cf63121a46d36e59cbf | 3,952 |
def fasta_to_dict(fasta_file):
"""Consolidate deflines and sequences from FASTA as dictionary"""
deflines = []
sequences = []
sequence = ""
with open(fasta_file, "r") as file:
for line in file:
if line.startswith(">"):
deflines.append(line.rstrip().lst... | e1740ad29672e5239d575df963e21a0bf5caee08 | 3,953 |
def find_roots(graph):
"""
return nodes which you can't traverse down any further
"""
return [n for n in graph.nodes() if len(list(graph.predecessors(n))) == 0] | 7dbf755d2b76f066370d149638433c6693e8e7b9 | 3,954 |
def _is_test_file(filesystem, dirname, filename):
"""Return true if the filename points to a test file."""
return (_has_supported_extension(filesystem, filename) and
not is_reference_html_file(filename)) | ba161818a6f2497e1122519945f255d56488f231 | 3,955 |
def kitchen_door_device() -> Service:
"""Build the kitchen door device."""
transitions: TransitionFunction = {
"unique": {
"open_door_kitchen": "unique",
"close_door_kitchen": "unique",
},
}
final_states = {"unique"}
initial_state = "unique"
return build_d... | 700a1d92087ac91f5311b4c55380f1a6f18860b4 | 3,956 |
import http
def sql_connection_delete(
request: http.HttpRequest,
pk: int
) -> http.JsonResponse:
"""AJAX processor for the delete SQL connection operation.
:param request: AJAX request
:param pk: primary key for the connection
:return: AJAX response to handle the form
"""
conn = mode... | 754e7d7f15a0be843b89c89446a7d4f39bc1401f | 3,957 |
from sage.all import solve
import html
def simpson_integration(
title = text_control('<h2>Simpson integration</h2>'),
f = input_box(default = 'x*sin(x)+x+1', label='$f(x)=$'),
n = slider(2,100,2,6, label='# divisions'),
interval_input = selector(['from slider','from keyboard'], label='Integration inte... | 45e575e9ebda475a613555dfcb43ae7d739131c9 | 3,958 |
def object_reactions_form_target(object):
"""
Get the target URL for the object reaction form.
Example::
<form action="{% object_reactions_form_target object %}" method="post">
"""
ctype = ContentType.objects.get_for_model(object)
return reverse("comments-ink-react-to-object", args=(ct... | 5bcd4d9fa8db783c78668820326dd55038ef609e | 3,959 |
def check_args(**kwargs):
"""
Check arguments for themis load function
Parameters:
**kwargs : a dictionary of arguments
Possible arguments are: probe, level
The arguments can be: a string or a list of strings
Invalid argument are ignored (e.g. probe = 'g', level=... | 3e25dc43df0a80a9a16bcca0729ee0b170a9fb89 | 3,960 |
def make_theta_mask(aa):
""" Gives the theta of the bond originating each atom. """
mask = np.zeros(14)
# backbone
mask[0] = BB_BUILD_INFO["BONDANGS"]['ca-c-n'] # nitrogen
mask[1] = BB_BUILD_INFO["BONDANGS"]['c-n-ca'] # c_alpha
mask[2] = BB_BUILD_INFO["BONDANGS"]['n-ca-c'] # carbon
mask[3... | f33c1b46150ed16154c9a10c92f30cf9f60c2f51 | 3,961 |
def create_keypoint(n,*args):
"""
Parameters:
-----------
n : int
Keypoint number
*args: tuple, int, float
*args must be a tuple of (x,y,z) coordinates or x, y and z
coordinates as arguments.
::
# Example
kp1 = 1
kp2 = 2
crea... | e498e36418ec19d2feef122d3c42a346f9de4af7 | 3,962 |
import time
def wait_for_sidekiq(gl):
"""
Return a helper function to wait until there are no busy sidekiq processes.
Use this with asserts for slow tasks (group/project/user creation/deletion).
"""
def _wait(timeout=30, step=0.5):
for _ in range(timeout):
time.sleep(step)
... | 7fe98f13e9474739bfe4066f20e5f7d813ee4476 | 3,963 |
import os
import shutil
import subprocess
def ldd(file):
"""
Given a file return all the libraries referenced by the file
@type file: string
@param file: Full path to the file
@return: List containing linked libraries required by the file
@rtype: list
"""
rlist = []
if os.path.e... | d893fd9dc61a7b0c1f35c19b3f300b9f1b333eb2 | 3,964 |
def insert_node_after(new_node, insert_after):
"""Insert new_node into buffer after insert_after."""
next_element = insert_after['next']
next_element['prev'] = new_node
new_node['next'] = insert_after['next']
insert_after['next'] = new_node
new_node['prev'] = insert_after
return new_node | e03fbd7bd44a3d85d36069d494464b9237bdd306 | 3,965 |
def apply_wavelet_decomposition(mat, wavelet_name, level=None):
"""
Apply 2D wavelet decomposition.
Parameters
----------
mat : array_like
2D array.
wavelet_name : str
Name of a wavelet. E.g. "db5"
level : int, optional
Decomposition level. It is constrained to retur... | d91f534d605d03c364c89383629a7142f4705ac8 | 3,966 |
import math
def ACE(img, ratio=4, radius=300):
"""The implementation of ACE"""
global para
para_mat = para.get(radius)
if para_mat is not None:
pass
else:
size = radius * 2 + 1
para_mat = np.zeros((size, size))
for h in range(-radius, radius + 1):
for w ... | 6809067ec1aed0f20d62d672fcfb554e0ab51f28 | 3,967 |
def classname(object, modname):
"""Get a class name and qualify it with a module name if necessary."""
name = object.__name__
if object.__module__ != modname:
name = object.__module__ + '.' + name
return name | af4e05b0adaa9c90bb9946edf1dba67a40e78323 | 3,968 |
import time
def demc_block(y, pars, pmin, pmax, stepsize, numit, sigma, numparams, cummodels, functype, myfuncs, funcx, iortholist, fits, gamma=None, isGR=True, ncpu=1):
"""
This function uses a differential evolution Markov chain with block updating to assess uncertainties.
PARAMETERS
----------
... | 414168976c732d66165e19c356800158b2056a1e | 3,969 |
def shape5d(a, data_format="NDHWC"):
"""
Ensuer a 5D shape, to use with 5D symbolic functions.
Args:
a: a int or tuple/list of length 3
Returns:
list: of length 5. if ``a`` is a int, return ``[1, a, a, a, 1]``
or ``[1, 1, a, a, a]`` depending on data_format "NDHWC" or "NCDH... | fe6d974791a219c45a543a4d853f5d44770d0c9a | 3,970 |
def _compute_node_to_inventory_dict(compute_node):
"""Given a supplied `objects.ComputeNode` object, return a dict, keyed
by resource class, of various inventory information.
:param compute_node: `objects.ComputeNode` object to translate
"""
result = {}
# NOTE(jaypipes): Ironic virt driver wil... | 385170dd5021da202364d03c66a0b6d268580945 | 3,971 |
def resnet152(pretrained=False, num_classes=1000, ifmask=True, **kwargs):
"""Constructs a ResNet-152 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
block = Bottleneck
model = ResNet(block, [3, 8, 36, 3], num_classes=1000, **kwargs)
if pretrained:
... | 8b72a8e284d098a089448e4a10d5f393345d7278 | 3,972 |
def register_driver(cls):
"""
Registers a driver class
Args:
cls (object): Driver class.
Returns:
name: driver name
"""
_discover_on_demand()
if not issubclass(cls, BaseDriver):
raise QiskitChemistryError('Could not register class {} is not subclass of BaseDriver'.fo... | 82eca23a5cf5caf9a028d040ac523aa6e20ae01d | 3,973 |
def ceil(array, value):
"""
Returns the smallest index i such that array[i - 1] < value.
"""
l = 0
r = len(array) - 1
i = r + 1
while l <= r:
m = l + int((r - l) / 2)
if array[m] >= value:
# This mid index is a candidate for the index we are searching for
... | 689148cebc61ee60c99464fde10e6005b5d901a9 | 3,974 |
import copy
def FindOrgByUnionEtIntersection(Orgs):
"""Given a set of organizations considers all the possible unions and intersections to find all the possible organizations"""
NewNewOrgs=set([])
KnownOrgs=copy.deepcopy(Orgs)
for h in combinations(Orgs,2):
#checks only if one is not contained in the other
Ne... | 6e2450f49522186094b205dd86d8e698aca708bc | 3,975 |
def get_sf_fa(
constraint_scale: float = 1
) -> pyrosetta.rosetta.core.scoring.ScoreFunction:
"""
Get score function for full-atom minimization and scoring
"""
sf = pyrosetta.create_score_function('ref2015')
sf.set_weight(
pyrosetta.rosetta.core.scoring.ScoreType.atom_pair_constraint,
... | b82b352f3fc031cc18951b037779a71247e5095f | 3,976 |
from typing import Optional
from typing import List
def make_keypoint(class_name: str, x: float, y: float, subs: Optional[List[SubAnnotation]] = None) -> Annotation:
"""
Creates and returns a keypoint, aka point, annotation.
Parameters
----------
class_name : str
The name of the class for... | bc4a96c8376890eaaa2170ab1cc1401dcb2781a4 | 3,977 |
def plane_mean(window):
"""Plane mean kernel to use with convolution process on image
Args:
window: the window part to use from image
Returns:
Normalized residual error from mean plane
Example:
>>> from ipfml.filters.kernels import plane_mean
>>> import numpy as np
>>> wi... | 7383078ec3c88ac52728cddca9a725f6211b2d2c | 3,978 |
def _eval_field_amplitudes(lat, k=5, n=1, amp=1e-5, field='v',
wave_type='Rossby', parameters=Earth):
"""
Evaluates the latitude dependent amplitudes at a given latitude point.
Parameters
----------
lat : Float, array_like or scalar
latitude(radians)
k : Int... | db74c50ef6328055ab2a59faecba72cc28afd136 | 3,979 |
def get_uframe_info():
""" Get uframe configuration information. (uframe_url, uframe timeout_connect and timeout_read.) """
uframe_url = current_app.config['UFRAME_URL'] + current_app.config['UFRAME_URL_BASE']
timeout = current_app.config['UFRAME_TIMEOUT_CONNECT']
timeout_read = current_app.config['UFRA... | 921f42d59af265152d7ce453a19cb8057af8415e | 3,980 |
def yd_process_results(
mentions_dataset,
predictions,
processed,
sentence2ner,
include_offset=False,
mode='default',
rank_pred_score=True,
):
"""
Function that can be used to process the End-to-End results.
:return: dictionary with results and document as key.
"""
assert... | 32352c6aabea6750a6eb410d62232c96ad6b7e7d | 3,981 |
import re
def valid(f):
"""Formula f is valid if and only if it has no
numbers with leading zero, and evals true."""
try:
return not re.search(r'\b0[0-9]', f) and eval(f) is True
except ArithmeticError:
return False | 1303729dc53288ea157687f78d7266fa7cb2ce79 | 3,982 |
def user_info():
"""
渲染个人中心页面
:return:
"""
user = g.user
if not user:
return redirect('/')
data={
"user_info":user.to_dict()
}
return render_template("news/user.html",data=data) | 54c6c6122f28553f0550a744d5b51c26221f7c60 | 3,983 |
def _check_X(X, n_components=None, n_features=None, ensure_min_samples=1):
"""Check the input data X.
See https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/mixture/_base.py .
Parameters
----------
X : array-like, shape (n_samples, n_features)
n_components : integer
Returns... | 429120092a963d1638e04cc96afdfe5979470fee | 3,984 |
def read_viirs_geo (filelist, ephemeris=False, hgt=False):
"""
Read JPSS VIIRS Geo files and return Longitude, Latitude, SatelliteAzimuthAngle, SatelliteRange, SatelliteZenithAngle.
if ephemeris=True, then return midTime, satellite position, velocity, attitude
"""
if type(filelist) is str: fi... | 1b8bbd34651e13aabe752fa8e3ac8c6679d757ca | 3,985 |
def _in_terminal():
"""
Detect if Python is running in a terminal.
Returns
-------
bool
``True`` if Python is running in a terminal; ``False`` otherwise.
"""
# Assume standard Python interpreter in a terminal.
if "get_ipython" not in globals():
return True
ip = globa... | 9716c2a1809f21ed8b827026d29b4ad69045f8d5 | 3,986 |
import re
def create_text_pipeline(documents):
"""
Create the full text pre-processing pipeline using spaCy that first cleans the texts
using the cleaning utility functions and then also removes common stopwords and corpus
specific stopwords. This function is used specifically on abstracts.
:... | d31632c7c1d9a2c85362e05ae43f96f35993a746 | 3,987 |
def giou_dist(tlbrs1, tlbrs2):
"""Computes pairwise GIoU distance."""
assert tlbrs1.ndim == tlbrs2.ndim == 2
assert tlbrs1.shape[1] == tlbrs2.shape[1] == 4
Y = np.empty((tlbrs1.shape[0], tlbrs2.shape[0]))
for i in nb.prange(tlbrs1.shape[0]):
area1 = area(tlbrs1[i, :])
for j in range... | 40dcd6b59f350f167ab8cf31be425e98671243d4 | 3,988 |
def easter(date):
"""Calculate the date of the easter.
Requires a datetime type object. Returns a datetime object with the
date of easter for the passed object's year.
"""
if 1583 <= date.year < 10000: # Delambre's method
b = date.year / 100 # Take the firsts two digits of t... | 90bfaf56fb5164cdfb185f430ca11e7a5d9c2785 | 3,989 |
from typing import Dict
def state_mahalanobis(od: Mahalanobis) -> Dict:
"""
Mahalanobis parameters to save.
Parameters
----------
od
Outlier detector object.
"""
state_dict = {'threshold': od.threshold,
'n_components': od.n_components,
'std_clip... | 7be602c5a0c89d67adc223c911abccd96d359664 | 3,990 |
def show_table(table, **options):
"""
Displays a table without asking for input from the user.
:param table: a :class:`Table` instance
:param options: all :class:`Table` options supported, see :class:`Table` documentation for details
:return: None
"""
return table.show_table(**options) | ec040d4a68d2b3cb93493f336daf1aa63289756e | 3,991 |
def create_client(name, func):
"""Creating resources/clients for all needed infrastructure: EC2, S3, IAM, Redshift
Keyword arguments:
name -- the name of the AWS service resource/client
func -- the boto3 function object (e.g. boto3.resource/boto3.client)
"""
print("Creating client for", name)
... | a688c36918ebb4bc76ee1594c6f4cca638587d7d | 3,992 |
def hamming(s0, s1):
"""
>>> hamming('ABCD', 'AXCY')
2
"""
assert len(s0) == len(s1)
return sum(c0 != c1 for c0, c1 in zip(s0, s1)) | efaba3e6aca8349b0dc5df575b937ba67a148d0e | 3,993 |
import pickle
def load_embeddings(topic):
"""
Load TSNE 2D Embeddings generated from fitting BlazingText on the news articles.
"""
print(topic)
embeddings = pickle.load(
open(f'covidash/data/{topic}/blazing_text/embeddings.pickle', 'rb'))
labels = pickle.load(
open(f'covidash/d... | de2f74c7e467e0f057c10a0bc15b79ee9eecb40f | 3,994 |
import shutil
import os
import sys
def get_EAC_macro_log(year,DOY,dest_path):
"""
Copy the EAC macro processor log
This gets the macro processor log which is created by the 'at' script
which starts the macro processor.
Notes
=====
This uses find_EAC_macro_log() to get the log names.
@param year :... | 2cc91ef42eef883f35917b41a29a9578fbfc6fa8 | 3,995 |
def mosaic_cut(image, original_width, original_height, width, height, center,
ptop, pleft, pbottom, pright, shiftx, shifty):
"""Generates a random center location to use for the mosaic operation.
Given a center location, cuts the input image into a slice that will be
concatenated with other slices... | 2874ea65a695d7ebebf218e5a290069a9f3c1e8e | 3,996 |
import requests
def get_children_info(category_id: str) -> list[dict]:
"""Get information about children categories of the current category.
:param: category_id: category id.
:return: info about children categories.
"""
# Create the URL
url = f'{POINT}/resources/v2/title/domains/{DOMAIN}/' \
... | f5a651c1f58c75ee56d1140ee41dc6dd39570f88 | 3,997 |
from datetime import datetime
def GetTypedValue(field_type, value):
"""Returns a typed value based on a schema description and string value.
BigQuery's Query() method returns a JSON string that has all values stored
as strings, though the schema contains the necessary type information. This
method provides ... | 8e6198d089bae4e1044b2998da97a8cbcf6130b2 | 3,998 |
def predict_from_file(audio_file,
hop_length=None,
fmin=50.,
fmax=MAX_FMAX,
model='full',
decoder=torchcrepe.decode.viterbi,
return_harmonicity=False,
return_periodic... | 7e1f8036e5d0506f28a4b36b9e23c2d4a0237218 | 3,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.