content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def hello_who(who='World'):
"""
Функция печатает приветствие в красивом формате
**********
Hello {who}!
##########
:param who: кого мы приветствуем, по умолчанию World
:return: None
"""
sBeg = '*' * 10
sEnd = '#' * 10
print( sBeg + f'\nHello {who}!\n' + sEnd ) | 5,310,900 |
def energy_distance(x, y, **kwargs):
"""
energy_distance(x, y, *, exponent=1)
Computes the estimator for the energy distance of the
random vectors corresponding to :math:`x` and :math:`y`.
Both random vectors must have the same number of components.
Parameters
----------
x: array_like
... | 5,310,901 |
def bids_scan_file_walker(dataset=".", include_types=None, warn_no_files=False):
"""
Traverse a BIDS dataset and provide a generator interface
to the imaging files contained within.
:author: @chrisfilo
https://github.com/preprocessed-connectomes-project/quality-assessment-prot\
ocol/blob/master/sc... | 5,310,902 |
def train_step(net, optim, batch):
"""
one training step
"""
(loss, net), grads = pax.value_and_grad(loss_fn, has_aux=True)(net, batch)
net, optim = opax.apply_gradients(net, optim, grads)
net = net.replace(rnn=net.gru_pruner(net.rnn))
net = net.replace(o1=net.o1_pruner(net.o1))
net = ne... | 5,310,903 |
def insert_dim(arg, pos=-1):
"""insert 1 fake dimension inside the arg before pos'th dimension"""
shape = [i for i in arg.shape]
shape.insert(pos, 1)
return arg.reshape(shape) | 5,310,904 |
def encode_captions(captions):
"""
Convert all captions' words into indices.
Input:
- captions: dictionary containing image names and list of corresponding captions
Returns:
- word_to_idx: dictionary of indices for all words
- idx_to_word: list containing all words
- vocab_size... | 5,310,905 |
def post_dataset(conn, dataset_name, project_id=None, description=None,
across_groups=True):
"""Create a new dataset.
Parameters
----------
conn : ``omero.gateway.BlitzGateway`` object
OMERO connection.
dataset_name : str
Name of the Dataset being created.
proje... | 5,310,906 |
def design():
"""
Projection of a Latin Hypercube design into two dimensions. (Deprecated - needs update)
"""
fig = plt.figure(figsize=figsize(.6, aspect=1))
ratio = 5
gs = plt.GridSpec(ratio + 1, ratio + 1)
ax_j = fig.add_subplot(gs[1:, :-1])
ax_x = fig.add_subplot(gs[0, :-1], sharex=... | 5,310,907 |
def load_stop_words(stop_word_file):
"""
Utility function to load stop words from a file and return as a list of words
@param stop_word_file Path and file name of a file containing stop words.
@return list A list of stop words.
"""
stop_words = []
for line in open(stop_word_file):
if... | 5,310,908 |
def run_gcloud_command(cmd, project_id):
"""Execute a gcloud command and return the output.
Args:
cmd (list): a list of strings representing the gcloud command to run
project_id (string): append `--project {project_id}` to the command. Most
commands should specify the project ID, for those that don't... | 5,310,909 |
def convert_gmx_flow_1_to_2(flow: GmxFlow, width: float) -> GmxFlow:
"""Convert flow data from 'GMX_FLOW_1' to 'GMX_FLOW_2'.
This changes the field 'M' to represent the mass density instead of
the total mass in the bin. Thus we also require the width of the system,
in order to calculate the bin volume.... | 5,310,910 |
def gen_onenine():
"""
ONENINE -> '1' .. '9'
"""
yield chr(random.randint(0x31, 0x39)) | 5,310,911 |
def NullFlagHandler(feature):
""" This handler always returns False """
return False | 5,310,912 |
def add_image(axes, path):
"""Add the image given by ``path`` to the plot ``axes``.
:param axes: represents an individual plot
:param path: path to the image
:type axes: matplotlib.pyplot.Axes
:type path: str
:return: mpimg.AxesImage
"""
try:
img = Image.open(path)
retur... | 5,310,913 |
def abandonAffaire_reopenParentAffaire_view(request):
"""
Abandon child_affaire, reopen parent child_affaire and reattribute numbers to parent child_affaire.
"""
settings = request.registry.settings
etape_abandon_id = settings['affaire_etape_abandon_id']
etape_reactivation_id = settings['affair... | 5,310,914 |
def get_dataset(
*,
batch_size,
eval_batch_size,
num_shards,
dtype_str='float32', # pylint: disable=unused-argument
shuffle_seed=0,
rng=None,
dataset_configs=None,
dataset_service_address: Optional[str] = None): # pylint: disable=unused-argument
"""Returns generators for the Wiki... | 5,310,915 |
def test_primitive_color_mix(scene_hex_sphere_, generate=False):
"""Test the primitive_color_mix property."""
geometry = scene_hex_sphere_.geometry[0]
geometry.material = fresnel.material.Material(solid=1.0,
color=fresnel.color.linear(
... | 5,310,916 |
def find_paths(orbital_graph, starting_node, ending_node, visited_nodes=None):
"""Recursively find all the paths from starting_node to ending_node in the graph
Paths are returned as a list of paths, where paths are a list of nodes.
An empty list means that no valid path exists.
"""
path = copy.copy(... | 5,310,917 |
def rp_from_filename(filename, split_char=ELT_SPLIT,
rp_regex=REGEX_RP):
"""Gets the Rp (proton radius?) label from the file name, returns None if
not found.
:param filename: the name of the file to parse
:param split_char: the character which separates filename elements
:param ... | 5,310,918 |
def check_duplication(request):
"""API check_duplication"""
check_type = request.POST.get('check_type')
name = request.POST.get('username')
if check_type == 'id':
min_limit = settings.ID_MIN_LENGTH
max_limit = settings.ID_MAX_LENGTH
else:
min_limit = settings.NICKNAME_MIN_LE... | 5,310,919 |
def _merge_numeric_stats(
left, right,
feature_name):
"""Merge two partial numeric statistics and return the merged statistics."""
# Check if the types from the two partial statistics are not compatible.
# If so, raise an error.
if (left.type is not None and right.type is not None and
left.type !=... | 5,310,920 |
def get_pod_names(client, namespace, name):
"""Get pod names from k8s.
"""
core_api = k8s_client.CoreV1Api(client)
resp = core_api.list_namespaced_pod(
namespace, label_selector=to_selector({TF_JOB_NAME_LABEL: name}))
logging.info("list_namespaced_pod: %s", str(resp))
pod_names = []
for pod in resp.it... | 5,310,921 |
def main() -> None:
""" The Good Stuff """
args = get_args()
files = args.files
num = args.number
line_num = 0
for file in files:
for line_num, line in enumerate(file):
out_str = ''
if num:
out_str += f'{line_num + 1:6d}\t'
out_str +... | 5,310,922 |
def calculate_drawdown(input_series: pd.Series, is_returns: bool = False) -> pd.Series:
"""Calculate the drawdown (MDD) of historical series. Note that the calculation is done
on cumulative returns (or prices). The definition of drawdown is
DD = (current value - rolling maximum) / rolling maximum
... | 5,310,923 |
def search_traversal(**kwargs):
"""Search Traversal in Database"""
db_inst = app.config['ARANGO_CONN']
db_inst.get_database()
graph = db_inst.get_graph(kwargs.get('graph_name'))
try:
traversal_results = graph.traverse(
start_vertex=kwargs.get('start_vertex'),
directi... | 5,310,924 |
def find_matching_nodes(search_for, search_in, matches=[]):
"""
Search Vertex tree 'search_in' for the first isomorphic occurance of the
Vertex tree search_for
Return a list of [(x,y)...] for node in search_for (x) matched with
a pair (y) from search in, such as the two graphs preserve their ... | 5,310,925 |
def getStrategicManagementBodies(project):
"""Returns the strategic management bodies for a given project."""
return getManagementBodies(project, MANAGEMENT_BODY_CATEGORY_STRATEGIC) | 5,310,926 |
def _create_bigm(model, md):
"""
Create the big-M transformation explicitly
"""
branches = dict(md.elements(element_type='branch'))
model.BIGM = dict()
for branch_name, branch in branches.items():
branch = branches[branch_name]
tau = 1.0
shift = 0.0
if branch['b... | 5,310,927 |
def clip(x, min_value, max_value):
"""Element-wise value clipping."""
if max_value is not None and max_value < min_value:
max_value = min_value
if max_value is None:
max_value = np.inf
min_value = _to_tensor(min_value, x.dtype.base_dtype)
max_value = _to_tensor(max_value, x.dtype.bas... | 5,310,928 |
def dotnet_restore(path=""):
"""Restore the dotnet solution from the root of the project via dotnet restore """
if path:
cmd.append(path)
info("Restoring nuget packages (via %s" % " ".join(cmd))
result = subprocess.run(cmd)
status = result.returncode
if status != 0:
error("Sol... | 5,310,929 |
def SendMessage(service, user_id, message):
"""Send an email message.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
message: Message to be sent.
Returns:
Se... | 5,310,930 |
def cummul(iterator):
"""Cumulative p.
.. seealso:: :func:`itertools.accumulate` and :func:`np.cumsum`
"""
yield from itertools.accumulate(iterator, operator.mul) | 5,310,931 |
def getPolicy(lunaToken, policyName, network, account_key=''):
""" Gets a specific policy on a given network in JSON format """
session.headers.update({'Luna-Token': lunaToken})
if network == 'staging':
get_policy_endpoint = "/imaging/v2/network/staging/policies/" + policyName
else:
get... | 5,310,932 |
def clean_str(string):
# Remove punctuation
"""
Tokenization/string cleaning for all datasets except for SST.
Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py
"""
string = re.sub(r"[^\u4e00-\u9fff]", " ", string)
string = re.sub(r"\s{2,}", " ", string)
... | 5,310,933 |
def extract_ops(page: PageObject) -> List[Tuple]:
"""extract all operators"""
content = page.getContents()
if not isinstance(content, ContentStream):
content = ContentStream(content, page.pdf)
return list(content.operations) | 5,310,934 |
def pointnet_to_cleanpoint(data_dir, samples, labels):
""" read pointnet dataset point cloud and transfer it to pcpnet dataset format """
shape_names_dir = os.path.join(data_dir, 'shape_names.txt')
with open(shape_names_dir) as f:
label_names = f.readlines()
# save in the pcp data set f... | 5,310,935 |
def make_reg_ex_mm(seq, mm):
"""Make regular expression for mis-matches."""
if mm > 2:
raise NotImplementedError("At most 2 mismatches allowed!")
seq = seq.upper()
yield make_reg_ex(seq)
for i in range(1, mm + 1):
# Missing first/last i bases at very start/end of sequence
for... | 5,310,936 |
def get_project_info(project_name, dnac_jwt_token):
"""
This function will retrieve all templates associated with the project with the name {project_name}
:param project_name: project name
:param dnac_jwt_token: DNA C token
:return: list of all templates, including names and ids
"""
url = DN... | 5,310,937 |
def main(args):
"""This functions annotates a PDF document using the Document AI API"""
if not args.project_id:
_, project_id = google.auth.default()
args.project_id = project_id
parent = f"projects/{args.project_id}/locations/{args.multi_region_location}"
client = DocumentProcessorServi... | 5,310,938 |
def generate(tag_cls):
"""
generate generates documentation for given wrapper tag class
:param tag_cls: wrapper_tag class
:return:
"""
doc = textwrap.dedent(tag_cls.__doc__ or '').strip()
arguments_doc = ""
for ag, arguments in six.iteritems(ArgumentsGroup.group_arguments(tag_cls)):
... | 5,310,939 |
def load_data(database_filepath):
"""Load data from SQLite into memory.
"""
engine = create_engine(f'sqlite:///{database_filepath}')
df = pd.read_sql_table("Messages", engine)
X = df["message"]
Y = df.drop(["message", "id", "original", "genre"], axis=1)
return X, Y, Y.columns | 5,310,940 |
def column_thresh(C, eps):
"""
cleans out C, removes all values below eps.
otherwise
"""
n1 = C.shape[1]
for i in range(n1):
if la.norm(C[:,i], 2) < eps: # norm here defaults to 2 norm for vector
C[:,i]=0
else:
C[:,i]=C[:,i]-eps*C[:,i]/la.norm(C[:,i],2)
... | 5,310,941 |
def getJobStatementButton(self):
"""Triggered when job is chosen for inspection in the Job Costs tab
Returns materials associated with chosen job, shown in projectInfoTree.
The jobs total cost is shown in the totalCostBox"""
workingProject = selectedProject.get()
chosenJob... | 5,310,942 |
def distance_between_points(p1, p2):
""" Function that computes the euclidean distance between to points.
Returns:
float: distance value
"""
return ((p1['x']-p2['x']) * (p1['x'] - p2['x']) + (p1['y']-p2['y']) * (p1['y']-p2['y'])) ** 0.5 | 5,310,943 |
def sigmoid(z):
"""
Compute the sigmoid of z
Arguments:
z -- A scalar or numpy array of any size.
Return:
s -- sigmoid(z)
"""
#(≈ 1 line of code)
# s = ...
# YOUR CODE STARTS HERE
s = 1/(1+np.exp(-z))
# YOUR CODE ENDS HERE
return s | 5,310,944 |
def _decompose_expressions(circ: Circuit) -> Tuple[Circuit, bool]:
"""Rewrite a circuit command-wise, decomposing ClassicalExpBox."""
bit_heap = BitHeap()
reg_heap = RegHeap()
# add already used heap variables to heaps
for b in circ.bits:
if b.reg_name == _TEMP_BIT_NAME:
bit_heap... | 5,310,945 |
def export_request_sample(postman, index):
"""
Prints a sample body in the Postman.
"""
api = postman.get_api(index)
print(api.get_request_body_sample()) | 5,310,946 |
def get(ctx: click.Context, experiment_id: str):
"""Get information about an experiment."""
client = ctx.obj['client']
output_format = ctx.obj['output']
response = client.get_experiment(experiment_id)
_display_experiment(response, output_format) | 5,310,947 |
def get_trailing_app_metrics(args):
"""
Returns trailing app_name metrics for a given time period.
Args:
args: dict The parsed args from the request
args.limit: number The max number of apps to return
args.time_range: one of "week", "month", "all_time"
Returns:
[{ name: ... | 5,310,948 |
def get_all_related_objects(opts):
"""
Django 1.8 changed meta api, see
https://docs.djangoproject.com/en/1.8/ref/models/meta/#migrating-old-meta-api
https://code.djangoproject.com/ticket/12663
https://github.com/django/django/pull/3848
:param opts: Options instance
:return: list of relatio... | 5,310,949 |
async def fetch_dialog(
customer_id: str,
dialog_id: str,
db: motor_asyncio.AsyncIOMotorClient = fastapi.Depends(mongodb.get_database),
) -> utils.OrjsonResponse:
"""
Fetch a dialog.
- **customer_id**: customer id of the dialog to return
- **dialog_id**: dialog id of the dialog to return
... | 5,310,950 |
def create_topology(workspace, folder_basename):
"""Creates topology in the edit workspace and adds rules to the TFL Lines"""
arcpy.env.workspace = workspace
cluster_tol = 0.0001
topology = workspace + os.sep + 'TFL_Line_Topology'
feature_class = workspace + os.sep + folder_basename + '_Line'
t... | 5,310,951 |
def _get(pseudodict, key, single=True):
"""Helper method for getting values from "multi-dict"s"""
matches = [item[1] for item in pseudodict if item[0] == key]
if single:
return matches[0]
else:
return matches | 5,310,952 |
def test_use_pseudos(sto_calc_inps_or_builder, create_otfg_group):
"""Test the `use_psudos_from_family` function"""
from aiida_castep.calculations.tools import use_pseudos_from_family
create_otfg_group(['QC5'], 'QC5')
use_pseudos_from_family(sto_calc_inps_or_builder, 'QC5')
assert all([
pseu... | 5,310,953 |
def write_json(des: Path):
"""
Write a JSON file.
:param des: destination file path
"""
with des.open('w') as f:
json.dump(SAMPLE_TEXT, f) | 5,310,954 |
def test_locationparamtype__invalid(value: str) -> None:
"""
Invalid values should faile
"""
parser = click_utils.LocationParamType()
with pytest.raises(click.BadParameter):
parser.convert(value, None, None) | 5,310,955 |
def guess_domain(tree, blacklist=_DOMAIN_BLACKLIST, get_domain=get_domain):
""" Return most common domain not in a black list. """
domains = [get_domain(href) for href in tree.xpath('//*/@href')]
domains = [d for d in domains if d and d not in blacklist]
if not domains:
return '' # unknown
... | 5,310,956 |
def get_course_last_published(course_key):
"""
We use the CourseStructure table to get when this course was last
published.
Args:
course_key: a CourseKey
Returns: The datetime the course was last published at, converted into
text, or None, if there's no record of the last time this ... | 5,310,957 |
def test_execute_search_anonymous(elasticsearch):
"""execute_search should execute an Elasticsearch search with an anonymous user"""
user = AnonymousUser()
query = {"a": "query"}
elasticsearch.conn.search.return_value = {"hits": {"total": 10}}
assert (
execute_search(user=user, query=query)... | 5,310,958 |
def rgb_to_hex(rgb_triplet):
"""
Convert a 3-tuple of integers, suitable for use in an ``rgb()``
color triplet, to a normalized hexadecimal value for that color.
Examples:
>>> rgb_to_hex((255, 255, 255))
'#ffffff'
>>> rgb_to_hex((0, 0, 128))
'#000080'
"""
return '#%02x%02x%02x... | 5,310,959 |
def dec2stringTime(decim, precision=5):
""" Convert a decimale time or coordinate to a formatted string.
Parameters
----------
decim : int, float
precision : int
Returns
-------
String formatted HH:MM:SS.SSSSS
"""
return hms2stringTime(*dec2sex(decim), precision=precision) | 5,310,960 |
def test_check_if_ggd_recipe_internet_free():
"""
test the check_if_ggd_recipe function in pkg-info in a internet free context
(pkg-info)
"""
## Check show-env in an internet free context
pytest_disable_socket()
### Check that there is no interent
assert utils.check_for_interne... | 5,310,961 |
def getCartShape(dimension, communicator=None):
"""
Returns :samp:`getCartShapeForSize(dimension, communicator.Get_size())`.
:type dimension: int
:param dimension: Spatial dimension for returned cartesian layout.
:type communicator: :obj:`mpi4py.MPI.Comm`
:param communicator: If :samp:`None... | 5,310,962 |
def runtimes():
"""
Creates a table of ranking the algorithms by average runtimes
"""
results= pickle.load(open(results_path, 'rb'))
oversampling_bibtex= oversampling_bib_lookup()
results= results[results['sampler'] != 'NoSMOTE']
results_agg= results.groupby('sampler').aggrega... | 5,310,963 |
def gumbel_log_survival(x):
"""Returns log P(g > x) for a standard Gumbel g.
log P(g > x) = log(1 - P(g < x)) = log(1 - exp(-exp(-x))). The implementation
is more numerically robust than a naive implementation of that formula.
Args:
x: The cutoff Gumbel value.
"""
# Adapted from
# https://gist.githu... | 5,310,964 |
def platform_is(requested_platform: str) -> bool:
"""
Compare requested platform with current platform.
Common platforms:
- Win / Windows
- Mac / macOS / Darwin
- Linux
- Unix (Mac, SunOS, BSD unix's)
- *nix / posix (Not Windows)
:return: True if current platform matches requested p... | 5,310,965 |
def write_flagfile(flagfile_fn, flags):
"""Write a flags dictionary to disk in gflags format.
Args:
flagfile_fn (str): Path to the flagfile.
flags (dict[str, _]): Flags and their corresponding values.
"""
with open(flagfile_fn, "w") as f:
for flag, value in flags.items():
... | 5,310,966 |
def segment_mp_worker(ytid, ts_start, ts_end, data_dir, ffmpeg_path,
ffprobe_path, **ffmpeg_cfg):
"""
Pool worker that downloads video segments.o
Wraps around the download_yt_video function to catch errors and log them.
Args:
ytid: Youtube ID string
... | 5,310,967 |
def prepare_bert(content, max_len, bow_vocab_size=1000, vectorizer=None, ctx=mx.cpu()):
"""
Utility function to take text content (e.g. list of document strings), a maximum sequence
length and vocabulary size, returning a data_train object that can be used
by a SeqBowEstimator object for the call to fit... | 5,310,968 |
def create_file(filename, filesize_mb=1):
"""
Create file for testing purposes.
Parameters
----------
filename: str
The filename
filesize_mb: numeric
The file size in Mb.
"""
with open(filename, "wb") as f:
f.seek(1024 * 1024 * filesize_mb)
f.write(b"0") | 5,310,969 |
def requires_qe_access(func):
"""
Decorator that signals that the test uses the online API:
* determines if the test should be skipped by checking environment
variables.
* if the test is not skipped, it reads `QE_TOKEN` and `QE_URL` from
`Qconfig.py` or from environment v... | 5,310,970 |
def to_homogeneous(t, is_point):
"""Makes a homogeneous space tensor given a tensor with ultimate coordinates.
Args:
t: Tensor with shape [..., K], where t is a tensor of points in
K-dimensional space.
is_point: Boolean. True for points, false for directions
Returns:
Tensor with shape... | 5,310,971 |
def name_from_archive(archive_path):
""" Name From Archive """
archive = zipfile.ZipFile(archive_path, allowZip64=True)
xml_data = archive.read("manifest.xml")
elem = etree.fromstring(xml_data)
return elem.get("uuid") | 5,310,972 |
def datedfile(filename,date):
""" select file based on observation date and latest version
Parameters
----------
filename: text file name pattern, including "yyyymmdd_vnn" place holder for date and version
date: yyyymmdd of observation
Returns: file name
"""
filelist = sorted(glob.gl... | 5,310,973 |
def p_break_statement(p):
"""break_statement : BREAK STMT_TERMINATOR
""" | 5,310,974 |
def random_user(n):
"""generate a random user id of size n"""
chars = []
for i in range(n):
chars.append(random.choice(string.ascii_lowercase))
return ''.join(chars) | 5,310,975 |
def playerStandings():
"""Returns a list of the players and their win records, sorted by wins.
The first entry in the list should be the player in first place,
or a player tied for first place if there is currently a tie.
Returns:
A list of tuples, each of which contains (id, name, wins, matches... | 5,310,976 |
def load_statistics(
input_path: Text) -> statistics_pb2.DatasetFeatureStatisticsList:
"""Loads data statistics proto from file.
Args:
input_path: Data statistics file path. The file should be a one-record
TFRecord file or a plain file containing the statistics proto in Proto
Text Format.
Re... | 5,310,977 |
def get_counter(request):
"""
Get the Counter object associated with a request.
Raise AjaxError if session is invalid or counter is not found.
"""
if "counter" not in request.session:
raise AjaxError(RET_UNAUTHORIZED, _(u"Not logged in."))
counter_id = request.session["counter"]
tr... | 5,310,978 |
def test_list_id_max_length_4_nistxml_sv_iv_list_id_max_length_5_3(mode, save_output, output_format):
"""
Type list/ID is restricted by facet maxLength with value 10.
"""
assert_bindings(
schema="nistData/list/ID/Schema+Instance/NISTSchema-SV-IV-list-ID-maxLength-5.xsd",
instance="nistDa... | 5,310,979 |
def _get_parse_input(parse_args, args_in, dict_in):
"""Return default for parse_input.
This is to decide if context_parser should run or not.
To make it easy on an API consumer, default behavior is ALWAYS to run
parser UNLESS dict_in initializes context and there is no args_in.
If dict_in specifi... | 5,310,980 |
def creds_list(ctx, pin):
"""
List credentials.
"""
creds = _init_credman(ctx, pin)
for (rp_id, _, user_id, user_name) in _gen_creds(creds):
click.echo(_format_cred(rp_id, user_id, user_name)) | 5,310,981 |
def get_haiku(
text: str,
inflect_p,
pronounce_dict: Dict,
syllable_dict: Dict,
emoticons_list: List,
guess_syl_method: str,
) -> str:
"""Attempt to turn a string into a haiku.
Returns haiku if able, otherwise returns empty string.
Inspired by https://github.com/tomwardill/python-ha... | 5,310,982 |
def get_parser():
"""
Creates and returns the argument parser for jExam
Returns:
``argparse.ArgumentParser``: the argument parser for jExam
"""
parser = argparse.ArgumentParser()
parser.add_argument("master", type=str, help="Path to exam master notebook")
parser.add_argument("re... | 5,310,983 |
def is_average_pooling(layer):
"""Checks if layer is an average-pooling layer."""
AVERAGEPOOLING_LAYERS = (
keras_layers.AveragePooling1D,
keras_layers.AveragePooling2D,
keras_layers.AveragePooling3D,
keras_layers.GlobalAveragePooling1D,
keras_layers.GlobalAveragePooling2... | 5,310,984 |
def find_source_filename(source_name, dir_path):
"""Find the filename matching the source/module name
in the specified path. For example searching for "queue"
might return "queue.py" or "queue.pyc"
"""
source_filenames = [
os.path.join(dir_path, source_name + ext) for
ext in ... | 5,310,985 |
def MergeDictsRecursively(original_dict, merging_dict):
"""
Merges two dictionaries by iterating over both of their keys and returning the merge
of each dict contained within both dictionaries.
The outer dict is also merged.
ATTENTION: The :param(merging_dict) is modified in the process!
:para... | 5,310,986 |
def eq_assoc(u, v, eq=core.eq, n=None):
""" Goal for associative equality
>>> from logpy import run, var, fact
>>> from logpy.assoccomm import eq_assoc as eq
>>> fact(commutative, 'add') # declare that 'add' is commutative
>>> fact(associative, 'add') # declare that 'add' is associative
... | 5,310,987 |
def test_hillshade_shape(hillshade_arr):
"""A 3-dimensional array should return a ValueError."""
# Test 3-dimensional array
hillshade_arr_3d = hillshade_arr[np.newaxis, :]
# Check ValueError
with pytest.raises(
ValueError, match="Input array should be two-dimensional"
):
es.hil... | 5,310,988 |
def debugAll(isEnabled):
"""Toggle all API debugging, which overrides the str() functionality of
various API classes to print more useful information."""
if isEnabled:
for apiClass in overrideFunctions:
apiClass.__str__ = overrideFunctions[apiClass]
else:
for apiClass in apiFunctions:
apiClass.__str__ = a... | 5,310,989 |
def printer(func=None, **options):
""" Decorator used to print whatever text is returned in the caller
function.
When a list or a tuple are returned, then the contents are iterated
and printed.
Options:
dedent - whether or not to dedent the text (default: True)
"""... | 5,310,990 |
def stdoutlogger(name, level=logging.INFO):
"""
Return a standard python logger with a stdout handler attached and using a prefix
format that will make logging consistent between scripts.
"""
logger = logging.getLogger(name)
logger.setLevel(level)
# send messages to sys.stderr
... | 5,310,991 |
def send_email_summary(interval, settings):
"""
Send an email summary of the snapshot
:param interval: The type of interval that was snapped
:param settings: The settings module
:return: None
"""
# Make sure we should even send this email, based on the timing interval
if interval in set... | 5,310,992 |
def parse_args():
"""
Parse command line arguments for CLI
:return: namespace containing the arguments passed.
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'--login',
type=str,
required=True,
help="Full path to file containing JSON with DB login cr... | 5,310,993 |
def cmd_prune_repo(name):
"""Prune untagged images from Repo"""
try:
imageIds = ecr.list_images(repositoryName=name, maxResults=50, filter={'tagStatus': 'UNTAGGED'})
if imageIds:
result = ecr.batch_delete_image(repositoryName=name, imageIds=imageIds['imageIds'])
if res... | 5,310,994 |
def strio():
"""
This was difficult to get right in doctests when porting to Python 3.
"""
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
return StringIO() | 5,310,995 |
def getJamLengthMeters(detID):
"""getJamLengthMeters(string) -> double
Returns the jam length in meters within the last simulation step.
"""
return _getUniversal(tc.JAM_LENGTH_METERS, detID) | 5,310,996 |
async def grant_access(hub, ctx, name, resource_group, access, duration, **kwargs):
"""
.. versionadded:: 4.0.0
Grants access to a disk.
:param name: The name of the disk to grant access to.
:param resource_group: The resource group name assigned to the disk.
:param access: Possible values i... | 5,310,997 |
def get_device_uptime(status: dict, last_uptime: str) -> str:
"""Return device uptime string, tolerate up to 5 seconds deviation."""
delta_uptime = utcnow() - timedelta(seconds=status["uptime"])
if (
not last_uptime
or abs((delta_uptime - datetime.fromisoformat(last_uptime)).total_seconds()... | 5,310,998 |
def int_deg(angle):
"""Return an angle object with only integer degrees."""
dms = str(angle).split(':')
return ephem.degrees(dms[0]) | 5,310,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.