content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def set_default_clear(remember: bool):
"""Toggle for clearing console before showing menu"""
_assert_supported(type(remember), "remember", (bool,))
cng.DEFAULT_CLEAR = remember | 79,600 |
def service_http_delete(request, application_id, service_http_id):
"""
Delete service model
"""
service = get_object_or_404(HTTPCodeService, pk=service_http_id)
service.service.delete()
return redirect(reverse('project', args=[application_id])) | 79,601 |
def configJbossSSL(xmlObj):
"""
configure SSL for jboss
"""
logging.debug("Configuring SSL for jboss")
logging.debug("Registering web namespaces")
xmlObj.registerNs('web', 'urn:jboss:domain:web:1.1')
sslConnectorStr='''
<connector name="https" protocol="HTTP/1.1" socket-binding="https" ... | 79,602 |
def create_app(config):
"""
Flask application factory to create the app object.
"""
app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)
from app.shortener import shortener
app.register_blueprint(shortener)
return app | 79,603 |
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the GPMDP platform."""
codeconfig = load_json(hass.config.path(GPMDP_CONFIG_FILE))
if codeconfig:
code = codeconfig.get("CODE")
elif discovery_info is not None:
if "gpmdp" in _CONFIGURING:
return
... | 79,604 |
def rafem(cd) -> None:
"""The River Avulsion and Floodplain Evolution Model (RAFEM)
\b
Examples:
Create a folder with example input files,
$ mkdir example && rafem setup
Run a simulation using the examples input files,
$ cd example && rafem run
Commands can also be ch... | 79,605 |
def is_uptodate(picklefile, path_list=None, min_time=1343682423):
"""Check if the pickle files is uptodate compare to a list of files.
If no files are given, the pickle files is checked against it\' current
directory"""
if not os.path.exists(picklefile):
return False
if path_list... | 79,606 |
def ilmaandmed_veebist(dt_utc):
"""
Tagastab etteantud ajahetke (dt_utc) viimase möödunud täistunni ilmaandmed
ilmateenistus.ee veebilehelt
"""
jaam = 'Valga'
cols = ['airtemperature',
'relativehumidity',
'airpressure',
'airpressure_delta',
'winddi... | 79,607 |
def setLog(filename=None, clear=False):
"""
Replace sys.stderr and sys.stdout with a StreamModifier, capturing
all output for these streams to a log file while still passing it
to the original stream.
"""
if not isinstance(sys.stdout, StreamModifier):
sys.stdout = StreamModifier(sys.stdo... | 79,608 |
def set_value(obj, value):
"""
设置固定数值
:param value: 数值
:return: 数值
"""
return value | 79,609 |
def AddSliceTag(slicename, key, value, node, nodegroup):
""" AddSliceTag() calls s.api.AddSliceTag() with the correct set of arguments.
Args:
slicename - string slicename i.e. "iupui_ndt"
key - the slice tag name, i.e. "vsys"
value - the value for the slice tag, i.e. "web... | 79,610 |
def euler245_():
"""Solution for problem 245."""
pass | 79,611 |
def initialize_all(y0, t0, t1, n):
""" An initialization routine for the different ODE solving
methods in the lab. This initializes Y, T, and h. """
if isinstance(y0, np.ndarray):
Y = np.empty((n, y0.size),dtype=complex).squeeze()
else:
Y = np.empty(n,dtype=complex)
Y[0] = y0
T = np.linspace(t0, t1, n)
h =... | 79,612 |
def test_sat_illumination_distance():
"""
Vallado, 11-6, p.913
"""
rsat = np.array([885.7296, -4389.3856, 5070.1765])
rsun = np.array([-1.43169570e+08, 4.12567046e+07, 1.27096677e+07])
dist = _solar.sat_illumination_distance(rsat, rsun)
assert dist == approx(6564.6870, abs=1.0) | 79,613 |
def test_catkin_lint_tool_plugin_parse_output():
"""
Check that manual exceptions are applied.
These tests make sure the functionality works in the absence of the tool. If the
tool is installed the lines dealing with manual exceptions are already covered.
"""
cltp = setup_catkin_lint_tool_plugi... | 79,614 |
def test_config_overlapping_mcc_mncs():
"""Test Depot not known yet.
Verify that config parser doesn't allow MCC-MNC values that "overlap" (where one MCC-MNC pair is prefixed by
another)
"""
msg = 'MCC-MNC pair 0101 found which starts with another configured MCC-MNC pair 010'
cfg = {'region': {... | 79,615 |
def generate_points(num_points):
"""
:param num_points: an integer, the number of data points
:return:
"""
points = [Point() for _ in range(num_points)]
vmin, vmax = 100, 0
for p in points:
vector = np.random.choice(list(range(1000)), 2)
word = ''.join(random.choice(string.as... | 79,616 |
def camel_shuffle(sequence):
"""
Inspired by https://stackoverflow.com/q/42549212/610569
>>> list(range(12)) # Linear.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>>> camel_shuffle(list(range(12))) # M-shape.
[0, 4, 8, 9, 5, 1, 2, 6, 10, 11, 7, 3]
>>> camel_shuffle(list(rev... | 79,617 |
def random_date(start, end, prop):
"""
get random date between start and end
"""
return str_time_prop(start, end, '%Y-%m-%d %I:%M:%S', prop) | 79,618 |
def calc_distances(x, targets):
""" within and between class distances """
def c_s(l):
l.sort()
s, r = 0, 0
n = len(l)
for i in range(n - 1):
s += l[i]
r += 2 * (n - i - 1) * l[i]
s += l[-1]
return (n - 1) * s - r
within_class = 0
for y, inclass_x ... | 79,619 |
def handle_antimeridian(item: Item, antimeridian_strategy: Strategy) -> None:
"""Handles some quirks of the antimeridian.
Applies the requested SPLIT or NORMALIZE strategy via the stactools
antimeridian utility. If the geometry is already SPLIT (a MultiPolygon,
which can occur when using USGS geometry)... | 79,620 |
def rank_zero_info(*args: Any, stacklevel: int = 4, **kwargs: Any) -> None:
"""Function used to log info-level messages only on rank 0."""
_info(*args, stacklevel=stacklevel, **kwargs) | 79,621 |
def check_symmetry_and_dim(number, dim=3):
"""
check if it is a valid number for the given symmetry
Args:
number: int
dim: 0, 1, 2, 3
"""
valid = True
msg = 'This is a valid group number'
numbers = [56, 75, 80, 230]
if dim not in [0, 1, 2, 3]:
msg = "invalid... | 79,622 |
def merge_layers(input_layer,
merge_layer,
merge_attributes=None,
output_name=None,
gis=None,
context=None,
future=False):
"""
.. image:: _static/images/merge_layers/merge_layers.png
The ``merge_l... | 79,623 |
def anonymous_required(redirect_url):
"""For views that allow only unauthenticated users to access view.
Usage:
@anonymous_required(redirect_url='company_info')
def homepage(request):
return render(request, 'homepage.html')
"""
def _wrapped(view_func, *args, **kwargs):
def check... | 79,624 |
def get_buffers(layer_instance, include_sublayer=True):
"""
Returns Variable buffers of decorated layers. If set `include_sublayer` True,
the Variable buffers created in sub layers will be added.
"""
buffers = collections.OrderedDict()
if layer_instance is not None:
if isinstance(layer_i... | 79,625 |
def user():
"""
exposes:
http://..../[app]/default/user/login
http://..../[app]/default/user/logout
http://..../[app]/default/user/register
http://..../[app]/default/user/profile
http://..../[app]/default/user/retrieve_password
http://..../[app]/default/user/change_password
http://..... | 79,626 |
def pagerank(A, p=0.85, personalize=None, reverse=False):
""" Calculates PageRank given a csr graph
Inputs:
-------
G: a csr graph.
p: damping factor
personlize: if not None, should be an array with the size of the nodes
containing probability distributions.
It wi... | 79,627 |
def test_apply():
"""test that apply correctly applies a simple function across 2d tiles of a Stack"""
stack = ImageStack.synthetic_stack()
assert (stack.numpy_array == 1).all()
output = stack.apply(divide, value=2)
assert (output.numpy_array == 0.5).all() | 79,628 |
def create_transforms(input_config):
"""Create transforms from configuration
Parameters
----------
input_config : dict
Dictionary containing the configuration options for input pre-processing.
Returns
-------
train_transforms : list
List of transforms to be applied to the i... | 79,629 |
def pulse_diagram_plotly(
schedule: Schedule,
port_list: Optional[List[str]] = None,
fig_ch_height: float = 300,
fig_width: float = 1000,
modulation: Literal["off", "if", "clock"] = "off",
modulation_if: float = 0.0,
sampling_rate: int = 1_000_000_000,
) -> go.Figure:
"""
Produce a p... | 79,630 |
def unbiased_std_factor(n):
"""
Returns 1/c4(n)
"""
if is_arraylike(n):
wh = n < 343
ans = np.ones(np.shape(n)) * (4. * n - 3.) / (4. * n - 4.)
n = n[wh]
ans[wh] = spec.gamma((n - 1) / 2) / np.sqrt(2 / (n - 1)) / spec.gamma(n / 2)
return ans
else:
ans... | 79,631 |
def is_test():
""" Detects if the application is currently running as a celery worker. """
return 'test' in sys.argv[1] | 79,632 |
def _ion_number_density(field, data):
"""
Creates the function for a derived field for following the number_density
of an ion over a dataset given that the specified ion's ion_fraction field
exists in the dataset.
"""
if isinstance(field.name, tuple):
ftype = field.name[0]
field_... | 79,633 |
def normalize_by_population(tidy_df):
""" Normalize by population the column "value" of a dataframe with
lines being the country ISO
"""
pop = get_populations()
normalized_values = (tidy_df.set_index('iso')['value']
/ pop.set_index('ISO3')['Population'])
# NAs appea... | 79,634 |
def _hex_to_int(input: str) -> int:
"""Given a hex string representing bytes, returns an int."""
valid_bytes = input[1:] if (len(input) % 2 != 0 and input[0] == "0") else input
hex_bytes = bytes.fromhex(valid_bytes)
return int.from_bytes(hex_bytes, BYTE_ORDER) | 79,635 |
def test_next_state_immutable():
"""
Hopefully you found a way to make the previous test pass. This test will check
so that your solution did not change the old state when creating the next state
It is important later that each state can not be changed after it has been created,
since we need to st... | 79,636 |
def get_creation_time(filepath, verbose=True):
"""
Try to get the date that a file was created, falling back to when it was
last modified if that isn't possible.
See http://stackoverflow.com/a/39501288/1709587 for explanation.
"""
import platform
if platform.system() == "Windows":
t... | 79,637 |
async def update_objects_by_id(model, conn, obj_id_list, data: dict) -> int:
"""Массовое обновление объектов в БД.
Args:
model (Table): обновляемая модель (таблица) в БД.
conn (SAConnection): открытое соединение с БД.
obj_id_list (list of int or int): список идентификаторов
... | 79,638 |
def AddZonalListerArgs(parser):
"""Add arguments defined by base_classes.ZonalLister."""
AddBaseListerArgs(parser)
parser.add_argument(
'--zones',
action=actions.DeprecationAction(
'zones',
warn='This flag is deprecated. '
'Use ```--filter="zone :( *ZONE ... )"``` instead... | 79,639 |
def plot_transformation(args):
"""
Plots the manifold transformation learned by the given model.
better represents the distances on a given graph.
"""
import matplotlib as mpl
import matplotlib.pyplot as plt
MEDIUM_SIZE = 18
BIGGER_SIZE = 24
plt.rc('text', usetex=True) ... | 79,640 |
def annotate_heatmap(im, data=None, valfmt="{x:.2f}",
textcolors=["white", "white"],
threshold=None, **textkw):
"""
A function to annotate a heatmap.
Arguments:
im : The AxesImage to be labeled.
Optional arguments:
data : Data used... | 79,641 |
def tf_tpt_pull_results(ctx, user, host, nobill=False):
"""
Pull results for TF throughput experiment
"""
TensorflowExperimentRunner.pull_results(user, host)
if not nobill:
TensorflowExperimentRunner.parse_results() | 79,642 |
def build_attention_mask_3d_causal(source_mask, target_mask):
"""
Returns a 3D joint attention mask for Megatron given two 2D masks
:param source_mask - True for non-masked, else masked [batch, src length]
:param target_mask - True for non-masked, else masked [batch, tgt length]
"""
causal_mask ... | 79,643 |
def get_run_list(filter_=None, page=1, page_size=25):
"""Get a list of runs
The `filter` parameter takes a list of filters to apply in the form of:
{name}{operator}{value}
where:
- `name` is any valid column in the database
- `operator` is one of `=`, `!`, `>`, `<`, `)`, `(`, `~`, `*... | 79,644 |
def split_timesteps(inputs):
"""Split the input matrix from (batch, timesteps, input_dim) to a step list ([[batch, input_dim], ..., ])."""
timesteps = inputs.get_shape()[1].value
feature_dims = inputs.get_shape()[2].value
inputs = tf.transpose(inputs, [1, 0, 2])
inputs = tf.reshape(inputs, [-1, feat... | 79,645 |
def get_all_dists(x, y):
"""Get L2 distance of x from each item in y."""
return torch.sqrt(torch.sum(torch.pow(x - y, 2), 1)) | 79,646 |
def get_xml_tail(full_xml_ordered_dict):
"""Get xml tail"""
xml_tail = get_rpc_tail(full_xml_ordered_dict)
return xml_tail | 79,647 |
def stats():
""" Run the stats command just to check it works at all. """
sys.argv = ["matador", "stats", "--db", DB_NAME]
if CONFIG_FNAME is not None:
sys.argv += ["--config", CONFIG_FNAME]
matador.cli.cli.main() | 79,648 |
def IPRange(Range, range_temp, language):
"""
IP range string to IPNetwork type
Args:
Range: IP range string
range_temp: range_temp filename
language: language
Returns:
an array of IP range in IPNetwork type
"""
myranges_now = open(range_temp).read().rsplit()
... | 79,649 |
def api_get_user_modelling_units_results(userModellingUnitId, period, divider):
"""
{
"doc": {
"title": "user modelling units results help",
"body": "<p> Obtain the user modelling units results </p>"
},
"GET": {
"label": "Obtain the user modelling unit... | 79,650 |
def test_writer_precision_nano_fail():
"""if writer is not set to nano, supplying this timestamp should be truncated"""
ts, pkt = (Decimal('1454725786.010203045'), b'foo')
writer.writepkt(pkt, ts=ts) # noqa
return [(1454725786.010203, pkt)] | 79,651 |
def _get_suggestions_index(name):
"""Returns suggestions index name for a regular index name."""
return f'df_suggestions_{name}' | 79,652 |
def get_controllers(controller_path=CONTROLLERS_PATH, nested=None):
"""
Return a list of controllers
"""
controllers = {}
parent_mod = 'fts3rest.controllers'
if nested:
parent_mod += '.' + nested
imp.load_source(parent_mod, os.path.join(controller_path, '__init__.py'))
for f in ... | 79,653 |
def draw_rois(
im,
notebook_url="localhost:8888",
table_height=100,
crosshair_tool_alpha=0.5,
color="white",
fill_alpha=0.1,
vertex_color="red",
vertex_size=10,
cmap=None,
frame_height=400,
frame_width=None,
length_units="pixels",
interpixel_distance=1.0,
x_range=... | 79,654 |
def boxplot(data1, data2=None, width=0.75, whiskers=1.5, axesAdjust=True, axes=None):
""" boxplot(*args, width=0.75, whiskers=1.5, axesAdjust=True, axes=None)
Create a box and whisker plot and returns a BoxPlot wobject that can
be used to change the appearance of the boxes (such as color).
... | 79,655 |
def show_actual_vendor_versions(vendor_txt_versions):
# type: (Dict[str, str]) -> None
"""Log the actual version and print extra info if there is
a conflict or if the actual version could not be imported.
"""
for module_name, expected_version in vendor_txt_versions.items():
extra_messa... | 79,656 |
def get_contacts_df(config: GetContactsConfig, pdb_name: str) -> pd.DataFrame:
"""
Reads GetContact File and returns it as a pd.DataFrame
:param config: GetContactsConfig object
:type config: GetContactsConfig
:param pdb_name: Name of PDB file. Contacts files are name {pdb_name}_contacts.tsv
:t... | 79,657 |
def add_config(request):
"""
新增配置
:param request:
:return:
"""
account = request.session["now_account"]
if request.is_ajax():
testconfig_info = json.loads(request.body.decode('utf-8'))
msg = config_info_logic(**testconfig_info)
return HttpResponse(get_ajax_msg(msg, '/... | 79,658 |
def test_process_incoming_anns_bgp_seeded(Policy):
"""Any incoming announcement should never replace a seeded announcement"""
prefix = '137.99.0.0/16'
ann1 = EasyAnn(_prefix=prefix, as_path=(1,),timestamp=0, seed_asn=1)
ann1.recv_relationship=Relationships.ORIGIN
ann2 = EasyAnn(_prefix=prefix, as_pa... | 79,659 |
def get_scene_index(glTF, name):
"""
Return the scene index in the glTF array.
"""
if glTF.get('scenes') is None:
return -1
index = 0
for scene in glTF['scenes']:
if scene['name'] == name:
return index
index += 1
return -1 | 79,660 |
def wifi_toggle_state(ad, new_state=None):
"""Toggles the state of wifi.
Args:
ad: An AndroidDevice object.
new_state: Wifi state to set to. If None, opposite of the current state.
Returns:
True if the toggle was successful, False otherwise.
"""
# Check if the new_state is ... | 79,661 |
def _preprocess_include(include):
"""
A utility function for processing the `include` input
Parameters
----------
include : numpy.ndarray
A list of (zero-based) indices corresponding to the dimensions in `T` that
must be included in the constrained multidimensional motif search.
... | 79,662 |
def get_storage(path=None, options=None):
"""
Get the specified storage configured with options.
:param path: Path in Python dot style to module containing the storage
class. If empty settings.DBBACKUP_STORAGE will be used.
:type path: ``str``
:param options: Parameters for config... | 79,663 |
def _find_channels(action, bone, channel_type):
"""
:param action:
:param bone:
:param channel_type:
"""
result = []
if len(action.groups):
group_index = -1
for index, group in enumerate(action.groups):
if group.name == bone.name:
group_index =... | 79,664 |
def parse_waveglow_args(parent, add_help=False):
"""
Parse commandline arguments.
"""
parser = argparse.ArgumentParser(parents=[parent], add_help=add_help)
# misc parameters
parser.add_argument('--n-mel-channels', default=80, type=int,
help='Number of bins in mel-spe... | 79,665 |
def _ord_to_str(ordinal, weights):
"""Reverse function of _str_to_ord."""
chars = []
for weight in weights:
if ordinal == 0:
return "".join(chars)
ordinal -= 1
index, ordinal = divmod(ordinal, weight)
chars.append(_ALPHABET[index])
return "".join(chars) | 79,666 |
def aws(flox: Flox, args, **kwargs):
"""awscli command wrapper with session credentials provider"""
command_name = next(iter(args), None)
if command_name == "console":
args = list(args)
with EmptyContext(flox, console, args[1:], allow_interspersed_args=True, ignore_unknown_options=True) as ... | 79,667 |
def is_inactive_link(node_status_at_link):
"""Find links that are inactive.
A link is inactive if it connects two boundary nodes or one of
its nodes is closed.
Parameters
----------
node_status_at_link : ndarray of int, shape `(n_links, 2)`
Node status a link tail and head.
Return... | 79,668 |
def LOG_INFO(message, subsystem=None):
"""convenience wrapper for info logging"""
s_logger._logInfo(message, subsystem) | 79,669 |
def run_cmd(cmdlist):
""" reusable function for running shell commands"""
try:
stdout = subprocess.check_output(cmdlist)
except subprocess.CalledProcessError:
pass
else:
if stdout:
return stdout | 79,670 |
def found_value(gpio_value):
"""checks if the gpio value entered in command line is supported and return the corresponding value"""
if gpio_value in common.gpio_supported_values:
if common.gpio_supported_values[gpio_value] == 0 or common.gpio_supported_values[gpio_value] == 1:
return common.... | 79,671 |
def scrape_html_table(bs_table, f = lambda tags_list, index : list( map(lambda tag: tag.string, tags_list) )):
"""
Returns a nested list based on the contents of the table
html = \"\"\"<table class="formulario">
<tr>
<td class="very important stuff">Hotel</td>
<td>Trivago</t... | 79,672 |
def calculate_immediate_post_dominators(nodes, _pdom, _spdom):
""" Calculate immediate post dominators for all nodes.
Do this by choosing n from spdom(x) such that pdom(n) == spdom(x).
"""
_ipdom = {}
for node in nodes:
if _spdom[node]:
for x in _spdom[node]:
i... | 79,673 |
def create_role(token, name, description):
"""
Create a Keycloak role.
"""
url = '{keycloak}/auth/admin/realms/{realm}/roles'.format(
keycloak=settings.KEYCLOAK['SERVICE_ACCOUNT_KEYCLOAK_API_BASE'],
realm=settings.KEYCLOAK['SERVICE_ACCOUNT_REALM'])
headers = {'Authorization': 'Beare... | 79,674 |
def valid_dotfile_permissions():
"""Return a dictionary of all valid dotfiles, mapped to """
"""their octal permissions."""
permissions = dict()
ST_MODE = stat.ST_MODE
for elem in recurse_valid_dotfiles(this_directory()):
for file in glob(elem+'*'):
permissions[file] = oct(stat.... | 79,675 |
def test_clear_queue(pq):
"""
Test for ``PlanQueueOperations.clear_queue`` function
"""
async def testing():
await pq.add_item_to_queue({"name": "a"})
await pq.add_item_to_queue({"name": "b"})
await pq.add_item_to_queue({"name": "c"})
# Set one of 3 plans as running (rem... | 79,676 |
def validate_runner_claims(claims: Dict):
""" Validate claims required for runner to function"""
runner_metadata_schema = RunnerMetadataSchema(unknown=EXCLUDE)
return runner_metadata_schema.load(claims) | 79,677 |
def repay_margin(order_id, amount):
"""
:param order_id:
:param amount:
:return:
"""
params = {"order-id": order_id,
"amount": amount}
url = "/v1/margin/orders/{0}/repay".format(order_id)
return api_key_post(params, url) | 79,678 |
def test_rename():
""" test vmat.rename
"""
ref_renamed_zma = (
('C', (None, None, None), (None, None, None),
(None, None, None)),
('C', (0, None, None), ('R1', None, None),
(2.894126135733367, None, None)),
('H', (0, 1, None), ('R2', 'A2', None),
(2.10025... | 79,679 |
def serve_test():
"""TODO: write some tests"""
serve("test") | 79,680 |
def clinvar_track(build, chrom):
"""Return a dictionary consisting in the clinVar snvs track
Accepts:
build(str): "37" or "38"
chrom(str)
Returns:
clinvar_track(dict)
"""
clinvar_track = {
"name": "ClinVar",
"type": "annotation",
"sourceType": "file... | 79,681 |
def test_cached_property(dummy):
"""Test that property is cached"""
# Test that doc string is transferred by decorator
assert type(dummy).takes_some_time.__doc__ == """some documentation code"""
# first time takes 1 second
t0 = time.time()
err = dummy.takes_some_time
dt = time.time()-t0
... | 79,682 |
def calc_batch_loss(batch, teacher_forcing=1):
"""
Calculate the loss for given batch of data
:param batch: batch of data.
:param teacher_forcing: (float, default=1) rate of teacher forcing
:return: loss tensor
"""
x, x_len = batch.text
data = x[:-1].clone()
target = x[1:].c... | 79,683 |
def attach(config, model):
"""
Attach to model and show creation logs.
MODEL may be specified by name or ID, but ID is preferred.
"""
models = config.trainml.run(config.trainml.client.models.list())
found = search_by_id_name(model, models)
if None is found:
raise click.UsageError("... | 79,684 |
def cg_solve(f_Ax, b, cg_iters=10, callback=None, verbose=False, residual_tol=1e-10, x_init=None):
"""
Goal: Solve Ax=b equivalent to minimizing f(x) = 1/2 x^T A x - x^T b
Assumption: A is PSD, no damping term is used here (must be damped externally in f_Ax)
Algorithm template from wikipedia
Verbose... | 79,685 |
def parang (hourangle, declination, latitude):
"""Calculate the parallactic angle of a sky position.
This computes the parallactic angle of a sky position expressed in terms
of an hour angle and declination. Arguments:
hourangle
The hour angle of the location on the sky.
declination
Th... | 79,686 |
def dataset(params):
"""
The input batch generator.
"""
with tf.name_scope("dataset"):
def sample():
input_mean = tf.constant(params.input_mean, dtype=tf.float32)
input_stddev = tf.constant(params.input_stddev, dtype=tf.float32)
count = len(params.input_mean)
... | 79,687 |
def frac_diff_ffd(data: pd.Series, d: float, threshold=1e-5, parallel=False):
"""
Fractionally Differentiated Features Fixed Window
:param data: data
:param d: difference coefficient
:param threshold: threshold
:param parallel: run in parallel
"""
if isinstance(data.index, pd.MultiIndex)... | 79,688 |
def _get_args():
"""Parse command-line arguments."""
parser = argparse.ArgumentParser(prog="nix-server")
parser.add_argument("--version", action="version", version=__version__)
parser.add_argument("--port", type=int,
default=int(os.getenv("PORT", 5000)),
h... | 79,689 |
def call_notifiers(tnotifiers, onotifiers, obj, name, old_value, new_value):
"""Call all notifiers for a specified trait"""
new_value_has_traits = isinstance(new_value, CHasTraits)
args = (obj, name, old_value, new_value)
# Do nothing if the user has explicitly requested no traits notifications
... | 79,690 |
def test_values_that_cannot_be_parsed_as_bool(value):
"""
config_file.parse_value.can_be_parsed_as_bool
Returns False for values that cannot be parsed as a bool.
"""
assert not can_be_parsed_as_bool(value) | 79,691 |
def test_atomic_normalized_string_min_length_3_nistxml_sv_iv_atomic_normalized_string_min_length_4_3(mode, save_output, output_format):
"""
Type atomic/normalizedString is restricted by facet minLength with
value 74.
"""
assert_bindings(
schema="nistData/atomic/normalizedString/Schema+Instan... | 79,692 |
def SetIamPolicy(taxonomy_id, policy):
"""Sets IAM policy, for a given taxonomy.
Args:
taxonomy_id: Id of the taxonomy.
policy: An IamPolicy message.
Returns:
An IamPolicy message.
"""
messages = utils.GetMessagesModule()
return _GetService().SetIamPolicy(
messages.DatapolTaxonomyStoresD... | 79,693 |
def modify_doc_title_dir(abspath_rstfiles_dir):
"""
rst文件中:有‘========’和‘----------’行的表示其行上一行的文字是标题,
‘=’和‘-’要大于等于标题的长度。
使用sphinx-apidoc -o ./source/rst_files /home/myubuntu/pro/mypro命令将
生成rst文件放在./source/rst_files目录下, 执行sphinx-quickstart命令生成的
index.rst不用放到这个目录中。 或在source目录下新建
rst_files目录然后将rs... | 79,694 |
def format_committer(input_row: dict) -> tuple:
"""Format a committer row form commit input_row."""
return format_contributor(input_row, CONTRIBUTOR_TYPE_COMMITTER) | 79,695 |
def test_targeting_all(get_resource_status: MagicMock):
"""Should target all resources if no target is set on the command line."""
get_resource_status.return_value = RESPONSE_SCENARIOS[-1]
bundle = kuber.create_bundle()
bundle.add("v1", "Namespace", "foo")
bundle.add("v1", "Namespace", "bar")
bu... | 79,696 |
def test_pki(salt_mm_failover_master_1, salt_mm_failover_master_2, caplog):
"""
Verify https://docs.saltproject.io/en/latest/topics/tutorials/multimaster_pki.html
"""
# At first we spin up a simple minion in order to capture its logging output.
config_defaults = {
"transport": salt_mm_failov... | 79,697 |
async def consumer(condition, n):
""":type condition asyncio.Condition"""
with await condition:
print('consumer {} is waiting'.format(n))
await condition.wait()
print('consumer {} triggered'.format(n))
print('ending consumer {}'.format(n)) | 79,698 |
async def about(request):
"""Renders the About page."""
return templates.TemplateResponse("about.html", {"request": request}) | 79,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.