content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import List
def flatten(lst: List[List[object]]) -> List[object]:
"""
Flattens a list of lists by one level.
:param list lst: A list of lists.
"""
return [item for sublist in lst for item in sublist] | 3d6cd5be545b26666ce4a4695c7325cf1407d36e | 73,200 |
from typing import Optional
from typing import Sequence
def get_catalog_nodes(query_options: Optional[Sequence[pulumi.InputType['GetCatalogNodesQueryOptionArgs']]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetCatalogNodesResult:
"""
Use this data source to access i... | 5380c534a3cfc34cb778b7967d8d50bfa444d280 | 73,201 |
def wait(status, timeout=None, *, poll_rate="DEPRECATED"):
"""(Blocking) wait for the status object to complete
Parameters
----------
status: StatusBase
A Status object
timeout: Union[Number, None], optional
Amount of time in seconds to wait. None disables, such that wait() will
... | 3311714c7aee5cbbecf658bfa563826c363752e2 | 73,202 |
def get_all_objects_in_scene():
"""
Gets all the objects in the scene
:return: *list* with object names
"""
return [obj.name for obj in bpy.data.objects] | 777e129356a9434110dd20d2dfe9af51e79a1f87 | 73,203 |
from pathlib import Path
def get_tle_dir() -> Path:
"""Return the directory containing TLEs."""
tle_dir = get_data_dir() / "tle"
if not tle_dir.exists():
Path.mkdir(tle_dir)
return tle_dir | f38a0bbf905edebcb0f7fb1901fccd53637438ab | 73,204 |
import re
def find_md_links(md):
"""Returns dict of links in markdown:
'regular': [foo](some.url)
'footnotes': [foo][3]
[3]: some.url
"""
# https://stackoverflow.com/a/30738268/2755116
INLINE_LINK_RE = re.compile(r'\[([^\]]+)\]\(([^)]+)\)')
FOOTNOTE_LINK_TEXT_RE = re.compile(r'\[... | d630d22d571e774312516fc4005444087d23392f | 73,205 |
import struct
def _cgo_codegen(name, srcs, c_hdrs=[], deps=[], copts=[], linkopts=[],
go_tool=None, toolchain=None):
"""Generates glue codes for interop between C and Go
Args:
name: A unique name of the rule
srcs: list of Go source files.
Each of them must contain `import "C"`.
... | d9f3dc4d3464b0ad1d370ef98ebba38346973369 | 73,206 |
def col2im_manual_schedule(shape, kernel, stride, pad, dtype, output_H_W, polyhedral=True, attrs=None):
"""
Col2im operation with manual schedule.
Args:
shape (Union[list, tuple]): seven int numbers for the input's image size.
kernel (Union[list, tuple]): two int numbers for the sliding wi... | 49df3c6f4e52329366421059be6865c09efa04b4 | 73,207 |
import base64
def create_message(sender, to, subject, message_text):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
Returns:
An obje... | 49f2cda4511110eefe91bf424f7bba85c3a18a99 | 73,208 |
def ensure_request(view_func):
"""
Decorator that ensure request from typeform.
"""
@wraps(view_func)
def _wrapped_view_func(request, *args, **kwargs):
logger.info('Typeform request received')
if not _ensure_request(request):
return HttpResponse('')
else:
... | 6fa2d4e63e3adc837831e1d427eeef2f28641316 | 73,209 |
def timeave(ys):
"""
Function returns data averaged
:param ys: array with two dimensions
:return:
"""
y = []
for i in range(ys.shape[1]):
y.append(sum(ys[:,i])/ys.shape[0])
return np.array(y) | 7e937187eb94cd189a14a7d34ee6122efbf0948e | 73,210 |
import os
import multiprocessing
def multi_upload(client,
hdfs_path,
local_path,
multi_processes=5,
overwrite=False,
sync=True):
"""
Upload files to HDFS using multi process.
Args:
client(HDFSClient): instance of... | f6624d3f8a11cdac8043d53d1eb21825f780bd3d | 73,211 |
def dup_factor_list(f, K0):
"""Factor polynomials into irreducibles in `K[x]`. """
j, f = dup_terms_gcd(f, K0)
if not K0.has_CharacteristicZero:
coeff, factors = dup_gf_factor(f, K0)
elif K0.is_Algebraic:
coeff, factors = dup_ext_factor(f, K0)
else:
if not K0.is_Exact:
... | 93a306dab1a1ab0eaab2b7a67cc6867452771ba2 | 73,212 |
def get_roots(word):
"""
Returns list of root-words which are titles of dictionary articles containing the given word.
If the dictionary doesn't contain the given word the list containing word itself is returned.
:param word: russian word
:return: list of root-words
"""
"""
:param word:... | 951be8ae666c1669e9241e53c2a6e81faf953fbe | 73,213 |
def sex(return_expectations=None):
"""
Returns M, F or empty string if unknown or other
"""
return "sex", locals() | 4f461d76d96f6c0559d20693b28280436af1a594 | 73,214 |
def epoch_time(start_time, end_time):
"""
Computes the time for each epoch in minutes and seconds.
:param start_time: start of the epoch
:param end_time: end of the epoch
:return: time in minutes and seconds
"""
elapsed_time = end_time - start_time
elapsed_mins = int(elapsed_time / 60)
... | 8265cb78c26a96a83a1035c09a7dccb0edf8c4d0 | 73,215 |
def conversion_helper(val, conversion):
"""Apply conversion to val. Recursively apply conversion if `val`
#is a nested tuple/list structure."""
if not isinstance(val, (tuple, list)):
return conversion(val)
rtn = [conversion_helper(v, conversion) for v in val]
if isinstance(val, tuple):
... | 4381a4ac0f1d3e32cf22abd41ae224252fbe40fc | 73,216 |
def fibonaccinumber(n):
"""
>>fibonaccinumber(6)
1 1 2 3 5 8
>>fibonaccinumber(10)
1 1 2 3 5 8 13 21 34 55
"""
if n<0:
print("Incorrect input")
elif n==0:
return 0
elif n==1:
return 1
else:
n1 , n2 =1,1
count = 1
w... | c69d23d2603360cba6b5d5e600da1aa96dcfec60 | 73,217 |
import numpy
import copy
def get_uniform_colours_in_hsv_space(
num_colours, colour_to_exclude_rgb=None,
min_rgb_distance_from_colour=DEFAULT_MIN_RGB_DISTANCE):
"""Returns array of uniformly spaced colours in HSV space.
N = number of colours
:param num_colours: Number of colours.
:par... | 13a9995868a552411e3c255a6c3c2d1ecdaeaece | 73,218 |
def obtain_centroid(X_train, clustering_algorithm, categorical_cols, sc, n_clusters):
"""
Function to obtain the centroid of a group of data points.
It uses K-Prototypes or with K-Modes algorithm.
It returns the centroid/prototype point
for that data as well as the assigned clusters for each d... | 41809d604d593640ba0ba4a24ab54c4bd1e1ecc6 | 73,219 |
def play(pet) -> bool:
"""Return False if any of the stats is 0."""
if (not pet.hunger) or (not pet.thirst) or (not pet.energy) or (not pet.fitness) or (not pet.mental_health):
print("Oh no! Take better care of", pet.name, "next time!")
print("Thank you for playing!")
print(" - - - ")
... | 482b38868d402d40687ed0c7495a122c50783fe3 | 73,220 |
def expand_composites (properties):
""" Expand all composite properties in the set so that all components
are explicitly expressed.
"""
explicit_features = get_grist (properties)
result = []
# now expand composite features
for p in properties:
expanded = expand_composite (p)
... | 01ad6406277a163349390e8c8f3260b1363c6395 | 73,221 |
def all():
"""all() -> [ all toolbars ]"""
return _toolbars.values() | 216ebc5a20e9326ce08bf2422593471daf92b118 | 73,222 |
def base_prob(phred_score):
""" Returns the probabilty that a base is incorrect, given its
Phred score.
"""
prob = 10.0**(-float(phred_score)/10)
return prob | 8231019213204e65d577ea86d1e2e0e7352a3f70 | 73,223 |
import os
def datasource_config_path():
"""Return path to configuration info for datasources."""
path = test_path()
path = os.path.join(path, "datasources.conf")
return path | b18a15f8924724c7475513e0999dcdb3e93450f2 | 73,224 |
def create_hostname_from_ip(mgmt_ip, country_code):
"""
example country code: CH, UK
creates the switch hostname based on the mgmt IP and the country code
"""
try:
temp_ip_split = mgmt_ip.split(".")
hostname = \
f"SWI{country_code}{temp_ip_split[1].zfill(3)}{temp_ip_split... | a1b366a5b03f36f48e832e53f772482d5967b106 | 73,225 |
import os
import yaml
def load_config(config_file):
"""Load Config."""
if not USE_GOOGLE_API:
return {'google_api_key': ''}
if not os.path.isfile(config_file):
raise ValueError("Configuration file {0} not found.".format(config_file))
with open(config_file, 'r') as ymlfile:
... | 58ea9262d51e38bc10e894addb6d78d13892d5d7 | 73,226 |
import re
def need_format(line: str) -> bool:
"""
Return true if line as a title declaration followed by content
"""
return (
(
re.search("\t+e_\w*[-'\w]*\W*=", line) is not None
and re.search("\t+e_\w*[-'\w]*\W*=\W*{[\w\t]*\n", line) is None
and re.search("... | 61576aa02a745db8b0ce0c9c4c9a4d4589e8d842 | 73,227 |
def radec_to_eci(ra, dec):
"""
Convert from RA,Dec to ECI. The input ``ra`` and ``dec`` values can be 1-d
arrays of length N in which case the output ``ECI`` will be an array with
shape (N, 3). The N dimension can actually be any multidimensional shape.
:param ra: Right Ascension (degrees)
:pa... | c967443c057a426b9317fda992157e00a7b9f219 | 73,228 |
import argparse
def parse():
"""
Handles the arguments and options.
"""
parser = argparse.ArgumentParser(
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument(
"-w", "--what", dest="what",
help="REQUIRED - The absolute path to the folder containing the tests"... | ef1700cc5a3692fd5cd85d84cd24f37f859df7a7 | 73,229 |
import re
def format_float(value, width=np.get_printoptions()['precision']):
"""Return a float value with the specified width.
This function results in a more compact scientific notation where relevant.
"""
text = "{:.{width}g}".format(value, width=width)
return re.sub(r"e(-?)0*(\d+)", r"e\1\... | 36da161711ce435303dd35350d38c40627ac3740 | 73,230 |
from typing import Union
def is_bool(value: Union[str, bool]) -> bool:
"""validate whether the value is boolean"""
return (value in true_list + false_list) or (isinstance(value, bool)) | 92b7c34278a1df7be4a095201e1e565d2dd664da | 73,231 |
import functools
def creator_only_query(func):
"""
If given user is not a creator, restrict access.
"""
@functools.wraps(func)
def wrapper(update: Update, context: CallbackContext):
query = update.callback_query
if not is_creator(context.bot, update.effective_chat.id, query.from_u... | 4a7e9fa4850798362c4614450f85ba4586ed9a3b | 73,232 |
import logging
def if_action(hass, config):
""" Wraps action method with state based condition. """
entity_id = config.get(CONF_ENTITY_ID)
state = config.get(CONF_STATE)
if entity_id is None or state is None:
logging.getLogger(__name__).error(
"Missing if-condition configuration k... | ad39b6143f7ac0a40db21ff14005a93116230241 | 73,233 |
def builderFor(action, hypervisor=None, template=None, service=None):
"""
This decorator is used to supply metadata for functions which is then used to find suitable methods
during building just by these properties.
:param action: Name of the generic step/action (see planner) that this function impleme... | 1dddfd8dc5dbc87e5a018fc4fb144bef8a8f98e3 | 73,234 |
from typing import Dict
from typing import List
from typing import Union
from pathlib import Path
import json
def compile_standard(
input_data: Dict,
base_path: str = None,
allow_paths: List = None,
output_dir: str = None,
overwrite: bool = False,
solc_binary: Union[str, Path] = None,
solc... | 8f50e7fe42a54d1005469128632e3a374aeccf76 | 73,235 |
def undeployed_value_only_calculator(repository, undeployed_value_tuple, deployed_value_tuple):
"""
Just return the undeployed value as the value.
This calculator can be used when there will be no deployed value.
"""
return undeployed_value_tuple[2] | 58294274d37b4c7bb9cad21bb01260986cb0d6ae | 73,236 |
from matplotlib import pyplot
from . import det as calc
from . import ppndf
import numpy
def det(negatives, positives, npoints=2000, min_far=-8, **kwargs):
"""Plots Detection Error Trade-off (DET) curve as defined in the paper:
Martin, A., Doddington, G., Kamm, T., Ordowski, M., & Przybocki, M. (1997).
The DET... | 044acf8803ee2106c48aaaf611bc281c7200d505 | 73,237 |
import re
def _remove_inner_punctuation(string):
"""
If two strings are separated by & or -, remove
the symbol and join the strings.
Example
-------
>>> _remove_inner_punctuation("This is AT&T here")
'This is ATT here'
>>> _remove_inner_punctuation("A T & T")
'A T T'
"""
... | 4ca3e7f91e35dba2e0a34f1dfd935e004623875e | 73,238 |
def makeLighter(color: colors.Color) -> colors.Color:
"""
Takes a color and returns a slightly lighter version of
the original color.
:param Color color: the color you want to lighten
:return: the new, lighter color
:rtype: Color
:raises TypeError: if ``color`` is not a :py:class:`~.colors.... | 8b715ff6da82378e8c2078ddf9cd0bfd483c39a4 | 73,239 |
def _get_pgpass(params):
"""Find a password for the given connection parameters.
The params parameter MUST be a dict!"""
def _matchparam(name, value, defval=""):
"""Match .pgpass parameter with a value."""
if value == '*':
return True
else:
return value == s... | 67ea73722be8b5843da1f1edbf80ad796b4279a3 | 73,240 |
import webbrowser
import sys
def setup_and_run_hass(config_dir, args, top_process=False):
"""Setup HASS and run.
Block until stopped. Will assume it is running in a subprocess unless
top_process is set to true.
"""
if args.demo_mode:
config = {
'frontend': {},
'dem... | 90c5a71c70e3d35c1b8454740e96c74bec61adb2 | 73,241 |
def tsdf_via_vox(depth, scene_info, vox_map, is_flipped):
"""
Convert a vox into tsdf format
:param depth: the depth info
:param scene_info: the scene info, including voxel resolution and image viewpoint
:param vox_map: the non-empty voxel
:param is_flipped: whether to use the flipped signal
... | ae960bcb7238a342b4ed46ef692cbd4cd028d7e0 | 73,242 |
def _scrape_main_synonym_section(left_content):
"""Scrapes the main/default synonym section for a word.
If there is no pos listed, use the one listed for the word
"""
synonym_header = left_content.find('div',
{'class' : 'synonyms_list'})
synonym_labels = synony... | 21063c652e733e6e6f6ca32bdf0d343bdbbb80f4 | 73,243 |
def get_cluster(*, cluster_name: str, region: str, vpc_id: str) -> EC2Cluster:
"""
Get an existing EC2 cluster.
"""
cluster = get_clusters(
cluster_names=[cluster_name],
region=region,
vpc_id=vpc_id)
return cluster[0] | 79d7bdabc8ce265febe18b99ad7f1154af275ffb | 73,244 |
def make_web_driver():
"""制造web driver"""
# 原理:web driver定义耗时较多,缓存web driver(在同一个session下)可以提高速度,但是内存占用会缓慢提升
global driver_cache
if driver_cache is None:
print('Load web driver')
if run_with_firefox:
# selenium Firefox
options = webdriver.FirefoxOptions()
... | 349218346b08c32095edee363689ee0f077a4244 | 73,245 |
import typing
def lydia_fail() -> typing.RouteReturn:
"""Route the user is sent back by Lydia after cancelling payment."""
flask.flash(_("Paiement annulé"), "danger")
return utils.ensure_safe_redirect("payments.pay", next=None) | 552e04bf8c324d2ea292eb2664a5706cad3e30e3 | 73,246 |
def function(*args, **kwargs):
"""Wrapper for tf.function with TF Agents-specific customizations.
Example:
```python
@common.function()
def my_eager_code(x, y):
...
```
Args:
*args: Args for tf.function.
**kwargs: Keyword args for tf.function.
Returns:
A tf.function wrapper.
"""
... | bbc12b679353b006fabbfaf69b030c90921602fa | 73,247 |
import zipfile
def get_templates(templates_zip_archive):
"""
Unzip the Summary File Templates archive file; generate and
return a dictionary mapping 'geo' and seq # to corresponding
file column name lists.
"""
templates = dict()
with zipfile.ZipFile(templates_zip_archive) as z:
# L... | c3861389577d230983ea78e6d1e7ddc809da8031 | 73,248 |
def get_candidate_objects(output, img_size, classes, anchors=None):
""" convert network output to bounding box predictions """
threshold = 0.2
iou_threshold = 0.4
boxes, probs = parse_yolo_output(output, img_size, len(classes), anchors)
filter_mat_probs = (probs >= threshold)
filter_mat_boxes ... | 66aeae6db2fbd57155731e0c1d6443eb447ae079 | 73,249 |
import re
def generateHashtags(randomTests):
"""Generates a hashtag from a level 1+ category name using Regular Expressions and other rules.
Arguments:
randomTests {Dictionary} -- A test category and hashtag (level 1+) categories
Returns:
Dictionary -- The input dictionary with added has... | 96478924f04706b88cb367d5aca334225771788b | 73,250 |
def check_url(url):
"""Checks whether `url` is a valid URL.
"""
parsed = urlparse(url)
return bool(parsed.netloc) and bool(parsed.scheme) | 17c8f546df43f107f84a855f78abcfc2c008d38f | 73,251 |
def _cache_getter(key):
""" Generates a function that will get the cached data of a key """
def f():
data = memcache.get(key)
if data == none_sentinel_string:
return None
return data
return f | 9acf6c4b412bbcad0b08d381326480a3ed2178d6 | 73,252 |
def synthetic_data(w, b, num_examples):
"""生成 y = Xw + b + 噪声。"""
X = flow.randn(num_examples, w.shape[0])
y = flow.matmul(X, w.reshape(w.shape[0], -1)) + b
y = y.reshape(-1)
y += flow.tensor(np.random.normal(0, 0.01, y.shape[0]).astype(np.float32))
return X, flow.reshape(y, (-1, 1)) | 5e3e69c7c23843c0c4b232dcd157d0c2c3b6f72e | 73,253 |
def NewCMessage(full_message_name):
"""Creates a new C++ protocol message by its name."""
return _net_proto2___python.NewCMessage(full_message_name) | 2456c6cdd604660c8a0ea36e4988a2bb5ed2acdd | 73,254 |
def get_description(khoros_object, identifier=None, category_details=None):
"""This function retrieves the description for a given category.
.. versionadded:: 2.1.0
:param khoros_object: The core :py:class:`khoros.Khoros` object
:type khoros_object: class[khoros.Khoros]
:param identifier: The Cate... | b0b28c60fc133ca0982ee63cfd2da55f199375bf | 73,255 |
def get_longest_element(focus):
"""
cycles thru the status_results dictionary in the indicated key or field list and finds the
longest piece of text in it
:param focus: the key or field in value list that is being searched for longest value
:return: the longest value
"""
return (len(max(focu... | d00c02d3d02ebd371f16ef16fd2e7daa0ead47ac | 73,256 |
from pathlib import Path
def get_facemap_root_data_dir() -> list:
"""
It is recommended that all paths in DataJoint Elements stored as relative
paths, with respect to some user-configured "root" director(y/ies). The
root(s) may vary between data modalities and user machines
get_fm_root_data_dir() ... | c02903b9828495e1d5533e91367ddbc7ec14f656 | 73,257 |
import torch
def caption_image_beam_search(encoder, decoder, image_path, word_map, beam_size):
"""
Reads an image and captions it with beam search.
:param encoder: encoder model
:param decoder: decoder model
:param image_path: path to image
:param word_map: word map
:param beam_size: numb... | 2f08ac5289714c4de51a6ff5a4031bf29a9d4d98 | 73,258 |
def _NodeConfigResolver(single_node_fn, all_nodes_fn, node_uuids, opts):
"""Calculate node addresses using configuration.
Note that strings in node_uuids are treated as node names if the UUID is not
found in the configuration.
"""
accept_offline_node = (opts is rpc_defs.ACCEPT_OFFLINE_NODE)
assert accept... | 925931bc0f80b8af48c7d7e5a5bd52587378d103 | 73,259 |
def get_num_classes(labels):
"""Get total number of classes.
Arguments:
labels {list} -- label values.
"""
num_classes = max(labels) + 1
missing_classes = []
for l in range(num_classes):
if l not in labels:
missing_classes.append(l)
if len(missing_classes):
... | 4573bbf81fab0396454167287e86492e0ee7cd48 | 73,260 |
def detail_url(address_id):
"""Return the detail url for user address"""
return reverse('user:address-detail', args=[address_id]) | 047d96aa4f878021ad912bce91b33f5fe1a3acff | 73,261 |
def get_empty_concat_loss(sentence, inv):
"""Returns list of empty concatenation loss matrices."""
empty_concat_loss = []
for i in range(1, len(sentence)):
prev_diphone = sentence[i - 1]
this_diphone = sentence[i]
loss_mat = np.zeros((len(inv[prev_diphone]), len(inv[this_diphone])))
... | 7f86ff28a63a5ed6cb3ca933c26db1dc51553b04 | 73,262 |
from typing import List
def existing_ids() -> List[str]:
"""
Return a list of existing post ids so that we don't send duplicate
notifications for posts the user has already seen.
"""
existing_ids = CURSOR.execute(
f"""
SELECT id FROM posts;
"""
).fetchall()
# Unpack th... | fd810b3e104408be038089b0da4d9c5ff17da53b | 73,263 |
from typing import List
def context_table_to_dicts(table: Table, orient='index', use_nan=True) -> List[dict]:
"""
Converts a context table in a feature file into a list of dictionaries
:param use_nan:
:param table: The context.table from a scenario
:param orient: orient for df to_dict
... | 4a535a6ee20eefd971a67257b106edd969ee7100 | 73,264 |
def store_edges(edge_data):
"""Store edges in a dict where the keys are the edge times"""
time_edge_map = {}
for i in range(len(edge_data)):
current_time = edge_data[i,0]
if not current_time in time_edge_map:
time_edge_map[current_time] = []
time_edge_map[current_time].ap... | 885bb4f4e6480904a09bb7afe7d85053643a3f1a | 73,265 |
def group_list(auth=None, **kwargs):
"""
List groups
CLI Example:
.. code-block:: bash
salt '*' keystoneng.group_list
salt '*' keystoneng.group_list domain_id=b62e76fbeeff4e8fb77073f591cf211e
"""
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return ... | bfdb1563fcc843e0db577888a866d3dcbd044132 | 73,266 |
def get_yaml_basepath():
"""Returns the full path of the directory in which builtins are located."""
if _handler_dir is None:
set_builtins_dir(DEFAULT_DIR)
return _handler_dir | 4b824c8bb040aea3db085c85adbbbe715df12c19 | 73,267 |
def filter_linker_flavour(args):
"""Remove `-flavor gnu`."""
new_args = []
ignore = False
for arg in args:
if ignore:
ignore = False # ignore this argument
else:
if arg == '-flavor':
ignore = True
else:
new_args.append(a... | f37aac3c7b14f25350c945c5258d851402292330 | 73,268 |
def str_sha1(str):
"""Calculates the SHA1 hex digest of a unicode string."""
return bytes_sha1(bytes(str, encoding='latin1', errors='replace')) | dc986b4129f082458321f0e614df87751648a2df | 73,269 |
import csv
def convert_connections_csv_to_list_of_dics(connectionsDB):
"""
"""
connections_list_of_dics=[]
with open(connectionsDB, 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"',skipinitialspace=True)
for row in reader:
this_line_dic={}
# print(row)
# p... | 5cdc1d40878ec2d3eb4ff8128102713cd5d76602 | 73,270 |
from enum import Enum
from typing import List
def declare(*, group: Enum, version: int, event_types: List[int]) -> callable:
"""
Declare class builder for a particular MOF group version and event types
:param group: Event trace group
:param version: version of mof class
:param event_types: list of... | f1aa9421f4a12efa5d34ae7d04b85fd2a2347a9f | 73,271 |
from unittest.mock import Mock
import requests
def timeout_se(*args, **kwargs):
"""A function to mock requests timeouts over multiple responses.
You must set REQUEST_COUNT global variable to 0 and TIMEOUTS global variable to desired
number before this function is be called.
Returns:
Mock: A ... | f1abea240335301ebb059dc07e180f289cf65fbe | 73,272 |
def get_argument(arguments, index=None, key=None):
"""
Return the indicated argument.
If `arguments` is a collection, then the indicated argument value is
looked up by index or key (depending on the collection). If
`arguments` is just a single, atomic value, then that value is
returned. Other... | 3d0a0932cf4ca7fc2de5e233dbf4cc890a4422b4 | 73,273 |
def norm_p(z):
"""
Caclulate (approx) the p-value for a standard normal distribution
Parameters:
z (ee.Image): image containing z-scores
Returns:
ee.Image: image containing p-values
"""
return ee.Image.constant(1).subtract(z.multiply(-1.65451).exp().add(1).pow(-1)) | 2d066983daa6eee5d2b7a1fa0235399e37f31a26 | 73,274 |
import random
def random_string(length, charset):
"""
Return a random string of the given length from the
given character set.
:param int length: The length of string to return
:param str charset: A string of characters to choose from
:returns: A random string
:rtype: str
"""
n = ... | 1370f86a2e696ba6030b719ec8e32631f1865e01 | 73,275 |
import requests
import json
def infer_batch(seqs, host, model, ver=None):
"""Returns 3d then 8d
None goes to default url
This url : 'http://131.215.2.28:8501/v1/models/dspace_embed/versions/6:predict'
host = '131.215.2.28:8501'
ver = 6
model = 'models/dspace_embed'
"""
seq_arr = pre... | 94e8239d12a1bef852d19c7d390ea3709eaf9c26 | 73,276 |
import traceback
def dynamic_content_by_key(context, key):
"""DynamicContent content handlers do not require any Block to be stored
in the database, but can be fired directly. A BlockType is registered
as usual, but this method, unlike block_by_key, doesn't look for a Block,
but renders the ContentHa... | a96645080f9c3dc789110c32eb7957fef4edbdaf | 73,277 |
def preproccessing(locator, total_demand, buildings_heating_demand, buildings_cooling_demand,
weather_file, district_heating_network, district_cooling_network):
"""
This function aims at preprocessing all data for the optimization.
:param locator: path to locator function
:param tota... | 76beb45f02013de20c48518d82cbda2a76308ac1 | 73,278 |
import os
def dstat(infile):
"""
Wrapper around os.stat(), which returns the output as a dict instead of an object
"""
fsx = os.stat(infile)
sout = {
'dev': fsx.st_dev,
'ino': fsx.st_ino,
'mode': fsx.st_mode,
'nlink': fsx.st_nlink,
... | 36779bd505a154fd63cb19724f99652d4e2457ef | 73,279 |
from pkg_resources import resource_stream
import logging
import os
import yaml
def load_or_default(name):
"""
Load the YAML configuration file from the current directory or use default. The approach is threefold and shown in order:
1. check if env 'WAVY_CONFIG' is set or specified in .env
2. check if... | 39f42b58772d2f66a2651a3736592140829a0bee | 73,280 |
def XYZ_to_sd_Jakob2019(
XYZ,
cmfs=STANDARD_OBSERVER_CMFS['CIE 1931 2 Degree Standard Observer']
.copy().align(DEFAULT_SPECTRAL_SHAPE_JAKOB_2019),
illuminant=sd_ones(DEFAULT_SPECTRAL_SHAPE_JAKOB_2019),
optimisation_kwargs=None,
additional_data=False):
"""
Recovers... | d7c4a1fda23fc659cce6e004610ddaa96580e7a7 | 73,281 |
def primepi(n):
""" Return the value of the prime counting function pi(n) = the number
of prime numbers less than or equal to n. The number n need not
necessarily be an integer.
Examples
========
>>> from sympy import primepi
>>> primepi(25)
9
See A... | 90534c01bbaa600ff9689110911e01fc43f1ac8a | 73,282 |
def delete_item(category_name, item_id):
"""
Performs the actual item delete
"""
user = get_user(login_session['email'])
item = session.query(Item).filter_by(id=item_id).one()
if item.user_id != user.id:
flash("You cannot delete other users' items")
return redirect(url_for('show_... | 7b073d0a1a61c8619683f8761a74a3cab89b3947 | 73,283 |
def get_variables(x):
"""
Gets all variables in a formula.
"""
v = {}
VariablesVisitor(v)(x)
return [val for _, val in sorted(v.items(), key=lambda x: x[0])] | f2a62951f4feb2c8061f775e7482e3b2ebb933ea | 73,284 |
def scalar(dtype=dtypes.float32):
""" Convenience function that defines a scalar (array of size 1). """
return ndarray([1], dtype) | 3a20d5cf141b8f26bf21f84a9abd724caf5dac94 | 73,285 |
import sys
import os
def _GetPythonPath(paths):
"""Return the set of Python library paths to use."""
return sys.path + [
# Add the Portage installation inside the chroot to the Python path.
# This ensures that scripts that need to import portage can do so.
os.path.join(constants.SOURCE_ROOT, 'chroot',... | edd1fc2f0b6a93373e691cbab6af2c252f0058d2 | 73,286 |
def fill_sym_mat(mat):
"""Make a upper diagonal or lower diagonal matrix symmetric
Parameters
----------
mat : 2d array
the matrix we want symmetric
"""
return mat + mat.T - np.diag(mat.diagonal()) | 3c1d536f585e787b27c74255afb11d1bfe09fd05 | 73,287 |
def psql_settings_from_config(config, section_name):
""" load psql connection settings from config object """
conf = config[section_name]
psql = SectionKey(section_name)
return PsqlSettings(host=conf[psql.key('host')].strip(),
port=conf[psql.key('port')].strip(),
... | f7eede68c9a370d4ca852d6f4896d51f933eedae | 73,288 |
def get_workspace_dir():
"""Returns the workspace directory to use for tiflash.
Returns:
str: workspace to use for tiflash (fullpath)
"""
# Uses user's home directory
workspace = DEFAULT_WORKSPACE
return workspace | 14c83f40dc508d93209877ba28b72826c0efbdf3 | 73,289 |
def xlate(vname):
"""Translate"""
if vname in ["ws_10m_nw", "ws_40m_nw", "ws_120m_nw"]:
return vname + "ht"
return vname | 8759031dcc47f5b34128f6b621f837e92e6c9b23 | 73,290 |
def reverse_spline(tck):
"""Reverse the direction of a spline (parametric or nonparametric),
without changing the range of the t (parametric) or x (nonparametric) values."""
t, c, k = tck
rt = t[-1] - t[::-1]
rc = c[::-1]
return rt, rc, k | 77c239fa8360657ed4ad4c1eb8d18493c97a84a1 | 73,291 |
import inspect
def is_param_method(obj, has_deps=False):
"""Whether the object is a method on a parameterized object.
Args:
obj: Object to check
has_deps (boolean, optional): Check for dependencies
Whether to also check whether the method has been annotated
with param.depend... | 55896f9e2e6f58ef12ec4f83ece318e797c4f7eb | 73,292 |
import importlib
import pkgutil
def list_submodules(package, recursive=True):
"""
Recursively (optional) find the submodules from a module or directory
Args:
package (str or module): Root module or directory to load submodules from
recursive (bool, optional): Recursively find. Defaults to... | a5d69affc4cd19bd3e7c67c2d006c224bbafe80d | 73,293 |
def trainee_already_marked_training_date(trainee, training_date):
"""Check whether trainee already marked the given training date.
If trainee already has training day info it means he/she answered marked the given date.
Args:
trainee(models.Trainee): trainee instance to check whether already marke... | 138006be069201923017e0277ffec6a7c06080b4 | 73,294 |
import operator
def empirical_direct_ntk_fn(f):
"""Computes the ntk without batching for inputs x1 and x2.
The Neural Tangent Kernel is defined as J(X_1)^T J(X_2) where J is the
jacobian df/dparams.
Args:
f: The function whose NTK we are computing. f should have the signature
f(params, inputs) an... | 0dc3acffa6ff1f32870520e70acd991cd2d83a0d | 73,295 |
def permission_list():
"""权限列表"""
if request.method == 'GET':
permissions = Permission.query.all()
return render_template('permissions.html', permissions=permissions) | 94128ed17bb3806ffcbc09779ca7b2aac1530d5e | 73,296 |
import os
import sys
def __validate_directory__(paths):
"""
Validates the given path, it first check if it's a directory,
then validates if contains a specific identifier.
:param paths: dictionary with path and path identifier
"""
for path, file in paths.items():
if not os.path.isdir(... | 0986099a31c76992187bdcfca8e9d26605483806 | 73,297 |
def serving_input_receiver_fn():
"""
Build serving inputs
"""
input_ids = tf.placeholder(dtype= tf.int32, shape=[None, 128], name='input_ids')
input_mask = tf.placeholder(dtype= tf.int32, shape=[None, 128], name='input_mask')
segment_ids = tf.placeholder(dtype= tf.int32, shape=[None, 128], name=... | 6d4dc551f446d49a695e46dd9909c17ba6a793de | 73,298 |
import collections
def _load_features(root):
"""Returns {name: Feature}"""
out = collections.OrderedDict()
for elem in root.findall('feature'):
name = elem.attrib['name']
api = elem.attrib['api']
number = tuple([int(x) for x in elem.attrib['number'].split('.')])
requires = ... | 37bc0e9c6c0d827f020a6667679936274b5f87e0 | 73,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.