content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def df_to_annotations(df, output_dir):
"""Converts and saves pandas DataFrame annotation info (see aggregate_annotations_as_df)
in output_dir.
The DataFrame should have columns: "imageName", "className", "attributeGroupName",
"attributeName", "type", "error", "locked", "visible", trackingId", "probabili... | 5,307,900 |
def build_embedding_matrix(
embedding_model: gensim.models.keyedvectors.KeyedVectors,
embedding_dim,
vocab) -> np.ndarray:
"""
Builds the embedding matrix.
Parameters
----------
embedding_model : gensim.models.keyedvectors.KeyedVectors
Embedding model.
embedding_... | 5,307,901 |
def calls_fixture(hass):
"""Track calls to a mock service."""
return async_mock_service(hass, "test", "automation") | 5,307,902 |
def Run():
"""Server main"""
try:
if not _gInitialized:
raise RuntimeError("The server is not initialized")
SoapHandler.Setup()
if gValidatorList is not None:
for validator in gValidatorList:
SoapHandler.RegisterValidator(validator)
globa... | 5,307,903 |
def load_yaml(yaml_file, template_params=None, return_config_str=False):
"""
load_yaml_str will take in a string that has the correct yaml formatting
and generate classes or types according to the configuration in the yaml.
Example:
params = {'SOURCE_PATH': '/tmp/source', 'AGE': 30}
obj... | 5,307,904 |
def bprp_to_bv(bprp):
"""
Calculate a B-V color from a G_BP - G_RP color.
Poor fit at large and small bp-rp. (Especially bad for low-mass stars).
"""
p = [-0.0334115504231673, 0.3754200727545447, -1.4691791496336342,
2.209433533403669, -0.39641699367657274, 0.14752490961352926]
retur... | 5,307,905 |
def have_flirt():
""" Return True if we can call flirt without error
Relies on the fact that flirt produces text on stdout when called with no
arguments
"""
p = Popen('flirt', stdout=PIPE, stderr=PIPE, shell=True)
stdout, stderr = p.communicate()
return stdout != '' | 5,307,906 |
def main(ctx):
"""HDG is a network tool suite
Here a better description
"""
pass | 5,307,907 |
def effective_request_host(request):
"""Return the effective request-host, as defined by RFC 2965."""
return eff_request_host(request)[1] | 5,307,908 |
def get_nginx_generation_value(host) -> int:
"""
Send request to /api/api_version/nginx and parse the response.
:param host:
:return: 'generation' value
"""
resp = ast.literal_eval(requests.get(f"{host}/api/{NGINX_API_VERSION}/nginx").text)
return resp['generation'] | 5,307,909 |
def cds(cat,xcat='vizier:I/350/gaiaedr3',maxdist=2,colRA='RA',colDec='DEC',
selection='best',epoch=None,colpmRA='pmra',colpmDec='pmdec',
savefilename=None,gaia_all_columns=False):
"""
NAME:
cds
PURPOSE:
Cross-match against a catalog in the CDS archive using the CDS cross-matchi... | 5,307,910 |
def get_job_by_id(job_id): # noqa: E501
"""Find my job by Id
For valid response try integer Ids with value >= 1 and <= 1000.\\ \\ Other values will generated exceptions # noqa: E501
:param job_id: Id of job to be fetched
:type job_id: str
:rtype: Job
"""
job = q.fetch_job... | 5,307,911 |
def delete_client(client_id):
"""
Delete a client
---
tags:
- clients
parameters:
- name: client_id
in: path
type: integer
example: 1
operationId: deleteClient
produces:
- application/json
schemes: ['http', 'https']
responses:
200:
... | 5,307,912 |
def CYKParserTable(gramm, word):
"""Evaluates CYK parser table
:param gramm: grammar
:type gramm: CNF
:param word: word to be parsed
:type word: string
:returns: the CYK table
:rtype: list of lists of symbols"""
pass | 5,307,913 |
def test_return_date_with_year_keyword(my_photo, year, expected):
"""Test src\\photonomist\\photo.Photo> get_date
"""
assert my_photo.get_date(year=year) == expected | 5,307,914 |
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up sensors for a Nexia device."""
coordinator: NexiaDataUpdateCoordinator = hass.data[DOMAIN][config_entry.entry_id]
nexia_home = coordinator.nexia_home
en... | 5,307,915 |
def test_bioprocesses():
"""Smoke test to see if bioprocesses analysis works."""
bp.analyze(eval_file) | 5,307,916 |
def get_textregion_avg_line_distance(text_region: PageXMLTextRegion,
avg_type: str = "macro") -> np.float:
"""Returns the median distance between subsequent lines in a
textregion object. If the textregion contains smaller textregions, it only
considers line distances bet... | 5,307,917 |
def dns_lookup(qname, **kwargs):
"""Function to perform DNS lookup queries.
Args:
qname (str) : The Domain name that you would like perform a DNS lookup for.
**ns (str/list): The nameserver to use when querying the provided domain.
If no... | 5,307,918 |
def L0Path(CD_J = None,
CD_J_AS = None,
lam_1 = None,
lams_2 = None,
active_set = None,
active_interaction_set = None,
beta = None,
zeta = None,
delta = None,
alpha = None,
B = None,
BT_B = None,
... | 5,307,919 |
def kras_Rotate_Shift_old(krasFile, krasPos, angle):
"""For x1 KRAS rotate by a specific angle around z axes and shit to given x,y pos - Works for 4B only CYF based"""
kras = mda.Universe(krasFile)
farCOM = kras.select_atoms("resname CYF and name SC1").center_of_mass()
farCOM_z = 5.455 # Set all KRAS F... | 5,307,920 |
def get_hostname_prefix():
"""Returns the hostname prefix of a running Endpoints service.
The prefix is the portion of the hostname that comes before the API name.
For example, if a non-default version and a non-default service are in use,
the returned result would be '{VERSION}-dot-{SERVICE}-'.
Returns:
... | 5,307,921 |
def get_aperture_fluxes(data, ap_radius):
"""
Make an aperture for every pixel, and do aperture photometry at all of them.
:param data: A 2D numpy array with the data to do photometry on
:ap_radius: The radius of the aperture to use.
"""
# Get all coordinates
nx, ny = data.shape
xx, yy... | 5,307,922 |
def _trash_ratio(text):
"""
Return ratio of non-common symbols.
"""
trash_count = 0
for char in text:
if char in list(u'.\'"+-!?()[]{}*+@#$%^&_=|/\\'):
trash_count += 1
return trash_count / float(len(text)) | 5,307,923 |
def compute_graph_nn_2(xyz, k_nn1, k_nn2):
"""compute simulteneoulsy 2 knn structures
only saves target for knn2
assumption : knn1 <= knn2"""
assert k_nn1 <= k_nn2, "knn1 must be smaller than knn2"
num_ver = xyz.shape[0]
#compute nearest neighbors
graph = dict([("is_nn", True)])
nn = Nea... | 5,307,924 |
def index_of_spaces(text):
"""
Given text, return all space indices
@param text is the string to analyze
@returns a list of integers representing the indices
"""
res = []
for i in range(0, len(text)):
if text[i] == ' ':
res.append(i)
return res | 5,307,925 |
def strip_checkin(tweet):
""" Strip useless information from tweets as a checkin.
:tweet: @todo
:returns: @todo
"""
place = tweet['place']
return {
'created_at': tweet['created_at'].isoformat(),
'retweeted': tweet['retweeted'],
'retweet_count': tweet['retweet_count'],
... | 5,307,926 |
def update_params(potential):
"""
Assign potential dependent simulation's parameters.
Parameters
----------
potential : :class:`sarkas.potentials.core.Potential`
Class handling potential form.
"""
potential.screening_lengths = array(potential.screening_lengths)
potential.screen... | 5,307,927 |
def decrypt_story():
"""Load the file store.txt, and decript it"""
return CiphertextMessage(get_story_string()).decrypt_message() | 5,307,928 |
def aaa_get_kvm_launch_url(in_cookie, in_ipv4):
""" Auto-generated UCS XML API Method. """
method = ExternalMethod("AaaGetKVMLaunchUrl")
method.in_cookie = in_cookie
method.in_ipv4 = in_ipv4
xml_request = method.to_xml(option=WriteXmlOption.DIRTY)
return xml_request | 5,307,929 |
def _do_nothing() -> None:
"""
Does nothing
"""
frame = inspect.stack()[1][0]
info = inspect.getframeinfo(frame)
line = str(info.lineno)
line = f"{bcolors.FAIL}{bcolors.BOLD}{line}{bcolors.ENDC}"
print("this does nothing")
print(f"change that at line {line}")
print("Exiting...")
... | 5,307,930 |
def get_default_hparams():
""" Return default hyper-parameters """
params_dict = {
# Experiment Params:
'is_training': True, # train mode (relevant only for accelerated LSTM mode)
'data_set': 'cat', # datasets to train on
'epochs': 50, # how many times to go over the full trai... | 5,307,931 |
def _get_mf_picks(info, int_order, ext_order, ignore_ref=False, verbose=None):
"""Pick types for Maxwell filtering."""
# Check for T1/T2 mag types
mag_inds_T1T2 = _get_T1T2_mag_inds(info)
if len(mag_inds_T1T2) > 0:
warn('%d T1/T2 magnetometer channel types found. If using SSS, it is '
... | 5,307,932 |
def bbcMicro_partPhonemeCount(pronunc):
"""Returns the number of 'part phonemes' (at least that's what I'm calling them) for the BBC Micro phonemes in pronunc. The *SPEAK command cannot take more than 117 part-phonemes at a time before saying "Line too long", and in some cases it takes less than that (I'm not sure... | 5,307,933 |
def disable(node):
"""Disable <node>'s obm"""
client.node.disable_obm(node) | 5,307,934 |
def build_MLP(X, y, layers=(50, 25, 15), dropout=0.1, activation='relu',
out_act='softmax'):
"""Utility function for building a Multi-layer perceptron.
Args:
- X: numpy array, input to the model.
- y: numpy array, target of the model.
- layers: tuple of ints, number of hid... | 5,307,935 |
def idc(funcname):
"""获取所属机房逻辑"""
try:
custom_args = handle(custom_param_file,"custom_args")
return custom_args[funcname]
except Exception as e:
print "[error]:",e
return None | 5,307,936 |
def format_bundle(bundle):
"""
Converts a bundle object into a push-ready bundle by
changing list values of 'customResourceDefinitions',
'clusterServiceVersions', and 'packages' into stringified yaml literals.
This format is required by the Marketplace backend.
:param bundle: A bundle object
... | 5,307,937 |
def es_client(
host: Text,
port: int = 9200,
url_prefix: Optional[Text] = None,
username: Optional[Text] = None,
password: Optional[Text] = None,
timeout: int = 180) -> elasticsearch.client.Elasticsearch:
""" Elasticsearch client """
connection = {
"host"... | 5,307,938 |
def transform(
dataset_reader,
data_dir,
output_dir,
splits,
only_classes,
only_images,
limit_examples,
class_examples,
overrides,
debug,
):
"""
Prepares dataset for ingestion.
Converts the dataset into different (one per split) TFRecords files.
"""
tf.loggin... | 5,307,939 |
def collect_type_path():
"""
收集不同任务的权重路径名
"""
all_weights_path = os.listdir(directory.MODEL_DIR)
weights_path_list = []
for weight_path in all_weights_path:
method = weight_path.split('_')[0] # 分开训练还是联合训练
task_name = weight_path.split('_')[1] # 训练的任务:区域/类型
if method... | 5,307,940 |
def insert_at_midpoint(item, iterable):
"""
Inserts an item at the index of the midpoint of a list
Returns that list with the item inserted
"""
midpoint = int(len(iterable) / 2)
iterable.insert(midpoint, item)
return iterable | 5,307,941 |
def upgrade(sql_connection, version=None):
"""
Upgrade the database's current migration level
:param sql_connection: sqlalchemy connection string
:param version: version to upgrade (defaults to latest)
:retval version number
"""
db_version(sql_connection) # Ensure db is under migration con... | 5,307,942 |
def unwrap_if_necessary(graph_node: PerceptionGraphNode) -> UnwrappedPerceptionGraphNode:
"""
Some nodes might be wrapped in tuples together with IDs to prevent them
from being compared equal and collapsed in perception graphs.
This method removes that wrapping.
"""
if isinstance(graph_node, tup... | 5,307,943 |
def test_columns_have_value_accessor(new_col_val):
"""Ensure resulting column has ``.value`` accessor to raw data, irrespective of type of input.
The test won't be needed once https://github.com/astropy/astropy/pull/10962 is in astropy
release and Lightkurve requires the corresponding astropy release (5.0)... | 5,307,944 |
def func(p, data):
"""
Calculate z = (x/maj)**2 + (y/min)**2
Note that z = 1 is an ellipse
"""
x0, y0, major, minor, pa = p
x, y = data
pa = radians(pa)
sinP = sin(-pa)
cosP = cos(-pa)
xt = x - x0
yt = y - y0
xr = xt * cosP - yt * sinP
yr = xt * sinP + yt * cosP
re... | 5,307,945 |
def urlEncode(s):
"""
Returns the encoded version of the given string, safe for using as a URL.
"""
return string.join(map(lambda c: _urlEncode[c], list(s)), '') | 5,307,946 |
def euclideanDistance(data_points, query_instance):
"""
Calculate euclidean distance
:param data_points: data points of a given dataset
:param query_instance: instance of a dataset for which the distance matrix will be computed for
:return: distance value
"""
return np.sqrt(((data_points -... | 5,307,947 |
def test_default_response_index_view(dummy_request):
"""
test home view
"""
from ..views.default import index_view
response = index_view(dummy_request)
assert len(response) == 0
assert type(response) == dict | 5,307,948 |
def _move_jackknife_sample_id_to_value(
slice_key: slicer.SliceKeyType, sample: metric_types.MetricsDict
) -> Tuple[slicer.SliceKeyType, metric_types.MetricsDict]:
"""Moves the jackknife sample ID from the key to value.
Args:
slice_key: The slice key which contains the sample_id.
sample: The per-sample... | 5,307,949 |
def dfanet(classes=19, **kwargs):
"""
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
return xceptionAx3(classes, **kwargs) | 5,307,950 |
def experiment_fn(run_config: RunConfig, params: HParams):
"""The experiment function, provided to learn_runner.
:param run_config:
:param params:
:return:
"""
run_config = run_config.replace(save_checkpoints_steps=params.min_eval_frequency)
estimator = tf.estimator.Estimator(
mod... | 5,307,951 |
def _check_antonymy(antonym_library: Dict[str, List[str]],
attr_value1: 'AttributeValue',
attr_value2: 'AttributeValue') -> Dict[str, str]:
"""
Check if there are any shared antonyms within the two values
Parameters
----------
antonym_library
set of a... | 5,307,952 |
async def test_form_cannot_connect(hass: HomeAssistant) -> None:
"""Test we handle cannot connect error."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch(
"custom_components.plum_ecomax.config_flow.EcomaxTcpConnec... | 5,307,953 |
def innerip(funcname):
"""获取内网IP逻辑"""
inner_ip = get_ip_address('eth0')
return inner_ip | 5,307,954 |
def create_single_choice_question(text, choices, topic_id=None, scenario_id=None):
"""
Create a single choice question for either a topic *or* a scenario.
Parameters
----------
text : str
Body of the question.
choices : list
List of question choices.
It must be a list of... | 5,307,955 |
def render_cmdhelp_border(term: Terminal) -> str:
"""Render border around cmdhelp box"""
return render_border(
start_x=const.CMDHELP_X,
start_y=const.CMDHELP_Y,
height=const.CMDHELP_HEIGHT,
width=const.CMDHELP_WIDTH,
title=" Help ",
term=term,
) | 5,307,956 |
def run_inference(opts):
"""Run the model on KITTI"""
network_params = {"height": 320, "width": 640, "is_training": False}
dataset_params = {
"height": 320,
"width": 640,
"data_path": opts.data_path,
"data_list_file": opts.data_list_file,
}
dataset = KITTILoader(datas... | 5,307,957 |
def drop_child_cases(pcts, keep_child_entitlements=True):
"""
Drop all child cases from a PCTS extract (as indicated by them
having a parent case listed).
Parameters
==========
pcts: pandas.DataFrame
A PCTS extract of the shape returned by subset_pcts.
keep_child_entitl... | 5,307,958 |
def reopen_gap(decanonicalized: BlockNumber, base_gaps: ChainGaps) -> ChainGaps:
"""
Add a new gap, for a header that was decanonicalized.
"""
current_gaps, tip_child = base_gaps
if tip_child <= decanonicalized:
return base_gaps
new_raw_gaps = current_gaps + ((decanonicalized, decanoni... | 5,307,959 |
def is_std_wstring(type_):
"""
Returns True, if type represents C++ `std::wstring`, False otherwise.
"""
if utils.is_str(type_):
return type_ in wstring_equivalences
else:
type_ = remove_alias(type_)
type_ = remove_reference(type_)
type_ = remove_cv(type_)
r... | 5,307,960 |
def alternating_havel_hakimi_graph(aseq, bseq, create_using=None):
"""Returns a bipartite graph from two given degree sequences using
an alternating Havel-Hakimi style construction.
Nodes from the set A are connected to nodes in the set B by
connecting the highest degree nodes in set A to alternatively... | 5,307,961 |
def write_conformers(mol_input, mol_reference, conf_file):
"""
Generate conformer and calculate rmsd wrt reference
"""
top_rmsd = -1
conformer_generator = conformer.ConformerGenerator()
conformer_generator.settings.superimpose_conformers_onto_reference = True
conformers = conformer_generator... | 5,307,962 |
def get_stdout():
"""Return the redirected stdout in the current context."""
return _get_context().get(REDIRECTING, {}).get('stdout') | 5,307,963 |
def test_medicationdispense_1(base_settings):
"""No. 1 tests collection for MedicationDispense.
Test File: medicationdispense0317.json
"""
filename = base_settings["unittest_data_dir"] / "medicationdispense0317.json"
inst = medicationdispense.MedicationDispense.parse_file(
filename, content_... | 5,307,964 |
def draw_triangle(ax, x1, y1, x2, y2, x3, y3, _dim, _angle, color):
"""Wrapper for drawing triangle; called like `draw_triangle(ax, *coords, None, None, color)`"""
ax.add_patch(
Polygon(
xy=[(x1, y1), (x2, y2), (x3, y3)],
closed=True,
facecolor=color,
edge... | 5,307,965 |
def _get_ner_tags_and_mask(current_instance: Instance,
input_field_to_attack: str,
ignore_tokens: List[str]):
"""
Used for the NER task. Sets the num_ignore tokens, saves the original predicted tag and a 0/1
mask in the position of the tags
"""
#... | 5,307,966 |
def get_employees(filepath):
""" takes a Toolbox csv filepath, retrieves it and exports as dataframe
"""
import pandas as pd
if not filepath:
print("Please provide a Toolbox filepath to 'employees.csv'")
return
try:
df =pd.read_csv(filepath, usecols=['employeeID','mail',... | 5,307,967 |
def normalize_spec(value: t.Any) -> "TypeSpec":
"""normalize tensor spec"""
if not _isinstance_wrapper(value, TENSOR_CLASS_NAMES):
return value
if _isinstance_wrapper(value, "RaggedTensor"):
return tf.RaggedTensorSpec.from_value(value)
if _isinstance_wrapper(value, "SparseTensor"):
... | 5,307,968 |
def get_cost(state):
"""Calculates cost/fitness for the solution/route."""
distance = 0
for i in range(len(state)):
from_city = state[i]
to_city = None
if i+1 < len(state):
to_city = state[i+1]
else:
to_city = state[0]
distance ... | 5,307,969 |
def fit_decision_tree(printscore=False):
"""
This function fits sklearn's decision tree classifier
on the college dataset and returns the model
The data values are first scaled using MinMaxScaler
and then split into train and test sets before using for fitting ML model
"""
dataset = l... | 5,307,970 |
def run_parallel_pipe(transforms, img_paths):
"""Run a single list of transforms on multiple images
Args:
transforms [Transform]: list of transforms in order of execution
img_paths ([str]): List of paths to images. First image is master
"""
# Can only have a single window
windows =... | 5,307,971 |
def tmp_env(tmp_path):
"""
Create temporary environment for each integration tests
"""
curr = os.getcwd()
expected = os.path.join(curr, expected_rel)
os.chdir(tmp_path)
yield expected
os.chdir(curr) | 5,307,972 |
def parse_info(file_path, counter=1, verbose=True):
""" Grab html code from a file and parse for information - return dict of dicts. """
this_counter = counter
# Open file and parse with BS4
with open(file_path, "r") as f:
soup = bs(f.read().decode("utf-8"), "lxml")
# Get category
cate... | 5,307,973 |
def set_name(input_path, name_id, platform, language, string, output_dir, recalc_timestamp, overwrite):
"""Writes the specified namerecord in the name table.
If the namerecord is not present, it will be created. If it already exists, will be overwritten.
If name_id parameter is not specified, the first av... | 5,307,974 |
def describe(profile, description):
"""
Generate a query by describing it as a series of actions
and parameters to those actions. These map directly
to Query methods and arguments to those methods.
This is an alternative to the chaining interface.
Mostly useful if you'd like to put your queries... | 5,307,975 |
def pearsonMatrix(dataset_filtered, patterns_filtered, cellTypeColumnName, num_cell_types, projectionName, plotName,
plot, row_cluster=True, col_cluster=True, path=None, display=True, dpi=300, xtickSize=8, ytickSize=8):
"""This method finds the pearson correlation coefficient between every pattern... | 5,307,976 |
def get_filenames_request(products, download_directory):
"""Get local files url corresponding to a Copernicus request (must be already downloaded).
:param products: (dict) Copernicus Hub query
:param download_directory: (str) Url of folder for downloaded products
:return: (list) List of strings with lo... | 5,307,977 |
def test_compress_below():
""" Test compressing below (and not equal to) a value """
A = np.array([[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10]]).astype(float)
A_transform = np.array([[4, 4, 4, 4], [4, 5, 6, 7], [7, 8, 9, 10]]).astype(float)
constr = ConstraintCompressBelow(copy=True, value=4)
out = c... | 5,307,978 |
def display_xray_image(xray_image):
""" utility function to display the x-ray image.
"""
if isinstance(xray_image, str):
img1 = io.imread(xray_image)
io.imshow(img1)
elif isinstance(xray_image, np.ndarray):
img1 = xray_image
io.imshow(img1)
else:
raise Typ... | 5,307,979 |
def load_bdf_from_hdf5_file(h5_file, model):
"""
Loads an h5 file object into an OP2 object
Parameters
----------
h5_file : H5File()
an h5py file object
model : BDF()
the BDF file to put the data into
"""
encoding = _cast_string(h5_file['minor_attributes']['encoding'], ... | 5,307,980 |
def nt_service_action(service: str, action: str) -> bool:
"""
Handle windows service
"""
elapsed_time = 0 # Number of seconds elapsed since we started Windows service
max_wait = 15 # Number of seconds we'll wait for Windows service to start
is_running = nt_service_status(service)
try:
... | 5,307,981 |
def home():
"""Home endpoint that redirects to docs"""
return RedirectResponse("/docs") | 5,307,982 |
def check_bandpass_biquad(method):
"""Wrapper method to check the parameters of BandpassBiquad."""
@ wraps(method)
def new_method(self, *args, **kwargs):
[sample_rate, central_freq, Q, const_skirt_gain], _ = parse_user_args(
method, *args, **kwargs)
check_biquad_sample_rate(samp... | 5,307,983 |
def get_cached_ip():
"""
Retrieve Cached IP From File, cuts down on API requests if
IP Address hasn't changed.
Returns:
cached_ip: Cached IP or 0 to force refresh of public IP
"""
try:
cached_file = open(CACHE_FILE_PATH, 'r')
cached_ip = cached_file.read()
cache... | 5,307,984 |
def map_box_to_image(box, proj_mat):
"""
Projects 3D bounding box into the image plane.
Args:
box (Box3D)
proj_mat: projection matrix
"""
# box in camera coordinate
points_3d = box.in_camera_coordinate()
# project the 3d bounding box into the image plane
points_2d = proj... | 5,307,985 |
def loadCache(fname):
"""
Loads a pickle file from a filename and returns the resulting data.
@param fname: Filename to load
@return: data retrieved from file
"""
try:
data = util.file_pickle_load(fname)
except Exception:
raise RuntimeError("Could not read %s" % fname)
r... | 5,307,986 |
async def test_onto_channel():
"""
WHEN
Called with a collection and a channel.
EXPECT
All items to be put on channel and then closed.
"""
coll = (1, 2, 3)
ch = create_channel()
done = onto_channel(coll, ch)
taken = []
async for x in ch:
taken.append(x)
aw... | 5,307,987 |
def max_pool(inputs, size=-1):
"""max_pool downsamples a feature map."""
if not inputs[1]:
x_input = inputs[0][0]
else:
x_input = sum_op(inputs)
if size in [3, 5, 7]:
return tf.nn.max_pool(x_input, ksize=[1, size, size, 1], strides=[1, 1, 1, 1], padding='SAME')
else:
... | 5,307,988 |
def _repo_choices(repos_map=None):
"""Make up repo choices.
"""
if repos_map is None:
repos_map = fleure.globals.REPOS_MAP
rss = [[(k, v) for v in vs] for k, vs in repos_map.items()]
return fleure.utils.uconcat(rss) | 5,307,989 |
def grid_plot(filename, slice_index=0, axes=None, title="", vmin=None,
vmax=None, rel_smoothing_scale=None, filename2=None, factor=1.,
boxsize=None, colorbar=True, fix_colorbar=True, v_ratio=False,
factor_minus_allowed=False, cmap=None, norm=None, log_cbar=False,
... | 5,307,990 |
def get_overrides(_conf=None):
"""
Read the configuration file and look for ceph-medic sections and flags to
set the defaults, these are later checked by the main method to see if any
need to be overridden *again* if specified on the CLI directly.
"""
# Get the subcommand name to avoid overwritt... | 5,307,991 |
def get_dqlite_endpoints():
"""
Return the endpoints the current node has on dqlite and the endpoints of the rest of the nodes.
:return: two lists with the endpoints
"""
with open("{}/info.yaml".format(cluster_dir)) as f:
data = yaml.load(f, Loader=yaml.FullLoader)
out = subprocess.chec... | 5,307,992 |
def left_hist_data(hotel_type="All", year=2016, month=1):
"""returns a data frame containing binned counts of hotel guests' country of origin
for the selected hotel type and time period
Parameters
----------
hotel_type : string, either "City", "Resort", or "Both
year: the year selected f... | 5,307,993 |
def inundation_damage(sww_base_name, exposure_files_in,
exposure_file_out_marker=None,
ground_floor_height=0.3,
overwrite=False, verbose=True,
use_cache = True):
"""
This is the main function for calculating tsuna... | 5,307,994 |
def test4():
"""The fifth test tests the random init file generating process and the import
process. It generates an random init file, imports it again and compares the entries
in both dictionaries.
"""
for _ in range(10):
gen_dict = generate_random_dict()
init_file_name = gen_dict[... | 5,307,995 |
def get_first_day_next_month(day):
"""
Returns the next month given the current day
:param day:
:return:
"""
last_day = calendar.monthrange(day.year, day.month)[1]
one_day = datetime.timedelta(days=1)
return datetime.date(day.year, day.month, last_day) + one_day | 5,307,996 |
def orbit_properties(name):
"""Print properties of a stream"""
t = Table.read('../data/crb/ar_orbital_summary.fits')
t = t[t['name']==name]
for k in t.colnames:
print(k, np.array(t[k])[0]) | 5,307,997 |
def peek_tests(**kwargs):
"""Peek tests"""
fobj = io.StringIO('abc~def~gh!i~jkl')
rdr = ReadLines(fobj, delimiter='~', **kwargs)
assert next(rdr) == 'abc~'
assert rdr.peek(0) == ''
assert rdr.peek(2) == 'de'
assert rdr.peek() == 'def~'
assert rdr.peek() == 'def~'
assert next(rdr) == ... | 5,307,998 |
def ensure_namespace(ctx):
"""创建命名空间"""
k8s_client = K8SClient(ctx)
def _add_token_to_ctx(k8s_client, ctx):
# 获取service_account_token
try:
ctx["service_account_token"] = get_service_account_token(k8s_client)
except Exception as error:
logger.error("get servic... | 5,307,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.