content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _validate_config_file(config: Dict[str, str], prompts: Dict[str, Any]):
"""Checks that the configuration file contains all needed variables.
Args:
config: The config as a dictionary.
prompts: Prompts from prompts.yml.
Raises:
KedroCliError: If the config file is empty or does n... | 20,500 |
def f5_list_policy_hostnames_command(client: Client, policy_md5: str) -> CommandResults:
"""
Get a list of all policy hostnames.
Args:
client (Client): f5 client.
policy_md5 (str): MD5 hash of the policy.
"""
result = client.list_policy_hostnames(policy_md5)
table_name = 'f5 da... | 20,501 |
def predict(m, count, s, A):
"""predict the chain after s
calculate the probability of a m-length chain,
then return chains.
CAUTION the number of chains maybe less then count
args:
m: the length of predict chain
count: the number of predict chain
s: the last elem... | 20,502 |
def read_lengths_from_fastx_file(fastx_file):
"""
@param fastx_file: file path
@type fastx_file: str
@rtype: dict[str, int]
"""
file_type = mimetypes.guess_type(fastx_file)[1]
if file_type == 'gzip':
f = gzip.open(fastx_file, "rt")
elif not file_type:
f = open(fastx_file... | 20,503 |
def f_multidim(anchors, basis, distance_measurements, coeffs):
"""
:param anchors: anchors dim x N
:param basis: basis vectors K x M
:param distance_measurements: matrix of squared distances M x N
:param coeffs: coefficient matrix dim x K
:return: vector of differences between estimate distanc... | 20,504 |
def getHomography(indict, outdict, outsize=None):
"""Returns a transformation to go from input pts to output pts using a homography.
'indict' and 'outdict' should contain identical keys mapping to 2-tuples.
We create A:
x1 y1 1 0 0 0 -x1*x1' -y1*x1'
0 0 0 x1 y1 1 -x1*y1' -y1*y1'
... | 20,505 |
def variables_to_restore(scope=None, strip_scope=False):
"""Returns a list of variables to restore for the specified list of methods.
It is supposed that variable name starts with the method's scope (a prefix
returned by _method_scope function).
Args:
methods_names: a list of names of configurable methods... | 20,506 |
def uninstall():
"""Uninstall Blender configuration for Avalon."""
sys.excepthook = ORIGINAL_EXCEPTHOOK
pyblish.api.deregister_host("blender")
pyblish.api.deregister_plugin_path(str(PUBLISH_PATH))
deregister_loader_plugin_path(str(LOAD_PATH))
avalon.api.deregister_plugin_path(LegacyCreator, st... | 20,507 |
def from_strings(data, gaps="-", length=None, dtype=np.int8):
"""Convert a series of strings to an array of integer encoded alleles.
Parameters
----------
data : array_like, str
Sequence of strings of alleles.
gaps : str, optional
String of symbols to be interpreted as gaps in the s... | 20,508 |
def geocode(scene, dem, tmpdir, outdir, spacing, scaling='linear', func_geoback=1,
nodata=(0, -99), osvdir=None, allow_RES_OSV=False,
cleanup=True, export_extra=None, basename_extensions=None,
removeS1BorderNoiseMethod='gamma', refine_lut=False):
"""
general function for radi... | 20,509 |
def fetch_new_stock_datasets():
"""fetch_new_stock_datasets
Collect datasets for a ticker from IEX Cloud or Tradier
.. warning: IEX Cloud charges per request. Here are example
commands to help you monitor your usage while handling
first time users and automation (intraday, daily, and weekl... | 20,510 |
def get_relationship_targets(item_ids, relationships, id2rec):
"""Get item ID set of item IDs in a relationship target set"""
# Requirements to use this function:
# 1) item Terms must have been loaded with 'relationships'
# 2) item IDs in 'item_ids' arguement must be present in id2rec
# ... | 20,511 |
def cli(ctx, newick, analysis_id, name="", xref_db="null", xref_accession="", match_on_name=False, prefix=""):
"""Load a phylogenetic tree (Newick format) into Chado db
Output:
Number of inserted trees
"""
return ctx.gi.phylogeny.load_tree(newick, analysis_id, name=name, xref_db=xref_db, xref_accessio... | 20,512 |
def punkt_feature(punkter: pd.DataFrame) -> Dict[str, str]:
"""Omsæt punktinformationer til JSON-egnet dict"""
for i in range(punkter.shape[0]):
punkt = punkter.at[i, "Punkt"]
# Fastholdte punkter har ingen ny kote, så vi viser den gamle
if punkter.at[i, "Fasthold"] == "x":
... | 20,513 |
def roll_neighbors(sites, site, dims=None, radius=1):
""" N-dimensional pixel neighborhood
for periodic images on regular grids """
index = np.unravel_index(site, dims=dims)
neighs = sites.take(nbr_range+index, axis=0, mode='wrap')
return neighs.flatten() | 20,514 |
def test_list_date_length_nistxml_sv_iv_list_date_length_1_3(mode, save_output, output_format):
"""
Type list/date is restricted by facet length with value 5.
"""
assert_bindings(
schema="nistData/list/date/Schema+Instance/NISTSchema-SV-IV-list-date-length-1.xsd",
instance="nistData/list... | 20,515 |
def download(datadir, conn):
"""Download UPDATED.csv and reinstatements to the DATADIR
CONN is a model.LEIE instance we'll use to log to the database"""
if dload_if_stale(os.path.join(datadir, "UPDATED.csv"),
'https://oig.hhs.gov/exclusions/downloadables/UPDATED.csv',
... | 20,516 |
def save_numpy_object(obj, output_path, if_file_exists, name='file'):
"""Utility to save a numpy object
Parameters
----------
obj: numpy.ndarray
Object to save
output_path: str
Where to save the file
if_file_exists: str, optional
One of 'overwrite', 'abort', 'skip'. If... | 20,517 |
def print_columns(left_text, right_text, column_width):
"""Print two columns of text given two strings of multi-line text.
Either (but not both) text string may be None.
Text will be separated by a vertical bar with one space of pad on either side (' | ')
"""
assert left_text is not None or right_te... | 20,518 |
def extract_node_name(path, ignore_missing_nodes=False):
"""extracts the token after the 'nodes'"""
tokens = path.split(os.sep)
last_nodes_index = -1
for i, token in enumerate(tokens):
if token == "nodes":
last_nodes_index = i
if last_nodes_index == -1:
if ignore_missing_... | 20,519 |
def say_my_name(first_name, last_name=""):
"""Prints "My name is" followed by the first name and optional last name"""
if type(first_name) is not str:
raise TypeError("first_name must be a string")
if type(last_name) is not str:
raise TypeError("last_name must be a string")
print("My nam... | 20,520 |
def run_model(model, raw_cohort, delta_encoder):
"""
Run the given model using the given cohort and experimental settings contained in args.
This function:
(1) balanced the dataset
(2) splits the cohort intro training:development:testing sets at the patient-level
(3) trains PRONTO and saves che... | 20,521 |
def folder0_content(folder0_id, host, token):
"""
Modules
-------
request, json
----------
Parameters
----------
folder0_id : Onedata folder level 0 id containing the data to publish.
host : OneData provider (e.g., ceta-ciemat-02.datahub.egi.eu).
token : OneData personal access t... | 20,522 |
def _update_collection_info(file_name, doi, title, short_name, force):
"""
Adds an entry to the gloabl infomation file. If the entry exists, will be overwritten.
"""
info, info_file = _get_collection_info()
if file_name in info:
if not force and short_name != info[file_name]["short_name"]:
... | 20,523 |
def fetch_object(object_id: int, url: str):
"""
Fetch a single object from a feature layer. We have to fetch objects one by one, because they
can get pretty big. Big enough, that if you ask for more than one at a time, you're likely to
encounter 500 errors.
object_id: object id to fetch (e.g. 1)
... | 20,524 |
def density_forecast_param(Yp, sigma, _, rankmatrix, errordist_normed, dof):
"""creates a density forecast for Yp with Schaake Schuffle
Parameters
----------
Yp: numpy.array
24-dimensional array with point-predictions of day ahead prices
sig... | 20,525 |
def test_rundak_driver():
""" run dakota on an aep scan, test case for full dakota/openmdao/twister pipeline"""
print "rundak_driver"
dak = AEP_CSM_DAKOTA_Scanner(10)
set_as_top(dak)
dak.run() | 20,526 |
def vae_latent_space_offset(data_dir, model_dir, encoded_dir, latent_dim, gene_id, percent_low, percent_high):
"""
vae_latent_space_offset(data_dir: string, model_dir: string, encoded_dir: string, gene_id: string):
input:
data_dir: directory containing the raw gene expression data for all gen... | 20,527 |
def gaussian_blur(img: np.ndarray, kernel_size: int) -> np.ndarray:
"""Applies a Gaussian Noise kernel"""
if not is_valid_kernel_size(kernel_size):
raise ValueError(
"kernel_size must either be 0 or a positive, odd integer")
return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0) | 20,528 |
def get_controls_snapshots_count(selenium, src_obj):
"""Return dictionary with controls snapshots actual count and count taken
from tab title."""
controls_ui_service = webui_service.ControlsService(selenium)
return {
"controls_tab_count": controls_ui_service.get_count_objs_from_tab(
src_obj=src_... | 20,529 |
def fast_gnp_random_graph(n, p, seed=None, directed=False):
"""Returns a `G_{n,p}` random graph, also known as an Erdős-Rényi graph or
a binomial graph.
Parameters
----------
n : int
The number of nodes.
p : float
Probability for edge creation.
seed : int, optional
S... | 20,530 |
def round_to(f: float, p: int = 0) -> float:
"""Round to the specified precision using "half up" rounding."""
# Do no rounding, just return a float with full precision
if p == -1:
return float(f)
# Integer rounding
elif p == 0:
return round_half_up(f)
# Round to the specified ... | 20,531 |
def get_interface_type(interface):
"""Gets the type of interface
"""
if interface.upper().startswith('GI'):
return 'GigabitEthernet'
elif interface.upper().startswith('TE'):
return 'TenGigabitEthernet'
elif interface.upper().startswith('FA'):
return 'FastEthernet'
elif i... | 20,532 |
def __get_global_options(cmd_line_options, conf_file_options=None):
""" Get all global options
:type cmd_line_options: dict
:param cmd_line_options: Dictionary with all command line options
:type conf_file_options: dict
:param conf_file_options: Dictionary with all config file options
:returns: ... | 20,533 |
def add_to_cache(blob_cache, txs_by_key_index, scanned_blocks, password):
"""
password ->
txs_by_gindex
recent block hashes/heights
minimum height of blocks in block_hashes
"""
cache_data = {
'txs': txs_by_key_index,
'scanned_blocks': scanned_blocks
}
blob_cache.clear_objs(password)
blob_cache.add_ob... | 20,534 |
def test_visualization():
"""Test that the visualization is created as expected
"""
nr_bottom = 4
capacity = 250
pour = 1000
bartender = Bartender(nr_bottom, capacity)
bartender.place_order(pour)
tower = bartender._fountain.tower
graph_fountain = bartender._visualizer.visualize(tow... | 20,535 |
def download_file(service, drive_file):
"""Download a file's content.
Args:
service: Drive API service instance.
drive_file: Drive File instance.
Returns:
File's content if successful, None otherwise.
"""
download_url = drive_file.get('downloadUrl')
if download_url:
resp, content = service... | 20,536 |
def get_include_file_end_before(block: Block) -> str:
"""
>>> # test end-before set to 'end-marker'
>>> block = lib_test.get_test_block_ok()
>>> get_include_file_end_before(block)
'# end-marker'
>>> assert block.include_file_end_before == '# end-marker'
>>> # test end-before not set
>>>... | 20,537 |
def add_random_circles(tensor: torch.Tensor, n_circles: int, equalize_overlaps: bool = True):
"""Adds n_circles random circles onto the image."""
height, width = tensor.shape
circle_img = torch.zeros_like(tensor)
for _ in range(n_circles):
circle_img = add_circle(circle_img, {'x': random.randint... | 20,538 |
def sample_quadric_surface(quadric, center, samples):
"""Samples the algebraic distance to the input quadric at sparse locations.
Args:
quadric: Tensor with shape [..., 4, 4]. Contains the matrix of the quadric
surface.
center: Tensor with shape [..., 3]. Contains the [x,y,z] coordinates of the
... | 20,539 |
def mol2df(mols: Mols[pd.DataFrame], multiindex=False) -> pd.DataFrame:
"""
flattens a mol into a dataframe with the columns containing the start, stop and price
:param mols: mols to transform
:return:
"""
if multiindex:
flat = {
((start, stop), price): series
for... | 20,540 |
def load_sequence_classifier_configs(args) -> Tuple[WrapperConfig, pet.TrainConfig, pet.EvalConfig]:
"""
Load the model, training and evaluation configs for a regular sequence classifier from the given command line
arguments. This classifier can either be used as a standalone model or as the final classifie... | 20,541 |
def plot(graph):
"""Plots the graph.
:param graph: graph to plot
:type graph: networkx graph
"""
fig, axis = plt.subplots(1, 1, figsize=(10, 10))
pos = graphviz_layout(graph)
values = networkx.get_node_attributes(graph, 'value')
node_labels = {}
for name, value in values.items():
... | 20,542 |
def gender(word):
""" Returns the gender for the given word, either:
MALE, FEMALE, (MALE, FEMALE), (MALE, PLURAL) or (FEMALE, PLURAL).
"""
w = word.lower()
# Adjectives ending in -e: cruciale, difficile, ...
if w.endswith(("ale", "ile", "ese", "nte")):
return (MALE, FEMALE)
# Mos... | 20,543 |
def fcmp(d,r):
"""
Compares two files, d and r, cell by cell. Float comparisons
are made to 4 decimal places. Extending this function could
be a project in and of itself.
"""
# we need to compare the files
dh=open(d,'rb')
rh=open(r,'rb')
dlines = dh.readlines()
rlines = rh.... | 20,544 |
def is_vector_equal(vec1, vec2, tolerance=1e-10):
"""Compare if two vectors are equal (L1-norm) according to a tolerance"""
return np.all(np.abs(vec1 - vec2) <= tolerance) | 20,545 |
def partition_pair(bif_point):
"""Calculate the partition pairs at a bifurcation point.
The number of nodes in each child tree is counted. The partition
pairs is the number of bifurcations in the two child subtrees
at each branch point.
"""
n = float(sum(1 for _ in bif_point.children[0].ipreord... | 20,546 |
def readPyCorrFit(file):
"""
Read header and data of .csv PyCorrFit output file
========== ===============================================================
Input Meaning
---------- ---------------------------------------------------------------
file String with path to .csv file
... | 20,547 |
def end_of_time(t):
""" Return the next hour of the passed time. e.g, 18:25:36 --> 19:00:00 """
return t + timedelta(minutes=60) - timedelta(minutes=t.minute) - timedelta(seconds=t.second) | 20,548 |
def modf(x):
"""modf(x)
Return the fractional and integer parts of x. Both results carry the sign
of x.
"""
signx = sign(x)
absx = Abs(x)
return (signx * Mod(absx, 1), signx * floor(absx)) | 20,549 |
def get_user_from_request(request, available_query_params: list()) -> Tuple[User, GeneralApiResponse]:
"""
Entra com o request da view e uma lista de query params do user que podem ser consultados
Retorna um user caso seja si mesmo, ou tenha permissão de acesso a outros usuários
Retorna uma resposta de ... | 20,550 |
def longest_CD(values):
"""
Return the sequence range for the longest continuous
disorder (CDl) subsequence.
"""
# Filter residues with score equal or greater than 0.5
# and store its position index
dis_res = [index for index, res in enumerate(values)
if float(res) >= 0.5]
... | 20,551 |
def get_read_length(filename):
""" Return the first read length of fastq file.
:param str filename: fastq file.
"""
with FastqReader(filename) as filin:
read_len = len(next(iter(filin)))
return read_len | 20,552 |
def no_outliers_estimator(base_estimator, x, alpha=0.01):
""" Calculate base_estimator function after removal of extreme quantiles
from the sample
"""
x = np.array(x)
if len(x.shape) < 3:
x = np.expand_dims(x, -1)
low_value = np.quantile(x, alpha, axis=(0, 1))
high_value = np.quantil... | 20,553 |
def error_state_to_dict(err: ErrorState) -> ErrorDict:
"""Return an ErrorDict based on the exception, string or tuple in the ErrorState.
Args:
err: ErrorState from a api error state
Returns:
An ErrorDict containing the error message a status_code and a traceback if available
"""
#... | 20,554 |
def test_user_extract_bogus_data():
"""User doesn't exist, user is GUEST"""
http = httplib2.Http()
response, content = http.request('http://our_test_domain:8001/current_user', method='GET',
headers={'Authorization': 'Basic %s' % b64encode(':')})
assert response['status'] == '200'
assert ... | 20,555 |
def english_words() -> Set[str]:
"""Return a set of english words from the nltk corpus "words".
Returns:
Set of english words.
"""
nltk_resource("corpora/words")
return set(nltk.corpus.words.words()) | 20,556 |
def bipartite_matching_wrapper(a, b, score_func, symmetric=False):
"""A wrapper to `bipartite_matching()` that returns `(matches, unmatched_in_a, unmatched_in_b)`
The list of `matches` contains tuples of `(score, a_element, b_element)`. The two unmatched
lists are elements from each of the respective input... | 20,557 |
def get_entsoe(connection_string, user, pwd, category, directory):
"""
downloads dataset from ENTSO-E's transparency data sftp server.
contact ENTSO-E to receive login credentials.
:param connection_string: url of ENTSO-E transparency server, as of May 1, 2020: 'sftp-transparency.entsoe.eu'
:param u... | 20,558 |
def gen_seldicts(
da,
dims=None,
check_empty=True,
unstack=True
):
"""
TODO: improve documentation
generates a list of dictionaries to be passed into dataarray selection
functions.
Parameters
----------
da : xr.DataArray
datarray to generate selection... | 20,559 |
def get_interface_type(interface):
"""Gets the type of interface
Args:
interface (str): full name of interface, i.e. Ethernet1/1, loopback10,
port-channel20, vlan20
Returns:
type of interface: ethernet, svi, loopback, management, portchannel,
or unknown
"""
if in... | 20,560 |
def GetExpandedPaths(
args,
heartbeat_cb = _NoOp):
"""Expands given path patterns.
Args:
args: A `FileFinderArgs` instance that dictates the behaviour of the path
expansion.
heartbeat_cb: A function to be called regularly to send heartbeats.
Yields:
Absolute paths (as string objects) d... | 20,561 |
def create_int_feature_list(name, key, prefix="", module_dict=None):
"""Creates accessor functions for bytes feature lists.
The provided functions are has_${NAME}, get_${NAME}_size, get_${NAME}_at,
clear_${NAME}, and add_${NAME}.
example = tensorflow.train.SequenceExample()
add_image_timestamp(1000000, exam... | 20,562 |
def ROC(y_pred, y_true, positive_column = 0,draw = True):
"""
ROC
"""
y_pred = y_pred[:,0]
y_true = y_true[:,0]
# sort by y_pred
sort_index = np.argsort(-y_pred)
y_pred = y_pred[sort_index]
y_true = y_true[sort_index]
tprs = []
fprs = []
positive_num = (y_tru... | 20,563 |
def pip_install_with_cursor(*args, **kwargs):
"""Just slicer.util.pip_install but with a busy cursor while it executes."""
qt.QApplication.setOverrideCursor(qt.Qt.BusyCursor)
try:
slicer.util.pip_install(*args, **kwargs)
finally:
qt.QApplication.restoreOverrideCursor() | 20,564 |
def ignore_check(self, channel: discord.TextChannel, ignore_dm: bool = False, from_main: bool = False):
"""
A function that checks whether or not that channel allows command.
Args:
self: instance of the class this command calls or this can be commands.Bot
channel (discord.TextChannel): the ... | 20,565 |
def network_count_allocated_ips(context, network_id):
"""Return the number of allocated non-reserved ips in the network."""
return IMPL.network_count_allocated_ips(context, network_id) | 20,566 |
def _parse_transform_spec( transform_spec ):
"""
Parses a transform specification into its name and parameters dictionary.
Raises ValueError if the specification is invalid, it represents an unknown
transform, or if the encoded parameters do not match the transform's expected
types.
Takes 1 ar... | 20,567 |
def mock_get_backend(backend):
"""Replace qiskit.IBMQ with a mock that returns a single backend.
Note this will set the value of qiskit.IBMQ to a MagicMock object. It is
intended to be run as part of docstrings with jupyter-example in a hidden
cell so that later examples which rely on ibmq devices so t... | 20,568 |
def describe_delivery_channels(DeliveryChannelNames=None):
"""
Returns details about the specified delivery channel. If a delivery channel is not specified, this action returns the details of all delivery channels associated with the account.
See also: AWS API Documentation
:example: response ... | 20,569 |
def test_atomic_integer_min_inclusive_nistxml_sv_iv_atomic_integer_min_inclusive_1_4(mode, save_output, output_format):
"""
Type atomic/integer is restricted by facet minInclusive with value
-999999999999999999.
"""
assert_bindings(
schema="nistData/atomic/integer/Schema+Instance/NISTSchema-... | 20,570 |
def while_Zero():
""" Pattern of Number : '0' using while loop"""
i=0
while i<7:
j=0
while j<5:
if i in (0,6) and j not in(0,4) or j in(0,4) and i not in(0,6) or i+j==5:
print('*',end=' ')
... | 20,571 |
def parse_text_multiline(data: Union[str, List[str]]) -> str:
"""Parse the text in multiline mode."""
if isinstance(data, str):
return data
elif isinstance(data, list) and all(map(is_str, data)):
return '\n'.join(data)
else:
raise ValueError(data) | 20,572 |
def get_latest_episode_release(series, downloaded=True, season=None):
"""
:param series series: SQLAlchemy session
:param downloaded: find only downloaded releases
:param season: season to find newest release for
:return: Instance of Episode or None if not found.
"""
session = Session.object... | 20,573 |
def _set_user_permissions_for_volumes(users, volumes):
"""
Returns the section of the user data script to create a Linux
user group and grant the group permission to access the mounted
volumes on the EC2 instance.
"""
group_name = 'volumes'
user_data_script_section = f"""
groupadd {group_n... | 20,574 |
def cached_examples():
"""This view should be cached for 60 sec"""
examples = ExampleModel.query()
return render_template('list_examples_cached.html', examples=examples) | 20,575 |
def corona_surface_integral(solution, E, candidate_attach_pts, corona_elem, phys_param, debug_flag=False):
"""
Surface integral around the points that are marked as possible attachment candidates
"""
pcg_idx_vec = np.zeros((len(candidate_attach_pts.keys())), dtype=np.int64)
Q_vec = np.zeros((le... | 20,576 |
def librispeech_adversarial(
split_type: str = "adversarial",
epochs: int = 1,
batch_size: int = 1,
dataset_dir: str = None,
preprocessing_fn: Callable = None,
cache_dataset: bool = True,
framework: str = "numpy",
clean_key: str = "clean",
adversarial_key: str = "adversarial",
) -> d... | 20,577 |
def search4letters(phrase, letters='aeiou'):
"""
->return a set of the 'letters' found in 'phrase'.
:param phrase: phrase where the search will be made
:param letters:set of letters that will be searched for in the sentence
:return returns a set ()
"""
return set(letters).intersection(set(ph... | 20,578 |
def handle_cmdline_args():
"""
Return an object with attributes 'infile' and
'outfile', after handling the command line arguments
"""
parser = argparse.ArgumentParser(
description='Generate synthetic data from a specification in a json '
'file using the "synth-method" de... | 20,579 |
def merge_flights(prev_flights_filename, next_flights_filename, ids_df, log):
"""
Gets the next days flights that are the continuation of the previous days
flights and merges them with the previous days flights.
It writes the new next days and previous days flights to files prepended
with new.
... | 20,580 |
def findClusters( peaks, thresh ):
"""Since the peaks are in sequence, this method follows a very simplistic
approach. For each peak it checks its distance from the previous peak. If
it is less than threshold, it clusters that peak with the previous one.
Note that in each of the clusters, input ord... | 20,581 |
def docker_compose_file(pytestconfig):
"""Get docker compose file"""
return os.path.join(str(pytestconfig.rootdir), "docker-compose.yml") | 20,582 |
def sample():
"""
Returns the path to the sample of the given name.
"""
def inner(name):
return os.path.join(
os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'samples'
), name
)
return inner | 20,583 |
def connectAnimAndRigJoints(animJoints, rigJoints):
"""
Given a list of animation joints and a list of rig joints,
connects each pair of joints with translate, rotate, and
scale. Note: animJoints and rigJoints should follow the
exact same hierarchy.
"""
for animJoint in animJoints:
... | 20,584 |
def acq_max_single_seed(ac, gp, y_max, bounds):
"""
A function to find the maximum of the acquisition function using
the 'L-BFGS-B' method.
Input Parameters
----------
ac: The acquisition function object that return its point-wise value.
gp: A gaussian process fitted to the relevant... | 20,585 |
def futures_pig_rank(symbol: str = "外三元") -> pd.DataFrame:
"""
价格排行榜
https://zhujia.zhuwang.cc/lists.shtml
:param symbol: choice of {"外三元", "内三元", "土杂猪", "玉米", "豆粕"}
:type symbol: str
:return: 价格排行榜
:rtype: pandas.DataFrame
"""
if symbol == "外三元":
temp_df = pd.read_html("http... | 20,586 |
def psubl_T(T):
"""
EQ 6 / Sublimation Pressure
"""
T_star = 273.16
p_star = 611.657E-6
a = (-0.212144006E2, 0.273203819E2, -0.610598130E1)
b = ( 0.333333333E-2, 0.120666667E1, 0.170333333E1)
theta = T / T_star
sum = 0
for i in range(0, 3):
sum += a[i] * theta ** b[i]
... | 20,587 |
def map_key_values(f, dct):
"""
Like map_with_obj but expects a key value pair returned from f and uses it to form a new dict
:param f: Called with a key and value
:param dct:
:return:
"""
return from_pairs(values(map_with_obj(f, dct))) | 20,588 |
def plot_ppc(
ax,
length_plotters,
rows,
cols,
figsize,
animated,
obs_plotters,
pp_plotters,
posterior_predictive,
pp_sample_ix,
kind,
alpha,
linewidth,
mean,
xt_labelsize,
ax_labelsize,
jitter,
total_pp_samples,
legend,
markersize,
ani... | 20,589 |
def startGroup():
"""
StartGroup used at the start of a group operaction or secondary function.
"""
global stackFlag, errCode, networkSet, netSetStack, redoStack
redoStack = TStack()
netSetStack.push(networkSet)
stackFlag = False | 20,590 |
def wait_for_es(es_url: str, logger):
"""Wait for es to come up by polling."""
logger.info("Waiting for es...")
es = elasticsearch.Elasticsearch(hosts=[es_url])
while not es.ping():
time.sleep(0.5) | 20,591 |
def load_module(name):
"""Load the named module without registering it in ``sys.modules``.
Parameters
----------
name : string
Module name
Returns
-------
mod : module
Loaded module
"""
spec = importlib.util.find_spec(name)
mod = importlib.util.module_from_spec(spec)... | 20,592 |
def make_no_graph_input_fn(graph_data, args, treatments, outcomes, filter_test=False):
"""
A dataset w/ all the label processing, but no graph structure.
Used at evaluation and prediction time
"""
def input_fn():
vertex_dataset = tf.data.Dataset.from_tensor_slices(
({'vertex_in... | 20,593 |
def compute_gradient_penalty(D, real_samples, fake_samples):
"""Calculates the gradient penalty loss for WGAN GP"""
# Random weight term for interpolation between real and fake samples
alpha = torch.tensor(np.random.random((real_samples.size(0), 1, 1, 1,1)), dtype = real_samples.dtype, device = real_samples... | 20,594 |
def prune_min(t):
"""Prune the tree mutatively from the bottom up.
>>> t1 = Tree(6)
>>> prune_min(t1)
>>> t1
Tree(6)
>>> t2 = Tree(6, [Tree(3), Tree(4)])
>>> prune_min(t2)
>>> t2
Tree(6, [Tree(3)])
>>> t3 = Tree(6, [Tree(3, [Tree(1), Tree(2)]), Tree(5, [Tree(3), Tree(4)])])
... | 20,595 |
def _perform_aggregation(resource, pipeline, options):
"""
.. versionadded:: 0.7
"""
# TODO move most of this down to the Mongo layer?
# TODO experiment with cursor.batch_size as alternative pagination
# implementation
def parse_aggregation_stage(d, key, value):
for st_key, st_valu... | 20,596 |
def email_role(role, subject, html=None, plain=None):
"""Send an email to a user with a given address."""
if role.email is None:
log.info("Role [%r]: does not have email.", role)
return
try:
sender = "%s <%s>" % (settings.APP_TITLE, settings.MAIL_FROM)
subject = "[%s] %s" % ... | 20,597 |
def tab(num):
"""
Get tab indentation.
Parameters
----------
num : int
indentation depth
"""
return num * 4 * " " | 20,598 |
def merge_sort(lst):
"""Sorts the input list into ascending order."""
if len(lst) < 2:
return lst
half = len(lst) // 2
# This variant of merge sort uses O(N * log N) memory, since list slicing in Python 3 creates a copy.
return merge(merge_sort(lst[:half]), merge_sort(lst[half:])) | 20,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.