content
stringlengths 22
815k
| id
int64 0
4.91M
|
---|---|
def upload_object(
self, key, body, metadata=None, acl=None, content_type="application/json"
):
"""Upload an arbitrary object to an S3 bucket.
Parameters
----------
S3 key : `str`
The Object's key identifier.
body : `str` or `bytes`
Object data
metadata : `dict`
Header metadata values. These keys will appear in headers as
``x-amz-meta-*``.
acl : `str`, optional
A pre-canned access control list. See
http://boto3.readthedocs.io/en/latest/reference/services/s3.html#bucket
Default is `None`, meaning that no ACL is applied to the object.
content_type : `str`, optional
The object's content type. Default is 'application/json'
Returns
-------
S3 URI of the uploaded object: `str`
The location of the S3 object uploaded in the form:
s3://<S3_BUCKET>/<key>
Note:
-----
Boto3 will check these environment variables for credentials:
AWS_ACCESS_KEY_ID
The access key for your AWS account.
AWS_SECRET_ACCESS_KEY
The secret key for your AWS account.
"""
s3 = boto3.resource("s3")
object = s3.Object(S3_BUCKET, key)
args = {}
if metadata is not None:
args["Metadata"] = metadata
if acl is not None:
args["ACL"] = acl
if content_type is not None:
args["ContentType"] = content_type
self.update_state(state="STARTED")
object.put(Body=body, **args)
s3_uri = get_s3_uri(key)
return s3_uri
| 5,346,100 |
def min_ui_count(proteins):
"""
Counts the minimum number of unique identifier peptides across all proteins
in a set
input:
proteins: list of protein sequences as strings ['protein_seq', ...]
output:
minimum number of unique identifier peptides across all proteins in
a set
"""
temp = []
for p in peptides_per_protein(unique_identifiers(proteins)):
temp.append(len(p[1]))
if len(proteins) > len(temp):
return 0
else:
return min(temp)
| 5,346,101 |
def check_normalize_py(method):
"""A wrapper that wrap a parameter checker to the original function(normalize operation written in Python)."""
@wraps(method)
def new_method(self, *args, **kwargs):
[mean, std], _ = parse_user_args(method, *args, **kwargs)
check_normalize_py_param(mean, std)
return method(self, *args, **kwargs)
return new_method
| 5,346,102 |
def GetOS(build_id, builder_name, step_name, partial_match=False):
# pylint:disable=unused-argument
"""Returns the operating system in the step_metadata.
Args:
build_id (int): Build id of the build.
builder_name (str): Builder name of the build.
step_name (str): The original step name used to get the step metadata.
Returns:
The operating system if it exists, otherwise, None.
"""
step_metadata = GetStepMetadata(build_id, step_name, partial_match)
return step_metadata.get('dimensions',
{}).get('os') if step_metadata else None
| 5,346,103 |
def _list(state, format, filter):
"""Lists the users on the Departing Employees list."""
employee_generator = _get_departing_employees(state.sdk, filter)
list_employees(
employee_generator, format, {"departureDate": "Departure Date"},
)
| 5,346,104 |
def __add_registration_args(parser):
"""
keywords defined for image registration
:param parser:
:return:
"""
parser.add_argument(
"--label_normalisation",
metavar='',
help="whether to map unique labels in the training set to "
"consecutive integers (the smallest label will be mapped to 0)",
type=str2boolean,
default=False)
from niftynet.application.label_driven_registration import SUPPORTED_INPUT
parser = add_input_name_args(parser, SUPPORTED_INPUT)
return parser
| 5,346,105 |
def get_catalog_item(catalog_id: Optional[str] = None,
catalog_item_id: Optional[str] = None,
location: Optional[str] = None,
project: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetCatalogItemResult:
"""
Gets a specific catalog item.
"""
__args__ = dict()
__args__['catalogId'] = catalog_id
__args__['catalogItemId'] = catalog_item_id
__args__['location'] = location
__args__['project'] = project
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('google-native:recommendationengine/v1beta1:getCatalogItem', __args__, opts=opts, typ=GetCatalogItemResult).value
return AwaitableGetCatalogItemResult(
category_hierarchies=__ret__.category_hierarchies,
description=__ret__.description,
item_attributes=__ret__.item_attributes,
item_group_id=__ret__.item_group_id,
product_metadata=__ret__.product_metadata,
tags=__ret__.tags,
title=__ret__.title)
| 5,346,106 |
def get_ext_suffix() -> str:
"""Get the extension suffix"""
return get_config_vars()["EXT_SUFFIX"]
| 5,346,107 |
def install_nbextension(extension: str,
*flags,
py=True,
sys_prefix=True,
symlink=False,
overwrite=True,
config: str = '',
log_level: Union[int, str] = logging.INFO):
"""Install nbextension.
:param extension: path to the extension or Python package name (if py=True)
:param py: bool, Whether to install from Python package (default: True)
:param sys_prefix: bool, Whether to use sys prefix, use this in virtual envs (default: True)
:param symlink: bool, Whether to create symlink to package data (default: False)
:param overwrite: bool, Whether to overwrite current files (default: True)
:param config: str, full path to a config file
:param log_level: enum, application log level
:param flags: str, additional flags
"""
version = subprocess.check_output(
args=shlex.split("jupyter nbextension --version"),
stderr=subprocess.STDOUT,
universal_newlines=True,
)
logger.debug("Jupyter nbextension version: %s", version.strip())
install_cmd = "jupyter nbextension install"
opts = ''
opts += ' --py' if py else ''
opts += ' --sys-prefix' if sys_prefix else ''
opts += ' --symlink' if symlink else ''
opts += ' --overwrite' if overwrite else ''
args = ''
args += f' --config {config}' if config else ''
args += f' --log-level {log_level}'
flags = ' '.join(flags)
cmd = ' '.join([install_cmd, opts, args, flags, extension])
p = subprocess.Popen(
args=shlex.split(cmd),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True,
)
logger.debug("Installing extension: %s", extension)
out, err = p.communicate(timeout=60)
logger.info(out)
if err:
logger.error(err)
logger.debug("Success.")
return p.returncode
| 5,346,108 |
def confusion_matrix(y_true, y_pred):
"""
Args:
y_true: pd.Series or array or list, ground truth (correct) labels.
y_pred: pd.Series or array or list, predicted labels, as returned by a classifier.
Returns:
Confusion matrix.
"""
t = pd.DataFrame({'actual':y_true, 'predict':y_pred})
t = pd.crosstab(t.predict, t.actual)
return t
| 5,346,109 |
def p_method_arg_optional_array(p):
"""
method_arg_optional_array : method_arg_array method_arg_optional_array
|
"""
if len(p) > 1:
p[0] = '%s%s' % (p[1], p[2])
else:
p[0] = ''
| 5,346,110 |
def load_currency_abbreviation_file(path: str) -> List[str]:
"""
Return a list of currency abbreviations present as one value per line in a file.
"""
with open(
os.path.join(__location__, path), "r", encoding="utf-8"
) as _file:
file_content = _file.read()
result = file_content.split("\n")
if result[-1] == "":
return result[:-1]
return result
| 5,346,111 |
def encode_boxes(boxes, im_shape, encode=True, dim_position=64, wave_length=1000, normalize=False, quantify=-1):
""" modified from PositionalEmbedding in:
Args:
boxes: [bs, num_nodes, 4] or [num_nodes, 4]
im_shape: 2D tensor, [bs, 2] or [2], the size of image is represented as [width, height]
encode: bool, whether to encode the box
dim_position: int, the dimension for position embedding
wave_length: the wave length for the position embedding
normalize: bool, whether to normalize the embedded features
quantify: int, if it is > 0, it will be used to quantify the position of objects
"""
batch = boxes.dim() > 2
if not batch:
boxes = boxes.unsqueeze(dim=0)
im_shape = im_shape.unsqueeze(dim=0)
if quantify > 1:
boxes = boxes // quantify
# in this case, the last 2 dims of input data is num_samples and 4.
# we compute the pairwise relative postion embedings for each box
if boxes.dim() == 3: # [bs, num_sample, 4]
# in this case, the boxes should be tlbr: [x1, y1, x2, y2]
device = boxes.device
bs, num_sample, pos_dim = boxes.size(0), boxes.size(1), boxes.size(2) # pos_dim should be 4
x_min, y_min, x_max, y_max = torch.chunk(boxes, 4, dim=2) # each has the size [bs, num_sample, 1]
# handle some invalid box
x_max[x_max<x_min] = x_min[x_max<x_min]
y_max[y_max<y_min] = y_min[y_max<y_min]
cx_a = (x_min + x_max) * 0.5 # [bs, num_sample_a, 1]
cy_a = (y_min + y_max) * 0.5 # [bs, num_sample_a, 1]
w_a = (x_max - x_min) + 1. # [bs, num_sample_a, 1]
h_a = (y_max - y_min) + 1. # [bs, num_sample_a, 1]
cx_b = cx_a.view(bs, 1, num_sample) # [bs, 1, num_sample_b]
cy_b = cy_a.view(bs, 1, num_sample) # [bs, 1, num_sample_b]
w_b = w_a.view(bs, 1, num_sample) # [bs, 1, num_sample_b]
h_b = h_a.view(bs, 1, num_sample) # [bs, 1, num_sample_b]
delta_x = ((cx_b - cx_a) / w_a).unsqueeze(dim=-1) # [bs, num_sample_a, num_sample_b, 1]
delta_y = ((cy_b - cy_a) / h_a).unsqueeze(dim=-1) # [bs, num_sample_a, num_sample_b, 1]
delta_w = torch.log(w_b / w_a).unsqueeze(dim=-1) # [bs, num_sample_a, num_sample_b, 1]
delta_h = torch.log(h_b / h_a).unsqueeze(dim=-1) # [bs, num_sample_a, num_sample_b, 1]
relative_pos = torch.cat((delta_x, delta_y, delta_w, delta_h), dim=-1) # [bs, num_sample_a, num_sample_b, 4]
# if im_shape is not None:
im_shape = im_shape.unsqueeze(dim=-1) # [bs, 2, 1]
im_width, im_height = torch.chunk(im_shape, 2, dim=1) # each has the size [bs, 1, 1]
x = ((cx_b - cx_a) / im_width).unsqueeze(dim=-1) # [bs, num_sample_a, num_sample_b, 1]
y = ((cy_b - cy_a) / im_height).unsqueeze(dim=-1) # [bs, num_sample_a, num_sample_b, 1]
# w = ((w_b + w_a) / (2 * im_width)).unsqueeze(dim=-1) - 0.5 # [bs, num_sample_a, num_sample_b, 1]
# h = ((h_b + h_a) / (2 * im_height)).unsqueeze(dim=-1) - 0.5 # [bs, num_sample_a. num_sample_b, 1]
w = ((w_b - w_a) / im_width).unsqueeze(dim=-1) # [bs, num_sample_a, num_sample_b, 1]
h = ((h_b - h_a) / im_height).unsqueeze(dim=-1) # [bs, num_sample_a. num_sample_b, 1]
relative_pos = torch.cat((relative_pos, x, y, w, h), dim=-1) # [bs, num_sample_a, num_sample_b, 8]
if not encode:
embedding = relative_pos
else:
position_mat = relative_pos # [bs, num_sample_a, num_sample_b, 8]
pos_dim = position_mat.size(-1)
feat_range = torch.arange(dim_position / (2*pos_dim)).to(device) # [self.dim_position / 16]
dim_mat = feat_range / (dim_position / (2*pos_dim))
dim_mat = 1. / (torch.pow(wave_length, dim_mat)) # [self.dim_position / 16]
dim_mat = dim_mat.view(1, 1, 1, 1, -1) # [1, 1, 1, 1, self.dim_position / 16]
# position_mat = position_mat.view(bs, num_sample, num_sample, pos_dim, -1) # [bs, num_sample_a, num_sample_b, 4, 1]
position_mat = position_mat.unsqueeze(dim=-1) # [bs, num_sample_a, num_sample_b, 8, 1]
position_mat = 100. * position_mat # [bs, num_sample_a, num_sample_b, 8, 1]
mul_mat = position_mat * dim_mat # [bs, num_sample_a, num_sample_b, 8, dim_position / 16]
mul_mat = mul_mat.view(bs, num_sample, num_sample, -1) # [bs, num_sample_a, num_sample_b, dim_position / 2]
sin_mat = torch.sin(mul_mat)# [bs, num_sample_a, num_sample_b, dim_position / 2]
cos_mat = torch.cos(mul_mat)# [bs, num_sample_a, num_sample_b, dim_position / 2]
embedding = torch.cat((sin_mat, cos_mat), -1)# [bs, num_sample_a, num_sample_b, dim_position]
if normalize:
embedding = embedding / torch.clamp(torch.norm(embedding, dim=-1, p=2, keepdim=True), 1e-6)
else:
raise ValueError("Invalid input of boxes.")
if not batch: # 2D tensor, [num_boxes, 4]
embedding = embedding.squeeze(dim=0)
return relative_pos, embedding
| 5,346,112 |
def get_docstring_and_version_via_import(target):
"""
Return a tuple like (docstring, version) for the given module,
extracted by importing the module and pulling __doc__ & __version__
from it.
"""
log.debug("Loading module %s", target.file)
sl = SourceFileLoader(target.name, str(target.file))
with _module_load_ctx():
m = sl.load_module()
docstring = m.__dict__.get('__doc__', None)
version = m.__dict__.get('__version__', None)
return docstring, version
| 5,346,113 |
def plot_t1(times: List[float], contrast: List[float], fname: str = None) -> Figure:
"""
Plot T1 relaxation figure along with laser delay time intervals
:param times: frequencies, unit: ns
:param contrast: contrast, range between 0 and 1
:param fname: if assigned, a '.png' file will be saved
:return: a matplotlib Figure instance
"""
fig = plt.figure()
plt.plot(times, contrast, 'o-')
plt.title('T1 Relaxometry')
plt.xlabel('Relaxation time (ns)')
plt.ylabel('Contrast $N_{sig}/N_{ref}$')
if fname is not None:
plt.savefig(fname, dpi=350)
return fig
| 5,346,114 |
def init(linter):
"""For each module get `rules` dictionary and visitors. Instantiate each visitor and map it to the
rule class instance using `reports` visitor attribute."""
for module in get_modules(linter.config.ext_rules):
classes = inspect.getmembers(module, inspect.isclass)
module_rules = {rule.name: rule for rule in getattr(module, "rules", {}).values()}
for checker in classes:
if issubclass(checker[1], BaseChecker) and getattr(checker[1], "reports", False):
checker_instance = checker[1]()
for reported_rule in checker_instance.reports:
if reported_rule not in module_rules:
raise RuleReportsNotFoundError(reported_rule, checker_instance) from None
checker_instance.rules[reported_rule] = module_rules[reported_rule]
linter.register_checker(checker_instance)
| 5,346,115 |
def partition_girvan_newman(graph, max_depth):
"""
Use your approximate_betweenness implementation to partition a graph.
Unlike in class, here you will not implement this recursively. Instead,
just remove edges until more than one component is created, then return
those components.
That is, compute the approximate betweenness of all edges, and remove
them until multiple components are created.
You only need to compute the betweenness once.
If there are ties in edge betweenness, break by edge name (e.g.,
(('A', 'B'), 1.0) comes before (('B', 'C'), 1.0)).
Note: the original graph variable should not be modified. Instead,
make a copy of the original graph prior to removing edges.
See the Graph.copy method https://networkx.github.io/documentation/stable/reference/classes/generated/networkx.Graph.copy.html
Params:
graph.......A networkx Graph
max_depth...An integer representing the maximum depth to search.
Returns:
A list of networkx Graph objects, one per partition.
>>> components = partition_girvan_newman(example_graph(), 5)
>>> components = sorted(components, key=lambda x: sorted(x.nodes())[0])
>>> sorted(components[0].nodes())
['A', 'B', 'C']
>>> sorted(components[1].nodes())
['D', 'E', 'F', 'G']
"""
graph_copy = graph.copy()
between_list = approximate_betweenness(graph_copy, max_depth)
between_list_ordered = sorted(between_list.items(), key=lambda i: i[1], reverse=True)
while len(get_components(graph_copy))==1:
graph_copy.remove_edge(*between_list_ordered[0][0])
del between_list_ordered[0]
components = get_components(graph_copy)
# [n.nodes() for n in components]
return components
###TODO
| 5,346,116 |
def start(ctx):
""" Start the API according to the config file
"""
module = ctx.config.get("api", "poloniex")
# unlockWallet
if module == "poloniex":
from .apis import poloniex
poloniex.run(ctx, port=5000)
else:
print_message("Unkown 'api'!", "error")
| 5,346,117 |
def inspect_project(dirpath=None):
"""Fetch various information about an already-initialized project"""
if dirpath is None:
dirpath = Path()
else:
dirpath = Path(dirpath)
def exists(*fname):
return Path(dirpath, *fname).exists()
if not exists("pyproject.toml"):
raise InvalidProjectError("Project is missing pyproject.toml file")
if not exists("setup.cfg"):
raise InvalidProjectError("Project is missing setup.cfg file")
if not exists("src"):
raise InvalidProjectError("Project does not have src/ layout")
cfg = read_configuration(str(dirpath / "setup.cfg"))
env = {
"name": cfg["metadata"]["name"],
"short_description": cfg["metadata"]["description"],
"author": cfg["metadata"]["author"],
"author_email": cfg["metadata"]["author_email"],
"python_requires": util.sort_specifier(cfg["options"]["python_requires"]),
"install_requires": cfg["options"].get("install_requires", []),
# Until <https://github.com/pypa/setuptools/issues/2575> is fixed, we
# have to determine versions via read_version() instead of
# read_configuration().
# "version": cfg["metadata"].get("version"),
"keywords": cfg["metadata"].get("keywords", []),
"supports_pypy3": False,
"default_branch": get_default_branch(dirpath),
}
# if env["version"] is None:
# raise InvalidProjectError("Cannot determine project version")
if cfg["options"].get("packages"):
env["is_flat_module"] = False
env["import_name"] = cfg["options"]["packages"][0]
env["version"] = read_version(
(dirpath / "src" / env["import_name"] / "__init__.py").resolve()
)
else:
env["is_flat_module"] = True
env["import_name"] = cfg["options"]["py_modules"][0]
env["version"] = read_version(
(dirpath / "src" / (env["import_name"] + ".py")).resolve()
)
env["python_versions"] = []
for clsfr in cfg["metadata"]["classifiers"]:
m = re.fullmatch(r"Programming Language :: Python :: (\d+\.\d+)", clsfr)
if m:
env["python_versions"].append(m.group(1))
if clsfr == "Programming Language :: Python :: Implementation :: PyPy":
env["supports_pypy3"] = True
env["commands"] = {}
try:
commands = cfg["options"]["entry_points"]["console_scripts"]
except KeyError:
pass
else:
for cmd in commands:
k, v = re.split(r"\s*=\s*", cmd, maxsplit=1)
env["commands"][k] = v
m = re.fullmatch(
r"https://github.com/([^/]+)/([^/]+)",
cfg["metadata"]["url"],
)
assert m, "Project URL is not a GitHub URL"
env["github_user"] = m.group(1)
env["repo_name"] = m.group(2)
if "Documentation" in cfg["metadata"]["project_urls"]:
m = re.fullmatch(
r"https?://([-a-zA-Z0-9]+)\.(?:readthedocs|rtfd)\.io",
cfg["metadata"]["project_urls"]["Documentation"],
)
assert m, "Documentation URL is not a Read the Docs URL"
env["rtfd_name"] = m.group(1)
else:
env["rtfd_name"] = env["name"]
toxcfg = ConfigParser(interpolation=None)
toxcfg.read(str(dirpath / "tox.ini")) # No-op when tox.ini doesn't exist
env["has_tests"] = toxcfg.has_section("testenv")
env["has_doctests"] = False
for pyfile in (dirpath / "src").rglob("*.py"):
if re.search(r"^\s*>>>\s+", pyfile.read_text(), flags=re.M):
env["has_doctests"] = True
break
env["has_typing"] = exists("src", env["import_name"], "py.typed")
env["has_ci"] = exists(".github", "workflows", "test.yml")
env["has_docs"] = exists("docs", "index.rst")
env["codecov_user"] = env["github_user"]
try:
with (dirpath / "README.rst").open(encoding="utf-8") as fp:
rdme = Readme.parse(fp)
except FileNotFoundError:
env["has_pypi"] = False
else:
for badge in rdme.badges:
m = re.fullmatch(
r"https://codecov\.io/gh/([^/]+)/[^/]+/branch/.+" r"/graph/badge\.svg",
badge.href,
)
if m:
env["codecov_user"] = m.group(1)
env["has_pypi"] = any(link["label"] == "PyPI" for link in rdme.header_links)
with (dirpath / "LICENSE").open(encoding="utf-8") as fp:
for line in fp:
m = re.match(r"^Copyright \(c\) (\d[-,\d\s]+\d) \w+", line)
if m:
env["copyright_years"] = list(intspan(m.group(1)))
break
else:
raise InvalidProjectError("Copyright years not found in LICENSE")
env["extra_testenvs"] = parse_extra_testenvs(
dirpath / ".github" / "workflows" / "test.yml"
)
return env
| 5,346,118 |
def test_bidirectional_mode(target_data):
"""
Testing NetGear's Bidirectional Mode with different datatypes
"""
try:
logger.debug('Given Input Data: {}'.format(target_data))
#open strem
stream = VideoGear(source=return_testvideo_path()).start()
#activate bidirectional_mode
options = {'bidirectional_mode': True}
#define params
client = NetGear(receive_mode = True, logging = True, **options)
server = NetGear(logging = True, **options)
#get frame from stream
frame_server = stream.read()
assert not(frame_server is None)
#sent frame and data from server to client
server.send(frame_server, message = target_data)
#client recieves the data and frame and send its data
server_data, frame_client = client.recv(return_data = target_data)
#server recieves the data and cycle continues
client_data = server.send(frame_server, message = target_data)
#clean resources
stream.stop()
server.close()
client.close()
#logger.debug data recieved at client-end and server-end
logger.debug('Data recieved at Server-end: {}'.format(server_data))
logger.debug('Data recieved at Client-end: {}'.format(client_data))
#check if recieved frame exactly matches input frame
assert np.array_equal(frame_server, frame_client)
#check if client-end data exactly matches server-end data
assert client_data == server_data
except Exception as e:
if isinstance(e, (ZMQError, ValueError)):
logger.error(traceback.print_tb(e.__traceback__))
else:
pytest.fail(str(e))
| 5,346,119 |
def requirements(ctx):
"""Write the `requirements-agent-release.txt` file at the root of the repo
listing all the Agent-based integrations pinned at the version they currently
have in HEAD.
"""
echo_info('Freezing check releases')
checks = get_valid_checks()
checks.remove('stackstate_checks_dev')
entries = []
for check in checks:
if check in AGENT_V5_ONLY:
echo_info('Check `{}` is only shipped with Agent 5, skipping'.format(check))
continue
try:
version = get_version_string(check)
entries.append('{}\n'.format(get_agent_requirement_line(check, version)))
except Exception as e:
echo_failure('Error generating line: {}'.format(e))
continue
lines = sorted(entries)
req_file = get_agent_release_requirements()
write_file_lines(req_file, lines)
echo_success('Successfully wrote to `{}`!'.format(req_file))
| 5,346,120 |
def current_user(request):
"""
Returning the current user with data use of token
"""
serializer = UserSerializer(request.user)
return Response(serializer.data)
| 5,346,121 |
def getPercentileLevels(h, frac=[0.5, 0.65, 0.95, 0.975]):
"""
Return image levels that corresponds to given percentiles values
Uses the cumulative distribution of the sorted image density values
Hence this works also for any nd-arrays
inputs:
h array
outputs:
res array containing level values
keywords:
frac sample fractions (percentiles)
could be scalar or iterable
default: 50%, 65%, 95%, and 97.5%
"""
if getattr(frac, '__iter__', False):
return numpy.asarray( [getPercentileLevels(h, fk) for fk in frac])
assert( (frac >= 0.) & (frac <1.)), "Expecting a sample fraction in 'frac' and got %f" %frac
# flatten the array to a 1d list
val = h.ravel()
# inplace sort
val.sort()
#reverse order
rval = val[::-1]
#cumulative values
cval = rval.cumsum()
#retrieve the largest indice up to the fraction of the sample we want
ind = numpy.where(cval <= cval[-1]*float(frac))[0].max()
res = rval[ind]
del val, cval, ind, rval
return res
| 5,346,122 |
def test_submission_validate_invalid_no_payload_dict():
"""
Test process_answer.submission_validate function.
"""
submission: dict = {
"xqueue_files": {"student_response.txt": "http://captive.apple.com"},
"xqueue_body": {"student_response": "5", "grader_payload": {"test": "1"}},
}
with pytest.raises(InvalidSubmissionException):
process_answer.submission_validate(submission)
| 5,346,123 |
def _rasterize_polygon(lon, lat, i, method):
"""
routine to rasterize polygon
as separate function to allow for parallel operations
"""
global THE_POLYGONS
global THE_MASK
P = THE_POLYGONS[i]
if not isinstance(P, Polygon):
raise ValueError('No Polygon object provided!')
if P.id < 0:
raise ValueError('ERROR: ID value must not be negative!')
if method != 'full':
raise ValueError('Only FULL method currently thoroughly validated!')
# check if data across the dateline. This is currently not supported yet!
if method != 'full':
if P.across_dateline(): # check routine not existing yet!
print('WARNING: seems that polygon is across the dateline. This is currently not supported yet! SKIPPING polygon with ID: ', P.id)
return
id = float(P.id)
# check if id already existing
msk = THE_MASK == float(id)
if msk.sum() > 0:
raise ValueError('The ID value is already existing!')
if method == 'full':
#~ hlp = np.ones_like(THE_MASK)*np.nan
#~ uvals = np.unique(THE_MASK[~np.isnan(THE_MASK)])
#~ print 'THE_MASK before: ', i, P.id, len(uvals)
# use fast cython based method
get_point_in_poly_mask(THE_MASK, lon, lat, P)
#~ print 'THE_MASK after: ', hlp
#~ mm = ~np.isnan(hlp)
#~ print 'N-valid: ', np.sum(mm)
#~ THE_MASK[mm] = hlp[mm]*1.
#~ uvals = np.unique(THE_MASK[~np.isnan(THE_MASK)])
#~ print 'THEMASK-after: ', i, len(uvals)
#~ del hlpe
elif method == 'fullold':
assert False
ny, nx = lon.shape
for i in range(ny):
#~ if i % 1 == 0:
print('Rasterization complete by ', np.round(100. * float(i) / float(ny), 0), '% \r',)
for j in range(nx):
if P.point_in_poly(lon[i, j], lat[i, j]):
if np.isnan(mask[i, j]):
mask[i, j] = id
else:
print(i, j, lon[i, j], lat[i, j])
raise ValueError(
'Overlapping polygons not supported yet!')
else:
pass
# an alternative implementation. This is however not necessarily faster
# than 'full'
elif method == 'faster':
assert False, 'Option currently not supported!'
print('Using CYTHON method for rasterization!')
mask = fast_point_in_poly(lon, lat, P)
elif method == 'fast':
assert False
xmin, xmax, ymin, ymax = P.bbox()
# determine bounding box very roughly NOT THAT THIS MIGHT BE NOT
# CORRECT
valid_points = (lon >= xmin) & (
lon <= xmax) & (lat >= ymin) & (lat <= ymax)
# preselect points that are likely to fall within polygon
plon = lon[valid_points]
plat = lat[valid_points]
resmsk = np.zeros_like(plon) * np.nan
for i in range(len(plon)):
#~ if i % 500 == 0:
#~ print i, len(plon)
if P.point_in_poly(plon[i], plat[i]):
if np.isnan(resmsk[i]):
resmsk[i] = id
else:
raise ValueError('Overlapping polygons not supported yet!')
# reassign mask
newmsk = np.ones_like(lon) * np.nan
newmsk[valid_points] = resmsk
newvalues = ~np.isnan(newmsk)
if np.any(~np.isnan(mask[newvalues])):
print(newmsk[newvalues])
print(sum(~np.isnan(mask[newvalues])))
raise ValueError('Some values had been set already before!')
mask[newvalues] = newmsk[newvalues]
else:
raise ValueError('ERROR: Invalid method')
| 5,346,124 |
def main(argv):
"""
Main entry point of this utility application.
This is simply a function called by the checking of namespace __main__, at
the end of this script (in order to execute only when this script is ran
directly).
Parameters
------
argv: list of str
Arguments received from the command line.
"""
annotationPath = 'C:/Users/luigi/Dropbox/Doutorado/dataset/annotation-all'
print('Reading data...')
fileName = '{}/../subjects.csv'.format(annotationPath)
games = pd.read_csv(fileName, sep=',', usecols=[0, 5], index_col=0)
subjects = []
data = pd.DataFrame(columns=['subject', 'frame', 'game', 'emotion', 'value'])
for dirpath, _, filenames in os.walk(annotationPath):
for f in filenames:
name = os.path.splitext(f)[0]
parts = name.split('-')
if len(parts) != 2 or parts[1] != 'emotions':
continue
parts = parts[0].split('_')
subject = int(parts[1])
subjects.append(subject)
# Get the subject's game
game = games.loc[subject]['Game Played']
# Read the emotions
fileName = os.path.join(dirpath, f)
df = pd.read_csv(fileName, sep=',')
df.columns = ['frame', 'neutral', 'happiness', 'sadness', 'anger',
'fear', 'surprise', 'disgust']
df = pd.melt(df, id_vars=['frame'], var_name='emotion', value_name='value')
#df = df[df['value'] != 0]
df['subject'] = [subject for _ in range(len(df))]
df['game'] = [game for _ in range(len(df))]
#df.columns = ['subject', 'frame', 'game', 'emotion', 'value']
df = df[['subject', 'frame', 'game', 'emotion', 'value']]
data = data.append(df)
data['subject'] = data['subject'].astype(int)
data['frame'] = data['frame'].astype(int)
#plotStack(data, 'neutral')
#plotStack(data, 'happiness')
#plotStack(data, 'sadness')
#plotStack(data, 'anger')
#plotStack(data, 'fear')
#plotStack(data, 'surprise')
#plotStack(data, 'disgust')
plotCountings(data)
#sns.violinplot(x='emotion', y='value', hue='game', data=data)
#plt.show()
| 5,346,125 |
def _ParseSparse(data):
"""Concat sparse tensors together.
Args:
data: A dict of name -> Tensor.
Returns:
A single sparse tensor and a 1-D input spec Tensor.
Raises:
NotImplementedError: Combining dense and sparse tensors is not
supported.
ValueError: If data contains non-string Tensors.
"""
for k in sorted(data.keys()):
if not isinstance(data[k], sparse_tensor.SparseTensor):
raise NotImplementedError(
'Features should be either all sparse or all dense. Use a '
'feature engineering function to convert some of them.')
data_spec = [
constants.DATA_CATEGORICAL if data[data.keys()[0]].dtype == dtypes.string
else constants.DATA_FLOAT
]
return sparse_ops.sparse_concat(1, data.values()), data_spec
| 5,346,126 |
def get_spectra2(X, E_in, p_dict, outputs=None):
"""
Calls get_Efield() to get Electric field, then use Jones matrices
to calculate experimentally useful quantities.
Alias for the get_spectra2 method in libs.spectra.
Inputs:
detuning_range [ numpy 1D array ]
The independent variable and defines the detuning points over which to calculate. Values in MHz
E_in [ numpy 1/2D array ]
Defines the input electric field vector in the xyz basis. The z-axis is always the direction of propagation (independent of the magnetic field axis), and therefore the electric field should be a plane wave in the x,y plane. The array passed to this method should be in one of two formats:
(1) A 1D array of (Ex,Ey,Ez) which is the input electric field for all detuning values;
or
(2) A 2D array with dimensions (3,len(detuning_range)) - i.e. each detuning has a different electric field associated with it - which will happen on propagation through a birefringent/dichroic medium
p_dict [ dictionary ]
Dictionary containing all parameters (the order of parameters is therefore not important)
Dictionary keys:
Key DataType Unit Description
--- --------- ---- -----------
Elem str -- The chosen alkali element.
Dline str -- Specifies which D-line transition to calculate for (D1 or D2)
# Experimental parameters
Bfield float Gauss Magnitude of the applied magnetic field
T float Celsius Temperature used to calculate atomic number density
GammaBuf float MHz Extra lorentzian broadening (usually from buffer gas
but can be any extra homogeneous broadening)
shift float MHz A global frequency shift of the atomic resonance frequencies
DoppTemp float Celsius Temperature linked to the Doppler width (used for
independent Doppler width and number density)
Constrain bool -- If True, overides the DoppTemp value and sets it to T
# Elemental abundancies, where applicable
rb85frac float % percentage of rubidium-85 atoms
K40frac float % percentage of potassium-40 atoms
K41frac float % percentage of potassium-41 atoms
lcell float m length of the vapour cell
theta0 float degrees Linear polarisation angle w.r.t. to the x-axis
Pol float % Percentage of probe beam that drives sigma minus (50% = linear polarisation)
NOTE: If keys are missing from p_dict, default values contained in p_dict_defaults will be loaded.
outputs: an iterable (list,tuple...) of strings that defines which spectra are returned, and in which order.
If not specified, defaults to None, in which case a default set of outputs is returned, which are:
S0, S1, S2, S3, Ix, Iy, I_P45, I_M45, alphaPlus, alphaMinus, alphaZ
Returns:
A list of output arrays as defined by the 'outputs' keyword argument.
Example usage:
To calculate the room temperature absorption of a 75 mm long Cs reference cell in an applied magnetic field of 100 G aligned along the direction of propagation (Faraday geometry), between -10 and +10 GHz, with an input electric field aligned along the x-axis:
detuning_range = np.linspace(-10,10,1000)*1e3 # GHz to MHz conversion
E_in = np.array([1,0,0])
p_dict = {'Elem':'Cs', 'Dline':'D2', 'Bfield':100, 'T':21, 'lcell':75e-3}
[Transmission] = calculate(detuning_range,E_in,p_dict,outputs=['S0'])
"""
# get some parameters from p dictionary
# need in try/except or equiv.
if 'Elem' in list(p_dict.keys()):
Elem = p_dict['Elem']
else:
Elem = p_dict_defaults['Elem']
if 'Dline' in list(p_dict.keys()):
Dline = p_dict['Dline']
else:
Dline = p_dict_defaults['Dline']
if 'shift' in list(p_dict.keys()):
shift = p_dict['shift']
else:
shift = p_dict_defaults['shift']
if 'lcell' in list(p_dict.keys()):
lcell = p_dict['lcell']
else:
lcell = p_dict_defaults['lcell']
if 'theta0' in list(p_dict.keys()):
theta0 = p_dict['theta0']
else:
theta0 = p_dict_defaults['theta0']
if 'Pol' in list(p_dict.keys()):
Pol = p_dict['Pol']
else:
Pol = p_dict_defaults['Pol']
# get wavenumber
exec('transition = AC.'+Elem+Dline+'Transition')
wavenumber = transition.wavevectorMagnitude
# Calculate Susceptibility
ChiPlus, ChiMinus, ChiZ = calc_chi(X, p_dict)
Chi = [ChiPlus, ChiMinus, ChiZ]
# Complex refractive index
nPlus = sqrt(1.0+ChiPlus) #Complex refractive index driving sigma plus transitions
nMinus = sqrt(1.0+ChiMinus) #Complex refractive index driving sigma minus transitions
nZ = sqrt(1.0+ChiZ) # Complex index driving pi transitions
# convert (if necessary) detuning axis X to np array
if type(X) in (int, float, int):
X = np.array([X])
else:
X = np.array(X)
# Calculate E_field
E_out, R = get_Efield(X, E_in, Chi, p_dict)
#print 'Output E field (Z): \n', E_out[2]
## Apply Jones matrices
# Transmission - total intensity - just E_out**2 / E_in**2
E_in = np.array(E_in)
if E_in.shape == (3,):
E_in = np.array([np.ones(len(X))*E_in[0],np.ones(len(X))*E_in[1],np.ones(len(X))*E_in[2]])
# normalised by input intensity
I_in = (E_in * E_in.conjugate()).sum(axis=0)
S0 = (E_out * E_out.conjugate()).sum(axis=0) / I_in
Iz = (E_out[2] * E_out[2].conjugate()).real / I_in
Transmission = S0
## Some quantities from Faraday geometry don't make sense when B and k not aligned, but leave them here for historical reasons
TransLeft = exp(-2.0*nPlus.imag*wavenumber*lcell)
TransRight = exp(-2.0*nMinus.imag*wavenumber*lcell)
# Faraday rotation angle (including incident linear polarisation angle)
phiPlus = wavenumber*nPlus.real*lcell
phiMinus = wavenumber*nMinus.real*lcell
phi = (phiMinus-phiPlus)/2.0
##
#Stokes parameters
#S1#
Ex = np.array(JM.HorizPol_xy * E_out[:2])
Ix = (Ex * Ex.conjugate()).sum(axis=0) / I_in
Ey = np.array(JM.VertPol_xy * E_out[:2])
Iy = (Ey * Ey.conjugate()).sum(axis=0) / I_in
S1 = Ix - Iy
#S2#
E_P45 = np.array(JM.LPol_P45_xy * E_out[:2])
E_M45 = np.array(JM.LPol_M45_xy * E_out[:2])
I_P45 = (E_P45 * E_P45.conjugate()).sum(axis=0) / I_in
I_M45 = (E_M45 * E_M45.conjugate()).sum(axis=0) / I_in
S2 = I_P45 - I_M45
#S3#
# change to circular basis
E_out_lrz = BC.xyz_to_lrz(E_out)
El = np.array(JM.CPol_L_lr * E_out_lrz[:2])
Er = np.array(JM.CPol_R_lr * E_out_lrz[:2])
Il = (El * El.conjugate()).sum(axis=0) / I_in
Ir = (Er * Er.conjugate()).sum(axis=0) / I_in
S3 = Ir - Il
Ir = Ir.real
Il = Il.real
Ix = Ix.real
Iy = Iy.real
## (Real part) refractive indices
#nMinus = nPlus.real
#nPlus = nMinus.real
## Absorption coefficients - again not a physically relevant quantity anymore since propagation is not as simple as k * Im(Chi) * L in a non-Faraday geometry
alphaPlus = 2.0*nMinus.imag*wavenumber
alphaMinus = 2.0*nPlus.imag*wavenumber
alphaZ = 2.0*nZ.imag*wavenumber
# Refractive/Group indices for left/right/z also no longer make any sense
#d = (array(X)-shift) #Linear detuning
#dnWRTv = derivative(d,nMinus.real)
#GIPlus = nMinus.real + (X + transition.v0*1.0e-6)*dnWRTv
#dnWRTv = derivative(d,nPlus.real)
#GIMinus = nPlus.real + (X + transition.v0*1.0e-6)*dnWRTv
if (outputs == None) or ('All' in outputs):
# Default - return 'all' outputs (as used by GUI)
return S0.real,S1.real,S2.real,S3.real,Ix.real,Iy.real,I_P45.real,I_M45.real,alphaPlus,alphaMinus,alphaZ
else:
# Return the variable names mentioned in the outputs list of strings
# the strings in outputs must exactly match the local variable names here!
return [locals()[output_str] for output_str in outputs]
| 5,346,127 |
def get_device_components(ralph_device_id):
"""Yields dicts describing all device components to be taken in assets"""
try:
ralph_device = Device.objects.get(id=ralph_device_id)
except Device.DoesNotExist:
raise LookupError('Device not found')
else:
components = ralph_device.get_components()
for processor in components.get('processors', []):
yield {
'model_proposed': processor.model.name,
}
for memory in components.get('memory', []):
yield {
'model_proposed': memory.model.name,
}
for storage in components.get('storages', []):
yield {
'model_proposed': storage.model.name,
'sn': storage.sn,
}
for ethernet in components.get('ethernets', []):
yield {
'model_proposed': unicode(ethernet),
'sn': ethernet.mac,
}
for fibrechannel in components.get('fibrechannels', []):
yield {
'model_proposed': fibrechannel.model.name,
}
| 5,346,128 |
def clear():
"""Set all LEDS to 0/off"""
all(0)
| 5,346,129 |
def resolve_resource_file(res_name, root_path=None, config=None):
"""Convert a resource into an absolute filename.
Resource names are in the form: 'filename.ext'
or 'path/filename.ext'
The system wil look for ~/.mycroft/res_name first, and
if not found will look at /opt/mycroft/res_name,
then finally it will look for res_name in the 'mycroft/res'
folder of the source code package.
Example:
With mycroft running as the user 'bob', if you called
resolve_resource_file('snd/beep.wav')
it would return either '/home/bob/.mycroft/snd/beep.wav' or
'/opt/mycroft/snd/beep.wav' or '.../mycroft/res/snd/beep.wav',
where the '...' is replaced by the path where the package has
been installed.
Args:
res_name (str): a resource path/name
config (dict): mycroft.conf, to read data directory from
Returns:
str: path to resource or None if no resource found
"""
if config is None:
from ovos_utils.configuration import read_mycroft_config
config = read_mycroft_config()
# First look for fully qualified file (e.g. a user setting)
if os.path.isfile(res_name):
return res_name
# Now look for ~/.mycroft/res_name (in user folder)
filename = os.path.expanduser("~/.mycroft/" + res_name)
if os.path.isfile(filename):
return filename
# Next look for /opt/mycroft/res/res_name
data_dir = os.path.expanduser(config.get('data_dir', "/opt/mycroft"))
filename = os.path.expanduser(os.path.join(data_dir, res_name))
if os.path.isfile(filename):
return filename
# look in ovos_utils package itself
found = resolve_ovos_resource_file(res_name)
if found:
return found
# Finally look for it in the source package
paths = [
"/opt/venvs/mycroft-core/lib/python3.7/site-packages/", # mark1/2
"/opt/venvs/mycroft-core/lib/python3.4/site-packages/ ",
# old mark1 installs
"/home/pi/mycroft-core" # picroft
]
if root_path:
paths += [root_path]
for p in paths:
filename = os.path.join(p, 'mycroft', 'res', res_name)
filename = os.path.abspath(os.path.normpath(filename))
if os.path.isfile(filename):
return filename
return None
| 5,346,130 |
def writeDotGraph(taskInfoFile, taskStateFile, workflowClassName) :
"""
write out the current graph state in dot format
"""
addOrder = []
taskInfo = {}
headNodes = set()
tailNodes = set()
# read info file:
for (label, namespace, ptype, _nCores, _memMb, _priority, _isForceLocal, depStr, _cwdStr, _command) in taskInfoParser(taskInfoFile) :
tid = (namespace, label)
addOrder.append(tid)
taskInfo[tid] = Bunch(ptype=ptype,
parentLabels=getTaskInfoDepSet(depStr))
if len(taskInfo[tid].parentLabels) == 0 : headNodes.add(tid)
tailNodes.add(tid)
for plabel in taskInfo[tid].parentLabels :
ptid = (namespace, plabel)
if ptid in tailNodes : tailNodes.remove(ptid)
for (label, namespace, runState, _errorCode, _time) in taskStateParser(taskStateFile) :
tid = (namespace, label)
taskInfo[tid].runState = runState
dotFp = sys.stdout
dotFp.write("// Task graph from pyflow object '%s'\n" % (workflowClassName))
dotFp.write("// Process command: '%s'\n" % (cmdline()))
dotFp.write("// Process working dir: '%s'\n" % (os.getcwd()))
dotFp.write("// Graph capture time: %s\n" % (timeStrNow()))
dotFp.write("\n")
dotFp.write("digraph %s {\n" % (workflowClassName + "Graph"))
dotFp.write("\tcompound=true;\nrankdir=LR;\nnode[fontsize=10];\n")
labelToSym = {}
namespaceGraph = {}
for (i, (namespace, label)) in enumerate(addOrder) :
tid = (namespace, label)
if namespace not in namespaceGraph :
namespaceGraph[namespace] = ""
sym = "n%i" % i
labelToSym[tid] = sym
attrib1 = DotConfig.getRunstateDotAttrib(taskInfo[tid].runState)
attrib2 = DotConfig.getTypeDotAttrib(taskInfo[tid].ptype)
namespaceGraph[namespace] += "\t\t%s [label=\"%s\"%s%s];\n" % (sym, label, attrib1, attrib2)
for (namespace, label) in addOrder :
tid = (namespace, label)
sym = labelToSym[tid]
for plabel in taskInfo[tid].parentLabels :
ptid = (namespace, plabel)
namespaceGraph[namespace] += ("\t\t%s -> %s;\n" % (labelToSym[ptid], sym))
for (i, ns) in enumerate(namespaceGraph.keys()) :
isNs = ((ns is not None) and (ns != ""))
dotFp.write("\tsubgraph cluster_sg%i {\n" % (i))
if isNs :
dotFp.write("\t\tlabel = \"%s\";\n" % (ns))
else :
dotFp.write("\t\tlabel = \"%s\";\n" % (workflowClassName))
dotFp.write(namespaceGraph[ns])
dotFp.write("\t\tbegin%i [label=\"begin\" shape=diamond];\n" % (i))
dotFp.write("\t\tend%i [label=\"end\" shape=diamond];\n" % (i))
for (namespace, label) in headNodes :
if namespace != ns : continue
sym = labelToSym[(namespace, label)]
dotFp.write("\t\tbegin%i -> %s;\n" % (i, sym))
for (namespace, label) in tailNodes :
if namespace != ns : continue
sym = labelToSym[(namespace, label)]
dotFp.write("\t\t%s -> end%i;\n" % (sym, i))
dotFp.write("\t}\n")
if ns in labelToSym :
dotFp.write("\t%s -> begin%i [style=dotted];\n" % (labelToSym[ns], i))
# in LR orientation this will make the graph look messy:
# dotFp.write("\tend%i -> %s [style=invis];\n" % (i,labelToSym[ns]))
dotFp.write(DotConfig.getDotLegend())
dotFp.write("}\n")
hardFlush(dotFp)
| 5,346,131 |
def _CommonArgs(parser, api_version):
"""A helper function to build args based on different API version."""
messages = apis.GetMessagesModule('compute', api_version)
flags.MakeResourcePolicyArg().AddArgument(parser)
flags.AddCommonArgs(parser)
flags.AddGroupPlacementArgs(parser, messages)
parser.display_info.AddCacheUpdater(None)
| 5,346,132 |
def lambda_handler(event, context):
"""Sample pure Lambda function
Parameters
----------
event: dict, required
Input
Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format
context: object, required
Lambda Context runtime methods and attributes
Context doc: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html
Returns
------
dict
"""
command = event['command']
res = subprocess.check_output(command.split(' '))
return {
"statusCode": 200,
"body": res
}
| 5,346,133 |
def calculate_seat_district(district_deputy_number, parties, votes):
"""
Calculate seats for each party in list of parties for a district
Params:
- district_deputy_number: the number of seats for this district
- parties: list of parties
- votes: list of votes for each party in this district
Assume that parties and votes parameters have the same size
Return:
- A tuple represents number of seats for each party. This tuple has same size with parameter 'parties'
"""
party_count = len(parties)
# Each party has been initially allocated 0 seat
# Initialize a list with initial value is 0
# For example, if party_count = 5
# seats will be seats = [0, 0, 0, 0, 0]
seats = [0] * party_count
# N value for each party
# N= V/(s + 1)
# Init N as a copy of votes list
N = votes[:]
while sum(seats) < district_deputy_number:
# Get the maximum value in list of N value and the index of that maximum value
# Note: this below line uses the Python's builtin operator
max_index, max_value = max(enumerate(N), key=operator.itemgetter(1))
# Update the seats list
# increase the seat of the party that has maximum by 1
seats[max_index] += 1
# Update the lagest N with new value
# using the formal: N= V/(s + 1)
N[max_index] = votes[max_index] / (seats[max_index] + 1)
# return as tuple
# Note: It can be returned as list, however, the tuple is better because it's immutable
return tuple(seats)
| 5,346,134 |
def dispatch():
"""Run all dispatch tests"""
suite = ServiceTestSuite()
suite.addTest(unittest.makeSuite(TestCase, 'test_dispatch'))
return suite
| 5,346,135 |
def get_mask(height, width, grid_size = 10):
"""
Get the location based on the image size corresponding to relu_4_2
and relu_5_1 layer for a desired grid size.
"""
print(height, width)
x_jump = int(width/grid_size)
y_jump = int(height/grid_size)
x_idx = np.linspace(int(x_jump/2),int(width - x_jump/2), grid_size, dtype = np.int32)
y_idx = np.linspace(int(y_jump/2), int(height - y_jump/2), grid_size, dtype = np.int32)
f_mask = torch.zeros((height//(2**4),width//2**4)).byte()
u_mask = torch.zeros((height//(2**3),width//2**3)).byte()
for i in x_idx:
for j in y_idx:
f_mask[j//(2**4),i//(2**4)] = 1
u_mask[j//(2**3),i//(2**3)] = 1
return(u_mask, f_mask)
| 5,346,136 |
def arrivalTimes2TimeTraceBH(arrivalTimes, binLength):
"""
Convert a list of arrivalTimes to an intensity time trace I(t)
===========================================================================
Input Meaning
---------------------------------------------------------------------------
arrivalTimes Variable with the arrivalTimes for each detector
element [of ns]
binLength Duration of each bin [in ns]
===========================================================================
Output Meaning
---------------------------------------------------------------------------
data Vector with intensity trace vs time in bins of binLength
===========================================================================
"""
# calculate for each photon in which bin it should be
photonBins = np.int64(arrivalTimes / binLength)
# number of photon bins
Nbins = np.max(photonBins) + 1
# create output vector
data = np.zeros(Nbins, 'int16')
for i in range(len(photonBins)):
data[photonBins[i]] += 1
return data
| 5,346,137 |
def datetime_to_ts(dt):
"""
convert naive or aware datetime instance to timestamp in second
Args:
dt(datetime): datetime instance
Returns:
int: timestamp in second.
"""
epoch_dt = datetime.datetime.fromtimestamp(0, tz=pytz.utc)
if not hasattr(dt, 'tzinfo') or dt.tzinfo is None:
local_tz = tzlocal.get_localzone()
dt = local_tz.localize(dt)
delta = dt - epoch_dt
ts = delta.total_seconds()
return ts
| 5,346,138 |
def peaks(spectra,frequency,number=3,thresh=0.01):
""" Return the peaks from the Fourier transform
Variables:
number: integer. number of peaks to print.
thresh: float. Threshhold intensity for printing.
Returns: Energy (eV), Intensity (depends on type of spectra)
"""
from scipy.signal import argrelextrema as pks
# find all peak indices [idx], and remove those below thresh [jdx]
idx = pks(np.abs(spectra),np.greater,order=3)
jdx = np.where((np.abs(spectra[idx]) >= thresh))
kdx = idx[0][jdx[0]] # indices of peaks matching criteria
if number > len(kdx):
number = len(kdx)
print("First "+str(number)+" peaks (eV) found: ")
for i in xrange(number):
print("{0:.4f}".format(frequency[kdx][i]*27.2114),
"{0:.4f}".format(spectra[kdx][i]))
| 5,346,139 |
def load_csv(source_filepath, start_date = None, end_date = None,
timestamp_index = 0,
column_map = {"bidopen": "bidopen",
"bidclose": "bidclose",
"bidhigh": "bidhigh",
"bidlow": "bidlow",
"askopen": "askopen",
"askclose": "askclose",
"askhigh": "askhigh",
"asklow": "asklow",
"volume": "tickqty"}):
"""Loads a csv price data file
Args:
source_filepath (string): the full or relative filepath for csv input file
start_date (string): optional filter for price data
end_date (string): optional filter for price data
timestamp_index (int): column index for the start of bar timestamp
column_map (dict): maps the csv file columns (value) to the predefined
column names (key)
Returns:
Pandas.DataFrame: returns the price data
"""
#read the csv file
df = pd.read_csv(source_filepath, sep=",", index_col=timestamp_index, parse_dates=True)
#convert the columns to the correct data type
df["askopen"] = df[column_map["askopen"]].astype('float32')
df["askclose"] = df[column_map["askclose"]].astype('float32')
df["askhigh"] = df[column_map["askhigh"]].astype('float32')
df["asklow"] = df[column_map["asklow"]].astype('float32')
df["bidopen"] = df[column_map["bidopen"]].astype('float32')
df["bidclose"] = df[column_map["bidclose"]].astype('float32')
df["bidhigh"] = df[column_map["bidhigh"]].astype('float32')
df["bidlow"] = df[column_map["bidlow"]].astype('float32')
df["volume"] = df[column_map["volume"]].astype('int32')
#reorder the columns in the correct order
cols = ["askopen", "askclose", "askhigh", "asklow", "bidopen", "bidclose",
"bidhigh", "bidlow", "volume"]
df = df[cols]
#filter on dates if required
if start_date is not None:
df = df[df.index >= start_date]
if end_date is not None:
df = df[df.index <= end_date]
return df
| 5,346,140 |
def create_kernel(dim0, dim1):
"""Create a two-dimensional LPF kernel, with a half-Hamming window along
the first dimension and a Gaussian along the second.
Parameters
----------
dim0 : int
Half-Hamming window length.
dim1 : int
Gaussian window length.
Returns
-------
kernel : np.ndarray
The 2d LPF kernel.
"""
dim0_weights = np.hamming(dim0 * 2 + 1)[:dim0]
dim1_weights = gaussian(dim1, dim1 * 0.25, True)
kernel = dim0_weights[:, np.newaxis] * dim1_weights[np.newaxis, :]
return kernel / kernel.sum()
| 5,346,141 |
def generate_fractal_noise_3d(
shape, res, octaves=1, persistence=0.5, lacunarity=2,
tileable=(False, False, False), interpolant=interpolant
):
"""Generate a 3D numpy array of fractal noise.
Args:
shape: The shape of the generated array (tuple of three ints).
This must be a multiple of lacunarity**(octaves-1)*res.
res: The number of periods of noise to generate along each
axis (tuple of three ints). Note shape must be a multiple of
(lacunarity**(octaves-1)*res).
octaves: The number of octaves in the noise. Defaults to 1.
persistence: The scaling factor between two octaves.
lacunarity: The frequency factor between two octaves.
tileable: If the noise should be tileable along each axis
(tuple of three bools). Defaults to (False, False, False).
interpolant: The, interpolation function, defaults to
t*t*t*(t*(t*6 - 15) + 10).
Returns:
A numpy array of fractal noise and of shape shape generated by
combining several octaves of perlin noise.
Raises:
ValueError: If shape is not a multiple of
(lacunarity**(octaves-1)*res).
"""
noise = cp.zeros(shape)
frequency = 1
amplitude = 1
for _ in range(octaves):
noise += amplitude * generate_perlin_noise_3d(
shape,
(frequency*res[0], frequency*res[1], frequency*res[2]),
tileable,
interpolant
)
frequency *= lacunarity
amplitude *= persistence
return noise
| 5,346,142 |
def getDeltaBetweenPosition(data_outVTK, wall_outVTK, cord_choice, x_p0, x_p1, Npts, Uinf=None, Rhoinf=None):
"""
Compute the boundary layer thickness for *Npts* equally distributed between the 2 position
defined thanks to *x_p0*, *x_p1* and *cord_choice*. See the documentation of the function
getDeltaAtPosition() for more information.
Parameters
----------
data_outVTK : VTK output object from a VTK reader
This field data MUST fulfill 2 conditions:
- contain the field "U_AVG",
- represent a 2D field data, as we want to extract a 1D velocity
profile from it.
wall_outVTK : VTK output object from a VTK reader
This field is supposed to describe a curve with 1D cell type, like in getLineTangentialVector()
cord_choice : integer, 0, 1 or 2
Gives the axis that is going to be used to define the point where the velocity
profile is extracted. Convention :
- 0 = x axis
- 1 = y axis
- 2 = z axis
x_p0, x_p1 : float between 0 and 1
gives the bound of the line where to compute the BL thickness.
Npts: integer
Number of points where to compute delta wanted.
Uinf : float
(optional) Free stream velocity
Rhoinf : float
(optional) Free stream density
Returns
-------
pos : vector of tuple(3)
the coordinates of the points where delta have been computed.
delta : vector of floats
The BL thickness at the *Npts* different points.
deltaS : vector of floats
The compressible BL displacement thickness at the *Npts* different points.
theta : vector of floats
The compressible BL momentum thickness at the *Npts* different points.
"""
# function display
print '---- DAEPy::getDeltaBetweenPosition ----'
delta = np.zeros(Npts)
deltaS = np.zeros(Npts)
theta = np.zeros(Npts)
pos = np.zeros((Npts, 3))
for i in range(Npts):
x_p_temp = x_p0 + (x_p1-x_p0)/(Npts-1)*i
[pos[i,:], delta[i], deltaS[i], theta[i]] = getDeltaAtPosition(data_outVTK, wall_outVTK, cord_choice, x_p_temp, Uinf, Rhoinf)
return [pos, delta, deltaS, theta]
| 5,346,143 |
def get_clean_url(url):
""" Get a url without the language part, if i18n urls are defined
:param url: a string with the url to clean
:return: a string with the cleaned url
"""
url = url.strip('/')
url = '/' if not url else url
return '/'.join(url.split('/')[1:])
| 5,346,144 |
def get_fields_from_url():
"""Returns a list of fields defined in the url as expected by the RESTful standard"""
return request.args.get('fields', '').split(",")
| 5,346,145 |
def get_triples_processed(dcids, limit=_MAX_LIMIT):
"""
Generate the GetTriple query and send the request.
The response is processed into as triples strings. This API is used by the
pv tree tool.
"""
url = API_ROOT + API_ENDPOINTS['get_triples']
payload = send_request(url, req_json={'dcids': dcids, 'limit': limit})
# Create a map from dcid to list of triples.
results = collections.defaultdict(list)
for dcid in dcids:
# Make sure each dcid is mapped to an empty list.
results[dcid]
# Add triples as appropriate
for t in payload[dcid]:
if 'objectId' in t:
results[dcid].append(
(t['subjectId'], t['predicate'], t['objectId']))
elif 'objectValue' in t:
results[dcid].append(
(t['subjectId'], t['predicate'], t['objectValue']))
return dict(results)
| 5,346,146 |
def load_ipython_extension(ip=None):
"""This function is called when the extension is loaded.
It accepts an IPython |ip| instance. We can register the magic
with the :func:`IPython.core.magics.register_magic_function`
method.
Parameters
-----------
ip : |ip|
"""
if ip is None:
ip = get_ipython()
if ip is None:
return
ip.register_magic_function("pd_csv")
| 5,346,147 |
def cid_to_date(cid):
"""Converts a cid to date string YYYY-MM-DD
Parameters
----------
cid : int
A cid as it is generated by the function ``utils.create_cid()``
Returns
-------
str
A string formated date (e.g. YYYY-MM-DD, 2018-10-01)
"""
return datetime.utcfromtimestamp(
cid/10000000.0
).strftime("%Y-%m-%d")
| 5,346,148 |
def get_listings(max_pages=10):
"""Returns the listings from the first max_pages of craigslist."""
page = requests.get(URL)
tree = html.fromstring(page.content)
listing_xpath = '//li[@class="result-row"]'
listings = tree.xpath(listing_xpath)
# Get total number of listings
default_lpp = 120 # Default number of listings on each page
num_listings = int(tree.xpath('//span[@class="totalcount"]/text()')[0])
total_pages = ceil(num_listings / default_lpp)
# Get next pages
for i in range(min(max_pages - 1, total_pages)):
next_page = requests.get(URL + "&s=%s" % (default_lpp * i))
next_tree = html.fromstring(page.content)
next_listings = tree.xpath(listing_xpath)
listings.extend(next_listings)
return listings
| 5,346,149 |
def remove_edge_stochastic_function(G, parameter, prob_func, prob_func_kws={}, random_seed=None, copy=True):
"""
Recieves a Graph and p.
p is function of a defined parameter
Returns a degraded Graph
"""
if random_seed is not None:
random.seed(random_seed)
if copy:
G_ = G.copy()
else:
G_ = G
lst = [G.edges[n][parameter] for n in G.edges]
vmax, vmin = max(lst), min(lst)
prob_func_kws['vmax'] = vmax
prob_func_kws['vmin'] = vmin
lst=None
for edge in list(G.edges):
p = prob_func(G.edges[edge][parameter], **prob_func_kws)
if random.random()<=p:
G_.remove_edge(*edge)
return(G_)
| 5,346,150 |
def find(
_,
ticket_id,
author=False,
sort=None,
reverse=False,
only=None,
permissions=False,
utc=False,
env=None,
releases_only=False,
):
"""
What latest releases/deploys contain commits belonging to this ticket?
"""
# TODO: link these commits back to app releases
merged_commits = get_merged_commits_from_ticket(ticket_id)
all_commits = []
for repo_name, commits in merged_commits.items():
for commit in commits:
all_commits.append((repo_name, commit))
num_commits = len(all_commits)
utils.alert(
f"Found {num_commits} commit{'s' if num_commits != 1 else ''} linked to {ticket_id}\n"
)
for i, (repo_name, commit) in enumerate(all_commits, start=1):
utils.alert(f"Commit {i}/{num_commits}: {repo_name}: {commit}\n")
projects = list_projects(
contains=commit,
only=only,
permissions=permissions,
utc=utc,
env=env,
releases_only=releases_only,
)
format_projects(
projects,
author=author,
contains=True,
sort=sort,
reverse=reverse,
permissions=permissions,
)
| 5,346,151 |
def get_sh_type(sh_type):
"""Get the section header type."""
if sh_type == 0:
return 'SHT_NULL'
elif sh_type == 1:
return 'SHT_PROGBITS'
elif sh_type == 2:
return 'SHT_SYMTAB'
elif sh_type == 3:
return 'SHT_STRTAB'
elif sh_type == 4:
return 'SHT_RELA'
elif sh_type == 5:
return 'SHT_HASH'
elif sh_type == 6:
return 'SHT_DYNAMIC'
elif sh_type == 7:
return 'SHT_NOTE'
elif sh_type == 8:
return 'SHT_NOBITS'
elif sh_type == 9:
return 'SHT_REL'
elif sh_type == 10:
return 'SHT_SHLIB'
elif sh_type == 11:
return 'SHT_DYNSYM'
elif sh_type == 14:
return 'SHT_INIT_ARRAY'
elif sh_type == 15:
return 'SHT_FINI_ARRAY'
elif sh_type == 16:
return 'SHT_PREINIT_ARRAY'
elif sh_type == 17:
return 'SHT_GROUP'
elif sh_type == 18:
return 'SHT_SYMTAB_SHNDX'
elif sh_type == 19:
return 'SHT_NUM'
elif sh_type == 1610612736:
return 'SHT_LOOS'
else:
print('Unable to match {} to a sh_type.'.format(sh_type))
raise ValueError
| 5,346,152 |
def run_script():
"""
The main entry point of the script, as called by the client
via the scripting service, passing the required parameters.
"""
client = scripts.client(
'Dataset_Images_To_New_Figure.py',
"""Use Images from a Dataset to replace those in a Figure and
save the result as a new Figure, in the same group as the Images""",
scripts.String(
"Data_Type", optional=False, grouping="1",
description="Only support Dataset", values=[rstring("Dataset")],
default="Dataset"),
scripts.List(
"IDs", optional=False, grouping="2",
description="Dataset ID. Only 1 supported").ofType(rlong(0)),
scripts.List("Figure_IDs", optional=False, grouping="3",
description="Figure ID").ofType(rlong(0)),
)
try:
conn = BlitzGateway(client_obj=client)
params = client.getInputs(unwrap=True)
print("params", params)
msg = dataset_images_to_new_figure(conn, params)
client.setOutput("Message", rstring(msg))
finally:
client.closeSession()
| 5,346,153 |
def model_objectives(model):
"""Return a list of objectives in the model"""
for obj in model.component_map(aml.Objective, active=True).itervalues():
for idx in obj:
yield obj[idx]
| 5,346,154 |
def EnsureNoProprietaryMixins(errs, builder_groups, configs, mixins):
"""If we're checking the Chromium config, check that the 'chromium' bots
which build public artifacts do not include the chrome_with_codecs mixin.
"""
if 'chromium' in builder_groups:
for builder in builder_groups['chromium']:
config = builder_groups['chromium'][builder]
def RecurseMixins(current_mixin):
if current_mixin == 'chrome_with_codecs':
errs.append('Public artifact builder "%s" can not contain the '
'"chrome_with_codecs" mixin.' % builder)
return
if not 'mixins' in mixins[current_mixin]:
return
for mixin in mixins[current_mixin]['mixins']:
RecurseMixins(mixin)
for mixin in configs[config]:
RecurseMixins(mixin)
else:
errs.append('Missing "chromium" builder_group. Please update this '
'proprietary codecs check with the name of the builder_group '
'responsible for public build artifacts.')
| 5,346,155 |
def show_warn_message(text:str, *args:str) -> str:
"""
Show a warning message.
"""
return _base("showWarningMessage", text, *args)
| 5,346,156 |
def read_gmpe_file(resid_file, period):
"""
Reads the gmpe residuals file and returns all the data
"""
gmpe_data = []
# Read residuals file and get information we need
input_file = open(resid_file, 'r')
# Look over header and figure out which column contains the period
# we need to plot
header = input_file.readline()
header = header.strip()
items = header.split()
index = -1
for idx, item in enumerate(items):
try:
val = float(item)
if val == period:
# Found period, save index
index = idx
break
except:
pass
if index < 0:
# If we don't have this period, nothing to do
print("Residuals file %s does not have data for period %f" %
(resid_file, period))
# Close input file
input_file.close()
# Return empty sets
return gmpe_data
# Read the rest of the file
# Index #2 has station name
# Index #7 has distance
for line in input_file:
items = line.split()
stat = items[2]
dist = items[7]
value = items[index]
gmpe_data.append((stat, dist, value))
# Done reading the file
input_file.close()
return gmpe_data
| 5,346,157 |
def remove_sep(path, new_sep='--'):
"""Convert a real path into pseudo-path."""
return path.replace(os.sep, new_sep)
| 5,346,158 |
def correct_colors(im1, im2, landmarks1):
"""
Towards perceptual satisfaction of splicing donor image into recipient.
The color of images is argubly the strongest perceptual attribute, which is ameliorated here.
Note: Further work will improve on geometric distortion (cylindrical, spherical, etc.) and image intrinsics
"""
| 5,346,159 |
def git_commit(message, cwd):
"""Commit files to git server."""
cmd = ['git', 'commit', '-m', message]
subprocess.check_call(cmd, cwd=cwd)
return
| 5,346,160 |
def default_loggingfcn(log, time, entity):
"""
Default function used to log snapshots of agents' states.
"""
for name in entity._names:
log[name].append( copy(getattr(entity, name)) )
| 5,346,161 |
def get_types(name=None):
"""Retrieves the list of device types in the system.
Note that we actually use the "GET device-families" endpoint, as this returns a complete list in one request.
"""
all_types = []
all_families = get_families(name=None, includeTypes=True)
for family in all_families:
all_types.extend(family["types"])
return all_types
| 5,346,162 |
def read_socket(sock, buf_len, echo=True):
""" Read data from socket and return it in JSON format """
reply = sock.recv(buf_len).decode()
try:
ret = json.loads(reply)
except json.JSONDecodeError:
print("Error in reply: ", reply)
sock.close()
raise
if echo:
print(json.dumps(ret))
return ret
| 5,346,163 |
def do_monitor_media_list(client, args):
"""List media"""
kwargs = {'user_id': args.userid}
medias = client.media.list(**kwargs)
utils.print_list(medias)
| 5,346,164 |
def temperature_source_function(
rho,
district,
norm,
density: xr.DataArray,
etemp: xr.DataArray,
itemp: xr.DataArray,
density_source: xr.DataArray,
source_strength,
source_centre=0.3,
source_width=0.3,
):
"""
Smooth-step core power injection, mimicking Ohmic power deposition
The temperature source takes into account the power from the density source, to give a constant-power source
"""
core_source = core_temperature_source_function(
rho, district, norm, source_strength, source_centre, source_width
)
total_source = xr.DataArray(
core_source / density - density_source * (etemp + itemp) / density
).assign_attrs(norm=norm.Te0 / norm.tau_0)
core_source = xr.DataArray(core_source / density).assign_attrs(
norm=norm.Te0 / norm.tau_0
)
annular_sink = xr.DataArray(
-density_source * (etemp + itemp) / density
).assign_attrs(norm=norm.Te0 / norm.tau_0)
return total_source, core_source, annular_sink
| 5,346,165 |
def mock_dbt_cloud_response(
monkeypatch: MonkeyPatch,
dbt_manifest_file: Path,
dbt_run_results_file: Path,
) -> None:
"""
Mock the dbt cloud response.
Parameters
----------
monkeypatch : MonkeyPatch
The monkey patch fixture.
dbt_manifest_file : Path
The path to the manifest file.
dbt_run_results_file : Path
The path to the run results file.
"""
def get(url: str, headers: dict | None = None):
"""Mock the requests.get method."""
response = requests.Response()
if "manifest.json" in url:
file = dbt_manifest_file
elif "run_results.json" in url:
file = dbt_run_results_file
else:
raise ValueError(f"Unrecognized url: {url}")
with file.open("rb") as f:
response._content = f.read()
response.status_code = requests.codes.ok
return response
monkeypatch.setattr(requests, "get", get)
| 5,346,166 |
async def model_copy(request, model_id):
""" route for copy item per row """
request_params = {elem: request.form[elem][0] for elem in request.form}
base_obj_id = utils.extract_obj_id_from_query(request_params["_id"])
try:
new_obj_key = await create_object_copy(
model_id, base_obj_id, cfg.models[model_id]
)
message = f"Object with {base_obj_id} key was copied as {new_obj_key}"
flash_message = (message, "success")
log_history_event(request, message, new_obj_key)
except asyncpg.exceptions.UniqueViolationError as e:
flash_message = (
f"Duplicate in Unique column Error during copy: {e.args}. \n"
f"Try to rename existed id or add manual.",
"error",
)
except asyncpg.exceptions.ForeignKeyViolationError as e:
flash_message = (e.args, "error")
return await model_view_table(request, model_id, flash_message)
| 5,346,167 |
def _write_pyserini_corpus(pyserini_index_file, corpus):
"""Writes the in-memory corpus to disk in the Pyserini format."""
with open(pyserini_index_file, 'w', encoding='utf-8') as fOut:
for doc_id, document in corpus.items():
data = {
'id': doc_id,
'title': document.get('title', ''),
'contents': document.get('text', ''),
'queries': ' '.join(document.get('queries', '')),
}
json.dump(data, fOut)
fOut.write('\n')
| 5,346,168 |
def load_pr(fname):
"""Loads predicted tracks in tabular format."""
try:
data = np.loadtxt(fname, delimiter=',', dtype=np.float64, ndmin=2)
except (ValueError, IndexError):
# Try using whitespace delim (default).
data = np.loadtxt(fname, delimiter=None, dtype=np.float64, ndmin=2)
# If category is not -1, then filter by pedestrian.
_, num_cols = data.shape
if CATEGORY_COLUMN < num_cols and not np.all(data[:, CATEGORY_COLUMN] == -1):
data = data[data[:, CATEGORY_COLUMN] == POSITIVE_CATEGORY, :]
return data
| 5,346,169 |
def CheckPsenac(lamada, w, k):
"""Check the validation of parameter lamada, w and k.
"""
try:
if not isinstance(lamada, int) or lamada <= 0:
raise ValueError(
"Error, parameter lamada must be an int type and larger than and equal to 0."
)
elif w > 1 or w < 0:
raise ValueError("Error, parameter w must be ranged from 0 to 1.")
elif not isinstance(k, int) or k <= 0:
raise ValueError(
"Error, parameter k must be an int type and larger than 0."
)
except ValueError:
raise
| 5,346,170 |
def build_affine(rotation, scale, origin):
"""
Compute affine matrix given rotation, scaling, and origin.
Parameters
----------
rotation : np.array
rotation
scale : np.array
scale factor
Returns
-------
aff : np.array [4x4]
affine matrix
"""
aff = np.zeros((4, 4))
aff[0:3, 0:3] = rotation
aff[:, 3] = np.append(origin, 1).T
aff[0:3, 0:3] = np.dot(aff[0:3, 0:3], np.diag(scale))
return aff
| 5,346,171 |
def sample_per_group(data, group_by, ratio = None, n = None):
"""
:type data: DataFrame
:type group_by: list of str
:type ratio: float
:type num_rows: int
:return:
"""
# group the data
data = data.copy()
"""
:type data: DataFrame
"""
data['__order1'] = data.index
grouped = data.groupby(by = group_by)
training_sets = []
test_sets = []
for name, group in grouped:
if n is None:
num_rows = round(group.shape[0] * ratio)
else:
num_rows = round(min(n, group.shape[0]))
shuffled = shuffle(data=group).reset_index(drop=True)
new_training_set = shuffled.iloc[:num_rows, ]
if num_rows>group.shape[0]:
# if all of the data ends up in training set, test set should be empty instead of an error
new_test_set = shuffled[shuffled.index!=shuffled.index]
else:
new_test_set = shuffled.iloc[(num_rows + 1):, ]
training_sets.append(new_training_set)
test_sets.append(new_test_set)
training = concat(training_sets)
"""
:type training: DataFrame
"""
test = concat(test_sets)
"""
:type test: DataFrame
"""
training.reset_index(drop=True, inplace=True)
test.reset_index(drop=True, inplace=True)
training.index = training['__order1'].values
test.index = test['__order1'].values
training.sort_index(inplace=True)
test.sort_index(inplace=True)
training.drop(axis=1, labels = '__order1', inplace=True)
test.drop(axis=1, labels='__order1', inplace=True)
return training, test
| 5,346,172 |
def test_mbo_cell_capa_update_pmf(dev, apdev):
"""MBO cellular data capability update with PMF required"""
ssid = "test-wnm-mbo"
passphrase = "12345678"
params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
params["wpa_key_mgmt"] = "WPA-PSK-SHA256"
params["ieee80211w"] = "2"
params['mbo'] = '1'
hapd = hostapd.add_ap(apdev[0], params)
bssid = apdev[0]['bssid']
if "OK" not in dev[0].request("SET mbo_cell_capa 1"):
raise Exception("Failed to set STA as cellular data capable")
dev[0].connect(ssid, psk=passphrase, key_mgmt="WPA-PSK-SHA256",
proto="WPA2", ieee80211w="2", scan_freq="2412")
addr = dev[0].own_addr()
sta = hapd.get_sta(addr)
if 'mbo_cell_capa' not in sta or sta['mbo_cell_capa'] != '1':
raise Exception("mbo_cell_capa missing after association")
if "OK" not in dev[0].request("SET mbo_cell_capa 3"):
raise Exception("Failed to set STA as cellular data not-capable")
time.sleep(0.2)
sta = hapd.get_sta(addr)
if 'mbo_cell_capa' not in sta:
raise Exception("mbo_cell_capa missing after update")
if sta['mbo_cell_capa'] != '3':
raise Exception("mbo_cell_capa not updated properly")
| 5,346,173 |
def print_all_models() -> None:
"""
Print description of every model in this module.
"""
model_desc = _get_all_subclasses_from_superclass(
_NonTrainableUnivariateDetector
)
# model_desc.update(
# _get_all_subclasses_from_superclass(_NonTrainableMultivariateDetector)
# )
model_desc.update(
_get_all_subclasses_from_superclass(_TrainableUnivariateDetector)
)
model_desc.update(
_get_all_subclasses_from_superclass(_TrainableMultivariateDetector)
)
for key, value in model_desc.items():
print("-" * 80)
print(key)
print(value)
| 5,346,174 |
def get_base64_column(metadata_df: pd.DataFrame) -> pd.DataFrame:
"""
Get accession json base64 str
:return:
"""
# Get accession json object as base64 string
metadata_df['accession_json_base64_str'] = metadata_df[METADATA_PAYLOAD_COLUMNS].\
apply(lambda x: b64encode(bytes(x.to_json(), encoding='utf-8')).decode("ascii"),
axis="columns")
return metadata_df
| 5,346,175 |
def bible_studies_view(request):
"""Bible studies view."""
auth = False
try:
auth = request.cookies['auth_tkt']
auth_tools = request.dbsession.query(
MyModel
).filter(MyModel.category == 'admin').all()
except KeyError:
auth_tools = []
query = request.dbsession.query(MyModel)
content = query.filter(MyModel.page == 'ministries').all()
main_menu = query.filter(MyModel.subcategory == 'base').all()
submenu = [item for item in content if item.title == 'menu_place_holder']
topimg = [item for item in content if item.category == 'topimg']
main = [item for item in content if item.category == 'bible_studies']
return {
'auth': auth,
'main_menu': main_menu,
'submenu': submenu,
'topimg': topimg[0],
'main': main,
'auth_tools': auth_tools,
}
| 5,346,176 |
def get_num_channels(inputs):
""" Get number of channels in one tensor. """
return inputs.shape[1]
| 5,346,177 |
def single_face_marker():
"""
Face marker with a single value.
"""
return np.zeros((2, 3)).astype(int)
| 5,346,178 |
def check_qmc(fname=None, archive=False, xflags=(), eqlb=(1,), reblk=(2,20,2),
eqlb_flags=(), reblk_flags=(), quiet_stdout=0, force_raw=0):
"""Checks the QMC results (INFO file) using my stand-alone QMC inspect tools.
x is the extra flags to be passed on to check_* tools."""
if fname == None:
if os.path.isfile("INFO"):
fname = ("INFO",)
else:
fname = tuple(sh.sorted_glob("part[0-9]*/INFO"))
elif not hasattr(fname, "__iter__"):
fname = (fname,)
else:
fname = tuple(fname)
fname_format = {}
for f in fname:
if not is_qmc_output(f):
if not force_raw:
raise ValueError, "Not a QMC output file: " + f
else:
print >> sys.stderr, "Warning: assuming raw output: " + f
fname_format[f] = "raw"
else:
fname_format[f] = "qmc"
if archive:
fnarch = ifelse(isinstance(archive, basestring), archive, "analysis.txt")
farch = open(fnarch, "a")
if quiet_stdout:
def prn(x):
farch.write(str(x) + "\n")
else:
def prn(x):
sys.stdout.write(str(x) + "\n")
farch.write(str(x) + "\n")
else:
def prn(x):
sys.stdout.write(str(x) + "\n")
prn("")
prn("Date: " + time.strftime("%Y%m%d"))
prn("Checking QMC result: " + "\n + ".join(
ifelse(len(fname) > 0, [""],[]) + \
[ os.path.abspath(f) for f in fname ]
))
for f in fname:
if fname_format[f] == "qmc" and not is_qmc_output_finished(f):
prn("Warning: calculation unfinished yet: %s" % f)
prn("")
# Use the formal tool names here:
#sh.run("check_eqlb", (fname, "1"))
if eqlb:
prn("EQUILIBRATION/QMC RAW ENERGIES:")
eqlb_info = tuple(map(str, eqlb))
x = tuple(xflags) + tuple(eqlb_flags)
if True or len(x) > 0:
prn("Flags: " + " ".join(eqlb_info + x))
prn(sh.pipe_out(("check_eqlb",) + fname + eqlb_info + x).replace('\x0c', ''))
if reblk:
prn("REBLOCKING:")
reblk_info = tuple(map(str, reblk))
x = tuple(xflags) + tuple(reblk_flags)
if True or len(x) > 0:
prn("Flags: " + " ".join(reblk_info + x))
prn(sh.pipe_out(("check_reblocking",) + fname + reblk_info + ("plt", "txt") + x).replace('\x0c', ''))
if archive: farch.close()
| 5,346,179 |
def skew(arr, angle, dx=None, dy=None, fwd=True, fill_min=True):
"""
Skew the origin of successive lines by a specified angle
A skew with angle of 30 degrees causes the following transformation:
+-----------+ +---------------+
| | |000/ /|
| input | |00/ output /0|
| image | |0/ image /00|
| | |/ /000|
+-----------+ +---------------+
Calling skew with fwd=False will return the output image
back to the input image.
Skew angle must be between -45 and 45 degrees
Arguments:
arr: array to skew
angle: angle between -45 and 45 to skew by
dx: spacing of the array in the x (sample) direction
(if dx=dy, or dx or dy not supplied, spacing is ignored)
dy: spacing of the array in the y (line) direction
fwd: add skew to image if True, unskew image if False
fill_min: While IPW skew says it fills with zeros, the output
image is filled with the minimum value
Returns:
skewed array
"""
if angle == 0:
return arr
if angle > 45 or angle < -45:
raise ValueError('skew angle must be between -45 and 45 degrees')
if dx is None or dy is None:
dx = 1.0
dy = 1.0
nlines, nsamps = arr.shape
if angle >= 0.0:
negflag = False
else:
negflag = True
angle = -angle
# unequal dx/dy equivalent to changing skew angle
slope = np.tan(angle * np.pi / 180.0) * (dy/dx)
max_skew = int((nlines - 1) * slope + 0.5)
o_nsamps = nsamps
if fwd:
o_nsamps += max_skew
else:
o_nsamps -= max_skew
b = np.zeros((nlines, o_nsamps))
if fill_min:
b += np.min(arr)
# if skewing, first fill output array with original array
if fwd:
b[0:nlines, 0:nsamps] = arr
o = np.arange(nlines)
# positive skew angle means shifts decrease with increasing row index
if not negflag:
o = nlines - o - 1
offset = (o * slope + 0.5).astype(int)
if not fwd: # offset values are negative shifts if unskewing
offset *= -1
if fwd:
b = custom_roll(b, offset)
else:
# assignment indexing added to ensure array shape match
b[:, :] = custom_roll(arr, offset)[:, :o_nsamps]
"""
for line in range(nlines):
o = line if negflag else nlines - line - 1
offset = int(o * slope + 0.5)
if fwd:
b[line, offset:offset+nsamps] = arr[line, :]
else:
b[line, :] = arr[line, offset:offset+o_nsamps]
"""
return b
| 5,346,180 |
def websocket_call(configuration, _method, url, **kwargs):
"""An internal function to be called in api-client when a websocket
connection is required. method, url, and kwargs are the parameters of
apiClient.request method."""
url = get_websocket_url(url, kwargs.get("query_params"))
headers = kwargs.get("headers")
_request_timeout = kwargs.get("_request_timeout", 60)
_preload_content = kwargs.get("_preload_content", True)
capture_all = kwargs.get("capture_all", True)
try:
client = WSClient(configuration, url, headers, capture_all)
if not _preload_content:
return client
client.run_forever(timeout=_request_timeout)
return WSResponse('%s' % ''.join(client.read_all()))
except (Exception, KeyboardInterrupt, SystemExit) as e:
raise ApiException(status=0, reason=str(e))
| 5,346,181 |
def compute_metrics(feats, pids, camids, num_query):
""" Compute CMC and mAP metrics """
# query
qf = feats[:num_query]
q_pids = np.asarray(pids[:num_query])
q_camids = np.asarray(camids[:num_query])
# gallery
gf = feats[num_query:]
g_pids = np.asarray(pids[num_query:])
g_camids = np.asarray(camids[num_query:])
m, n = qf.shape[0], gf.shape[0]
distmat = np.power(qf, 2).sum(axis=1, keepdims=True).repeat(n, axis=1) + \
np.power(gf, 2).sum(axis=1, keepdims=True).repeat(m, axis=1).T
distmat = 1 * distmat - 2 * np.dot(qf, gf.transpose())
cmc, m_ap = eval_func(distmat, q_pids, g_pids, q_camids, g_camids)
return cmc, m_ap
| 5,346,182 |
def parse_date(string_date: str) -> datetime.datetime:
"""
Parses input string of format 'MMM-yyyy' to datetime.
:param str string_date: Date in string format 'MMM-yyyy'
:return: datetime.datetime: parsed datetime
"""
return datetime.datetime.strptime(string_date, '%b-%Y')
| 5,346,183 |
def dpr_json_reader(file_to_read):
"""A simple streaming json reader. It assumes the file is well formated,
which is the case of Facebook DPR data, but it cannot be used as a generic
JSON stream reader, where blocks start/end at arbitrary positions
(unlike Facebook DPR data).
:param file_to_read:
:return: yields an unparsed textual representation of all entries for one question
"""
current_depth = 0
buffer = []
for i, line in enumerate(map(lambda line: line.strip(), file_to_read)):
if current_depth == 0 and line in ("[", "]"):
continue
if line == "{":
current_depth += 1
if line == "}" or line == "},":
current_depth -= 1
if current_depth == 0:
buffer.append("}")
yield "\n".join(buffer)
buffer = []
else:
buffer.append(line)
else:
buffer.append(line)
| 5,346,184 |
def test_cytoband_by_chrom(real_populated_database):
"""Test function that returns cytobands by chromosome dictionary"""
test_cytobands = [
{
"_id": "7d3c64026fd1a3ae032f9715a82eac46",
"band": "p36.31",
"chrom": "1",
"start": "5400000",
"stop": "7200000",
"build": "37",
},
{
"_id": "b68883bc2b2b30af28d4e1958c6c9bb8",
"band": "p36.33",
"chrom": "1",
"start": "0",
"stop": "2300000",
"build": "37",
},
{
"_id": "0fb17721ec1e60adae5775883c965ca6",
"band": "p24.2",
"chrom": "3",
"start": "23900000",
"stop": "26400000",
"build": "37",
},
{
"_id": "56d086cf19ed191dd8be20c22412d217",
"band": "p36.32",
"chrom": "1",
"start": "2300000",
"stop": "5400000",
"build": "37",
},
]
# Having a database collection containing cytobands:
adapter = real_populated_database
adapter.cytoband_collection.insert_many(test_cytobands)
# The cytobands by chromosome function should return the expected result
result = adapter.cytoband_by_chrom("37")
assert len(result["1"]["cytobands"]) == 3
assert len(result["3"]["cytobands"]) == 1
| 5,346,185 |
def round_vzeros(v,d=10) :
"""Returns input vector with rounded to zero components
which precision less than requested number of digits.
"""
prec = pow(10,-d)
vx = v[0] if math.fabs(v[0]) > prec else 0.0
vy = v[1] if math.fabs(v[1]) > prec else 0.0
vz = v[2] if math.fabs(v[2]) > prec else 0.0
return vx,vy,vz
| 5,346,186 |
async def test_fossil_energy_consumption_hole(hass, hass_ws_client):
"""Test fossil_energy_consumption when some data points lack sum."""
now = dt_util.utcnow()
later = dt_util.as_utc(dt_util.parse_datetime("2022-09-01 00:00:00"))
await hass.async_add_executor_job(init_recorder_component, hass)
await async_setup_component(hass, "history", {})
await async_setup_component(hass, "sensor", {})
period1 = dt_util.as_utc(dt_util.parse_datetime("2021-09-01 00:00:00"))
period2 = dt_util.as_utc(dt_util.parse_datetime("2021-09-30 23:00:00"))
period2_day_start = dt_util.as_utc(dt_util.parse_datetime("2021-09-30 00:00:00"))
period3 = dt_util.as_utc(dt_util.parse_datetime("2021-10-01 00:00:00"))
period4 = dt_util.as_utc(dt_util.parse_datetime("2021-10-31 23:00:00"))
period4_day_start = dt_util.as_utc(dt_util.parse_datetime("2021-10-31 00:00:00"))
external_energy_statistics_1 = (
{
"start": period1,
"last_reset": None,
"state": 0,
"sum": None,
},
{
"start": period2,
"last_reset": None,
"state": 1,
"sum": 3,
},
{
"start": period3,
"last_reset": None,
"state": 2,
"sum": 5,
},
{
"start": period4,
"last_reset": None,
"state": 3,
"sum": 8,
},
)
external_energy_metadata_1 = {
"has_mean": False,
"has_sum": True,
"name": "Total imported energy",
"source": "test",
"statistic_id": "test:total_energy_import_tariff_1",
"unit_of_measurement": "kWh",
}
external_energy_statistics_2 = (
{
"start": period1,
"last_reset": None,
"state": 0,
"sum": 20,
},
{
"start": period2,
"last_reset": None,
"state": 1,
"sum": None,
},
{
"start": period3,
"last_reset": None,
"state": 2,
"sum": 50,
},
{
"start": period4,
"last_reset": None,
"state": 3,
"sum": 80,
},
)
external_energy_metadata_2 = {
"has_mean": False,
"has_sum": True,
"name": "Total imported energy",
"source": "test",
"statistic_id": "test:total_energy_import_tariff_2",
"unit_of_measurement": "kWh",
}
async_add_external_statistics(
hass, external_energy_metadata_1, external_energy_statistics_1
)
async_add_external_statistics(
hass, external_energy_metadata_2, external_energy_statistics_2
)
await async_wait_recording_done(hass)
client = await hass_ws_client()
await client.send_json(
{
"id": 1,
"type": "energy/fossil_energy_consumption",
"start_time": now.isoformat(),
"end_time": later.isoformat(),
"energy_statistic_ids": [
"test:total_energy_import_tariff_1",
"test:total_energy_import_tariff_2",
],
"co2_statistic_id": "test:co2_ratio_missing",
"period": "hour",
}
)
response = await client.receive_json()
assert response["success"]
assert response["result"] == {
period2.isoformat(): pytest.approx(3.0 - 20.0),
period3.isoformat(): pytest.approx(55.0 - 3.0),
period4.isoformat(): pytest.approx(88.0 - 55.0),
}
await client.send_json(
{
"id": 2,
"type": "energy/fossil_energy_consumption",
"start_time": now.isoformat(),
"end_time": later.isoformat(),
"energy_statistic_ids": [
"test:total_energy_import_tariff_1",
"test:total_energy_import_tariff_2",
],
"co2_statistic_id": "test:co2_ratio_missing",
"period": "day",
}
)
response = await client.receive_json()
assert response["success"]
assert response["result"] == {
period2_day_start.isoformat(): pytest.approx(3.0 - 20.0),
period3.isoformat(): pytest.approx(55.0 - 3.0),
period4_day_start.isoformat(): pytest.approx(88.0 - 55.0),
}
await client.send_json(
{
"id": 3,
"type": "energy/fossil_energy_consumption",
"start_time": now.isoformat(),
"end_time": later.isoformat(),
"energy_statistic_ids": [
"test:total_energy_import_tariff_1",
"test:total_energy_import_tariff_2",
],
"co2_statistic_id": "test:co2_ratio_missing",
"period": "month",
}
)
response = await client.receive_json()
assert response["success"]
assert response["result"] == {
period1.isoformat(): pytest.approx(3.0 - 20.0),
period3.isoformat(): pytest.approx((55.0 - 3.0) + (88.0 - 55.0)),
}
| 5,346,187 |
def calculation_test():
"""check that the shapiro-wilk test statistic is correctly calculated because p-value should be > 0.05"""
norm_values = np.random.normal(5, 2, 100)
assert shapiro_wilk(norm_values)[1] > 0.05
| 5,346,188 |
def euclidean_distance_loss(params, params_prev):
"""
Euclidean distance loss
https://en.wikipedia.org/wiki/Euclidean_distance
:param params: the current model parameters
:param params_prev: previous model parameters
:return: float
"""
return K.sqrt(K.sum(K.square(params - params_prev), axis=-1))
| 5,346,189 |
def read_cloudflare_api_file(prog, file, state):
"""Read the input file for Cloudflare login details.
Args:
prog (State): modified if errors encountered in opening or reading
the file.
file (str): the file to read.
state (ConfigState): to record config file syntax errors.
Returns:
list(str): returns a list of Cloudflare login parameters
(email and key) where a line in the file 'X = Y' is converted
to: 'X:Y'. No checks on the input to any parameters (i.e. 'Y')
are done here: only the list is constructed. If ANY errors
are encountered, 'None' is returned.
"""
try:
with open(str(file), "r") as f:
raw = f.read().splitlines()
except FileNotFoundError as ex:
prog.log.error(
"cloudflare API file '{}' not found".format(ex.filename))
return None
except OSError as ex:
prog.log.error(
"reading cloudflare API file '{}' failed: {}".format(
ex.filename, ex.strerror.lower()))
return None
allowed_params = {'dns_cloudflare_email': 'email',
'dns_cloudflare_api_key': 'key'}
errors = False
ret = []
linepos = 0
for l in raw:
linepos += 1
match = re.match(r'^\s*(#.*)?$', l)
if match:
continue
match = re.match(
r'\s*(?P<param>\w+)\s*=\s*(?P<input>[^#]*)(\s*|\s#.*)$', l)
if match:
param = match.group('param')
try:
inputs = shlex.split(match.group('input'))
except ValueError:
state.add_error(prog, "cloudflare API file '{}' has malformed expression on line {}".format(file, linepos))
errors = True
continue
if param in allowed_params:
if len(inputs) != 1:
state.add_error(prog, "cloudflare API file '{}': malformed '{}' command on line {}".format(file, param, linepos))
errors = True
continue
ret += [ '{}:{}'.format(allowed_params[param], inputs[0]) ]
continue
state.add_error(prog, "cloudflare API file '{}': unrecognized command on line {}: '{}'".format(file, linepos, param))
errors = True
continue
state.add_error(prog, "cloudflare API file '{}' has malformed expression on line {}".format(file, linepos))
errors = True
if errors:
return None
return ret
| 5,346,190 |
def hash_msg(key, msg):
"""Return SHA1 hash from key and msg"""
return b64encode(hmac.new(key, msg, sha1).digest())
| 5,346,191 |
def remove_tex_axis(ax, xtick_fmt='%d', ytick_fmt='%d', axis_remove='both'):
"""
Makes axes normal font in matplotlib.
Parameters
---------------
xtick_fmt : A string, defining the format of the x-axis
ytick_fmt : A string, defining the format of the y-axis
axis_remove : A string, which axis to remove. ['x', 'y', 'both']
"""
if axis_remove not in ['x','y','both']:
raise Exception('axis_remove value not allowed.')
fmt = matplotlib.ticker.StrMethodFormatter("{x}")
if axis_remove == 'both':
ax.xaxis.set_major_formatter(fmt)
ax.yaxis.set_major_formatter(fmt)
ax.xaxis.set_major_formatter(FormatStrFormatter(xtick_fmt))
ax.yaxis.set_major_formatter(FormatStrFormatter(ytick_fmt))
elif axis_remove == 'x':
ax.xaxis.set_major_formatter(fmt)
ax.xaxis.set_major_formatter(FormatStrFormatter(xtick_fmt))
else:
ax.yaxis.set_major_formatter(fmt)
ax.yaxis.set_major_formatter(FormatStrFormatter(ytick_fmt))
| 5,346,192 |
def insert_pattern(base, pattern, offset=None): #optional!
"""
Takes a base simulation field and places a given pattern with an offset
onto it. When offset is None, the object is placed into the middle
Parameters
----------
base : numpy.ndarray
The base simulation field. Can already hold objects.
pattern : numpy.ndarray
The pattern to be placed. Should fit onto the simulation field
offset : (offset_x, offset_y), optional
offset in the x and y directions, from the middle. The default is None.
Raises
------
ValueError
Error is raised, if the pattern does not fit onto the simulation field.
Returns
-------
field : TYPE
The simulation field with the pattern placed.
"""
#pass
pattern = np.array(pattern)
new_field_config = base
if offset == None:
offset = (0,0)
#neue pos mit offset
pos = (np.int(new_field_config.shape[0] / 2) + offset[0], np.int(new_field_config.shape[1] / 2 + offset[1]))
#überschreibe new_field_coinfig mit pattern an gewünschter pos
new_field_config[pos[0]:pos[0] + pattern.shape[0], pos[1]:pos[1] + pattern.shape[1]] = pattern
return new_field_config
| 5,346,193 |
def get_specific_label_dfs(raw_df, label_loc):
"""
Purpose: Split the instances of data in raw_df based on specific labels/classes
and load them to a dictionary structured -> label : Pandas Dataframe
Params: 1. raw_df (Pandas Dataframe):
- The df containing data
2. label_loc (String):
- The location where the output labels are stored in 1. raw_df
Returns: A dictionary structured -> label : Pandas Dataframe
"""
labels = list(raw_df[label_loc].unique())
# a list of dataframes storing only instances of data belonging to one specific class/label
label_dataframes = {}
for label in labels:
label_dataframes[label] = raw_df.loc[raw_df[label_loc] == label]
return label_dataframes
| 5,346,194 |
def update_figure(df1, n, autoscale=False, ax=None, axis=0, grayed=None, j=0, kind=None, rx=None, ry=None,
start=0, title=None):
""" update_figure.
Recalculates the whole plot for frame n.
:param df1: pandas dataframe, required
:param n: frame to render, required
:param autoscale: bool, if True will adjust the scale as data is processed, else will pre-render full scale
:param ax: matplotlib ax
:param axis: 0 or 1 for horizontal or vertical data
:param grayed: grayed out "background" data
:param j: this is used to calculate if we are dealing with an even or odd data series, for color selection.
:param kind: pandas plot kind
:param rx: remove x axis
:param ry: remove y axis
:param start: will be used in 0.3 for offset
:param title: optional, title for the plot
:return: affects ax
"""
if j % 2:
c0 = 'C0'
c1 = 'C1'
else:
c0 = 'C1'
c1 = 'C0'
if kind is None:
kind = 'line'
# Just to quiet pep8 warning. 0.3 uses start, so might as well document it
if start == 0:
pass
items = df1.shape[0]
ax.cla()
if title is not None:
ax.set_title(title)
if grayed is not None:
for row in range(grayed.shape[0]-1):
grayed.iloc[row].plot(ax=ax, color='k', alpha=0.25)
if axis:
if not autoscale:
df1.iloc[items - 1:items, ].plot(ax=ax, color=c0)
df1.iloc[:n, ].plot(ax=ax, color=c0, kind=kind)
else:
df1.iloc[0].plot(ax=ax, color=c0, alpha=0.25, kind=kind)
df1.iloc[items - 1].plot(ax=ax, color=c1, alpha=0.25, kind=kind)
if n >= items / 2:
df1.iloc[n].plot(ax=ax, color=c1, kind=kind)
else:
df1.iloc[n].plot(ax=ax, color=c0, kind=kind)
if title is not None:
ax.legend().set_visible(False)
plt.box(on=None)
if rx:
ax.axes.get_xaxis().set_visible(False)
if ry:
ax.axes.get_yaxis().set_visible(False)
| 5,346,195 |
def run(_):
"""
Meant for running/parallelizing training data preparation
:param _: Not used
:return: Runs prep() function
"""
return prep()
| 5,346,196 |
def extract_hcs():
"""
Extract HyperCube shuffle and output hypercube shuffle only plans
"""
with open("q4.json") as jf:
q4 = json.load(jf)
assert q4["language"] == 'MyriaL'
# get fragments
fragments = q4["plan"]["fragments"]
assert len(fragments) == 9
# store operators by its id
operators = dict()
for frag in fragments:
for op in frag["operators"]:
new_op = copy.deepcopy(op)
operators[int(new_op["opId"])] = new_op
if new_op["opType"] == "LeapFrogJoin":
lfj = new_op
stored_hcs_prefix = "q4_hcs_only_"
order_bys = []
# extract hcs
for i, child_id in enumerate(lfj["argChildren"]):
# extract related operators
order_by = operators[child_id]
hcs_consumer = operators[order_by["argChild"]]
hcs_producer = operators[hcs_consumer["argOperatorId"]]
scan = operators[hcs_producer["argChild"]]
# for later usage
order_bys.append(order_by)
# construct store operator
store = {
"opId": 4,
"opName": "MyriaStore(hcs_{})".format(i),
"relationKey": {
"programName": "adhoc",
"userName": "public",
"relationName": "q4_hcs_only_{}".format(i),
},
"argOverwriteTable": True,
"argChild": 3,
"opType": "DbInsert"
}
# link the operators
order_by["opId"] = 3
order_by["argChild"] = 2
hcs_consumer["opId"] = 2
hcs_consumer["argOperatorId"] = 1
hcs_producer["opId"] = 1
hcs_producer["argChild"] = 0
scan["opId"] = 0
# construct plan
plan = copy.deepcopy(plan_boiler_plate)
frag1 = {
"operators": [scan, hcs_producer]
}
frag2 = {
"operators": [hcs_consumer, order_by, store]
}
plan["rawQuery"] = "hypercube shuffle of q4 - part {}".format(i)
plan["plan"]["fragments"].append(frag1)
plan["plan"]["fragments"].append(frag2)
ofname = "q4_hc_{}.json".format(i)
print "write to {}".format(ofname)
with open(ofname, "wb") as ofile:
json.dump(plan, ofile)
# get number of relations
num_rel = len(lfj["argChildren"])
# add scans and orderbys
lfj_ops = []
for i in range(num_rel):
rel_name = "{}{}".format(stored_hcs_prefix, i)
scan = {
"relationKey": {
"programName": "adhoc",
"userName": "public",
"relationName": rel_name
},
"opId": i*2,
"opName": "MyriaScan({})".format(rel_name),
"opType": "TableScan"
}
lfj_ops.append(scan)
order_by = order_bys[i]
order_by["opId"] = i * 2 + 1
order_by["argChild"] = i * 2
lfj_ops.append(order_by)
# construct lfj op
new_lfj = copy.deepcopy(lfj)
new_lfj['argChildren'] = [i*2+1 for i in range(num_rel)]
new_lfj['opId'] = num_rel*2
lfj_ops.append(new_lfj)
# add sink root at end
sink_root = {
"opType": "SinkRoot",
"argChild": num_rel*2,
"opName": "SinkRoot",
"opId": num_rel*2+1
}
lfj_ops.append(sink_root)
plan = copy.deepcopy(plan_boiler_plate)
plan["rawQuery"] = "Local Tributary Join"
plan["plan"]["fragments"] = [
{
"operators": lfj_ops,
"workers": [57]
}
]
ofname = "q4_local_tj.json"
print "output {}".format(ofname)
with open(ofname, "wb") as ofile:
json.dump(plan, ofile)
| 5,346,197 |
def test_parse_timeframe():
"""
Tests the `parse_timeframe()` method in `Rule`.
"""
tf_minutes = {'minutes?': False, 'm': True}
tf_hours = {'hours?': False, 'h': True}
tf_days = {'days?': False, 'd': True}
tf_weeks = {'weeks?': False, 'w': True}
tf_months = {'months?': False, 'M': True}
tf_years = {'years?': False, 'y': True}
test_str = '3m'
assert rule_meta.Rule.parse_timeframe(test_str, tf_minutes) == 3
assert rule_meta.Rule.parse_timeframe(test_str, tf_hours) == 0
test_str = '3m 2m'
with pytest.raises(TimeframeArgDupeError):
rule_meta.Rule.parse_timeframe(test_str, tf_minutes)
test_str = '3m2m'
with pytest.raises(TimeframeArgDupeError):
rule_meta.Rule.parse_timeframe(test_str, tf_minutes)
test_str = '-4minute'
assert rule_meta.Rule.parse_timeframe(test_str, tf_minutes) == -4
test_str = '3h-4m+2M'
assert rule_meta.Rule.parse_timeframe(test_str, tf_minutes) == -4
assert rule_meta.Rule.parse_timeframe(test_str, tf_hours) == 3
assert rule_meta.Rule.parse_timeframe(test_str, tf_months) == 2
test_str = '''
1minute
2 hour
3Day
4w,5 mONths 6 y
'''
assert rule_meta.Rule.parse_timeframe(test_str, tf_minutes) == 1
assert rule_meta.Rule.parse_timeframe(test_str, tf_hours) == 2
assert rule_meta.Rule.parse_timeframe(test_str, tf_days) == 3
assert rule_meta.Rule.parse_timeframe(test_str, tf_weeks) == 4
assert rule_meta.Rule.parse_timeframe(test_str, tf_months) == 5
assert rule_meta.Rule.parse_timeframe(test_str, tf_years) == 6
| 5,346,198 |
def includeme(config):
"""Bind to the db engine specifed in ``config.registry.settings``."""
# Bind the engine.
settings = config.get_settings()
engine_kwargs_factory = settings.pop("sqlalchemy.engine_kwargs_factory", None)
if engine_kwargs_factory:
kwargs_factory = config.maybe_dotted(engine_kwargs_factory)
engine_kwargs = kwargs_factory(config.registry)
else:
engine_kwargs = {}
pool_class = settings.pop("sqlalchemy.pool_class", None)
if pool_class:
dotted_name = DottedNameResolver()
engine_kwargs["poolclass"] = dotted_name.resolve(pool_class)
should_bind = asbool(settings.get("basemodel.should_bind_engine", True))
should_create = asbool(settings.get("basemodel.should_create_all", False))
should_drop = asbool(settings.get("basemodel.should_drop_all", False))
if should_bind:
engine = engine_from_config(settings, "sqlalchemy.", **engine_kwargs)
config.action(
None,
bind_engine,
(engine,),
{"should_create": should_create, "should_drop": should_drop},
)
| 5,346,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.