content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_non_provider_fields(get_good_response):
"""Ensure provider fields are excluded when not requested"""
non_provider_specific_field = "elements"
request = f"/structures?response_fields={non_provider_specific_field}"
response = get_good_response(request)
returned_attributes = set()
for _ i... | 5,333,200 |
def track_to_note_string_list(
track: Track,
) -> List[str]:
"""Convert a mingus.containers.Track to a list of note strings"""
final_note_list = []
for element in track.get_notes():
for note in element[-1]:
final_note_list.append(note_to_string(note))
return final_note_list | 5,333,201 |
def test_number_of_interval_slicer_numberpoints3_numberintervals2_include_max(
test_data,
):
"""
Function to compare characterisics of reference interval generated by
NumberOfIntervalSlicer and manually generated interval. Specific test
case: the number of intervals = 3, the upper boundary of the la... | 5,333,202 |
def group_sums_dummy(x, group_dummy):
"""sum by groups given group dummy variable
group_dummy can be either ndarray or sparse matrix
"""
if data_util._is_using_ndarray_type(group_dummy, None):
return np.dot(x.T, group_dummy)
else: # check for sparse
return x.T * group_dummy | 5,333,203 |
def fixture_multi_check_schema() -> DataFrameSchema:
"""Schema with multiple positivity checks on column `a`"""
return _multi_check_schema() | 5,333,204 |
def get_featurizer(featurizer_key: str) -> ReactionFeaturizer:
"""
:param: featurizer_key: key of a ReactionFeaturizer
:return: a ReactionFeaturizer for a specified key
"""
if featurizer_key not in FEATURIZER_INITIALIZERS:
raise ValueError(f"No featurizer for key {featurizer_key}")
retu... | 5,333,205 |
def window_open(dev, temp, duration):
""" Gets and sets the window open settings. """
click.echo("Window open: %s" % dev.window_open)
if dev.window_open_temperature is not None:
click.echo("Window open temp: %s" % dev.window_open_temperature)
if dev.window_open_time is not None:
click.ec... | 5,333,206 |
def test_create_update_file_share_link(requests_mock, mocker):
"""
Tests the box-create-file-share-link function and command.
Configures requests_mock instance to generate the appropriate
files API response, loaded from a local JSON file. Checks
the output of the command function with the expected ... | 5,333,207 |
def is_negative_spec(*specs: List[List[str]]) -> bool:
""" Checks for negative values in a variable number of spec lists
Each spec list can have multiple strings. Each string within each
list will be searched for a '-' sign.
"""
for specset in specs:
if specset:
for spec... | 5,333,208 |
async def download(
client: HTTPClient,
outpath: FilePath,
api_root: DecodedURL,
cap: str,
child_path: Optional[Iterable[str]] = None,
) -> None:
"""
Download the object identified by the given capability to the given path.
:param client: An HTTP client to use to make requests to the Ta... | 5,333,209 |
def is_np_timedelta_like(dtype: DTypeLike) -> bool:
"""Check whether dtype is of the timedelta64 dtype."""
return np.issubdtype(dtype, np.timedelta64) | 5,333,210 |
def pp2mr(pv,p):
""" Calculates mixing ratio from the partial and total pressure
assuming both have same unitsa nd no condensate is present. Returns value
in units of kg/kg. Checked 20.03.20
"""
pv, scalar_input1 = flatten_input(pv) # don't specify pascal as this will wrongly corrected
p , sc... | 5,333,211 |
def test_p_plot():
"""
The purpose of this test is evaluating if the matplotlib object created with p_plot has the correct layers compared to the required
plot. The test will cover the same things we checked with R:
- The output is a matplotlib object.
- The axis labels are correct. In this case if... | 5,333,212 |
def initialize_database(app):
""" Takes an initalized flask application and binds a database context to allow query execution
"""
# see https://github.com/mitsuhiko/flask-sqlalchemy/issues/82
db.app = app
db.init_app(app)
return db | 5,333,213 |
def decrypt(input_file: TextIO, wordlist_filename: str) -> str:
"""
Using wordlist_filename, decrypt input_file according to the handout
instructions, and return the plaintext.
"""
encrypt = []
result = ''
ans = ''
plaintext = ''
# store English wordlist into a set
english_wordl... | 5,333,214 |
def loadEvents(fname):
"""
Reads a file that consists of first column of unix timestamps
followed by arbitrary string, one per line. Outputs as dictionary.
Also keeps track of min and max time seen in global mint,maxt
"""
events = []
ws = open(fname, 'r').read().splitlines()
events = []
for w in ws:
... | 5,333,215 |
def show_wordcloud(data, title = None):
"""
Word cloud
Parameters
----------
data : list
list of (string) documents
"""
stopwords = set(STOPWORDS)
wordcloud = WordCloud(
background_color='black',
stopwords=stopwords,
max_words=200,
max_font_s... | 5,333,216 |
def compute_relative_target_raw(current_pose, target_pose):
"""
Computes the relative target pose which has to be fed to the network as an input.
Both target pose and current_pose have to be in the same coordinate frame (gloabl map).
"""
# Compute the relative goal position
goal_position_difference = [targ... | 5,333,217 |
def get_tokeninfo_remote(token_info_url, token):
"""
Retrieve oauth token_info remotely using HTTP
:param token_info_url: Url to get information about the token
:type token_info_url: str
:param token: oauth token from authorization header
:type token: str
:rtype: dict
"""
token_reque... | 5,333,218 |
def make_site_object(config, seen):
"""Make object with site values for evaluation."""
now = datetime.today().strftime("%Y-%m-%d")
subtitle = (
f'<h2 class="subtitle">{config.subtitle}</h2>'
if config.subtitle
else ""
)
site = SN(
author=lambda: config.author,
... | 5,333,219 |
def get_filename():
"""
Build the output filename
"""
now_date = datetime.now()
out_date = now_date.strftime("%Y-%m-%d_%H-%M")
outfile_name = "node_ip_cfg_info_" + out_date + '.txt'
if os.path.exists(outfile_name):
os.remove(outfile_name)
print('Output file name is: {}'.... | 5,333,220 |
def map_aircraft_to_record(aircrafts, message_now, device_id):
"""
Maps the `aircraft` entity to a BigQuery record and its unique id.
Returns `(unique_ids, records)`
"""
def copy_data(aircraft):
result = {
'hex': aircraft.get('hex'),
'squawk': aircraft.get('squawk'),
'flight': aircraft.g... | 5,333,221 |
def add_gaussian_noise(image, mean=0, std=0.001):
"""
添加高斯噪声
mean : 均值
var : 方差
"""
image = np.array(image / 255, dtype=float)
noise = np.random.normal(mean, std ** 0.5, image.shape)
print(np.mean(noise ** 2) - np.mean(noise) ** 2)
out = image + noise
if image.min() <... | 5,333,222 |
def imagenet_get_datasets(data_dir, arch, load_train=True, load_test=True):
"""
Load the ImageNet dataset.
"""
# Inception Network accepts image of size 3, 299, 299
if distiller.models.is_inception(arch):
resize, crop = 336, 299
else:
resize, crop = 256, 224
if arch == 'googl... | 5,333,223 |
def sub(xs, ys):
"""
Computes xs - ys, such that elements in xs that occur in ys are removed.
@param xs: list
@param ys: list
@return: xs - ys
"""
return [x for x in xs if x not in ys] | 5,333,224 |
def create_folio_skill(request, folio_id):
"""
Creates a new folio skill
"""
if request.method == "POST":
form = FolioSkillForm(request.POST)
if form.is_valid():
skill = form.save(commit=False)
skill.author_id = request.user
skill.save()
... | 5,333,225 |
def lambda_handler(event, context):
"""AWS Lambda Function entrypoint to cancel booking
Parameters
----------
event: dict, required
Step Functions State Machine event
chargeId: string
pre-authorization charge ID
context: object, required
Lambda Context runtime ... | 5,333,226 |
def reduce_tags(tags):
"""Filter a set of tags to return only those that aren't descendents from others in the list."""
reduced_tags = []
for tag_a in tags:
include = True
for tag_b in tags:
if tag_a == tag_b:
continue
if not tag_before(tag_a, tag_b):
... | 5,333,227 |
def init():
"""
This method will be run once on startup. You should check if the supporting files your
model needs have been created, and if not then you should create/fetch them.
"""
# Placeholder init code. Replace the sleep with check for model files required etc...
global nlp
nlp = pipe... | 5,333,228 |
def test_basic():
"""A simple end-to-end test case."""
digits = load_digits()
X, y = digits.data, digits.target
clf = RandomForestClassifier(n_estimators=5)
param_def = [
{
'name': 'max_depth',
'integer': True,
'lb': 3,
'ub': 6,
},
... | 5,333,229 |
def default_param_noise_filter(var):
"""
check whether or not a variable is perturbable or not
:param var: (TensorFlow Tensor) the variable
:return: (bool) can be perturb
"""
if var not in tf.trainable_variables():
# We never perturb non-trainable vars.
return False
if "full... | 5,333,230 |
def test_model_instantiation() -> None:
"""Test that a plain Model can be used."""
Model() | 5,333,231 |
def cli() -> None:
"""A cli to provision and manage local developer environments.""" | 5,333,232 |
def input_fn(request_body, request_content_type):
"""
An input_fn that loads the pickled tensor by the inference server of SageMaker.
The function deserialize the inference request, then the predict_fn get invoked.
Does preprocessing and returns a tensor representation of the source sentence
ready t... | 5,333,233 |
def get_colors(k):
"""
Return k colors in a list. We choose from 7 different colors.
If k > 7 we choose colors more than once.
"""
base_colors = ['b', 'r', 'g', 'c', 'm', 'y', 'k']
colors = []
index = 1
for i in range(0, k):
if index % (len(base_colors) + 1) == 0:
in... | 5,333,234 |
def update_user(user_id: str, content: Optional[Dict] = None):
"""
Update a user with new fields in Auth0 with a given user id
:param user_id: the user id to update new information with
:param content: a dictionary of Auth0 matching fields to update content
See: https://auth0.com/docs/api/management... | 5,333,235 |
def test_significance(stat, A, b, eta, mu, cov, z, alpha):
"""
Compute an p-value by testing a one-tail.
Look at right tail or left tail?
Returns "h_0 Reject
"""
ppf, params = psi_inf(A, b, eta, mu, cov, z)
if np.isnan(params['scale']) or not np.isreal(params['scale']):
l... | 5,333,236 |
def _get_cluster_group_idx(clusters: np.ndarray) -> nb.typed.List:
"""
Get start and stop indexes for unique cluster labels.
Parameters
----------
clusters : np.ndarray
The ordered cluster labels (noise points are -1).
Returns
-------
nb.typed.List[Tuple[int, int]]
Tupl... | 5,333,237 |
def genes_flyaltas2(
genes: Union[str, list] = None,
gene_nametype: Optional[str] = "symbol",
stage: Optional[str] = "male_adult",
enrich_threshold: Optional[float] = 1.0,
fbgn_path: Optional[str] = "deml_fbgn.tsv.gz",
) -> pd.DataFrame:
"""
Annotate a gene list based on the flyaltas2 databa... | 5,333,238 |
def output_elbs(elbs=None):
"""
@type elbs: list
"""
if elbs:
elbs.sort(key=lambda k: k.get('DNSName'))
td = list()
table_header = [Color('{autoblue}name{/autoblue}'),
Color('{autoblue}instances{/autoblue}'),
Color('{autoblue}dns na... | 5,333,239 |
def loadEnv(envName):
"""
"""
with prefix("source ~/.bash_profile"):
with prefix("workon {}".format(envName)):
yield | 5,333,240 |
def _batch_embed(args, net, vecs: StringDataset, device, char_alphabet=None):
"""
char_alphabet[dict]: id to char
"""
# convert it into a raw string dataset
if char_alphabet != None:
vecs.to_bert_dataset(char_alphabet)
test_loader = torch.utils.data.DataLoader(vecs, batch_size=args.test... | 5,333,241 |
def get_adjacency_matrix(distance_df, sensor_ids, normalized_k=0.1):
"""
:param distance_df: data frame with three columns: [from, to, distance].
:param sensor_ids: list of sensor ids.
:param normalized_k: entries that become lower than normalized_k after normalization are set to zero for sparsity.
... | 5,333,242 |
def map_ids_to_strs(ids, vocab, join=True, strip_pad='<PAD>',
strip_bos='<BOS>', strip_eos='<EOS>', compat=True):
"""Transforms `int` indexes to strings by mapping ids to tokens,
concatenating tokens into sentences, and stripping special tokens, etc.
Args:
ids: An n-D numpy arra... | 5,333,243 |
def mock_finish_setup():
"""Mock out the finish setup method."""
with patch(
"openpeerpower.components.mqtt.MQTT.async_connect", return_value=mock_coro(True)
) as mock_finish:
yield mock_finish | 5,333,244 |
def _parse_args() -> argparse.Namespace:
"""Parses and returns the command line arguments."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('in_json',
type=argparse.FileType('r'),
help='The JSON file containing a list of file names... | 5,333,245 |
def rand_ascii_str(length):
"""Generates a random string of specified length, composed of ascii letters
and digits.
Args:
length: The number of characters in the string.
Returns:
The random string generated.
"""
letters = [random.choice(ascii_letters_and_digits) for _ in range(length)]
return ''... | 5,333,246 |
def set_achievement_disabled(aid, disabled):
"""
Updates a achievement's availability.
Args:
aid: the achievement's aid
disabled: whether or not the achievement should be disabled.
Returns:
The updated achievement object.
"""
return update_achievement(aid, {"disabled": ... | 5,333,247 |
def test_stochatreat_stratum_ids(df, misfit_strategy, stratum_cols):
"""Tests that the function returns the right number of stratum ids"""
treats = stochatreat(
data=df,
stratum_cols=stratum_cols,
treats=2,
idx_col="id",
random_state=42,
misfit_strategy=misfit_str... | 5,333,248 |
def test_azure_machine_pool_default(release, cluster_v1alpha4, azuremachinepool) -> None:
"""
test_azure_machine_pool_default tests defaulting of an AzureMachinePool where all required values are empty strings.
:param release: Release CR which is used by the Cluster.
:param cluster_v1alpha4: Cluster CR... | 5,333,249 |
def get_block(in_dt: datetime):
"""Get the BlockNumber instance at or before the datetime timestamp."""
return BlockNumber.from_timestamp(in_dt.replace(tzinfo=timezone.utc).timestamp()) | 5,333,250 |
def get_channels(posts):
"""
<summary> Returns post channel (twitter/facebook)</summary>
<param name="posts" type="list"> List of posts </param>
<returns> String "twitter" or "facebook" </returns>
"""
channel = []
for i in range(0, len(posts['post_id'])):
if len(posts['post_text'][i... | 5,333,251 |
def clean_text(text):
"""
text: a string
return: modified initial string
"""
text = BeautifulSoup(text, "lxml").text # HTML decoding
text = text.lower() # lowercase text
text = REPLACE_BY_SPACE_RE.sub(' ', text) # replace REPLACE_BY_SPACE_RE symbols by space in text
text... | 5,333,252 |
def assert_allclose(
actual: List[numpy.ndarray], desired: List[float], rtol: float, atol: float
):
"""
usage.scipy: 1
"""
... | 5,333,253 |
def ConvertToTypeEnum(type_enum, airflow_executor_type):
"""Converts airflow executor type string to enum.
Args:
type_enum: AirflowExecutorTypeValueValuesEnum, executor type enum value.
airflow_executor_type: string, executor type string value.
Returns:
AirflowExecutorTypeValueValuesEnum: the execut... | 5,333,254 |
def message(message,GUI,error=False):
"""Prints message in manner dictated by GUI and error."""
if GUI:
openMessageBox(message)
elif error:
raise SDEValueError(message)
else:
print(message) | 5,333,255 |
def plot_univariate_series(
series: pd.Series,
title: str,
xlabel: str,
ylabel: str,
graph_type: GraphType = None,
**kwargs) -> None:
"""Bar plots a interger series
Args:
series (pd.Series): series to be plotted
title (str): graph title... | 5,333,256 |
def main():
""" Command line tool for running simulate_data.py """
parser = ArgumentParser(description="Generate an artificial data set.")
optional = parser._action_groups.pop()
required = parser.add_argument_group('required arguments')
required.add_argument('-i', action='store', required=True, dest... | 5,333,257 |
def image2array(image):
"""PIL Image to NumPy array"""
assert image.mode in ('L', 'RGB', 'CMYK')
arr = numpy.fromstring(image.tostring(), numpy.uint8)
arr.shape = (image.size[1], image.size[0], len(image.getbands()))
return arr.swapaxes(0, 2).swapaxes(1, 2).astype(numpy.float32) | 5,333,258 |
def enum_name_callback(ctx: 'mypy.plugin.AttributeContext') -> Type:
"""This plugin refines the 'name' attribute in enums to act as if
they were declared to be final.
For example, the expression 'MyEnum.FOO.name' normally is inferred
to be of type 'str'.
This plugin will instead make the inferred ... | 5,333,259 |
def test_sort_with_axis_graph_mode():
"""
Feature: sort op support the axis value not -1 with graph mode.
Description: sort op support the axis value not -1.
Expectation: same as the calculation result on CPU.
"""
tensor = Tensor(np.random.random([3, 7, 7, 2]), mindspore.float16)
cpu_out = c... | 5,333,260 |
def test_can_add_reader(loop, sock_pair):
"""Verify that we can add a reader callback to an event loop."""
def can_read():
if fut.done():
return
data = srv_sock.recv(1)
if len(data) != 1:
return
nonlocal got_msg
got_msg = data
# Indicate that we're done
fut.set_result(None)
srv_sock.close()
... | 5,333,261 |
def is_forward_angle(n, theta):
"""
if a wave is traveling at angle theta from normal in a medium with index n,
calculate whether or not this is the forward-traveling wave (i.e., the one
going from front to back of the stack, like the incoming or outgoing waves,
but unlike the reflected wave). ... | 5,333,262 |
def get_data(cfg, working_dir, global_parameters, res_incl=None, res_excl=None):
"""Reads experimental measurements"""
exp_type = global_parameters['experiment_type']
path = os.path.dirname(__file__)
pkgs = [
modname
for _, modname, ispkg in pkgutil.iter_modules([path])
if ispk... | 5,333,263 |
def main_program_loop(glc,geh,gth):
"""GuiLayoutContext,GuiEventHandler,GuiTimeHandler"""
done=False
t=0
new_select_possible=True
selected=None
while not done:
try:
for event in pygame.event.get():
if event.type == pygame.QUIT:
... | 5,333,264 |
def fit_cubic1(points,rotate,properties=None):
"""This function attempts to fit a given set of points to a cubic polynomial line: y = a3*x^3 + a2*x^2 + a1*x + a0"""
r=mathutils.Matrix.Rotation(math.radians(rotate),4,'Z')
rr=mathutils.Matrix.Rotation(math.radians(-rotate),4,'Z')
Sxy = 0
Sx ... | 5,333,265 |
def tile_from_slippy_map(root, x, y, z):
"""Retrieve a single tile from a slippy map dir."""
path = glob.glob(os.path.join(os.path.expanduser(root), z, x, y + ".*"))
if not path:
return None
return mercantile.Tile(x, y, z), path[0] | 5,333,266 |
def init(quiet_mode, filename_only):
"""
Initialize output based on quiet/filename-only flags
"""
global quiet
# global quiet is used to pass -q to Sphinx build so it should be set when
# either in quiet mode or filename-only mode
quiet = quiet_mode or filename_only
# always handle wri... | 5,333,267 |
def get_labelstats_df_list(fimage_list, flabel_list):
"""loop over lists of image and label files and
extract label statisics as pandas.DataFrame
"""
if np.ndim(fimage_list) == 0:
fimage_list = [fimage_list]
if np.ndim(flabel_list) == 0:
flabel_list = [flabel_list]
columns = ['i... | 5,333,268 |
def index(web):
"""The web.request.params is a dictionary,
pointing to falcon.Request directly."""
name = web.request.params["name"]
return f"Hello {name}!\n" | 5,333,269 |
def process_object(obj):
""" Recursively process object loaded from json
When the dict in appropriate(*) format is found,
make object from it.
(*) appropriate is defined in create_object function docstring.
"""
if isinstance(obj, list):
result_obj = []
for elem in obj:
... | 5,333,270 |
def remove_role(principal, role):
"""Removes role from passed principal.
**Parameters:**
principal
The principal (actor or group) from which the role is removed.
role
The role which is removed.
"""
try:
if isinstance(principal, Actor):
ppr = PrincipalRoleRe... | 5,333,271 |
def set_var_input_validation(
prompt="",
predicate=lambda _: True,
failure_description="Value is illegal",
):
"""Validating user input by predicate.
Vars:
- prompt: message displayed when prompting for user input.
- predicate: lambda function to verify a condition.
- failure... | 5,333,272 |
def mad(data, axis=None):
"""Mean absolute deviation"""
return np.mean(np.abs(data - np.mean(data, axis)), axis) | 5,333,273 |
def spatial_2d_padding(x, padding=((1, 1), (1, 1)), data_format=None):
"""Pad the 2nd and 3rd dimensions of a 4D tensor
with "padding[0]" and "padding[1]" (resp.) zeros left and right.
"""
assert len(padding) == 2
assert len(padding[0]) == 2
assert len(padding[1]) == 2
top_pad, bottom_pad = ... | 5,333,274 |
def doms_hit_pass_threshold(mc_hits, threshold, pass_k40):
""" checks if there a at least <<threshold>> doms
hit by monte carlo hits. retuns true or false"""
if threshold == 0: return True
if len(mc_hits) == 0: return bool(pass_k40)
dom_id_set = set()
for hit in mc_hits:
dom_id = pm... | 5,333,275 |
def differ_filelist_with_two_dirs(s_p_dir, d_p_dir, filelist, mode='0'):
"""
使用 difflib 库对两个文件夹下的文件列表进行比较,输出原始结果
"""
output = ''
for f_path in filelist:
s_file_path = os.path.join(s_p_dir, f_path) if mode != '1' else None
d_file_path = os.path.join(d_p_dir, f_path) if mode != '2' els... | 5,333,276 |
def _parseLocalVariables(line):
"""Accepts a single line in Emacs local variable declaration format and
returns a dict of all the variables {name: value}.
Raises ValueError if 'line' is in the wrong format.
See http://www.gnu.org/software/emacs/manual/html_node/File-Variables.html
"""
paren = '... | 5,333,277 |
def add_custom_role(bot, plugin_name, role_name, role):
"""Adds the given role as a custom internal role used by the bot."""
roles = get(
bot, plugin_name, 'custom_roles',
guild_id=role.guild.id, create=True, default={}, save=True)
roles[role_name] = role.id | 5,333,278 |
def NLL(mu, sigma, mixing, y):
"""Computes the mean of negative log likelihood for P(y|x)
y = T.matrix('y') # (minibatch_size, output_size)
mu = T.tensor3('mu') # (minibatch_size, output_size, n_components)
sigma = T.matrix('sigma') # (minibatch_size, n_components)
mixing = T.matrix('mixing') #... | 5,333,279 |
def get_non_subscribed_trainers(user) -> Optional[str]:
"""
returns all trainers the user is not subscrbed to
"""
conn = get_db()
error = None
try:
trainers = conn.execute("""SELECT distinct u_name FROM user, trainer
where t_userID = u_userID
... | 5,333,280 |
def __clean_datetime_value(datetime_string):
"""Given"""
if datetime_string is None:
return datetime_string
if isinstance(datetime_string, str):
x = datetime_string.replace("T", " ")
return x.replace("Z", "")
raise TypeError("Expected datetime_string to be of type string (or No... | 5,333,281 |
def counts(df):
"""Print value counts for each column of a dataframe
:param df: Pandas dataframe
:return: void
"""
for c in df.columns:
print("---- %s ---" % c)
print(df[c].value_counts())
print("--------\n") | 5,333,282 |
def get_metric_by_name(metric: str, *args, **kwargs) -> Metric:
"""Returns metric using given `metric`, `args` and `kwargs`
Args:
metric (str): name of the metric
Returns:
Metric: requested metric as Metric
"""
assert metric in __metric_mapper__, "given metric {} is not found".form... | 5,333,283 |
def parse(handle,format):
"""Parses an output file of motif finding programs.
Currently supported formats:
- AlignAce
- MEME
You can also use single-motif formats, although the Bio.Motif.read()
function is simpler to use in this situation.
- jaspar-pfm
- jaspar-sites
For examp... | 5,333,284 |
def p_replacecmd_replace(p):
"""replacecmd : REPLACE wc_stringlist"""
p[0] = ParseTreeNode('COMMAND', raw='replace')
p[0].add_children(p[2].children) | 5,333,285 |
def Square(inputs, **kwargs):
"""Calculate the square of input.
Parameters
----------
inputs : Tensor
The input tensor.
Returns
-------
Tensor
The square result.
"""
CheckInputs(inputs, 1)
arguments = ParseArguments(locals())
output = Tensor.CreateOperator... | 5,333,286 |
def make_call(rpc_name, request, retries=None, timeout=None):
"""Make a call to the Datastore API.
Args:
rpc_name (str): Name of the remote procedure to call on Datastore.
request (Any): An appropriate request object for the call, eg,
`entity_pb2.LookupRequest` for calling ``Lookup`... | 5,333,287 |
def render_table(data, col_width=3.0, row_height=0.625, font_size=14,
header_color='#40466e', row_colors=['#f1f1f2', 'w'], edge_color='w',
bbox=[0, 0, 1, 1], header_columns=0,
ax=None, **kwargs):
"""[Taken from ref: https://stackoverflow.com/questions/... | 5,333,288 |
def segment_image(class_colours, pixel_classes, height, width, bg_alpha=0, fg_alpha=255):
"""visualise pixel classes"""
segment_colours = np.reshape(class_colours[pixel_classes], (height, width, 3))
segment_colours = segment_colours.astype("uint8")
img = Image.fromarray(segment_colours)
# set backgr... | 5,333,289 |
def deploy(instance):
"""
Takes all files from the 'deploy' folder in the the lobot directoy and uploads
them to the remote machines '~/lobot/deploy' folder.
"""
print("?")
deploy_path = os.path.dirname(os.path.realpath(__file__))+"/deploy/"
print("\nContent of \"deploy\" folder:")
for f... | 5,333,290 |
def cross_replica_average(inputs,
num_shards=None,
num_shards_per_group=None,
physical_shape=None,
tile_shape=None,
use_spatial_partitioning=False):
"""Customized cross replica sum op."""
... | 5,333,291 |
def run_length_to_bitstream(rl: np.ndarray, values: np.ndarray, v_high: int, v_low: int) -> np.ndarray:
"""Do run length DECODING and map low/high signal to logic 0/1.
Supposed to leave middle values untouched.
[1,2,1,1,1] [7,1,7,1,5] -->
[1 0 0 1 0 5]
:param rl: Array of run lengths
:param val... | 5,333,292 |
def edge_naming(col_list, split_collections=True):
""" This function normalize the naming of edges collections
If split_collections is True an edge collection name will be
generated between each listed collection in order.
So if col_list = [A, B, C]
result will be [A__B, B__C]
... | 5,333,293 |
def interactive_visual_difference_from_threshold_by_day(ds_ext):
"""
Returns: 1) xarray DataArray, with three variables, for each day in the dataset
i) Highest value difference from the threshold, across the area
ii) Lowest value difference from the threshold, across the area
... | 5,333,294 |
def _parse_compression_method(data):
"""Parses the value of "method" extension parameter."""
return common.parse_extensions(data) | 5,333,295 |
def my_distance(drij):
"""
Compute length of displacement vector drij
assume drij already accounts for PBC
Args:
drij (np.array) : vector(s) of length 3
Returns:
float: length (distance) of vector(s)
"""
return np.linalg.norm(drij, axis=0) | 5,333,296 |
def session_with_model(model_type, name):
"""Create a context manager that will start a TensorFlow session and load
a model into it, and return the session and the model.
Example:
with model.session_with_model("grapheme", name) as session, model:
session.run(model.outputs, ...)
"""... | 5,333,297 |
def list_shared_projects(sortBy=None, sortOrder=None, maxResults=None, nextToken=None):
"""
Gets a list of projects that are shared with other AWS accounts or users.
See also: AWS API Documentation
Exceptions
:example: response = client.list_shared_projects(
sortBy='ARN'|'MODIFIED_... | 5,333,298 |
def show(list_id):
"""Get single list via id."""
data = db_session.query(List).filter(List.id == list_id).first()
if '/json' in request.path:
return jsonify(data.as_dict())
else:
return render_template('list/show.html', list=data) | 5,333,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.