content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
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 returning True if a node within ``e... | 5,800 |
def save_melspectrogram(directory_path, file_name, sampling_rate=44100):
""" Will save spectogram into current directory"""
path_to_file = os.path.join(directory_path, file_name)
data, sr = librosa.load(path_to_file, sr=sampling_rate, mono=True)
data = scale(data)
melspec = librosa.feature.... | 5,801 |
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
comp_rule... | 5,802 |
def delete_vpc(vpc_id):
"""Delete a VPC."""
client = get_client("ec2")
params = {}
params["VpcId"] = vpc_id
return client.delete_vpc(**params) | 5,803 |
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) | 5,804 |
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)
# Add metadata and text files for test ... | 5,805 |
def merid_advec_spharm(arr, v, radius):
"""Meridional advection using spherical harmonics."""
_, d_dy = horiz_gradient_spharm(arr, radius)
return v * d_dy | 5,806 |
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... | 5,807 |
def rbbh(args):
"""
%prog rbbh A_vs_B.blast B_vs_A.blast
Identify the reciprocal best blast hit for each query sequence in set A
when compared to set B.
This program assumes that the BLAST results have already been filtered
based on a combination of %id, %cov, e-value cutoffs. BLAST output sho... | 5,808 |
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... | 5,809 |
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
log = int... | 5,810 |
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.array([True] * ... | 5,811 |
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... | 5,812 |
def list_videos(plugin, item_id, page, **kwargs):
"""Build videos listing"""
resp = urlquick.get(URL_REPLAY % page)
root = resp.parse()
for video_datas in root.iterfind(".//a"):
if video_datas.get('href') is not None:
video_title = video_datas.find('.//h3').text
video_i... | 5,813 |
def create_folder(folder_path):
"""
if folder does not exist, create it
:param folder_path:
"""
if not os.path.exists(folder_path):
try:
os.makedirs(folder_path)
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
... | 5,814 |
def fuzzyCompareDouble(p1, p2):
"""
compares 2 double as points
"""
return abs(p1 - p2) * 100000. <= min(abs(p1), abs(p2)) | 5,815 |
def test_get_map_not_found(client, session, map_fixtures):
"""Test if the response of /map is 404."""
response = client.get("/maps/404")
assert response.status_code == 404 | 5,816 |
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
... | 5,817 |
def mcmc_fit(x, y, yerr, p_init, p_max, id, RESULTS_DIR, truths, burnin=500,
nwalkers=12, nruns=10, full_run=500, diff_threshold=.5,
n_independent=1000):
"""
Run the MCMC
"""
try:
print("Total number of points = ", sum([len(i) for i in x]))
print("Number of li... | 5,818 |
def db_list(config: str, verbose: bool):
"""
List the DBs found in the database directory.
"""
m = CVDUpdate(config=config, verbose=verbose)
m.db_list() | 5,819 |
def set_transparent_color(rgb: tuple[int, int, int] = (0, 0, 0)) -> None:
"""Applies 100% transparency to <rgb>. A application window using
this value as it's clear color ("background") will also be transparent.
This may cause other renders of the same color within the application
window to also be tran... | 5,820 |
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) | 5,821 |
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] | 5,822 |
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_... | 5,823 |
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.
... | 5,824 |
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,
split_progress=None, candidate... | 5,825 |
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.keys()):
accuracy_ = stats[k][0]/stats[k]... | 5,826 |
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... | 5,827 |
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() | 5,828 |
def test_sanity(tmpdir, manifest_file, manifest):
"""
Does our mock manifest contents evaluate the same as a file?
"""
_file = tmpdir.join('manifest.yaml')
_file.write(manifest_file)
assert get_manifest_from_path(str(_file)).contents == manifest.contents | 5,829 |
def refresh_jwt_public_keys(user_api=None, logger=None):
"""
Update the public keys that the Flask app is currently using to validate
JWTs.
The get_keys_url helper function will prefer the user_api's
.well-known/openid-configuration endpoint, but if no jwks_uri
is found, will default to /jwt/ke... | 5,830 |
def save_data():
"""@Numpy Examples
数据的保存与加载
Examples:
# 保存 array
>>> a = np.asarray([1, 2, 3])
>>> fp = r'./array.npy' # 后缀为 .npy
>>> np.save(fp, a)
>>> _a = np.load(fp)
>>> assert (a == _a).all()
>>> _ = os.system(f'rm {fp}')
# 保存多个数据,不限于 ... | 5,831 |
def get_file(ctx, file_path):
""" Get content of a file from OneDrive
"""
tokens = auth.ensure_tokens(ctx.client_id, ctx.tokens)
ctx.save(tokens=tokens)
session = auth.get_request_session(tokens)
# Calling helper method to get the file
api_util.get_file(session, file_path) | 5,832 |
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, # ... | 5,833 |
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... | 5,834 |
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] | 5,835 |
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)) | 5,836 |
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... | 5,837 |
def show_image(txt):
"""
Print ASCII art (saved as txt file.
"""
with open(txt, "r") as f:
for line in f.readlines():
print(line, end="")
sleep(0.01)
return | 5,838 |
def create_csv(file_path: str, params_names: dict, site_number: str):
"""
Function that creates the final version of the CSV files
Parameters
----------
file_path : str
[description]
params_names : dict
[description]
site_number : str
[description]
"""
df = p... | 5,839 |
def test_json_file_is_valid(path):
"""Tests whether YAML data file is a valid YAML document."""
with path.open() as f:
assert yaml.safe_load(f) | 5,840 |
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 = models.SQLConnecti... | 5,841 |
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 interval', buttons=True),
interval_s = ra... | 5,842 |
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... | 5,843 |
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=... | 5,844 |
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
... | 5,845 |
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... | 5,846 |
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)
busy... | 5,847 |
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.exists(file) and shutil.which("ldd") is not N... | 5,848 |
def test_list_unsigned_long_min_length_4_nistxml_sv_iv_list_unsigned_long_min_length_5_4(mode, save_output, output_format):
"""
Type list/unsignedLong is restricted by facet minLength with value 10.
"""
assert_bindings(
schema="nistData/list/unsignedLong/Schema+Instance/NISTSchema-SV-IV-list-uns... | 5,849 |
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 | 5,850 |
def test_random_game_json_identity(base):
"""Test random game to/from json identity"""
game = random_game(base)
jgame = json.dumps(game.to_json())
copy = paygame.game_json(json.loads(jgame))
assert game == copy | 5,851 |
def test_rules_check_dependencies(mocker, rules):
""" Test the dependencies in process rules. """
mocked_hash = mocker.patch('supvisors.process.ProcessRules.check_hash_nodes')
mocked_auto = mocker.patch('supvisors.process.ProcessRules.check_autorestart')
mocked_start = mocker.patch('supvisors.process.Pr... | 5,852 |
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... | 5,853 |
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 in range(-radi... | 5,854 |
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 | 5,855 |
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
----------
y: Ar... | 5,856 |
def test_construction_resistance_low():
"""Calculate properties of a low capacitance wall."""
con = ConstructionLayered(
materials=[
MaterialResistanceOnly(thermal_resistance=0.060),
mats.Aluminium(thickness=1 / 1000),
MaterialResistanceOnly(thermal_resistance=0.020),... | 5,857 |
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... | 5,858 |
def replace_bytes(fbin, start_addr, new_bytes, fout=None):
"""replace bytes from a start address for a binary image
This function is replace variable number of bytes of a binary image and save it as a new image
:param fbin: input image file
:param start_addr: start address to replace
:param new_bytes... | 5,859 |
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... | 5,860 |
def test_octagonal_qubit_index():
"""test that OctagonalQubit properly calculates index and uses it for comparison"""
qubit0 = OctagonalQubit(0)
assert qubit0.index == 0
assert OctagonalQubit(1) > qubit0 | 5,861 |
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:
... | 5,862 |
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... | 5,863 |
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
... | 5,864 |
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
NewNewOrgs|=froz... | 5,865 |
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,
... | 5,866 |
def py_lines_with_regions():
"""Find lines with regions."""
lines, regions = {}, ev('s:R()')
specific_line, rev = evint('l:specific_line'), evint('a:reverse')
for r in regions:
line = int(r['l'])
#called for a specific line
if specific_line and line != specific_line:
... | 5,867 |
def print_red(content: str):
"""Prints the content in red
:param: the content to print
:type: str
"""
print(Fore.RED + content + Fore.RESET) | 5,868 |
async def test_flow_user(hass: HomeAssistant):
"""Test user initialized flow."""
port = com_port()
port_select = usb.human_readable_device_name(
port.device,
port.serial_number,
port.manufacturer,
port.description,
port.vid,
port.pid,
)
with patch_conf... | 5,869 |
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 this ``Annotation``.
x : float
The ``x`` ... | 5,870 |
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... | 5,871 |
def test_get_eth2_staking_deposits_fetch_from_db( # pylint: disable=unused-argument
ethereum_manager,
call_order,
ethereum_manager_connect_at_start,
inquirer,
price_historian,
freezer,
):
"""
Test new on-chain requests for existing addresses requires a difference... | 5,872 |
def test_list_unsigned_short_length_3_nistxml_sv_iv_list_unsigned_short_length_4_2(mode, save_output, output_format):
"""
Type list/unsignedShort is restricted by facet length with value 8.
"""
assert_bindings(
schema="nistData/list/unsignedShort/Schema+Instance/NISTSchema-SV-IV-list-unsignedSho... | 5,873 |
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... | 5,874 |
def assign(dest, src, transpose_on_convert=None):
"""Resizes the destination and copies the source."""
src = as_torch(src, transpose_on_convert)
if isinstance(dest, Variable):
dest.data.resize_(*shp(src)).copy_(src)
elif isinstance(dest, torch.Tensor):
dest.resize_(*shp(src)).copy_(src)
... | 5,875 |
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... | 5,876 |
def main():
"""
Set the client extensions of an open Trade in an Account
"""
parser = argparse.ArgumentParser()
#
# Add the command line argument to parse to the v20 config
#
common.config.add_argument(parser)
parser.add_argument(
"orderid",
help=(
"The... | 5,877 |
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... | 5,878 |
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 | 5,879 |
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) | 5,880 |
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... | 5,881 |
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... | 5,882 |
def test_default_configs_override():
"""
Test CLI warning when project create invoked for the first time
without specifying a template
"""
cmd = FakeCommand2(None, None, cmd_name='my_plugin fake_command')
configs = {'foo': 'bar'}
assert cmd.default_configs == configs | 5,883 |
def percent_cb(name, complete, total):
""" Callback for updating target progress """
logger.debug(
"{}: {} transferred out of {}".format(
name, sizeof_fmt(complete), sizeof_fmt(total)
)
)
progress.update_target(name, complete, total) | 5,884 |
def test_Sampler_start_text(abc_sampler_config: sampler_pb2.Sampler):
"""Test that start_text is set from Sampler proto."""
s = samplers.Sampler(abc_sampler_config)
assert s.start_text == abc_sampler_config.start_text | 5,885 |
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... | 5,886 |
def test_models(app: Teal, db: SQLAlchemy):
"""Checks that the models used in the fixture work."""
DeviceDef, ComponentDef, ComputerDef = \
app.config['RESOURCE_DEFINITIONS'] # type: Tuple[ResourceDef]
Component = ComponentDef.MODEL
Computer = ComputerDef.MODEL
component = Component(id=1, ... | 5,887 |
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.
:param docume... | 5,888 |
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... | 5,889 |
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... | 5,890 |
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': od.std_clip,
... | 5,891 |
def setup_module():
"""Setup test environment for the module:
- Adds dummy home dir tree
"""
# Do not mask exceptions here. In particular, catching WindowsError is a
# problem because that exception is only defined on Windows...
(Path.cwd() / IP_TEST_DIR).mkdir(parents=True) | 5,892 |
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) | 5,893 |
def refill_vaddresses():
"""
Ensures that always enough withdraw addresses are available
"""
while True:
try:
data = json.dumps({"password":publicserverpassword})
r = post(url + "len/vaddress", data).text
if int(r) < 100:
vaddress = versum.getn... | 5,894 |
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)
... | 5,895 |
def hamming(s0, s1):
"""
>>> hamming('ABCD', 'AXCY')
2
"""
assert len(s0) == len(s1)
return sum(c0 != c1 for c0, c1 in zip(s0, s1)) | 5,896 |
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/data/{topic}/blaz... | 5,897 |
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 : Year of observation
@param DOY : ... | 5,898 |
def visualize_dimensionality_reduction(cell_data, columns, category, color_map="Spectral",
algorithm="UMAP", dpi=None, save_dir=None):
"""Plots the dimensionality reduction of specified population columns
Args:
cell_data (pandas.DataFrame):
Dataframe c... | 5,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.