hexsha stringlengths 40 40 | size int64 1 1.03M | ext stringclasses 10 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 239 | max_stars_repo_name stringlengths 5 130 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 239 | max_issues_repo_name stringlengths 5 130 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 239 | max_forks_repo_name stringlengths 5 130 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 1 1.03M | avg_line_length float64 1 958k | max_line_length int64 1 1.03M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
acec67973a818493713689fccd932fa7df3549a4 | 401 | py | Python | startupmoney/startupmoney/wsgi.py | RanjithaRao22/TestWebApp | 581edcec8fb39001917d9132b7f371aabc506e51 | [
"MIT"
] | 1 | 2020-04-13T06:33:15.000Z | 2020-04-13T06:33:15.000Z | startupmoney/startupmoney/wsgi.py | vatsamail/TestWebApp | 581edcec8fb39001917d9132b7f371aabc506e51 | [
"MIT"
] | 7 | 2020-04-12T23:26:42.000Z | 2022-02-10T12:18:08.000Z | startupmoney/startupmoney/wsgi.py | vatsamail/TestWebApp | 581edcec8fb39001917d9132b7f371aabc506e51 | [
"MIT"
] | null | null | null | """
WSGI config for startupmoney project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'startupmoney.settings')
application = get_wsgi_application()
| 23.588235 | 78 | 0.790524 |
acec67abc7541a2ff8feaa790535c4e501563d32 | 46,256 | py | Python | sdks/python/apache_beam/runners/direct/transform_evaluator.py | jxub/beam | 8222fcc978a54d98d385c108fb5fcf7615d74829 | [
"Apache-2.0"
] | null | null | null | sdks/python/apache_beam/runners/direct/transform_evaluator.py | jxub/beam | 8222fcc978a54d98d385c108fb5fcf7615d74829 | [
"Apache-2.0"
] | 4 | 2020-11-13T18:41:43.000Z | 2022-02-10T00:45:14.000Z | sdks/python/apache_beam/runners/direct/transform_evaluator.py | jxub/beam | 8222fcc978a54d98d385c108fb5fcf7615d74829 | [
"Apache-2.0"
] | null | null | null | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""An evaluator of a specific application of a transform."""
# pytype: skip-file
from __future__ import absolute_import
import atexit
import collections
import logging
import random
import time
from builtins import object
from typing import TYPE_CHECKING
from typing import Any
from typing import Dict
from typing import List
from typing import Tuple
from typing import Type
from future.utils import iteritems
import apache_beam.io as io
from apache_beam import coders
from apache_beam import pvalue
from apache_beam.internal import pickler
from apache_beam.runners import common
from apache_beam.runners.common import DoFnRunner
from apache_beam.runners.common import DoFnState
from apache_beam.runners.dataflow.native_io.iobase import _NativeWrite # pylint: disable=protected-access
from apache_beam.runners.direct.direct_runner import _DirectReadFromPubSub
from apache_beam.runners.direct.direct_runner import _StreamingGroupAlsoByWindow
from apache_beam.runners.direct.direct_runner import _StreamingGroupByKeyOnly
from apache_beam.runners.direct.direct_userstate import DirectUserStateContext
from apache_beam.runners.direct.sdf_direct_runner import ProcessElements
from apache_beam.runners.direct.sdf_direct_runner import ProcessFn
from apache_beam.runners.direct.sdf_direct_runner import SDFProcessElementInvoker
from apache_beam.runners.direct.test_stream_impl import _TestStream
from apache_beam.runners.direct.test_stream_impl import _WatermarkController
from apache_beam.runners.direct.util import KeyedWorkItem
from apache_beam.runners.direct.util import TransformResult
from apache_beam.runners.direct.watermark_manager import WatermarkManager
from apache_beam.testing.test_stream import ElementEvent
from apache_beam.testing.test_stream import PairWithTiming
from apache_beam.testing.test_stream import ProcessingTimeEvent
from apache_beam.testing.test_stream import TimingInfo
from apache_beam.testing.test_stream import WatermarkEvent
from apache_beam.transforms import core
from apache_beam.transforms.trigger import InMemoryUnmergedState
from apache_beam.transforms.trigger import TimeDomain
from apache_beam.transforms.trigger import _CombiningValueStateTag
from apache_beam.transforms.trigger import _ListStateTag
from apache_beam.transforms.trigger import _ValueStateTag
from apache_beam.transforms.trigger import create_trigger_driver
from apache_beam.transforms.userstate import get_dofn_specs
from apache_beam.transforms.userstate import is_stateful_dofn
from apache_beam.transforms.window import GlobalWindows
from apache_beam.transforms.window import WindowedValue
from apache_beam.typehints.typecheck import TypeCheckError
from apache_beam.utils import counters
from apache_beam.utils.timestamp import MIN_TIMESTAMP
from apache_beam.utils.timestamp import Timestamp
if TYPE_CHECKING:
from apache_beam.io.gcp.pubsub import _PubSubSource
from apache_beam.io.gcp.pubsub import PubsubMessage
from apache_beam.pipeline import AppliedPTransform
from apache_beam.runners.direct.evaluation_context import EvaluationContext
_LOGGER = logging.getLogger(__name__)
class TransformEvaluatorRegistry(object):
"""For internal use only; no backwards-compatibility guarantees.
Creates instances of TransformEvaluator for the application of a transform.
"""
_test_evaluators_overrides = {
} # type: Dict[Type[core.PTransform], Type[_TransformEvaluator]]
def __init__(self, evaluation_context):
# type: (EvaluationContext) -> None
assert evaluation_context
self._evaluation_context = evaluation_context
self._evaluators = {
io.Read: _BoundedReadEvaluator,
_DirectReadFromPubSub: _PubSubReadEvaluator,
core.Flatten: _FlattenEvaluator,
core.Impulse: _ImpulseEvaluator,
core.ParDo: _ParDoEvaluator,
core._GroupByKeyOnly: _GroupByKeyOnlyEvaluator,
_StreamingGroupByKeyOnly: _StreamingGroupByKeyOnlyEvaluator,
_StreamingGroupAlsoByWindow: _StreamingGroupAlsoByWindowEvaluator,
_NativeWrite: _NativeWriteEvaluator,
_TestStream: _TestStreamEvaluator,
ProcessElements: _ProcessElementsEvaluator,
_WatermarkController: _WatermarkControllerEvaluator,
PairWithTiming: _PairWithTimingEvaluator,
} # type: Dict[Type[core.PTransform], Type[_TransformEvaluator]]
self._evaluators.update(self._test_evaluators_overrides)
self._root_bundle_providers = {
core.PTransform: DefaultRootBundleProvider,
_TestStream: _TestStreamRootBundleProvider,
}
def get_evaluator(
self, applied_ptransform, input_committed_bundle, side_inputs):
"""Returns a TransformEvaluator suitable for processing given inputs."""
assert applied_ptransform
assert bool(applied_ptransform.side_inputs) == bool(side_inputs)
# Walk up the class hierarchy to find an evaluable type. This is necessary
# for supporting sub-classes of core transforms.
for cls in applied_ptransform.transform.__class__.mro():
evaluator = self._evaluators.get(cls)
if evaluator:
break
if not evaluator:
raise NotImplementedError(
'Execution of [%s] not implemented in runner %s.' %
(type(applied_ptransform.transform), self))
return evaluator(
self._evaluation_context,
applied_ptransform,
input_committed_bundle,
side_inputs)
def get_root_bundle_provider(self, applied_ptransform):
provider_cls = None
for cls in applied_ptransform.transform.__class__.mro():
provider_cls = self._root_bundle_providers.get(cls)
if provider_cls:
break
if not provider_cls:
raise NotImplementedError(
'Root provider for [%s] not implemented in runner %s' %
(type(applied_ptransform.transform), self))
return provider_cls(self._evaluation_context, applied_ptransform)
def should_execute_serially(self, applied_ptransform):
"""Returns True if this applied_ptransform should run one bundle at a time.
Some TransformEvaluators use a global state object to keep track of their
global execution state. For example evaluator for _GroupByKeyOnly uses this
state as an in memory dictionary to buffer keys.
Serially executed evaluators will act as syncing point in the graph and
execution will not move forward until they receive all of their inputs. Once
they receive all of their input, they will release the combined output.
Their output may consist of multiple bundles as they may divide their output
into pieces before releasing.
Args:
applied_ptransform: Transform to be used for execution.
Returns:
True if executor should execute applied_ptransform serially.
"""
if isinstance(applied_ptransform.transform,
(core._GroupByKeyOnly,
_StreamingGroupByKeyOnly,
_StreamingGroupAlsoByWindow,
_NativeWrite)):
return True
elif (isinstance(applied_ptransform.transform, core.ParDo) and
is_stateful_dofn(applied_ptransform.transform.dofn)):
return True
return False
class RootBundleProvider(object):
"""Provides bundles for the initial execution of a root transform."""
def __init__(self, evaluation_context, applied_ptransform):
self._evaluation_context = evaluation_context
self._applied_ptransform = applied_ptransform
def get_root_bundles(self):
raise NotImplementedError
class DefaultRootBundleProvider(RootBundleProvider):
"""Provides an empty bundle by default for root transforms."""
def get_root_bundles(self):
input_node = pvalue.PBegin(self._applied_ptransform.transform.pipeline)
empty_bundle = (
self._evaluation_context.create_empty_committed_bundle(input_node))
return [empty_bundle]
class _TestStreamRootBundleProvider(RootBundleProvider):
"""Provides an initial bundle for the TestStream evaluator.
This bundle is used as the initial state to the TestStream. Each unprocessed
bundle emitted from the TestStream afterwards is its state: index into the
stream, and the watermark.
"""
def get_root_bundles(self):
test_stream = self._applied_ptransform.transform
bundle = self._evaluation_context.create_bundle(
pvalue.PBegin(self._applied_ptransform.transform.pipeline))
bundle.add(
GlobalWindows.windowed_value(
test_stream.begin(), timestamp=MIN_TIMESTAMP))
bundle.commit(None)
return [bundle]
class _TransformEvaluator(object):
"""An evaluator of a specific application of a transform."""
def __init__(self,
evaluation_context, # type: EvaluationContext
applied_ptransform, # type: AppliedPTransform
input_committed_bundle,
side_inputs
):
self._evaluation_context = evaluation_context
self._applied_ptransform = applied_ptransform
self._input_committed_bundle = input_committed_bundle
self._side_inputs = side_inputs
self._expand_outputs()
self._execution_context = evaluation_context.get_execution_context(
applied_ptransform)
self._step_context = self._execution_context.get_step_context()
def _expand_outputs(self):
outputs = set()
for pval in self._applied_ptransform.outputs.values():
if isinstance(pval, pvalue.DoOutputsTuple):
pvals = (v for v in pval)
else:
pvals = (pval, )
for v in pvals:
outputs.add(v)
self._outputs = frozenset(outputs)
def _split_list_into_bundles(
self,
output_pcollection,
elements,
max_element_per_bundle,
element_size_fn):
"""Splits elements, an iterable, into multiple output bundles.
Args:
output_pcollection: PCollection that the elements belong to.
elements: elements to be chunked into bundles.
max_element_per_bundle: (approximately) the maximum element per bundle.
If it is None, only a single bundle will be produced.
element_size_fn: Function to return the size of a given element.
Returns:
List of output uncommitted bundles with at least one bundle.
"""
bundle = self._evaluation_context.create_bundle(output_pcollection)
bundle_size = 0
bundles = [bundle]
for element in elements:
if max_element_per_bundle and bundle_size >= max_element_per_bundle:
bundle = self._evaluation_context.create_bundle(output_pcollection)
bundle_size = 0
bundles.append(bundle)
bundle.output(element)
bundle_size += element_size_fn(element)
return bundles
def start_bundle(self):
"""Starts a new bundle."""
pass
def process_timer_wrapper(self, timer_firing):
"""Process timer by clearing and then calling process_timer().
This method is called with any timer firing and clears the delivered
timer from the keyed state and then calls process_timer(). The default
process_timer() implementation emits a KeyedWorkItem for the particular
timer and passes it to process_element(). Evaluator subclasses which
desire different timer delivery semantics can override process_timer().
"""
state = self._step_context.get_keyed_state(timer_firing.encoded_key)
state.clear_timer(
timer_firing.window, timer_firing.name, timer_firing.time_domain)
self.process_timer(timer_firing)
def process_timer(self, timer_firing):
"""Default process_timer() impl. generating KeyedWorkItem element."""
self.process_element(
GlobalWindows.windowed_value(
KeyedWorkItem(
timer_firing.encoded_key, timer_firings=[timer_firing])))
def process_element(self, element):
"""Processes a new element as part of the current bundle."""
raise NotImplementedError('%s do not process elements.' % type(self))
def finish_bundle(self):
# type: () -> TransformResult
"""Finishes the bundle and produces output."""
pass
class _BoundedReadEvaluator(_TransformEvaluator):
"""TransformEvaluator for bounded Read transform."""
# After some benchmarks, 1000 was optimal among {100,1000,10000}
MAX_ELEMENT_PER_BUNDLE = 1000
def __init__(
self,
evaluation_context,
applied_ptransform,
input_committed_bundle,
side_inputs):
assert not side_inputs
self._source = applied_ptransform.transform.source
self._source.pipeline_options = evaluation_context.pipeline_options
super(_BoundedReadEvaluator, self).__init__(
evaluation_context,
applied_ptransform,
input_committed_bundle,
side_inputs)
def finish_bundle(self):
assert len(self._outputs) == 1
output_pcollection = list(self._outputs)[0]
def _read_values_to_bundles(reader):
read_result = [GlobalWindows.windowed_value(e) for e in reader]
return self._split_list_into_bundles(
output_pcollection,
read_result,
_BoundedReadEvaluator.MAX_ELEMENT_PER_BUNDLE,
lambda _: 1)
if isinstance(self._source, io.iobase.BoundedSource):
# Getting a RangeTracker for the default range of the source and reading
# the full source using that.
range_tracker = self._source.get_range_tracker(None, None)
reader = self._source.read(range_tracker)
bundles = _read_values_to_bundles(reader)
else:
with self._source.reader() as reader:
bundles = _read_values_to_bundles(reader)
return TransformResult(self, bundles, [], None, None)
class _WatermarkControllerEvaluator(_TransformEvaluator):
"""TransformEvaluator for the _WatermarkController transform.
This is used to enable multiple output watermarks for the TestStream.
"""
# The state tag used to store the watermark.
WATERMARK_TAG = _ValueStateTag('_WatermarkControllerEvaluator_Watermark_Tag')
def __init__(
self,
evaluation_context,
applied_ptransform,
input_committed_bundle,
side_inputs):
assert not side_inputs
self.transform = applied_ptransform.transform
super(_WatermarkControllerEvaluator, self).__init__(
evaluation_context,
applied_ptransform,
input_committed_bundle,
side_inputs)
self._init_state()
def _init_state(self):
"""Gets and sets the initial state.
This is used to keep track of the watermark hold between calls.
"""
transform_states = self._evaluation_context._transform_keyed_states
state = transform_states[self._applied_ptransform]
if self.WATERMARK_TAG not in state:
watermark_state = InMemoryUnmergedState()
watermark_state.set_global_state(self.WATERMARK_TAG, MIN_TIMESTAMP)
state[self.WATERMARK_TAG] = watermark_state
self._state = state[self.WATERMARK_TAG]
@property
def _watermark(self):
return self._state.get_global_state(self.WATERMARK_TAG)
@_watermark.setter
def _watermark(self, watermark):
self._state.set_global_state(self.WATERMARK_TAG, watermark)
def start_bundle(self):
self.bundles = []
def process_element(self, element):
# In order to keep the order of the elements between the script and what
# flows through the pipeline the same, emit the elements here.
event = element.value
if isinstance(event, WatermarkEvent):
self._watermark = event.new_watermark
elif isinstance(event, ElementEvent):
main_output = list(self._outputs)[0]
bundle = self._evaluation_context.create_bundle(main_output)
for tv in event.timestamped_values:
# Unreify the value into the correct window.
try:
bundle.output(WindowedValue(**tv.value))
except TypeError:
bundle.output(
GlobalWindows.windowed_value(tv.value, timestamp=tv.timestamp))
self.bundles.append(bundle)
def finish_bundle(self):
# The watermark hold we set here is the way we allow the TestStream events
# to control the output watermark.
return TransformResult(
self, self.bundles, [], None, {None: self._watermark})
class _PairWithTimingEvaluator(_TransformEvaluator):
"""TransformEvaluator for the PairWithTiming transform.
This transform takes an element as an input and outputs
KV(element, `TimingInfo`). Where the `TimingInfo` contains both the
processing time timestamp and watermark.
"""
def __init__(
self,
evaluation_context,
applied_ptransform,
input_committed_bundle,
side_inputs):
assert not side_inputs
super(_PairWithTimingEvaluator, self).__init__(
evaluation_context,
applied_ptransform,
input_committed_bundle,
side_inputs)
def start_bundle(self):
main_output = list(self._outputs)[0]
self.bundle = self._evaluation_context.create_bundle(main_output)
watermark_manager = self._evaluation_context._watermark_manager
watermarks = watermark_manager.get_watermarks(self._applied_ptransform)
output_watermark = watermarks.output_watermark
now = Timestamp(seconds=watermark_manager._clock.time())
self.timing_info = TimingInfo(now, output_watermark)
def process_element(self, element):
element.value = (element.value, self.timing_info)
self.bundle.output(element)
def finish_bundle(self):
return TransformResult(self, [self.bundle], [], None, {})
class _TestStreamEvaluator(_TransformEvaluator):
"""TransformEvaluator for the TestStream transform.
This evaluator's responsibility is to retrieve the next event from the
_TestStream and either: advance the clock, advance the _TestStream watermark,
or pass the event to the _WatermarkController.
The _WatermarkController is in charge of emitting the elements to the
downstream consumers and setting its own output watermark.
"""
def __init__(
self,
evaluation_context,
applied_ptransform,
input_committed_bundle,
side_inputs):
assert not side_inputs
super(_TestStreamEvaluator, self).__init__(
evaluation_context,
applied_ptransform,
input_committed_bundle,
side_inputs)
self.test_stream = applied_ptransform.transform
def start_bundle(self):
self.current_index = 0
self.bundles = []
self.watermark = MIN_TIMESTAMP
def process_element(self, element):
# The index into the TestStream list of events.
self.current_index = element.value
# The watermark of the _TestStream transform itself.
self.watermark = element.timestamp
# We can either have the _TestStream or the _WatermarkController to emit
# the elements. We chose to emit in the _WatermarkController so that the
# element is emitted at the correct watermark value.
# Set up the correct watermark holds in the Watermark controllers and the
# TestStream so that the watermarks will not automatically advance to +inf
# when elements start streaming. This can happen multiple times in the first
# bundle, but the operations are idempotent and adding state to keep track
# of this would add unnecessary code complexity.
events = []
if self.watermark == MIN_TIMESTAMP:
for event in self.test_stream._set_up(self.test_stream.output_tags):
events.append(event)
events += [e for e in self.test_stream.events(self.current_index)]
for event in events:
if isinstance(event, (ElementEvent, WatermarkEvent)):
# The WATERMARK_CONTROL_TAG is used to hold the _TestStream's
# watermark to -inf, then +inf-1, then +inf. This watermark progression
# is ultimately used to set up the proper holds to allow the
# _WatermarkControllers to control their own output watermarks.
if event.tag == _TestStream.WATERMARK_CONTROL_TAG:
self.watermark = event.new_watermark
else:
main_output = list(self._outputs)[0]
bundle = self._evaluation_context.create_bundle(main_output)
bundle.output(GlobalWindows.windowed_value(event))
self.bundles.append(bundle)
elif isinstance(event, ProcessingTimeEvent):
self._evaluation_context._watermark_manager._clock.advance_time(
event.advance_by)
else:
raise ValueError('Invalid TestStream event: %s.' % event)
def finish_bundle(self):
unprocessed_bundles = []
next_index = self.test_stream.next(self.current_index)
if not self.test_stream.end(next_index):
unprocessed_bundle = self._evaluation_context.create_bundle(
pvalue.PBegin(self._applied_ptransform.transform.pipeline))
unprocessed_bundle.add(
GlobalWindows.windowed_value(next_index, timestamp=self.watermark))
unprocessed_bundles.append(unprocessed_bundle)
# Returning the watermark in the dict here is used as a watermark hold.
return TransformResult(
self, self.bundles, unprocessed_bundles, None, {None: self.watermark})
class _PubSubReadEvaluator(_TransformEvaluator):
"""TransformEvaluator for PubSub read."""
# A mapping of transform to _PubSubSubscriptionWrapper.
# TODO(BEAM-7750): Prevents garbage collection of pipeline instances.
_subscription_cache = {} # type: Dict[AppliedPTransform, str]
def __init__(
self,
evaluation_context,
applied_ptransform,
input_committed_bundle,
side_inputs):
assert not side_inputs
super(_PubSubReadEvaluator, self).__init__(
evaluation_context,
applied_ptransform,
input_committed_bundle,
side_inputs)
self.source = self._applied_ptransform.transform._source # type: _PubSubSource
if self.source.id_label:
raise NotImplementedError(
'DirectRunner: id_label is not supported for PubSub reads')
sub_project = None
if hasattr(self._evaluation_context, 'pipeline_options'):
from apache_beam.options.pipeline_options import GoogleCloudOptions
sub_project = (
self._evaluation_context.pipeline_options.view_as(
GoogleCloudOptions).project)
if not sub_project:
sub_project = self.source.project
self._sub_name = self.get_subscription(
self._applied_ptransform,
self.source.project,
self.source.topic_name,
sub_project,
self.source.subscription_name)
@classmethod
def get_subscription(
cls, transform, project, short_topic_name, sub_project, short_sub_name):
from google.cloud import pubsub
if short_sub_name:
return pubsub.SubscriberClient.subscription_path(project, short_sub_name)
if transform in cls._subscription_cache:
return cls._subscription_cache[transform]
sub_client = pubsub.SubscriberClient()
sub_name = sub_client.subscription_path(
sub_project,
'beam_%d_%x' % (int(time.time()), random.randrange(1 << 32)))
topic_name = sub_client.topic_path(project, short_topic_name)
sub_client.create_subscription(sub_name, topic_name)
atexit.register(sub_client.delete_subscription, sub_name)
cls._subscription_cache[transform] = sub_name
return cls._subscription_cache[transform]
def start_bundle(self):
pass
def process_element(self, element):
pass
def _read_from_pubsub(self, timestamp_attribute):
# type: (...) -> List[Tuple[Timestamp, PubsubMessage]]
from apache_beam.io.gcp.pubsub import PubsubMessage
from google.cloud import pubsub
def _get_element(message):
parsed_message = PubsubMessage._from_message(message)
if (timestamp_attribute and
timestamp_attribute in parsed_message.attributes):
rfc3339_or_milli = parsed_message.attributes[timestamp_attribute]
try:
timestamp = Timestamp(micros=int(rfc3339_or_milli) * 1000)
except ValueError:
try:
timestamp = Timestamp.from_rfc3339(rfc3339_or_milli)
except ValueError as e:
raise ValueError('Bad timestamp value: %s' % e)
else:
timestamp = Timestamp(
message.publish_time.seconds, message.publish_time.nanos // 1000)
return timestamp, parsed_message
# Because of the AutoAck, we are not able to reread messages if this
# evaluator fails with an exception before emitting a bundle. However,
# the DirectRunner currently doesn't retry work items anyway, so the
# pipeline would enter an inconsistent state on any error.
sub_client = pubsub.SubscriberClient()
try:
response = sub_client.pull(
self._sub_name, max_messages=10, return_immediately=True)
results = [_get_element(rm.message) for rm in response.received_messages]
ack_ids = [rm.ack_id for rm in response.received_messages]
if ack_ids:
sub_client.acknowledge(self._sub_name, ack_ids)
finally:
sub_client.api.transport.channel.close()
return results
def finish_bundle(self):
# type: () -> TransformResult
data = self._read_from_pubsub(self.source.timestamp_attribute)
if data:
output_pcollection = list(self._outputs)[0]
bundle = self._evaluation_context.create_bundle(output_pcollection)
# TODO(ccy): Respect the PubSub source's id_label field.
for timestamp, message in data:
if self.source.with_attributes:
element = message
else:
element = message.data
bundle.output(
GlobalWindows.windowed_value(element, timestamp=timestamp))
bundles = [bundle]
else:
bundles = []
assert self._applied_ptransform.transform is not None
if self._applied_ptransform.inputs:
input_pvalue = self._applied_ptransform.inputs[0]
else:
input_pvalue = pvalue.PBegin(self._applied_ptransform.transform.pipeline)
unprocessed_bundle = self._evaluation_context.create_bundle(input_pvalue)
# TODO(udim): Correct value for watermark hold.
return TransformResult(
self,
bundles, [unprocessed_bundle],
None, {None: Timestamp.of(time.time())})
class _FlattenEvaluator(_TransformEvaluator):
"""TransformEvaluator for Flatten transform."""
def __init__(
self,
evaluation_context,
applied_ptransform,
input_committed_bundle,
side_inputs):
assert not side_inputs
super(_FlattenEvaluator, self).__init__(
evaluation_context,
applied_ptransform,
input_committed_bundle,
side_inputs)
def start_bundle(self):
assert len(self._outputs) == 1
output_pcollection = list(self._outputs)[0]
self.bundle = self._evaluation_context.create_bundle(output_pcollection)
def process_element(self, element):
self.bundle.output(element)
def finish_bundle(self):
bundles = [self.bundle]
return TransformResult(self, bundles, [], None, None)
class _ImpulseEvaluator(_TransformEvaluator):
"""TransformEvaluator for Impulse transform."""
def finish_bundle(self):
assert len(self._outputs) == 1
output_pcollection = list(self._outputs)[0]
bundle = self._evaluation_context.create_bundle(output_pcollection)
bundle.output(GlobalWindows.windowed_value(b''))
return TransformResult(self, [bundle], [], None, None)
class _TaggedReceivers(dict):
"""Received ParDo output and redirect to the associated output bundle."""
def __init__(self, evaluation_context):
self._evaluation_context = evaluation_context
self._null_receiver = None
super(_TaggedReceivers, self).__init__()
class NullReceiver(common.Receiver):
"""Ignores undeclared outputs, default execution mode."""
def receive(self, element):
# type: (WindowedValue) -> None
pass
class _InMemoryReceiver(common.Receiver):
"""Buffers undeclared outputs to the given dictionary."""
def __init__(self, target, tag):
self._target = target
self._tag = tag
def receive(self, element):
# type: (WindowedValue) -> None
self._target[self._tag].append(element)
def __missing__(self, key):
if not self._null_receiver:
self._null_receiver = _TaggedReceivers.NullReceiver()
return self._null_receiver
class _ParDoEvaluator(_TransformEvaluator):
"""TransformEvaluator for ParDo transform."""
def __init__(self,
evaluation_context, # type: EvaluationContext
applied_ptransform, # type: AppliedPTransform
input_committed_bundle,
side_inputs,
perform_dofn_pickle_test=True
):
super(_ParDoEvaluator, self).__init__(
evaluation_context,
applied_ptransform,
input_committed_bundle,
side_inputs)
# This is a workaround for SDF implementation. SDF implementation adds state
# to the SDF that is not picklable.
self._perform_dofn_pickle_test = perform_dofn_pickle_test
def start_bundle(self):
transform = self._applied_ptransform.transform
self._tagged_receivers = _TaggedReceivers(self._evaluation_context)
for output_tag in self._applied_ptransform.outputs:
output_pcollection = pvalue.PCollection(None, tag=output_tag)
output_pcollection.producer = self._applied_ptransform
self._tagged_receivers[output_tag] = (
self._evaluation_context.create_bundle(output_pcollection))
self._tagged_receivers[output_tag].tag = output_tag
self._counter_factory = counters.CounterFactory()
# TODO(aaltay): Consider storing the serialized form as an optimization.
dofn = (
pickler.loads(pickler.dumps(transform.dofn))
if self._perform_dofn_pickle_test else transform.dofn)
args = transform.args if hasattr(transform, 'args') else []
kwargs = transform.kwargs if hasattr(transform, 'kwargs') else {}
self.user_state_context = None
self.user_timer_map = {}
if is_stateful_dofn(dofn):
kv_type_hint = self._applied_ptransform.inputs[0].element_type
if kv_type_hint and kv_type_hint != Any:
coder = coders.registry.get_coder(kv_type_hint)
self.key_coder = coder.key_coder()
else:
self.key_coder = coders.registry.get_coder(Any)
self.user_state_context = DirectUserStateContext(
self._step_context, dofn, self.key_coder)
_, all_timer_specs = get_dofn_specs(dofn)
for timer_spec in all_timer_specs:
self.user_timer_map['user/%s' % timer_spec.name] = timer_spec
self.runner = DoFnRunner(
dofn,
args,
kwargs,
self._side_inputs,
self._applied_ptransform.inputs[0].windowing,
tagged_receivers=self._tagged_receivers,
step_name=self._applied_ptransform.full_label,
state=DoFnState(self._counter_factory),
user_state_context=self.user_state_context)
self.runner.start()
def process_timer(self, timer_firing):
if timer_firing.name not in self.user_timer_map:
_LOGGER.warning('Unknown timer fired: %s', timer_firing)
timer_spec = self.user_timer_map[timer_firing.name]
self.runner.process_user_timer(
timer_spec,
self.key_coder.decode(timer_firing.encoded_key),
timer_firing.window,
timer_firing.timestamp)
def process_element(self, element):
self.runner.process(element)
def finish_bundle(self):
self.runner.finish()
bundles = list(self._tagged_receivers.values())
result_counters = self._counter_factory.get_counters()
if self.user_state_context:
self.user_state_context.commit()
return TransformResult(self, bundles, [], result_counters, None)
class _GroupByKeyOnlyEvaluator(_TransformEvaluator):
"""TransformEvaluator for _GroupByKeyOnly transform."""
MAX_ELEMENT_PER_BUNDLE = None
ELEMENTS_TAG = _ListStateTag('elements')
COMPLETION_TAG = _CombiningValueStateTag('completed', any)
def __init__(
self,
evaluation_context,
applied_ptransform,
input_committed_bundle,
side_inputs):
assert not side_inputs
super(_GroupByKeyOnlyEvaluator, self).__init__(
evaluation_context,
applied_ptransform,
input_committed_bundle,
side_inputs)
def _is_final_bundle(self):
return (
self._execution_context.watermarks.input_watermark ==
WatermarkManager.WATERMARK_POS_INF)
def start_bundle(self):
self.global_state = self._step_context.get_keyed_state(None)
assert len(self._outputs) == 1
self.output_pcollection = list(self._outputs)[0]
# The output type of a GroupByKey will be Tuple[Any, Any] or more specific.
# TODO(BEAM-2717): Infer coders earlier.
kv_type_hint = (
self._applied_ptransform.outputs[None].element_type or
self._applied_ptransform.transform.get_type_hints().input_types[0][0])
self.key_coder = coders.registry.get_coder(kv_type_hint.tuple_types[0])
def process_timer(self, timer_firing):
# We do not need to emit a KeyedWorkItem to process_element().
pass
def process_element(self, element):
assert not self.global_state.get_state(
None, _GroupByKeyOnlyEvaluator.COMPLETION_TAG)
if (isinstance(element, WindowedValue) and
isinstance(element.value, collections.Iterable) and
len(element.value) == 2):
k, v = element.value
encoded_k = self.key_coder.encode(k)
state = self._step_context.get_keyed_state(encoded_k)
state.add_state(None, _GroupByKeyOnlyEvaluator.ELEMENTS_TAG, v)
else:
raise TypeCheckError(
'Input to _GroupByKeyOnly must be a PCollection of '
'windowed key-value pairs. Instead received: %r.' % element)
def finish_bundle(self):
if self._is_final_bundle():
if self.global_state.get_state(None,
_GroupByKeyOnlyEvaluator.COMPLETION_TAG):
# Ignore empty bundles after emitting output. (This may happen because
# empty bundles do not affect input watermarks.)
bundles = []
else:
gbk_result = []
# TODO(ccy): perhaps we can clean this up to not use this
# internal attribute of the DirectStepContext.
for encoded_k in self._step_context.existing_keyed_state:
# Ignore global state.
if encoded_k is None:
continue
k = self.key_coder.decode(encoded_k)
state = self._step_context.get_keyed_state(encoded_k)
vs = state.get_state(None, _GroupByKeyOnlyEvaluator.ELEMENTS_TAG)
gbk_result.append(GlobalWindows.windowed_value((k, vs)))
def len_element_fn(element):
_, v = element.value
return len(v)
bundles = self._split_list_into_bundles(
self.output_pcollection,
gbk_result,
_GroupByKeyOnlyEvaluator.MAX_ELEMENT_PER_BUNDLE,
len_element_fn)
self.global_state.add_state(
None, _GroupByKeyOnlyEvaluator.COMPLETION_TAG, True)
hold = WatermarkManager.WATERMARK_POS_INF
else:
bundles = []
hold = WatermarkManager.WATERMARK_NEG_INF
self.global_state.set_timer(
None, '', TimeDomain.WATERMARK, WatermarkManager.WATERMARK_POS_INF)
return TransformResult(self, bundles, [], None, {None: hold})
class _StreamingGroupByKeyOnlyEvaluator(_TransformEvaluator):
"""TransformEvaluator for _StreamingGroupByKeyOnly transform.
The _GroupByKeyOnlyEvaluator buffers elements until its input watermark goes
to infinity, which is suitable for batch mode execution. During streaming
mode execution, we emit each bundle as it comes to the next transform.
"""
MAX_ELEMENT_PER_BUNDLE = None
def __init__(
self,
evaluation_context,
applied_ptransform,
input_committed_bundle,
side_inputs):
assert not side_inputs
super(_StreamingGroupByKeyOnlyEvaluator, self).__init__(
evaluation_context,
applied_ptransform,
input_committed_bundle,
side_inputs)
def start_bundle(self):
self.gbk_items = collections.defaultdict(list)
assert len(self._outputs) == 1
self.output_pcollection = list(self._outputs)[0]
# The input type of a GroupByKey will be Tuple[Any, Any] or more specific.
kv_type_hint = self._applied_ptransform.inputs[0].element_type
key_type_hint = (kv_type_hint.tuple_types[0] if kv_type_hint else Any)
self.key_coder = coders.registry.get_coder(key_type_hint)
def process_element(self, element):
if (isinstance(element, WindowedValue) and
isinstance(element.value, collections.Iterable) and
len(element.value) == 2):
k, v = element.value
self.gbk_items[self.key_coder.encode(k)].append(v)
else:
raise TypeCheckError(
'Input to _GroupByKeyOnly must be a PCollection of '
'windowed key-value pairs. Instead received: %r.' % element)
def finish_bundle(self):
bundles = []
bundle = None
for encoded_k, vs in iteritems(self.gbk_items):
if not bundle:
bundle = self._evaluation_context.create_bundle(self.output_pcollection)
bundles.append(bundle)
kwi = KeyedWorkItem(encoded_k, elements=vs)
bundle.add(GlobalWindows.windowed_value(kwi))
return TransformResult(self, bundles, [], None, None)
class _StreamingGroupAlsoByWindowEvaluator(_TransformEvaluator):
"""TransformEvaluator for the _StreamingGroupAlsoByWindow transform.
This evaluator is only used in streaming mode. In batch mode, the
GroupAlsoByWindow operation is evaluated as a normal DoFn, as defined
in transforms/core.py.
"""
def __init__(
self,
evaluation_context,
applied_ptransform,
input_committed_bundle,
side_inputs):
assert not side_inputs
super(_StreamingGroupAlsoByWindowEvaluator, self).__init__(
evaluation_context,
applied_ptransform,
input_committed_bundle,
side_inputs)
def start_bundle(self):
assert len(self._outputs) == 1
self.output_pcollection = list(self._outputs)[0]
self.driver = create_trigger_driver(
self._applied_ptransform.transform.windowing,
clock=self._evaluation_context._watermark_manager._clock)
self.gabw_items = []
self.keyed_holds = {}
# The input type (which is the same as the output type) of a
# GroupAlsoByWindow will be Tuple[Any, Iter[Any]] or more specific.
kv_type_hint = self._applied_ptransform.outputs[None].element_type
key_type_hint = (kv_type_hint.tuple_types[0] if kv_type_hint else Any)
self.key_coder = coders.registry.get_coder(key_type_hint)
def process_element(self, element):
kwi = element.value
assert isinstance(kwi, KeyedWorkItem), kwi
encoded_k, timer_firings, vs = (
kwi.encoded_key, kwi.timer_firings, kwi.elements)
k = self.key_coder.decode(encoded_k)
state = self._step_context.get_keyed_state(encoded_k)
watermarks = self._evaluation_context._watermark_manager.get_watermarks(
self._applied_ptransform)
for timer_firing in timer_firings:
for wvalue in self.driver.process_timer(timer_firing.window,
timer_firing.name,
timer_firing.time_domain,
timer_firing.timestamp,
state,
watermarks.input_watermark):
self.gabw_items.append(wvalue.with_value((k, wvalue.value)))
if vs:
for wvalue in self.driver.process_elements(state,
vs,
watermarks.output_watermark,
watermarks.input_watermark):
self.gabw_items.append(wvalue.with_value((k, wvalue.value)))
self.keyed_holds[encoded_k] = state.get_earliest_hold()
def finish_bundle(self):
bundles = []
if self.gabw_items:
bundle = self._evaluation_context.create_bundle(self.output_pcollection)
for item in self.gabw_items:
bundle.add(item)
bundles.append(bundle)
return TransformResult(self, bundles, [], None, self.keyed_holds)
class _NativeWriteEvaluator(_TransformEvaluator):
"""TransformEvaluator for _NativeWrite transform."""
ELEMENTS_TAG = _ListStateTag('elements')
def __init__(
self,
evaluation_context,
applied_ptransform,
input_committed_bundle,
side_inputs):
assert not side_inputs
super(_NativeWriteEvaluator, self).__init__(
evaluation_context,
applied_ptransform,
input_committed_bundle,
side_inputs)
assert applied_ptransform.transform.sink
self._sink = applied_ptransform.transform.sink
@property
def _is_final_bundle(self):
return (
self._execution_context.watermarks.input_watermark ==
WatermarkManager.WATERMARK_POS_INF)
@property
def _has_already_produced_output(self):
return (
self._execution_context.watermarks.output_watermark ==
WatermarkManager.WATERMARK_POS_INF)
def start_bundle(self):
self.global_state = self._step_context.get_keyed_state(None)
def process_timer(self, timer_firing):
# We do not need to emit a KeyedWorkItem to process_element().
pass
def process_element(self, element):
self.global_state.add_state(
None, _NativeWriteEvaluator.ELEMENTS_TAG, element)
def finish_bundle(self):
# finish_bundle will append incoming bundles in memory until all the bundles
# carrying data is processed. This is done to produce only a single output
# shard (some tests depends on this behavior). It is possible to have
# incoming empty bundles after the output is produced, these bundles will be
# ignored and would not generate additional output files.
# TODO(altay): Do not wait until the last bundle to write in a single shard.
if self._is_final_bundle:
elements = self.global_state.get_state(
None, _NativeWriteEvaluator.ELEMENTS_TAG)
if self._has_already_produced_output:
# Ignore empty bundles that arrive after the output is produced.
assert elements == []
else:
self._sink.pipeline_options = self._evaluation_context.pipeline_options
with self._sink.writer() as writer:
for v in elements:
writer.Write(v.value)
hold = WatermarkManager.WATERMARK_POS_INF
else:
hold = WatermarkManager.WATERMARK_NEG_INF
self.global_state.set_timer(
None, '', TimeDomain.WATERMARK, WatermarkManager.WATERMARK_POS_INF)
return TransformResult(self, [], [], None, {None: hold})
class _ProcessElementsEvaluator(_TransformEvaluator):
"""An evaluator for sdf_direct_runner.ProcessElements transform."""
# Maximum number of elements that will be produced by a Splittable DoFn before
# a checkpoint is requested by the runner.
DEFAULT_MAX_NUM_OUTPUTS = None
# Maximum duration a Splittable DoFn will process an element before a
# checkpoint is requested by the runner.
DEFAULT_MAX_DURATION = 1
def __init__(
self,
evaluation_context,
applied_ptransform,
input_committed_bundle,
side_inputs):
super(_ProcessElementsEvaluator, self).__init__(
evaluation_context,
applied_ptransform,
input_committed_bundle,
side_inputs)
process_elements_transform = applied_ptransform.transform
assert isinstance(process_elements_transform, ProcessElements)
# Replacing the do_fn of the transform with a wrapper do_fn that performs
# SDF magic.
transform = applied_ptransform.transform
sdf = transform.sdf
self._process_fn = transform.new_process_fn(sdf)
transform.dofn = self._process_fn
assert isinstance(self._process_fn, ProcessFn)
self._process_fn.step_context = self._step_context
process_element_invoker = (
SDFProcessElementInvoker(
max_num_outputs=self.DEFAULT_MAX_NUM_OUTPUTS,
max_duration=self.DEFAULT_MAX_DURATION))
self._process_fn.set_process_element_invoker(process_element_invoker)
self._par_do_evaluator = _ParDoEvaluator(
evaluation_context,
applied_ptransform,
input_committed_bundle,
side_inputs,
perform_dofn_pickle_test=False)
self.keyed_holds = {}
def start_bundle(self):
self._par_do_evaluator.start_bundle()
def process_element(self, element):
assert isinstance(element, WindowedValue)
assert len(element.windows) == 1
window = element.windows[0]
if isinstance(element.value, KeyedWorkItem):
key = element.value.encoded_key
else:
# If not a `KeyedWorkItem`, this must be a tuple where key is a randomly
# generated key and the value is a `WindowedValue` that contains an
# `ElementAndRestriction` object.
assert isinstance(element.value, tuple)
key = element.value[0]
self._par_do_evaluator.process_element(element)
state = self._step_context.get_keyed_state(key)
self.keyed_holds[key] = state.get_state(
window, self._process_fn.watermark_hold_tag)
def finish_bundle(self):
par_do_result = self._par_do_evaluator.finish_bundle()
transform_result = TransformResult(
self,
par_do_result.uncommitted_output_bundles,
par_do_result.unprocessed_bundles,
par_do_result.counters,
par_do_result.keyed_watermark_holds,
par_do_result.undeclared_tag_values)
for key in self.keyed_holds:
transform_result.keyed_watermark_holds[key] = self.keyed_holds[key]
return transform_result
| 37.064103 | 106 | 0.72462 |
acec67d2460e8151b598b42c0b98d5391fa14311 | 920 | py | Python | Lab9/Code/Exercise2/mapper.py | keithnull/Learning-EE208 | 51c63dd539c0c21b488c8ff6eab84d5d3b509407 | [
"MIT"
] | null | null | null | Lab9/Code/Exercise2/mapper.py | keithnull/Learning-EE208 | 51c63dd539c0c21b488c8ff6eab84d5d3b509407 | [
"MIT"
] | null | null | null | Lab9/Code/Exercise2/mapper.py | keithnull/Learning-EE208 | 51c63dd539c0c21b488c8ff6eab84d5d3b509407 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
import sys
damping_factor = 0.85
page_num = 4
for line in sys.stdin:
line = line.split()
try:
page_id, initial_prob = int(line[0]), float(line[1])
except:
continue
print("{page} plus {plus}".format(page=page_id, plus=(1-damping_factor)/page_num))
if len(line) <= 2: # for pages that link to no other pages
prob_per_page = initial_prob/(page_num-1) * damping_factor
for page in range(1, page_num+1):
if page != page_id:
print("{page} plus {plus}".format(page=page, plus=prob_per_page))
else:
links_list = line[2:]
print("{page} links".format(page=page_id), *links_list) # print all the links of the current page
prob_per_link = initial_prob/(len(links_list)) * damping_factor
for link in links_list:
print("{page} plus {plus}".format(page=link, plus=prob_per_link))
| 36.8 | 106 | 0.630435 |
acec689400b17fe4af6ec3f8fb86be05d49264e2 | 436 | py | Python | cuppy/migrations/0003_mqttsensoractuatorclient_should_stop_loop.py | adinaborta/Cuppy | e6099e345e8b3fa4d25fde1e5a6485c6558922e5 | [
"Unlicense"
] | null | null | null | cuppy/migrations/0003_mqttsensoractuatorclient_should_stop_loop.py | adinaborta/Cuppy | e6099e345e8b3fa4d25fde1e5a6485c6558922e5 | [
"Unlicense"
] | null | null | null | cuppy/migrations/0003_mqttsensoractuatorclient_should_stop_loop.py | adinaborta/Cuppy | e6099e345e8b3fa4d25fde1e5a6485c6558922e5 | [
"Unlicense"
] | 1 | 2022-01-30T16:42:05.000Z | 2022-01-30T16:42:05.000Z | # Generated by Django 3.2.9 on 2021-12-04 19:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cuppy', '0002_mqttcentralclient_mqttsensoractuatorclient'),
]
operations = [
migrations.AddField(
model_name='mqttsensoractuatorclient',
name='should_stop_loop',
field=models.BooleanField(default=True),
),
]
| 22.947368 | 69 | 0.644495 |
acec6b4a293589c0ebb220de2b8d75d1c00a864e | 60,196 | py | Python | tensorflow/python/ops/rnn.py | dantkz/tensorflow | 5333bbeb3142af2a06f1ebd971061fc4e28da743 | [
"Apache-2.0"
] | null | null | null | tensorflow/python/ops/rnn.py | dantkz/tensorflow | 5333bbeb3142af2a06f1ebd971061fc4e28da743 | [
"Apache-2.0"
] | null | null | null | tensorflow/python/ops/rnn.py | dantkz/tensorflow | 5333bbeb3142af2a06f1ebd971061fc4e28da743 | [
"Apache-2.0"
] | null | null | null | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""RNN helpers for TensorFlow models.
@@bidirectional_dynamic_rnn
@@dynamic_rnn
@@raw_rnn
@@static_rnn
@@static_state_saving_rnn
@@static_bidirectional_rnn
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.eager import context
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import rnn_cell_impl
from tensorflow.python.ops import tensor_array_ops
from tensorflow.python.ops import variable_scope as vs
from tensorflow.python.util import nest
# pylint: disable=protected-access
_concat = rnn_cell_impl._concat
_like_rnncell = rnn_cell_impl._like_rnncell
# pylint: enable=protected-access
def _transpose_batch_time(x):
"""Transpose the batch and time dimensions of a Tensor.
Retains as much of the static shape information as possible.
Args:
x: A tensor of rank 2 or higher.
Returns:
x transposed along the first two dimensions.
Raises:
ValueError: if `x` is rank 1 or lower.
"""
x_static_shape = x.get_shape()
if x_static_shape.ndims is not None and x_static_shape.ndims < 2:
raise ValueError(
"Expected input tensor %s to have rank at least 2, but saw shape: %s" %
(x, x_static_shape))
x_rank = array_ops.rank(x)
x_t = array_ops.transpose(
x, array_ops.concat(
([1, 0], math_ops.range(2, x_rank)), axis=0))
x_t.set_shape(
tensor_shape.TensorShape([
x_static_shape[1].value, x_static_shape[0].value
]).concatenate(x_static_shape[2:]))
return x_t
def _best_effort_input_batch_size(flat_input):
"""Get static input batch size if available, with fallback to the dynamic one.
Args:
flat_input: An iterable of time major input Tensors of shape [max_time,
batch_size, ...]. All inputs should have compatible batch sizes.
Returns:
The batch size in Python integer if available, or a scalar Tensor otherwise.
Raises:
ValueError: if there is any input with an invalid shape.
"""
for input_ in flat_input:
shape = input_.shape
if shape.ndims is None:
continue
if shape.ndims < 2:
raise ValueError(
"Expected input tensor %s to have rank at least 2" % input_)
batch_size = shape[1].value
if batch_size is not None:
return batch_size
# Fallback to the dynamic batch size of the first input.
return array_ops.shape(flat_input[0])[1]
def _infer_state_dtype(explicit_dtype, state):
"""Infer the dtype of an RNN state.
Args:
explicit_dtype: explicitly declared dtype or None.
state: RNN's hidden state. Must be a Tensor or a nested iterable containing
Tensors.
Returns:
dtype: inferred dtype of hidden state.
Raises:
ValueError: if `state` has heterogeneous dtypes or is empty.
"""
if explicit_dtype is not None:
return explicit_dtype
elif nest.is_sequence(state):
inferred_dtypes = [element.dtype for element in nest.flatten(state)]
if not inferred_dtypes:
raise ValueError("Unable to infer dtype from empty state.")
all_same = all([x == inferred_dtypes[0] for x in inferred_dtypes])
if not all_same:
raise ValueError(
"State has tensors of different inferred_dtypes. Unable to infer a "
"single representative dtype.")
return inferred_dtypes[0]
else:
return state.dtype
# pylint: disable=unused-argument
def _rnn_step(
time, sequence_length, min_sequence_length, max_sequence_length,
zero_output, state, call_cell, state_size, skip_conditionals=False):
"""Calculate one step of a dynamic RNN minibatch.
Returns an (output, state) pair conditioned on the sequence_lengths.
When skip_conditionals=False, the pseudocode is something like:
if t >= max_sequence_length:
return (zero_output, state)
if t < min_sequence_length:
return call_cell()
# Selectively output zeros or output, old state or new state depending
# on if we've finished calculating each row.
new_output, new_state = call_cell()
final_output = np.vstack([
zero_output if time >= sequence_lengths[r] else new_output_r
for r, new_output_r in enumerate(new_output)
])
final_state = np.vstack([
state[r] if time >= sequence_lengths[r] else new_state_r
for r, new_state_r in enumerate(new_state)
])
return (final_output, final_state)
Args:
time: Python int, the current time step
sequence_length: int32 `Tensor` vector of size [batch_size]
min_sequence_length: int32 `Tensor` scalar, min of sequence_length
max_sequence_length: int32 `Tensor` scalar, max of sequence_length
zero_output: `Tensor` vector of shape [output_size]
state: Either a single `Tensor` matrix of shape `[batch_size, state_size]`,
or a list/tuple of such tensors.
call_cell: lambda returning tuple of (new_output, new_state) where
new_output is a `Tensor` matrix of shape `[batch_size, output_size]`.
new_state is a `Tensor` matrix of shape `[batch_size, state_size]`.
state_size: The `cell.state_size` associated with the state.
skip_conditionals: Python bool, whether to skip using the conditional
calculations. This is useful for `dynamic_rnn`, where the input tensor
matches `max_sequence_length`, and using conditionals just slows
everything down.
Returns:
A tuple of (`final_output`, `final_state`) as given by the pseudocode above:
final_output is a `Tensor` matrix of shape [batch_size, output_size]
final_state is either a single `Tensor` matrix, or a tuple of such
matrices (matching length and shapes of input `state`).
Raises:
ValueError: If the cell returns a state tuple whose length does not match
that returned by `state_size`.
"""
# Convert state to a list for ease of use
flat_state = nest.flatten(state)
flat_zero_output = nest.flatten(zero_output)
def _copy_one_through(output, new_output):
# If the state contains a scalar value we simply pass it through.
if output.shape.ndims == 0:
return new_output
copy_cond = (time >= sequence_length)
with ops.colocate_with(new_output):
return array_ops.where(copy_cond, output, new_output)
def _copy_some_through(flat_new_output, flat_new_state):
# Use broadcasting select to determine which values should get
# the previous state & zero output, and which values should get
# a calculated state & output.
flat_new_output = [
_copy_one_through(zero_output, new_output)
for zero_output, new_output in zip(flat_zero_output, flat_new_output)]
flat_new_state = [
_copy_one_through(state, new_state)
for state, new_state in zip(flat_state, flat_new_state)]
return flat_new_output + flat_new_state
def _maybe_copy_some_through():
"""Run RNN step. Pass through either no or some past state."""
new_output, new_state = call_cell()
nest.assert_same_structure(state, new_state)
flat_new_state = nest.flatten(new_state)
flat_new_output = nest.flatten(new_output)
return control_flow_ops.cond(
# if t < min_seq_len: calculate and return everything
time < min_sequence_length, lambda: flat_new_output + flat_new_state,
# else copy some of it through
lambda: _copy_some_through(flat_new_output, flat_new_state))
# TODO(ebrevdo): skipping these conditionals may cause a slowdown,
# but benefits from removing cond() and its gradient. We should
# profile with and without this switch here.
if skip_conditionals:
# Instead of using conditionals, perform the selective copy at all time
# steps. This is faster when max_seq_len is equal to the number of unrolls
# (which is typical for dynamic_rnn).
new_output, new_state = call_cell()
nest.assert_same_structure(state, new_state)
new_state = nest.flatten(new_state)
new_output = nest.flatten(new_output)
final_output_and_state = _copy_some_through(new_output, new_state)
else:
empty_update = lambda: flat_zero_output + flat_state
final_output_and_state = control_flow_ops.cond(
# if t >= max_seq_len: copy all state through, output zeros
time >= max_sequence_length, empty_update,
# otherwise calculation is required: copy some or all of it through
_maybe_copy_some_through)
if len(final_output_and_state) != len(flat_zero_output) + len(flat_state):
raise ValueError("Internal error: state and output were not concatenated "
"correctly.")
final_output = final_output_and_state[:len(flat_zero_output)]
final_state = final_output_and_state[len(flat_zero_output):]
for output, flat_output in zip(final_output, flat_zero_output):
output.set_shape(flat_output.get_shape())
for substate, flat_substate in zip(final_state, flat_state):
substate.set_shape(flat_substate.get_shape())
final_output = nest.pack_sequence_as(
structure=zero_output, flat_sequence=final_output)
final_state = nest.pack_sequence_as(
structure=state, flat_sequence=final_state)
return final_output, final_state
def _reverse_seq(input_seq, lengths):
"""Reverse a list of Tensors up to specified lengths.
Args:
input_seq: Sequence of seq_len tensors of dimension (batch_size, n_features)
or nested tuples of tensors.
lengths: A `Tensor` of dimension batch_size, containing lengths for each
sequence in the batch. If "None" is specified, simply reverses
the list.
Returns:
time-reversed sequence
"""
if lengths is None:
return list(reversed(input_seq))
flat_input_seq = tuple(nest.flatten(input_) for input_ in input_seq)
flat_results = [[] for _ in range(len(input_seq))]
for sequence in zip(*flat_input_seq):
input_shape = tensor_shape.unknown_shape(
ndims=sequence[0].get_shape().ndims)
for input_ in sequence:
input_shape.merge_with(input_.get_shape())
input_.set_shape(input_shape)
# Join into (time, batch_size, depth)
s_joined = array_ops.stack(sequence)
# Reverse along dimension 0
s_reversed = array_ops.reverse_sequence(s_joined, lengths, 0, 1)
# Split again into list
result = array_ops.unstack(s_reversed)
for r, flat_result in zip(result, flat_results):
r.set_shape(input_shape)
flat_result.append(r)
results = [nest.pack_sequence_as(structure=input_, flat_sequence=flat_result)
for input_, flat_result in zip(input_seq, flat_results)]
return results
def bidirectional_dynamic_rnn(cell_fw, cell_bw, inputs, sequence_length=None,
initial_state_fw=None, initial_state_bw=None,
dtype=None, parallel_iterations=None,
swap_memory=False, time_major=False, scope=None):
"""Creates a dynamic version of bidirectional recurrent neural network.
Takes input and builds independent forward and backward RNNs. The input_size
of forward and backward cell must match. The initial state for both directions
is zero by default (but can be set optionally) and no intermediate states are
ever returned -- the network is fully unrolled for the given (passed in)
length(s) of the sequence(s) or completely unrolled if length(s) is not
given.
Args:
cell_fw: An instance of RNNCell, to be used for forward direction.
cell_bw: An instance of RNNCell, to be used for backward direction.
inputs: The RNN inputs.
If time_major == False (default), this must be a tensor of shape:
`[batch_size, max_time, ...]`, or a nested tuple of such elements.
If time_major == True, this must be a tensor of shape:
`[max_time, batch_size, ...]`, or a nested tuple of such elements.
sequence_length: (optional) An int32/int64 vector, size `[batch_size]`,
containing the actual lengths for each of the sequences in the batch.
If not provided, all batch entries are assumed to be full sequences; and
time reversal is applied from time `0` to `max_time` for each sequence.
initial_state_fw: (optional) An initial state for the forward RNN.
This must be a tensor of appropriate type and shape
`[batch_size, cell_fw.state_size]`.
If `cell_fw.state_size` is a tuple, this should be a tuple of
tensors having shapes `[batch_size, s] for s in cell_fw.state_size`.
initial_state_bw: (optional) Same as for `initial_state_fw`, but using
the corresponding properties of `cell_bw`.
dtype: (optional) The data type for the initial states and expected output.
Required if initial_states are not provided or RNN states have a
heterogeneous dtype.
parallel_iterations: (Default: 32). The number of iterations to run in
parallel. Those operations which do not have any temporal dependency
and can be run in parallel, will be. This parameter trades off
time for space. Values >> 1 use more memory but take less time,
while smaller values use less memory but computations take longer.
swap_memory: Transparently swap the tensors produced in forward inference
but needed for back prop from GPU to CPU. This allows training RNNs
which would typically not fit on a single GPU, with very minimal (or no)
performance penalty.
time_major: The shape format of the `inputs` and `outputs` Tensors.
If true, these `Tensors` must be shaped `[max_time, batch_size, depth]`.
If false, these `Tensors` must be shaped `[batch_size, max_time, depth]`.
Using `time_major = True` is a bit more efficient because it avoids
transposes at the beginning and end of the RNN calculation. However,
most TensorFlow data is batch-major, so by default this function
accepts input and emits output in batch-major form.
scope: VariableScope for the created subgraph; defaults to
"bidirectional_rnn"
Returns:
A tuple (outputs, output_states) where:
outputs: A tuple (output_fw, output_bw) containing the forward and
the backward rnn output `Tensor`.
If time_major == False (default),
output_fw will be a `Tensor` shaped:
`[batch_size, max_time, cell_fw.output_size]`
and output_bw will be a `Tensor` shaped:
`[batch_size, max_time, cell_bw.output_size]`.
If time_major == True,
output_fw will be a `Tensor` shaped:
`[max_time, batch_size, cell_fw.output_size]`
and output_bw will be a `Tensor` shaped:
`[max_time, batch_size, cell_bw.output_size]`.
It returns a tuple instead of a single concatenated `Tensor`, unlike
in the `bidirectional_rnn`. If the concatenated one is preferred,
the forward and backward outputs can be concatenated as
`tf.concat(outputs, 2)`.
output_states: A tuple (output_state_fw, output_state_bw) containing
the forward and the backward final states of bidirectional rnn.
Raises:
TypeError: If `cell_fw` or `cell_bw` is not an instance of `RNNCell`.
"""
if not _like_rnncell(cell_fw):
raise TypeError("cell_fw must be an instance of RNNCell")
if not _like_rnncell(cell_bw):
raise TypeError("cell_bw must be an instance of RNNCell")
with vs.variable_scope(scope or "bidirectional_rnn"):
# Forward direction
with vs.variable_scope("fw") as fw_scope:
output_fw, output_state_fw = dynamic_rnn(
cell=cell_fw, inputs=inputs, sequence_length=sequence_length,
initial_state=initial_state_fw, dtype=dtype,
parallel_iterations=parallel_iterations, swap_memory=swap_memory,
time_major=time_major, scope=fw_scope)
# Backward direction
if not time_major:
time_dim = 1
batch_dim = 0
else:
time_dim = 0
batch_dim = 1
def _reverse(input_, seq_lengths, seq_dim, batch_dim):
if seq_lengths is not None:
return array_ops.reverse_sequence(
input=input_, seq_lengths=seq_lengths,
seq_dim=seq_dim, batch_dim=batch_dim)
else:
return array_ops.reverse(input_, axis=[seq_dim])
with vs.variable_scope("bw") as bw_scope:
inputs_reverse = _reverse(
inputs, seq_lengths=sequence_length,
seq_dim=time_dim, batch_dim=batch_dim)
tmp, output_state_bw = dynamic_rnn(
cell=cell_bw, inputs=inputs_reverse, sequence_length=sequence_length,
initial_state=initial_state_bw, dtype=dtype,
parallel_iterations=parallel_iterations, swap_memory=swap_memory,
time_major=time_major, scope=bw_scope)
output_bw = _reverse(
tmp, seq_lengths=sequence_length,
seq_dim=time_dim, batch_dim=batch_dim)
outputs = (output_fw, output_bw)
output_states = (output_state_fw, output_state_bw)
return (outputs, output_states)
def dynamic_rnn(cell, inputs, sequence_length=None, initial_state=None,
dtype=None, parallel_iterations=None, swap_memory=False,
time_major=False, scope=None):
"""Creates a recurrent neural network specified by RNNCell `cell`.
Performs fully dynamic unrolling of `inputs`.
Example:
```python
# create a BasicRNNCell
rnn_cell = tf.nn.rnn_cell.BasicRNNCell(hidden_size)
# 'outputs' is a tensor of shape [batch_size, max_time, cell_state_size]
# defining initial state
initial_state = rnn_cell.zero_state(batch_size, dtype=tf.float32)
# 'state' is a tensor of shape [batch_size, cell_state_size]
outputs, state = tf.nn.dynamic_rnn(rnn_cell, input_data,
initial_state=initial_state,
dtype=tf.float32)
```
```python
# create 2 LSTMCells
rnn_layers = [tf.nn.rnn_cell.LSTMCell(size) for size in [128, 256]]
# create a RNN cell composed sequentially of a number of RNNCells
multi_rnn_cell = tf.nn.rnn_cell.MultiRNNCell(rnn_layers)
# 'outputs' is a tensor of shape [batch_size, max_time, 256]
# 'state' is a N-tuple where N is the number of LSTMCells containing a
# tf.contrib.rnn.LSTMStateTuple for each cell
outputs, state = tf.nn.dynamic_rnn(cell=multi_rnn_cell,
inputs=data,
dtype=tf.float32)
```
Args:
cell: An instance of RNNCell.
inputs: The RNN inputs.
If `time_major == False` (default), this must be a `Tensor` of shape:
`[batch_size, max_time, ...]`, or a nested tuple of such
elements.
If `time_major == True`, this must be a `Tensor` of shape:
`[max_time, batch_size, ...]`, or a nested tuple of such
elements.
This may also be a (possibly nested) tuple of Tensors satisfying
this property. The first two dimensions must match across all the inputs,
but otherwise the ranks and other shape components may differ.
In this case, input to `cell` at each time-step will replicate the
structure of these tuples, except for the time dimension (from which the
time is taken).
The input to `cell` at each time step will be a `Tensor` or (possibly
nested) tuple of Tensors each with dimensions `[batch_size, ...]`.
sequence_length: (optional) An int32/int64 vector sized `[batch_size]`.
Used to copy-through state and zero-out outputs when past a batch
element's sequence length. So it's more for correctness than performance.
initial_state: (optional) An initial state for the RNN.
If `cell.state_size` is an integer, this must be
a `Tensor` of appropriate type and shape `[batch_size, cell.state_size]`.
If `cell.state_size` is a tuple, this should be a tuple of
tensors having shapes `[batch_size, s] for s in cell.state_size`.
dtype: (optional) The data type for the initial state and expected output.
Required if initial_state is not provided or RNN state has a heterogeneous
dtype.
parallel_iterations: (Default: 32). The number of iterations to run in
parallel. Those operations which do not have any temporal dependency
and can be run in parallel, will be. This parameter trades off
time for space. Values >> 1 use more memory but take less time,
while smaller values use less memory but computations take longer.
swap_memory: Transparently swap the tensors produced in forward inference
but needed for back prop from GPU to CPU. This allows training RNNs
which would typically not fit on a single GPU, with very minimal (or no)
performance penalty.
time_major: The shape format of the `inputs` and `outputs` Tensors.
If true, these `Tensors` must be shaped `[max_time, batch_size, depth]`.
If false, these `Tensors` must be shaped `[batch_size, max_time, depth]`.
Using `time_major = True` is a bit more efficient because it avoids
transposes at the beginning and end of the RNN calculation. However,
most TensorFlow data is batch-major, so by default this function
accepts input and emits output in batch-major form.
scope: VariableScope for the created subgraph; defaults to "rnn".
Returns:
A pair (outputs, state) where:
outputs: The RNN output `Tensor`.
If time_major == False (default), this will be a `Tensor` shaped:
`[batch_size, max_time, cell.output_size]`.
If time_major == True, this will be a `Tensor` shaped:
`[max_time, batch_size, cell.output_size]`.
Note, if `cell.output_size` is a (possibly nested) tuple of integers
or `TensorShape` objects, then `outputs` will be a tuple having the
same structure as `cell.output_size`, containing Tensors having shapes
corresponding to the shape data in `cell.output_size`.
state: The final state. If `cell.state_size` is an int, this
will be shaped `[batch_size, cell.state_size]`. If it is a
`TensorShape`, this will be shaped `[batch_size] + cell.state_size`.
If it is a (possibly nested) tuple of ints or `TensorShape`, this will
be a tuple having the corresponding shapes. If cells are `LSTMCells`
`state` will be a tuple containing a `LSTMStateTuple` for each cell.
Raises:
TypeError: If `cell` is not an instance of RNNCell.
ValueError: If inputs is None or an empty list.
"""
if not _like_rnncell(cell):
raise TypeError("cell must be an instance of RNNCell")
with vs.variable_scope(scope or "rnn") as varscope:
# Create a new scope in which the caching device is either
# determined by the parent scope, or is set to place the cached
# Variable using the same placement as for the rest of the RNN.
if context.in_graph_mode():
if varscope.caching_device is None:
varscope.set_caching_device(lambda op: op.device)
# By default, time_major==False and inputs are batch-major: shaped
# [batch, time, depth]
# For internal calculations, we transpose to [time, batch, depth]
flat_input = nest.flatten(inputs)
if not time_major:
# (B,T,D) => (T,B,D)
flat_input = [ops.convert_to_tensor(input_) for input_ in flat_input]
flat_input = tuple(_transpose_batch_time(input_) for input_ in flat_input)
parallel_iterations = parallel_iterations or 32
if sequence_length is not None:
sequence_length = math_ops.to_int32(sequence_length)
if sequence_length.get_shape().ndims not in (None, 1):
raise ValueError(
"sequence_length must be a vector of length batch_size, "
"but saw shape: %s" % sequence_length.get_shape())
sequence_length = array_ops.identity( # Just to find it in the graph.
sequence_length, name="sequence_length")
batch_size = _best_effort_input_batch_size(flat_input)
if initial_state is not None:
state = initial_state
else:
if not dtype:
raise ValueError("If there is no initial_state, you must give a dtype.")
state = cell.zero_state(batch_size, dtype)
def _assert_has_shape(x, shape):
x_shape = array_ops.shape(x)
packed_shape = array_ops.stack(shape)
return control_flow_ops.Assert(
math_ops.reduce_all(math_ops.equal(x_shape, packed_shape)),
["Expected shape for Tensor %s is " % x.name,
packed_shape, " but saw shape: ", x_shape])
if context.in_graph_mode() and sequence_length is not None:
# Perform some shape validation
with ops.control_dependencies(
[_assert_has_shape(sequence_length, [batch_size])]):
sequence_length = array_ops.identity(
sequence_length, name="CheckSeqLen")
inputs = nest.pack_sequence_as(structure=inputs, flat_sequence=flat_input)
(outputs, final_state) = _dynamic_rnn_loop(
cell,
inputs,
state,
parallel_iterations=parallel_iterations,
swap_memory=swap_memory,
sequence_length=sequence_length,
dtype=dtype)
# Outputs of _dynamic_rnn_loop are always shaped [time, batch, depth].
# If we are performing batch-major calculations, transpose output back
# to shape [batch, time, depth]
if not time_major:
# (T,B,D) => (B,T,D)
outputs = nest.map_structure(_transpose_batch_time, outputs)
return (outputs, final_state)
def _dynamic_rnn_loop(cell,
inputs,
initial_state,
parallel_iterations,
swap_memory,
sequence_length=None,
dtype=None):
"""Internal implementation of Dynamic RNN.
Args:
cell: An instance of RNNCell.
inputs: A `Tensor` of shape [time, batch_size, input_size], or a nested
tuple of such elements.
initial_state: A `Tensor` of shape `[batch_size, state_size]`, or if
`cell.state_size` is a tuple, then this should be a tuple of
tensors having shapes `[batch_size, s] for s in cell.state_size`.
parallel_iterations: Positive Python int.
swap_memory: A Python boolean
sequence_length: (optional) An `int32` `Tensor` of shape [batch_size].
dtype: (optional) Expected dtype of output. If not specified, inferred from
initial_state.
Returns:
Tuple `(final_outputs, final_state)`.
final_outputs:
A `Tensor` of shape `[time, batch_size, cell.output_size]`. If
`cell.output_size` is a (possibly nested) tuple of ints or `TensorShape`
objects, then this returns a (possibly nsted) tuple of Tensors matching
the corresponding shapes.
final_state:
A `Tensor`, or possibly nested tuple of Tensors, matching in length
and shapes to `initial_state`.
Raises:
ValueError: If the input depth cannot be inferred via shape inference
from the inputs.
"""
state = initial_state
assert isinstance(parallel_iterations, int), "parallel_iterations must be int"
state_size = cell.state_size
flat_input = nest.flatten(inputs)
flat_output_size = nest.flatten(cell.output_size)
# Construct an initial output
input_shape = array_ops.shape(flat_input[0])
time_steps = input_shape[0]
batch_size = _best_effort_input_batch_size(flat_input)
inputs_got_shape = tuple(input_.get_shape().with_rank_at_least(3)
for input_ in flat_input)
const_time_steps, const_batch_size = inputs_got_shape[0].as_list()[:2]
for shape in inputs_got_shape:
if not shape[2:].is_fully_defined():
raise ValueError(
"Input size (depth of inputs) must be accessible via shape inference,"
" but saw value None.")
got_time_steps = shape[0].value
got_batch_size = shape[1].value
if const_time_steps != got_time_steps:
raise ValueError(
"Time steps is not the same for all the elements in the input in a "
"batch.")
if const_batch_size != got_batch_size:
raise ValueError(
"Batch_size is not the same for all the elements in the input.")
# Prepare dynamic conditional copying of state & output
def _create_zero_arrays(size):
size = _concat(batch_size, size)
return array_ops.zeros(
array_ops.stack(size), _infer_state_dtype(dtype, state))
flat_zero_output = tuple(_create_zero_arrays(output)
for output in flat_output_size)
zero_output = nest.pack_sequence_as(structure=cell.output_size,
flat_sequence=flat_zero_output)
if sequence_length is not None:
min_sequence_length = math_ops.reduce_min(sequence_length)
max_sequence_length = math_ops.reduce_max(sequence_length)
time = array_ops.constant(0, dtype=dtypes.int32, name="time")
with ops.name_scope("dynamic_rnn") as scope:
base_name = scope
def _create_ta(name, dtype):
return tensor_array_ops.TensorArray(dtype=dtype,
size=time_steps,
tensor_array_name=base_name + name)
in_graph_mode = context.in_graph_mode()
if in_graph_mode:
output_ta = tuple(_create_ta("output_%d" % i,
_infer_state_dtype(dtype, state))
for i in range(len(flat_output_size)))
input_ta = tuple(_create_ta("input_%d" % i, flat_input[i].dtype)
for i in range(len(flat_input)))
input_ta = tuple(ta.unstack(input_)
for ta, input_ in zip(input_ta, flat_input))
else:
output_ta = tuple([0 for _ in range(time_steps.numpy())]
for i in range(len(flat_output_size)))
input_ta = flat_input
def _time_step(time, output_ta_t, state):
"""Take a time step of the dynamic RNN.
Args:
time: int32 scalar Tensor.
output_ta_t: List of `TensorArray`s that represent the output.
state: nested tuple of vector tensors that represent the state.
Returns:
The tuple (time + 1, output_ta_t with updated flow, new_state).
"""
if in_graph_mode:
input_t = tuple(ta.read(time) for ta in input_ta)
# Restore some shape information
for input_, shape in zip(input_t, inputs_got_shape):
input_.set_shape(shape[1:])
else:
input_t = tuple(ta[time.numpy()] for ta in input_ta)
input_t = nest.pack_sequence_as(structure=inputs, flat_sequence=input_t)
call_cell = lambda: cell(input_t, state)
if sequence_length is not None:
(output, new_state) = _rnn_step(
time=time,
sequence_length=sequence_length,
min_sequence_length=min_sequence_length,
max_sequence_length=max_sequence_length,
zero_output=zero_output,
state=state,
call_cell=call_cell,
state_size=state_size,
skip_conditionals=True)
else:
(output, new_state) = call_cell()
# Pack state if using state tuples
output = nest.flatten(output)
if in_graph_mode:
output_ta_t = tuple(
ta.write(time, out) for ta, out in zip(output_ta_t, output))
else:
for ta, out in zip(output_ta_t, output):
ta[time.numpy()] = out
return (time + 1, output_ta_t, new_state)
_, output_final_ta, final_state = control_flow_ops.while_loop(
cond=lambda time, *_: time < time_steps,
body=_time_step,
loop_vars=(time, output_ta, state),
parallel_iterations=parallel_iterations,
swap_memory=swap_memory)
# Unpack final output if not using output tuples.
if in_graph_mode:
final_outputs = tuple(ta.stack() for ta in output_final_ta)
# Restore some shape information
for output, output_size in zip(final_outputs, flat_output_size):
shape = _concat(
[const_time_steps, const_batch_size], output_size, static=True)
output.set_shape(shape)
else:
final_outputs = output_final_ta
final_outputs = nest.pack_sequence_as(
structure=cell.output_size, flat_sequence=final_outputs)
if not in_graph_mode:
final_outputs = array_ops.stack(final_outputs, axis=0)
return (final_outputs, final_state)
def raw_rnn(cell, loop_fn,
parallel_iterations=None, swap_memory=False, scope=None):
"""Creates an `RNN` specified by RNNCell `cell` and loop function `loop_fn`.
**NOTE: This method is still in testing, and the API may change.**
This function is a more primitive version of `dynamic_rnn` that provides
more direct access to the inputs each iteration. It also provides more
control over when to start and finish reading the sequence, and
what to emit for the output.
For example, it can be used to implement the dynamic decoder of a seq2seq
model.
Instead of working with `Tensor` objects, most operations work with
`TensorArray` objects directly.
The operation of `raw_rnn`, in pseudo-code, is basically the following:
```python
time = tf.constant(0, dtype=tf.int32)
(finished, next_input, initial_state, _, loop_state) = loop_fn(
time=time, cell_output=None, cell_state=None, loop_state=None)
emit_ta = TensorArray(dynamic_size=True, dtype=initial_state.dtype)
state = initial_state
while not all(finished):
(output, cell_state) = cell(next_input, state)
(next_finished, next_input, next_state, emit, loop_state) = loop_fn(
time=time + 1, cell_output=output, cell_state=cell_state,
loop_state=loop_state)
# Emit zeros and copy forward state for minibatch entries that are finished.
state = tf.where(finished, state, next_state)
emit = tf.where(finished, tf.zeros_like(emit), emit)
emit_ta = emit_ta.write(time, emit)
# If any new minibatch entries are marked as finished, mark these.
finished = tf.logical_or(finished, next_finished)
time += 1
return (emit_ta, state, loop_state)
```
with the additional properties that output and state may be (possibly nested)
tuples, as determined by `cell.output_size` and `cell.state_size`, and
as a result the final `state` and `emit_ta` may themselves be tuples.
A simple implementation of `dynamic_rnn` via `raw_rnn` looks like this:
```python
inputs = tf.placeholder(shape=(max_time, batch_size, input_depth),
dtype=tf.float32)
sequence_length = tf.placeholder(shape=(batch_size,), dtype=tf.int32)
inputs_ta = tf.TensorArray(dtype=tf.float32, size=max_time)
inputs_ta = inputs_ta.unstack(inputs)
cell = tf.contrib.rnn.LSTMCell(num_units)
def loop_fn(time, cell_output, cell_state, loop_state):
emit_output = cell_output # == None for time == 0
if cell_output is None: # time == 0
next_cell_state = cell.zero_state(batch_size, tf.float32)
else:
next_cell_state = cell_state
elements_finished = (time >= sequence_length)
finished = tf.reduce_all(elements_finished)
next_input = tf.cond(
finished,
lambda: tf.zeros([batch_size, input_depth], dtype=tf.float32),
lambda: inputs_ta.read(time))
next_loop_state = None
return (elements_finished, next_input, next_cell_state,
emit_output, next_loop_state)
outputs_ta, final_state, _ = raw_rnn(cell, loop_fn)
outputs = outputs_ta.stack()
```
Args:
cell: An instance of RNNCell.
loop_fn: A callable that takes inputs
`(time, cell_output, cell_state, loop_state)`
and returns the tuple
`(finished, next_input, next_cell_state, emit_output, next_loop_state)`.
Here `time` is an int32 scalar `Tensor`, `cell_output` is a
`Tensor` or (possibly nested) tuple of tensors as determined by
`cell.output_size`, and `cell_state` is a `Tensor`
or (possibly nested) tuple of tensors, as determined by the `loop_fn`
on its first call (and should match `cell.state_size`).
The outputs are: `finished`, a boolean `Tensor` of
shape `[batch_size]`, `next_input`: the next input to feed to `cell`,
`next_cell_state`: the next state to feed to `cell`,
and `emit_output`: the output to store for this iteration.
Note that `emit_output` should be a `Tensor` or (possibly nested)
tuple of tensors with shapes and structure matching `cell.output_size`
and `cell_output` above. The parameter `cell_state` and output
`next_cell_state` may be either a single or (possibly nested) tuple
of tensors. The parameter `loop_state` and
output `next_loop_state` may be either a single or (possibly nested) tuple
of `Tensor` and `TensorArray` objects. This last parameter
may be ignored by `loop_fn` and the return value may be `None`. If it
is not `None`, then the `loop_state` will be propagated through the RNN
loop, for use purely by `loop_fn` to keep track of its own state.
The `next_loop_state` parameter returned may be `None`.
The first call to `loop_fn` will be `time = 0`, `cell_output = None`,
`cell_state = None`, and `loop_state = None`. For this call:
The `next_cell_state` value should be the value with which to initialize
the cell's state. It may be a final state from a previous RNN or it
may be the output of `cell.zero_state()`. It should be a
(possibly nested) tuple structure of tensors.
If `cell.state_size` is an integer, this must be
a `Tensor` of appropriate type and shape `[batch_size, cell.state_size]`.
If `cell.state_size` is a `TensorShape`, this must be a `Tensor` of
appropriate type and shape `[batch_size] + cell.state_size`.
If `cell.state_size` is a (possibly nested) tuple of ints or
`TensorShape`, this will be a tuple having the corresponding shapes.
The `emit_output` value may be either `None` or a (possibly nested)
tuple structure of tensors, e.g.,
`(tf.zeros(shape_0, dtype=dtype_0), tf.zeros(shape_1, dtype=dtype_1))`.
If this first `emit_output` return value is `None`,
then the `emit_ta` result of `raw_rnn` will have the same structure and
dtypes as `cell.output_size`. Otherwise `emit_ta` will have the same
structure, shapes (prepended with a `batch_size` dimension), and dtypes
as `emit_output`. The actual values returned for `emit_output` at this
initializing call are ignored. Note, this emit structure must be
consistent across all time steps.
parallel_iterations: (Default: 32). The number of iterations to run in
parallel. Those operations which do not have any temporal dependency
and can be run in parallel, will be. This parameter trades off
time for space. Values >> 1 use more memory but take less time,
while smaller values use less memory but computations take longer.
swap_memory: Transparently swap the tensors produced in forward inference
but needed for back prop from GPU to CPU. This allows training RNNs
which would typically not fit on a single GPU, with very minimal (or no)
performance penalty.
scope: VariableScope for the created subgraph; defaults to "rnn".
Returns:
A tuple `(emit_ta, final_state, final_loop_state)` where:
`emit_ta`: The RNN output `TensorArray`.
If `loop_fn` returns a (possibly nested) set of Tensors for
`emit_output` during initialization, (inputs `time = 0`,
`cell_output = None`, and `loop_state = None`), then `emit_ta` will
have the same structure, dtypes, and shapes as `emit_output` instead.
If `loop_fn` returns `emit_output = None` during this call,
the structure of `cell.output_size` is used:
If `cell.output_size` is a (possibly nested) tuple of integers
or `TensorShape` objects, then `emit_ta` will be a tuple having the
same structure as `cell.output_size`, containing TensorArrays whose
elements' shapes correspond to the shape data in `cell.output_size`.
`final_state`: The final cell state. If `cell.state_size` is an int, this
will be shaped `[batch_size, cell.state_size]`. If it is a
`TensorShape`, this will be shaped `[batch_size] + cell.state_size`.
If it is a (possibly nested) tuple of ints or `TensorShape`, this will
be a tuple having the corresponding shapes.
`final_loop_state`: The final loop state as returned by `loop_fn`.
Raises:
TypeError: If `cell` is not an instance of RNNCell, or `loop_fn` is not
a `callable`.
"""
if not _like_rnncell(cell):
raise TypeError("cell must be an instance of RNNCell")
if not callable(loop_fn):
raise TypeError("loop_fn must be a callable")
parallel_iterations = parallel_iterations or 32
# Create a new scope in which the caching device is either
# determined by the parent scope, or is set to place the cached
# Variable using the same placement as for the rest of the RNN.
with vs.variable_scope(scope or "rnn") as varscope:
if context.in_graph_mode():
if varscope.caching_device is None:
varscope.set_caching_device(lambda op: op.device)
time = constant_op.constant(0, dtype=dtypes.int32)
(elements_finished, next_input, initial_state, emit_structure,
init_loop_state) = loop_fn(
time, None, None, None) # time, cell_output, cell_state, loop_state
flat_input = nest.flatten(next_input)
# Need a surrogate loop state for the while_loop if none is available.
loop_state = (init_loop_state if init_loop_state is not None
else constant_op.constant(0, dtype=dtypes.int32))
input_shape = [input_.get_shape() for input_ in flat_input]
static_batch_size = input_shape[0][0]
for input_shape_i in input_shape:
# Static verification that batch sizes all match
static_batch_size.merge_with(input_shape_i[0])
batch_size = static_batch_size.value
if batch_size is None:
batch_size = array_ops.shape(flat_input[0])[0]
nest.assert_same_structure(initial_state, cell.state_size)
state = initial_state
flat_state = nest.flatten(state)
flat_state = [ops.convert_to_tensor(s) for s in flat_state]
state = nest.pack_sequence_as(structure=state,
flat_sequence=flat_state)
if emit_structure is not None:
flat_emit_structure = nest.flatten(emit_structure)
flat_emit_size = [emit.shape if emit.shape.is_fully_defined() else
array_ops.shape(emit) for emit in flat_emit_structure]
flat_emit_dtypes = [emit.dtype for emit in flat_emit_structure]
else:
emit_structure = cell.output_size
flat_emit_size = nest.flatten(emit_structure)
flat_emit_dtypes = [flat_state[0].dtype] * len(flat_emit_size)
flat_emit_ta = [
tensor_array_ops.TensorArray(
dtype=dtype_i, dynamic_size=True, size=0, name="rnn_output_%d" % i)
for i, dtype_i in enumerate(flat_emit_dtypes)]
emit_ta = nest.pack_sequence_as(structure=emit_structure,
flat_sequence=flat_emit_ta)
flat_zero_emit = [
array_ops.zeros(_concat(batch_size, size_i), dtype_i)
for size_i, dtype_i in zip(flat_emit_size, flat_emit_dtypes)]
zero_emit = nest.pack_sequence_as(structure=emit_structure,
flat_sequence=flat_zero_emit)
def condition(unused_time, elements_finished, *_):
return math_ops.logical_not(math_ops.reduce_all(elements_finished))
def body(time, elements_finished, current_input,
emit_ta, state, loop_state):
"""Internal while loop body for raw_rnn.
Args:
time: time scalar.
elements_finished: batch-size vector.
current_input: possibly nested tuple of input tensors.
emit_ta: possibly nested tuple of output TensorArrays.
state: possibly nested tuple of state tensors.
loop_state: possibly nested tuple of loop state tensors.
Returns:
Tuple having the same size as Args but with updated values.
"""
(next_output, cell_state) = cell(current_input, state)
nest.assert_same_structure(state, cell_state)
nest.assert_same_structure(cell.output_size, next_output)
next_time = time + 1
(next_finished, next_input, next_state, emit_output,
next_loop_state) = loop_fn(
next_time, next_output, cell_state, loop_state)
nest.assert_same_structure(state, next_state)
nest.assert_same_structure(current_input, next_input)
nest.assert_same_structure(emit_ta, emit_output)
# If loop_fn returns None for next_loop_state, just reuse the
# previous one.
loop_state = loop_state if next_loop_state is None else next_loop_state
def _copy_some_through(current, candidate):
"""Copy some tensors through via array_ops.where."""
def copy_fn(cur_i, cand_i):
with ops.colocate_with(cand_i):
return array_ops.where(elements_finished, cur_i, cand_i)
return nest.map_structure(copy_fn, current, candidate)
emit_output = _copy_some_through(zero_emit, emit_output)
next_state = _copy_some_through(state, next_state)
emit_ta = nest.map_structure(
lambda ta, emit: ta.write(time, emit), emit_ta, emit_output)
elements_finished = math_ops.logical_or(elements_finished, next_finished)
return (next_time, elements_finished, next_input,
emit_ta, next_state, loop_state)
returned = control_flow_ops.while_loop(
condition, body, loop_vars=[
time, elements_finished, next_input,
emit_ta, state, loop_state],
parallel_iterations=parallel_iterations,
swap_memory=swap_memory)
(emit_ta, final_state, final_loop_state) = returned[-3:]
if init_loop_state is None:
final_loop_state = None
return (emit_ta, final_state, final_loop_state)
def static_rnn(cell,
inputs,
initial_state=None,
dtype=None,
sequence_length=None,
scope=None):
"""Creates a recurrent neural network specified by RNNCell `cell`.
The simplest form of RNN network generated is:
```python
state = cell.zero_state(...)
outputs = []
for input_ in inputs:
output, state = cell(input_, state)
outputs.append(output)
return (outputs, state)
```
However, a few other options are available:
An initial state can be provided.
If the sequence_length vector is provided, dynamic calculation is performed.
This method of calculation does not compute the RNN steps past the maximum
sequence length of the minibatch (thus saving computational time),
and properly propagates the state at an example's sequence length
to the final state output.
The dynamic calculation performed is, at time `t` for batch row `b`,
```python
(output, state)(b, t) =
(t >= sequence_length(b))
? (zeros(cell.output_size), states(b, sequence_length(b) - 1))
: cell(input(b, t), state(b, t - 1))
```
Args:
cell: An instance of RNNCell.
inputs: A length T list of inputs, each a `Tensor` of shape
`[batch_size, input_size]`, or a nested tuple of such elements.
initial_state: (optional) An initial state for the RNN.
If `cell.state_size` is an integer, this must be
a `Tensor` of appropriate type and shape `[batch_size, cell.state_size]`.
If `cell.state_size` is a tuple, this should be a tuple of
tensors having shapes `[batch_size, s] for s in cell.state_size`.
dtype: (optional) The data type for the initial state and expected output.
Required if initial_state is not provided or RNN state has a heterogeneous
dtype.
sequence_length: Specifies the length of each sequence in inputs.
An int32 or int64 vector (tensor) size `[batch_size]`, values in `[0, T)`.
scope: VariableScope for the created subgraph; defaults to "rnn".
Returns:
A pair (outputs, state) where:
- outputs is a length T list of outputs (one for each input), or a nested
tuple of such elements.
- state is the final state
Raises:
TypeError: If `cell` is not an instance of RNNCell.
ValueError: If `inputs` is `None` or an empty list, or if the input depth
(column size) cannot be inferred from inputs via shape inference.
"""
if not _like_rnncell(cell):
raise TypeError("cell must be an instance of RNNCell")
if not nest.is_sequence(inputs):
raise TypeError("inputs must be a sequence")
if not inputs:
raise ValueError("inputs must not be empty")
outputs = []
# Create a new scope in which the caching device is either
# determined by the parent scope, or is set to place the cached
# Variable using the same placement as for the rest of the RNN.
with vs.variable_scope(scope or "rnn") as varscope:
if context.in_graph_mode():
if varscope.caching_device is None:
varscope.set_caching_device(lambda op: op.device)
# Obtain the first sequence of the input
first_input = inputs
while nest.is_sequence(first_input):
first_input = first_input[0]
# Temporarily avoid EmbeddingWrapper and seq2seq badness
# TODO(lukaszkaiser): remove EmbeddingWrapper
if first_input.get_shape().ndims != 1:
input_shape = first_input.get_shape().with_rank_at_least(2)
fixed_batch_size = input_shape[0]
flat_inputs = nest.flatten(inputs)
for flat_input in flat_inputs:
input_shape = flat_input.get_shape().with_rank_at_least(2)
batch_size, input_size = input_shape[0], input_shape[1:]
fixed_batch_size.merge_with(batch_size)
for i, size in enumerate(input_size):
if size.value is None:
raise ValueError(
"Input size (dimension %d of inputs) must be accessible via "
"shape inference, but saw value None." % i)
else:
fixed_batch_size = first_input.get_shape().with_rank_at_least(1)[0]
if fixed_batch_size.value:
batch_size = fixed_batch_size.value
else:
batch_size = array_ops.shape(first_input)[0]
if initial_state is not None:
state = initial_state
else:
if not dtype:
raise ValueError("If no initial_state is provided, "
"dtype must be specified")
state = cell.zero_state(batch_size, dtype)
if sequence_length is not None: # Prepare variables
sequence_length = ops.convert_to_tensor(
sequence_length, name="sequence_length")
if sequence_length.get_shape().ndims not in (None, 1):
raise ValueError(
"sequence_length must be a vector of length batch_size")
def _create_zero_output(output_size):
# convert int to TensorShape if necessary
size = _concat(batch_size, output_size)
output = array_ops.zeros(
array_ops.stack(size), _infer_state_dtype(dtype, state))
shape = _concat(fixed_batch_size.value, output_size, static=True)
output.set_shape(tensor_shape.TensorShape(shape))
return output
output_size = cell.output_size
flat_output_size = nest.flatten(output_size)
flat_zero_output = tuple(
_create_zero_output(size) for size in flat_output_size)
zero_output = nest.pack_sequence_as(
structure=output_size, flat_sequence=flat_zero_output)
sequence_length = math_ops.to_int32(sequence_length)
min_sequence_length = math_ops.reduce_min(sequence_length)
max_sequence_length = math_ops.reduce_max(sequence_length)
for time, input_ in enumerate(inputs):
if time > 0:
varscope.reuse_variables()
# pylint: disable=cell-var-from-loop
call_cell = lambda: cell(input_, state)
# pylint: enable=cell-var-from-loop
if sequence_length is not None:
(output, state) = _rnn_step(
time=time,
sequence_length=sequence_length,
min_sequence_length=min_sequence_length,
max_sequence_length=max_sequence_length,
zero_output=zero_output,
state=state,
call_cell=call_cell,
state_size=cell.state_size)
else:
(output, state) = call_cell()
outputs.append(output)
return (outputs, state)
def static_state_saving_rnn(cell,
inputs,
state_saver,
state_name,
sequence_length=None,
scope=None):
"""RNN that accepts a state saver for time-truncated RNN calculation.
Args:
cell: An instance of `RNNCell`.
inputs: A length T list of inputs, each a `Tensor` of shape
`[batch_size, input_size]`.
state_saver: A state saver object with methods `state` and `save_state`.
state_name: Python string or tuple of strings. The name to use with the
state_saver. If the cell returns tuples of states (i.e.,
`cell.state_size` is a tuple) then `state_name` should be a tuple of
strings having the same length as `cell.state_size`. Otherwise it should
be a single string.
sequence_length: (optional) An int32/int64 vector size [batch_size].
See the documentation for rnn() for more details about sequence_length.
scope: VariableScope for the created subgraph; defaults to "rnn".
Returns:
A pair (outputs, state) where:
outputs is a length T list of outputs (one for each input)
states is the final state
Raises:
TypeError: If `cell` is not an instance of RNNCell.
ValueError: If `inputs` is `None` or an empty list, or if the arity and
type of `state_name` does not match that of `cell.state_size`.
"""
state_size = cell.state_size
state_is_tuple = nest.is_sequence(state_size)
state_name_tuple = nest.is_sequence(state_name)
if state_is_tuple != state_name_tuple:
raise ValueError("state_name should be the same type as cell.state_size. "
"state_name: %s, cell.state_size: %s" % (str(state_name),
str(state_size)))
if state_is_tuple:
state_name_flat = nest.flatten(state_name)
state_size_flat = nest.flatten(state_size)
if len(state_name_flat) != len(state_size_flat):
raise ValueError("#elems(state_name) != #elems(state_size): %d vs. %d" %
(len(state_name_flat), len(state_size_flat)))
initial_state = nest.pack_sequence_as(
structure=state_size,
flat_sequence=[state_saver.state(s) for s in state_name_flat])
else:
initial_state = state_saver.state(state_name)
(outputs, state) = static_rnn(
cell,
inputs,
initial_state=initial_state,
sequence_length=sequence_length,
scope=scope)
if state_is_tuple:
flat_state = nest.flatten(state)
state_name = nest.flatten(state_name)
save_state = [
state_saver.save_state(name, substate)
for name, substate in zip(state_name, flat_state)
]
else:
save_state = [state_saver.save_state(state_name, state)]
with ops.control_dependencies(save_state):
last_output = outputs[-1]
flat_last_output = nest.flatten(last_output)
flat_last_output = [
array_ops.identity(output) for output in flat_last_output
]
outputs[-1] = nest.pack_sequence_as(
structure=last_output, flat_sequence=flat_last_output)
return (outputs, state)
def static_bidirectional_rnn(cell_fw,
cell_bw,
inputs,
initial_state_fw=None,
initial_state_bw=None,
dtype=None,
sequence_length=None,
scope=None):
"""Creates a bidirectional recurrent neural network.
Similar to the unidirectional case above (rnn) but takes input and builds
independent forward and backward RNNs with the final forward and backward
outputs depth-concatenated, such that the output will have the format
[time][batch][cell_fw.output_size + cell_bw.output_size]. The input_size of
forward and backward cell must match. The initial state for both directions
is zero by default (but can be set optionally) and no intermediate states are
ever returned -- the network is fully unrolled for the given (passed in)
length(s) of the sequence(s) or completely unrolled if length(s) is not given.
Args:
cell_fw: An instance of RNNCell, to be used for forward direction.
cell_bw: An instance of RNNCell, to be used for backward direction.
inputs: A length T list of inputs, each a tensor of shape
[batch_size, input_size], or a nested tuple of such elements.
initial_state_fw: (optional) An initial state for the forward RNN.
This must be a tensor of appropriate type and shape
`[batch_size, cell_fw.state_size]`.
If `cell_fw.state_size` is a tuple, this should be a tuple of
tensors having shapes `[batch_size, s] for s in cell_fw.state_size`.
initial_state_bw: (optional) Same as for `initial_state_fw`, but using
the corresponding properties of `cell_bw`.
dtype: (optional) The data type for the initial state. Required if
either of the initial states are not provided.
sequence_length: (optional) An int32/int64 vector, size `[batch_size]`,
containing the actual lengths for each of the sequences.
scope: VariableScope for the created subgraph; defaults to
"bidirectional_rnn"
Returns:
A tuple (outputs, output_state_fw, output_state_bw) where:
outputs is a length `T` list of outputs (one for each input), which
are depth-concatenated forward and backward outputs.
output_state_fw is the final state of the forward rnn.
output_state_bw is the final state of the backward rnn.
Raises:
TypeError: If `cell_fw` or `cell_bw` is not an instance of `RNNCell`.
ValueError: If inputs is None or an empty list.
"""
if not _like_rnncell(cell_fw):
raise TypeError("cell_fw must be an instance of RNNCell")
if not _like_rnncell(cell_bw):
raise TypeError("cell_bw must be an instance of RNNCell")
if not nest.is_sequence(inputs):
raise TypeError("inputs must be a sequence")
if not inputs:
raise ValueError("inputs must not be empty")
with vs.variable_scope(scope or "bidirectional_rnn"):
# Forward direction
with vs.variable_scope("fw") as fw_scope:
output_fw, output_state_fw = static_rnn(
cell_fw,
inputs,
initial_state_fw,
dtype,
sequence_length,
scope=fw_scope)
# Backward direction
with vs.variable_scope("bw") as bw_scope:
reversed_inputs = _reverse_seq(inputs, sequence_length)
tmp, output_state_bw = static_rnn(
cell_bw,
reversed_inputs,
initial_state_bw,
dtype,
sequence_length,
scope=bw_scope)
output_bw = _reverse_seq(tmp, sequence_length)
# Concat each of the forward/backward outputs
flat_output_fw = nest.flatten(output_fw)
flat_output_bw = nest.flatten(output_bw)
flat_outputs = tuple(
array_ops.concat([fw, bw], 1)
for fw, bw in zip(flat_output_fw, flat_output_bw))
outputs = nest.pack_sequence_as(
structure=output_fw, flat_sequence=flat_outputs)
return (outputs, output_state_fw, output_state_bw)
| 41.258396 | 80 | 0.693518 |
acec6cb89af4fea4795c1d3e93b0e0e0786bf7b4 | 1,162 | py | Python | src/demo_quipuswap/handlers/on_fa2_transfer.py | arrijabba/dipdup-py | fa90bfd889c473966e0d5aed98cec90a575fcb90 | [
"MIT"
] | 39 | 2021-04-13T10:53:27.000Z | 2022-02-11T00:53:44.000Z | src/demo_quipuswap/handlers/on_fa2_transfer.py | arrijabba/dipdup-py | fa90bfd889c473966e0d5aed98cec90a575fcb90 | [
"MIT"
] | 113 | 2021-06-01T18:16:42.000Z | 2022-03-28T06:12:58.000Z | src/demo_quipuswap/handlers/on_fa2_transfer.py | arrijabba/dipdup-py | fa90bfd889c473966e0d5aed98cec90a575fcb90 | [
"MIT"
] | 16 | 2021-05-26T07:04:40.000Z | 2022-03-29T06:50:25.000Z | import demo_quipuswap.models as models
from demo_quipuswap.types.quipu_fa2.parameter.transfer import TransferParameter
from demo_quipuswap.types.quipu_fa2.storage import QuipuFa2Storage
from dipdup.context import HandlerContext
from dipdup.models import Transaction
async def on_fa2_transfer(
ctx: HandlerContext,
transfer: Transaction[TransferParameter, QuipuFa2Storage],
) -> None:
transfer_parameter = transfer.parameter.__root__[0]
symbol = ctx.template_values['symbol']
from_address = transfer_parameter.from_
from_position, _ = await models.Position.get_or_create(trader=from_address, symbol=symbol)
for transfer_tx in transfer_parameter.txs:
to_address = transfer_tx.to_
value = int(transfer_tx.amount)
from_position.shares_qty -= value # type: ignore
assert from_position.shares_qty >= 0, transfer.data.hash
to_position, _ = await models.Position.get_or_create(trader=to_address, symbol=symbol)
to_position.shares_qty += value # type: ignore
assert to_position.shares_qty >= 0, transfer.data.hash
await to_position.save()
await from_position.save()
| 37.483871 | 94 | 0.757315 |
acec6cf4e403a65f09a4d5e336fcb500110eb644 | 3,399 | py | Python | untitled7/dysms_python/mns_python_sdk/mns/mns_exception.py | pop993012/111122 | cee79d5e6eb5b1c9714e3f712503cce9fccfb8c2 | [
"Apache-2.0"
] | 17 | 2017-07-24T08:49:13.000Z | 2020-08-05T13:23:41.000Z | pjbbs/dysms_python/mns_python_sdk/mns/mns_exception.py | li765416060/li | 3a158218a2a0892577bde29f75f70cce6af11be5 | [
"Apache-2.0"
] | 6 | 2021-03-18T21:23:50.000Z | 2022-03-11T23:32:30.000Z | packages/dysms_python/mns_python_sdk/mns/mns_exception.py | hifeiwenchao/sharezone | 0a72cef8d9c1b6fa8e007c2df55d32fbdb43fa23 | [
"Apache-2.0"
] | 22 | 2019-07-29T03:04:52.000Z | 2021-12-08T05:38:48.000Z | #coding=utf-8
# Copyright (C) 2015, Alibaba Cloud Computing
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class MNSExceptionBase(Exception):
"""
@type type: string
@param type: 错误类型
@type message: string
@param message: 错误描述
@type req_id: string
@param req_id: 请求的request_id
"""
def __init__(self, type, message, req_id = None):
self.type = type
self.message = message
self.req_id = req_id
def get_info(self):
if self.req_id is not None:
return "(\"%s\" \"%s\") RequestID:%s\n" % (self.type, self.message, self.req_id)
else:
return "(\"%s\" \"%s\")\n" % (self.type, self.message)
def __str__(self):
return "MNSExceptionBase %s" % (self.get_info())
class MNSClientException(MNSExceptionBase):
def __init__(self, type, message, req_id = None):
MNSExceptionBase.__init__(self, type, message, req_id)
def __str__(self):
return "MNSClientException %s" % (self.get_info())
class MNSServerException(MNSExceptionBase):
""" mns处理异常
@note: 根据type进行分类处理,常见错误类型:
: InvalidArgument 参数不合法
: AccessDenied 无权对该资源进行当前操作
: QueueNotExist 队列不存在
: MessageNotExist 队列中没有消息
: 更多错误类型请移步阿里云消息和通知服务官网进行了解;
"""
def __init__(self, type, message, request_id, host_id, sub_errors=None):
MNSExceptionBase.__init__(self, type, message, request_id)
self.request_id = request_id
self.host_id = host_id
self.sub_errors = sub_errors
def __str__(self):
return "MNSServerException %s" % (self.get_info())
class MNSClientNetworkException(MNSClientException):
""" 网络异常
@note: 检查endpoint是否正确、本机网络是否正常等;
"""
def __init__(self, type, message, req_id=None):
MNSClientException.__init__(self, type, message, req_id)
def get_info(self):
return "(\"%s\", \"%s\")\n" % (self.type, self.message)
def __str__(self):
return "MNSClientNetworkException %s" % (self.get_info())
class MNSClientParameterException(MNSClientException):
""" 参数格式错误
@note: 请根据提示修改对应参数;
"""
def __init__(self, type, message, req_id=None):
MNSClientException.__init__(self, type, message, req_id)
def __str__(self):
return "MNSClientParameterException %s" % (self.get_info())
| 39.988235 | 461 | 0.675493 |
acec6d0c9999d7ec92b5c6807d410dadd3e77ae6 | 14,707 | py | Python | tensorflow/python/distribute/multi_process_runner_test.py | pnfisher/tensorflow | ceb12158ee471d95a2085dfdd2c0dc0bc33a8346 | [
"Apache-2.0"
] | 2 | 2020-11-10T15:43:40.000Z | 2021-05-26T05:19:05.000Z | tensorflow/python/distribute/multi_process_runner_test.py | pnfisher/tensorflow | ceb12158ee471d95a2085dfdd2c0dc0bc33a8346 | [
"Apache-2.0"
] | 1 | 2020-06-29T00:16:45.000Z | 2020-06-29T00:25:26.000Z | tensorflow/python/distribute/multi_process_runner_test.py | pnfisher/tensorflow | ceb12158ee471d95a2085dfdd2c0dc0bc33a8346 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for `multi_process_runner`."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import ctypes
import json
import os
import sys
import threading
import time
import unittest
from absl import logging
from tensorflow.python.distribute import multi_process_runner
from tensorflow.python.distribute import multi_worker_test_base
from tensorflow.python.eager import test
def proc_func_that_adds_task_type_in_return_data():
return multi_worker_test_base.get_task_type()
def proc_func_that_errors():
raise ValueError('This is an error.')
def proc_func_that_does_nothing():
pass
def proc_func_that_adds_simple_return_data():
return 'dummy_data'
def proc_func_that_returns_args_and_kwargs(*args, **kwargs):
return list(args) + list(kwargs.items())
def proc_func_with_barrier():
return multi_process_runner.barrier()
def proc_func_that_returns_pid():
return os.getpid()
V = None
def proc_func_that_sets_global(val):
global V
old_val = V
V = val
return old_val
class MultiProcessRunnerTest(test.TestCase):
def _worker_idx(self):
config_task = json.loads(os.environ['TF_CONFIG'])['task']
return config_task['index']
def test_multi_process_runner(self):
mpr_result = multi_process_runner.run(
proc_func_that_adds_task_type_in_return_data,
multi_worker_test_base.create_cluster_spec(
num_workers=2, num_ps=3, has_eval=1))
job_count_dict = {'worker': 2, 'ps': 3, 'evaluator': 1}
for data in mpr_result.return_value:
job_count_dict[data] -= 1
self.assertEqual(job_count_dict['worker'], 0)
self.assertEqual(job_count_dict['ps'], 0)
self.assertEqual(job_count_dict['evaluator'], 0)
def test_multi_process_runner_error_propagates_from_subprocesses(self):
runner = multi_process_runner.MultiProcessRunner(
proc_func_that_errors,
multi_worker_test_base.create_cluster_spec(num_workers=1, num_ps=1),
max_run_time=20)
runner.start()
with self.assertRaisesRegexp(ValueError, 'This is an error.'):
runner.join()
def test_multi_process_runner_queue_emptied_between_runs(self):
cluster_spec = multi_worker_test_base.create_cluster_spec(num_workers=2)
return_value = multi_process_runner.run(
proc_func_that_adds_simple_return_data, cluster_spec).return_value
self.assertTrue(return_value)
self.assertEqual(return_value[0], 'dummy_data')
self.assertEqual(return_value[1], 'dummy_data')
return_value = multi_process_runner.run(proc_func_that_does_nothing,
cluster_spec).return_value
self.assertFalse(return_value)
def test_multi_process_runner_args_passed_correctly(self):
return_value = multi_process_runner.run(
proc_func_that_returns_args_and_kwargs,
multi_worker_test_base.create_cluster_spec(num_workers=1),
args=('a', 'b'),
kwargs={
'c_k': 'c_v'
}).return_value
self.assertEqual(return_value[0][0], 'a')
self.assertEqual(return_value[0][1], 'b')
self.assertEqual(return_value[0][2], ('c_k', 'c_v'))
def test_stdout_captured(self):
def simple_print_func():
print('This is something printed.', flush=True)
return 'This is returned data.'
mpr_result = multi_process_runner.run(
simple_print_func,
multi_worker_test_base.create_cluster_spec(num_workers=2),
list_stdout=True)
std_stream_results = mpr_result.stdout
return_value = mpr_result.return_value
self.assertIn('[worker-0]: This is something printed.\n',
std_stream_results)
self.assertIn('[worker-1]: This is something printed.\n',
std_stream_results)
self.assertIn('This is returned data.', return_value)
def test_termination(self):
def proc_func():
for i in range(0, 10):
print(
'index {}, iteration {}'.format(self._worker_idx(), i), flush=True)
time.sleep(5)
mpr = multi_process_runner.MultiProcessRunner(
proc_func,
multi_worker_test_base.create_cluster_spec(num_workers=2),
list_stdout=True)
mpr.start()
time.sleep(5)
mpr.terminate('worker', 0)
std_stream_results = mpr.join().stdout
# Worker 0 is terminated in the middle, so it should not have iteration 9
# printed.
self.assertIn('[worker-0]: index 0, iteration 0\n', std_stream_results)
self.assertNotIn('[worker-0]: index 0, iteration 9\n',
std_stream_results)
self.assertIn('[worker-1]: index 1, iteration 0\n', std_stream_results)
self.assertIn('[worker-1]: index 1, iteration 9\n', std_stream_results)
def test_termination_and_start_single_process(self):
def proc_func():
for i in range(0, 10):
print(
'index {}, iteration {}'.format(self._worker_idx(), i), flush=True)
time.sleep(1)
mpr = multi_process_runner.MultiProcessRunner(
proc_func,
multi_worker_test_base.create_cluster_spec(num_workers=2),
list_stdout=True)
mpr.start()
time.sleep(3)
mpr.terminate('worker', 0)
mpr.start_single_process('worker', 0)
std_stream_results = mpr.join().stdout
# Worker 0 is terminated in the middle, but a new worker 0 is added, so it
# should still have iteration 9 printed. Moreover, iteration 0 of worker 0
# should happen twice.
self.assertLen(
[s for s in std_stream_results if 'index 0, iteration 0' in s], 2)
self.assertIn('[worker-0]: index 0, iteration 9\n', std_stream_results)
self.assertIn('[worker-1]: index 1, iteration 0\n', std_stream_results)
self.assertIn('[worker-1]: index 1, iteration 9\n', std_stream_results)
def test_streaming(self):
def proc_func():
for i in range(5):
logging.info('(logging) %s-%d, i: %d',
multi_worker_test_base.get_task_type(), self._worker_idx(),
i)
print(
'(print) {}-{}, i: {}'.format(
multi_worker_test_base.get_task_type(), self._worker_idx(), i),
flush=True)
time.sleep(1)
mpr = multi_process_runner.MultiProcessRunner(
proc_func,
multi_worker_test_base.create_cluster_spec(
has_chief=True, num_workers=2, num_ps=2, has_eval=True),
list_stdout=True)
mpr._dependence_on_chief = False
mpr.start()
mpr.start_single_process('worker', 2)
mpr.start_single_process('ps', 2)
mpr_result = mpr.join()
list_to_assert = mpr_result.stdout
for job in ['chief', 'evaluator']:
for iteration in range(5):
self.assertTrue(
any('(logging) {}-0, i: {}'.format(job, iteration) in line
for line in list_to_assert))
self.assertTrue(
any('(print) {}-0, i: {}'.format(job, iteration) in line
for line in list_to_assert))
for job in ['worker', 'ps']:
for iteration in range(5):
for task in range(3):
self.assertTrue(
any('(logging) {}-{}, i: {}'.format(job, task, iteration) in line
for line in list_to_assert))
self.assertTrue(
any('(print) {}-{}, i: {}'.format(job, task, iteration) in line
for line in list_to_assert))
task = 3
self.assertFalse(
any('(logging) {}-{}, i: {}'.format(job, task, iteration) in line
for line in list_to_assert))
self.assertFalse(
any('(print) {}-{}, i: {}'.format(job, task, iteration) in line
for line in list_to_assert))
def test_start_in_process_as(self):
def proc_func():
for i in range(5):
logging.info('%s-%d, i: %d', multi_worker_test_base.get_task_type(),
self._worker_idx(), i)
time.sleep(1)
mpr = multi_process_runner.MultiProcessRunner(
proc_func,
multi_worker_test_base.create_cluster_spec(
has_chief=True, num_workers=1),
list_stdout=True)
def eval_func():
time.sleep(1)
mpr.start_single_process(task_type='evaluator', task_id=0)
eval_thread = threading.Thread(target=eval_func)
eval_thread.start()
mpr.start_in_process_as(as_task_type='chief', as_task_id=0)
eval_thread.join()
list_to_assert = mpr.join().stdout
for job in ['worker', 'evaluator']:
for iteration in range(5):
self.assertTrue(
any('{}-0, i: {}'.format(job, iteration) in line
for line in list_to_assert))
def test_terminate_all_does_not_ignore_error(self):
mpr = multi_process_runner.MultiProcessRunner(
proc_func_that_errors,
multi_worker_test_base.create_cluster_spec(num_workers=2),
list_stdout=True)
mpr.start()
time.sleep(60)
mpr.terminate_all()
with self.assertRaisesRegexp(ValueError, 'This is an error.'):
mpr.join()
def test_barrier(self):
multi_process_runner.run(
proc_func_with_barrier,
cluster_spec=multi_worker_test_base.create_cluster_spec(
has_chief=True, num_workers=1),
)
def test_barrier_called_in_main_process(self):
with self.assertRaises(ValueError):
multi_process_runner.barrier()
def test_stdout_available_when_timeout(self):
def proc_func():
logging.info('something printed')
time.sleep(10000) # Intentionally make the test timeout.
with self.assertRaises(multi_process_runner.SubprocessTimeoutError) as cm:
mpr = multi_process_runner.MultiProcessRunner(
proc_func,
multi_worker_test_base.create_cluster_spec(num_workers=1),
list_stdout=True)
mpr.start()
mpr.join(timeout=60)
mpr.terminate_all()
list_to_assert = cm.exception.mpr_result.stdout
self.assertTrue(
any('something printed' in line for line in list_to_assert))
def test_seg_fault_raises_error(self):
def proc_func_expected_to_seg_fault():
ctypes.string_at(0) # Intentionally made seg fault.
with self.assertRaises(
multi_process_runner.UnexpectedSubprocessExitError) as cm:
multi_process_runner.run(
proc_func_expected_to_seg_fault,
multi_worker_test_base.create_cluster_spec(num_workers=1),
list_stdout=True)
self.assertIn('Missing status(es) from 1 subprocess(es).',
str(cm.exception))
list_to_assert = cm.exception.mpr_result.stdout
self.assertTrue(any('SIGSEGV' in line for line in list_to_assert))
def test_seg_fault_in_chief_raises_error(self):
def proc_func_expected_to_seg_fault():
if multi_worker_test_base.get_task_type() == 'worker':
time.sleep(10000)
ctypes.string_at(0) # Intentionally made seg fault.
with self.assertRaises(
multi_process_runner.UnexpectedSubprocessExitError) as cm:
multi_process_runner.run(
proc_func_expected_to_seg_fault,
multi_worker_test_base.create_cluster_spec(
has_chief=True, num_workers=1),
list_stdout=True)
self.assertIn('Subprocess chief-0 exited with exit code',
str(cm.exception))
list_to_assert = cm.exception.mpr_result.stdout
self.assertTrue(any('SIGSEGV' in line for line in list_to_assert))
def test_non_zero_exit_code_raises_error(self):
def proc_func_expected_to_exit_with_1():
sys.exit(1)
with self.assertRaises(
multi_process_runner.UnexpectedSubprocessExitError) as cm:
multi_process_runner.run(
proc_func_expected_to_exit_with_1,
multi_worker_test_base.create_cluster_spec(num_workers=1))
self.assertIn('Missing status(es) from 1 subprocess(es).',
str(cm.exception))
class MultiProcessPoolRunnerTest(test.TestCase):
def test_same_process_across_runs(self):
cluster_spec = multi_worker_test_base.create_cluster_spec(num_workers=2)
runner = multi_process_runner.MultiProcessPoolRunner(cluster_spec)
pid = runner.run(proc_func_that_returns_pid)
for _ in range(3):
self.assertAllEqual(runner.run(proc_func_that_returns_pid), pid)
def test_exceptions_in_sub_process(self):
cluster_spec = multi_worker_test_base.create_cluster_spec(num_workers=2)
runner = multi_process_runner.MultiProcessPoolRunner(cluster_spec)
pid = runner.run(proc_func_that_returns_pid)
with self.assertRaisesRegexp(ValueError, 'This is an error.'):
runner.run(proc_func_that_errors)
self.assertAllEqual(runner.run(proc_func_that_returns_pid), pid)
def test_tf_config(self):
cluster_spec = multi_worker_test_base.create_cluster_spec(
has_chief=True, num_workers=2)
runner = multi_process_runner.MultiProcessPoolRunner(cluster_spec)
result = runner.run(proc_func_that_adds_task_type_in_return_data)
job_count_dict = {'worker': 2, 'chief': 1}
for data in result:
job_count_dict[data] -= 1
self.assertEqual(job_count_dict['worker'], 0)
self.assertEqual(job_count_dict['chief'], 0)
@unittest.expectedFailure
def test_exception_in_main_process(self):
# When there's an exception in the main process, __del__() is not called.
# This test is to verify MultiProcessPoolRunner can cope with __del__() not
# being called.
cluster_spec = multi_worker_test_base.create_cluster_spec(
has_chief=True, num_workers=2)
runner = multi_process_runner.MultiProcessPoolRunner(cluster_spec)
runner.run(proc_func_that_returns_pid)
raise ValueError('failure')
def test_initializer(self):
cluster_spec = multi_worker_test_base.create_cluster_spec(num_workers=2)
runner = multi_process_runner.MultiProcessPoolRunner(
cluster_spec, initializer=lambda: proc_func_that_sets_global(1))
result = runner.run(proc_func_that_sets_global, args=(2,))
self.assertAllEqual(result, [1, 1])
if __name__ == '__main__':
multi_process_runner.test_main()
| 35.100239 | 80 | 0.690895 |
acec6efcb472966727ae3ebf2b30b7544798e032 | 528 | py | Python | aiogram/types/venue.py | muhammedfurkan/aiogram | 692c1340b4dda556da640e5f9ea2200848c06840 | [
"MIT"
] | null | null | null | aiogram/types/venue.py | muhammedfurkan/aiogram | 692c1340b4dda556da640e5f9ea2200848c06840 | [
"MIT"
] | 4 | 2020-11-04T15:55:55.000Z | 2020-11-08T21:36:02.000Z | aiogram/types/venue.py | muhammedfurkan/aiogram | 692c1340b4dda556da640e5f9ea2200848c06840 | [
"MIT"
] | null | null | null | from . import base, fields
from .location import Location
class Venue(base.TelegramObject):
"""
This object represents a venue.
https://core.telegram.org/bots/api#venue
"""
location: Location = fields.Field(base=Location)
title: base.String = fields.Field()
address: base.String = fields.Field()
foursquare_id: base.String = fields.Field()
foursquare_type: base.String = fields.Field()
google_place_id: base.String = fields.Field()
google_place_type: base.String = fields.Field()
| 27.789474 | 52 | 0.698864 |
acec70409808b481eebab7c32321bf9bdee9d5e1 | 57 | py | Python | queenbee/recipe/__init__.py | AntoineDao/queenbee | 800d5b26a69cffbce85864ea9430304b7fb8d11a | [
"MIT"
] | 10 | 2020-12-17T06:08:46.000Z | 2022-02-12T12:06:08.000Z | queenbee/recipe/__init__.py | AntoineDao/queenbee | 800d5b26a69cffbce85864ea9430304b7fb8d11a | [
"MIT"
] | 213 | 2020-12-06T03:34:01.000Z | 2022-03-28T01:07:41.000Z | queenbee/recipe/__init__.py | AntoineDao/queenbee | 800d5b26a69cffbce85864ea9430304b7fb8d11a | [
"MIT"
] | 4 | 2019-08-14T22:10:29.000Z | 2020-09-21T22:46:11.000Z | from .recipe import Recipe, BakedRecipe, RecipeInterface
| 28.5 | 56 | 0.842105 |
acec738d6534796ff41385eee4a5ae54e58b85cd | 2,019 | py | Python | src/utils/measure.py | wenchieh/catchcore | ef3c3a6a0da94fea98db1a86c5dc736ae9cddec0 | [
"MIT"
] | 7 | 2019-06-29T14:29:59.000Z | 2021-12-17T12:08:40.000Z | src/utils/measure.py | wenchieh/catchcore | ef3c3a6a0da94fea98db1a86c5dc736ae9cddec0 | [
"MIT"
] | null | null | null | src/utils/measure.py | wenchieh/catchcore | ef3c3a6a0da94fea98db1a86c5dc736ae9cddec0 | [
"MIT"
] | 2 | 2020-10-22T18:07:18.000Z | 2021-08-17T08:32:24.000Z | #!/usr/bin/python
# -*- coding=utf-8 -*-
# Project: catchcore
# measure.py
# Version: 1.0
# Goal: Subroutine script
# Created by @wenchieh on <10/23/2018>
#
__author__ = 'wenchieh'
def jaccard(pred, actual):
intersectSize = len(set.intersection(set(pred), set(actual)))
unionSize = len(set.union(set(pred), set(actual)))
return intersectSize * 1.0 / unionSize
def jaccard_MD(pred, actual, dims=None):
if dims is None:
dims = range(len(pred))
intersectSize, unionSize = 0.0, 0.0
for d in dims:
intersectSize += len(set.intersection(set(pred[d]), set(actual[d])))
unionSize += len(set.union(set(pred[d]), set(actual[d])))
return intersectSize * 1.0 / unionSize
def getPrecision(pred, actual):
intersectSize = len(set.intersection(set(pred), set(actual)))
return intersectSize * 1.0 / len(pred)
def getPrecision_MD(pred, actual, dims=None):
if dims is None:
dims = range(len(pred))
intersectSize, tols = 0.0, 0.0
for d in dims:
intersectSize += len(set.intersection(set(pred[d]), set(actual[d])))
tols += len(set(pred[d]))
return intersectSize * 1.0 / tols
def getRecall(pred, actual):
intersectSize = len(set.intersection(set(pred), set(actual)))
return intersectSize * 1.0 / len(actual)
def getRecall_MD(pred, actual, dims=None):
if dims is None:
dims = range(len(pred))
intersectSize, tols = 0.0, 0.0
for d in dims:
intersectSize += len(set.intersection(set(pred[d]), set(actual[d])))
tols += len(set(actual[d]))
return intersectSize * 1.0 / tols
def getFMeasure(pred, actual):
prec = getPrecision(pred, actual)
rec = getRecall(pred, actual)
return 0 if (prec + rec == 0) else (2 * prec * rec / (prec + rec))
def getFMeasure_MD(pred, actual, dims=None):
prec = getPrecision_MD(pred, actual, dims)
rec = getRecall_MD(pred, actual, dims)
return 0 if (prec + rec == 0) else (2 * prec * rec / (prec + rec))
| 26.92 | 76 | 0.63051 |
acec74e9e9169241d5f475cc9d533277d415151f | 21,446 | py | Python | tests/utils.py | jdreichmann/synapse | 6fde6aa9c02d35e0a908437ea49b275df9b58427 | [
"Apache-2.0"
] | 1 | 2020-11-07T03:29:01.000Z | 2020-11-07T03:29:01.000Z | tests/utils.py | jdreichmann/synapse | 6fde6aa9c02d35e0a908437ea49b275df9b58427 | [
"Apache-2.0"
] | null | null | null | tests/utils.py | jdreichmann/synapse | 6fde6aa9c02d35e0a908437ea49b275df9b58427 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
# Copyright 2018-2019 New Vector Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import atexit
import hashlib
import os
import time
import uuid
import warnings
from inspect import getcallargs
from typing import Type
from urllib import parse as urlparse
from mock import Mock, patch
from twisted.internet import defer, reactor
from synapse.api.constants import EventTypes
from synapse.api.errors import CodeMessageException, cs_error
from synapse.api.room_versions import RoomVersions
from synapse.config.database import DatabaseConnectionConfig
from synapse.config.homeserver import HomeServerConfig
from synapse.config.server import DEFAULT_ROOM_VERSION
from synapse.federation.transport import server as federation_server
from synapse.http.server import HttpServer
from synapse.logging.context import current_context, set_current_context
from synapse.server import HomeServer
from synapse.storage import DataStore
from synapse.storage.database import LoggingDatabaseConnection
from synapse.storage.engines import PostgresEngine, create_engine
from synapse.storage.prepare_database import prepare_database
from synapse.util.ratelimitutils import FederationRateLimiter
# set this to True to run the tests against postgres instead of sqlite.
#
# When running under postgres, we first create a base database with the name
# POSTGRES_BASE_DB and update it to the current schema. Then, for each test case, we
# create another unique database, using the base database as a template.
USE_POSTGRES_FOR_TESTS = os.environ.get("SYNAPSE_POSTGRES", False)
LEAVE_DB = os.environ.get("SYNAPSE_LEAVE_DB", False)
POSTGRES_USER = os.environ.get("SYNAPSE_POSTGRES_USER", None)
POSTGRES_HOST = os.environ.get("SYNAPSE_POSTGRES_HOST", None)
POSTGRES_PASSWORD = os.environ.get("SYNAPSE_POSTGRES_PASSWORD", None)
POSTGRES_BASE_DB = "_synapse_unit_tests_base_%s" % (os.getpid(),)
# the dbname we will connect to in order to create the base database.
POSTGRES_DBNAME_FOR_INITIAL_CREATE = "postgres"
def setupdb():
# If we're using PostgreSQL, set up the db once
if USE_POSTGRES_FOR_TESTS:
# create a PostgresEngine
db_engine = create_engine({"name": "psycopg2", "args": {}})
# connect to postgres to create the base database.
db_conn = db_engine.module.connect(
user=POSTGRES_USER,
host=POSTGRES_HOST,
password=POSTGRES_PASSWORD,
dbname=POSTGRES_DBNAME_FOR_INITIAL_CREATE,
)
db_conn.autocommit = True
cur = db_conn.cursor()
cur.execute("DROP DATABASE IF EXISTS %s;" % (POSTGRES_BASE_DB,))
cur.execute(
"CREATE DATABASE %s ENCODING 'UTF8' LC_COLLATE='C' LC_CTYPE='C' "
"template=template0;" % (POSTGRES_BASE_DB,)
)
cur.close()
db_conn.close()
# Set up in the db
db_conn = db_engine.module.connect(
database=POSTGRES_BASE_DB,
user=POSTGRES_USER,
host=POSTGRES_HOST,
password=POSTGRES_PASSWORD,
)
db_conn = LoggingDatabaseConnection(db_conn, db_engine, "tests")
prepare_database(db_conn, db_engine, None)
db_conn.close()
def _cleanup():
db_conn = db_engine.module.connect(
user=POSTGRES_USER,
host=POSTGRES_HOST,
password=POSTGRES_PASSWORD,
dbname=POSTGRES_DBNAME_FOR_INITIAL_CREATE,
)
db_conn.autocommit = True
cur = db_conn.cursor()
cur.execute("DROP DATABASE IF EXISTS %s;" % (POSTGRES_BASE_DB,))
cur.close()
db_conn.close()
atexit.register(_cleanup)
def default_config(name, parse=False):
"""
Create a reasonable test config.
"""
config_dict = {
"server_name": name,
"send_federation": False,
"media_store_path": "media",
"uploads_path": "uploads",
# the test signing key is just an arbitrary ed25519 key to keep the config
# parser happy
"signing_key": "ed25519 a_lPym qvioDNmfExFBRPgdTU+wtFYKq4JfwFRv7sYVgWvmgJg",
"event_cache_size": 1,
"enable_registration": True,
"enable_registration_captcha": False,
"macaroon_secret_key": "not even a little secret",
"trusted_third_party_id_servers": [],
"room_invite_state_types": [],
"password_providers": [],
"worker_replication_url": "",
"worker_app": None,
"block_non_admin_invites": False,
"federation_domain_whitelist": None,
"filter_timeline_limit": 5000,
"user_directory_search_all_users": False,
"user_consent_server_notice_content": None,
"block_events_without_consent_error": None,
"user_consent_at_registration": False,
"user_consent_policy_name": "Privacy Policy",
"media_storage_providers": [],
"autocreate_auto_join_rooms": True,
"auto_join_rooms": [],
"limit_usage_by_mau": False,
"hs_disabled": False,
"hs_disabled_message": "",
"max_mau_value": 50,
"mau_trial_days": 0,
"mau_stats_only": False,
"mau_limits_reserved_threepids": [],
"admin_contact": None,
"rc_message": {"per_second": 10000, "burst_count": 10000},
"rc_registration": {"per_second": 10000, "burst_count": 10000},
"rc_login": {
"address": {"per_second": 10000, "burst_count": 10000},
"account": {"per_second": 10000, "burst_count": 10000},
"failed_attempts": {"per_second": 10000, "burst_count": 10000},
},
"rc_joins": {
"local": {"per_second": 10000, "burst_count": 10000},
"remote": {"per_second": 10000, "burst_count": 10000},
},
"saml2_enabled": False,
"public_baseurl": None,
"default_identity_server": None,
"key_refresh_interval": 24 * 60 * 60 * 1000,
"old_signing_keys": {},
"tls_fingerprints": [],
"use_frozen_dicts": False,
# We need a sane default_room_version, otherwise attempts to create
# rooms will fail.
"default_room_version": DEFAULT_ROOM_VERSION,
# disable user directory updates, because they get done in the
# background, which upsets the test runner.
"update_user_directory": False,
"caches": {"global_factor": 1},
"listeners": [{"port": 0, "type": "http"}],
}
if parse:
config = HomeServerConfig()
config.parse_config_dict(config_dict, "", "")
return config
return config_dict
class TestHomeServer(HomeServer):
DATASTORE_CLASS = DataStore
def setup_test_homeserver(
cleanup_func,
name="test",
config=None,
reactor=None,
homeserver_to_use: Type[HomeServer] = TestHomeServer,
**kwargs
):
"""
Setup a homeserver suitable for running tests against. Keyword arguments
are passed to the Homeserver constructor.
If no datastore is supplied, one is created and given to the homeserver.
Args:
cleanup_func : The function used to register a cleanup routine for
after the test.
Calling this method directly is deprecated: you should instead derive from
HomeserverTestCase.
"""
if reactor is None:
from twisted.internet import reactor
if config is None:
config = default_config(name, parse=True)
config.ldap_enabled = False
if "clock" not in kwargs:
kwargs["clock"] = MockClock()
if USE_POSTGRES_FOR_TESTS:
test_db = "synapse_test_%s" % uuid.uuid4().hex
database_config = {
"name": "psycopg2",
"args": {
"database": test_db,
"host": POSTGRES_HOST,
"password": POSTGRES_PASSWORD,
"user": POSTGRES_USER,
"cp_min": 1,
"cp_max": 5,
},
}
else:
database_config = {
"name": "sqlite3",
"args": {"database": ":memory:", "cp_min": 1, "cp_max": 1},
}
database = DatabaseConnectionConfig("master", database_config)
config.database.databases = [database]
db_engine = create_engine(database.config)
# Create the database before we actually try and connect to it, based off
# the template database we generate in setupdb()
if isinstance(db_engine, PostgresEngine):
db_conn = db_engine.module.connect(
database=POSTGRES_BASE_DB,
user=POSTGRES_USER,
host=POSTGRES_HOST,
password=POSTGRES_PASSWORD,
)
db_conn.autocommit = True
cur = db_conn.cursor()
cur.execute("DROP DATABASE IF EXISTS %s;" % (test_db,))
cur.execute(
"CREATE DATABASE %s WITH TEMPLATE %s;" % (test_db, POSTGRES_BASE_DB)
)
cur.close()
db_conn.close()
hs = homeserver_to_use(
name, config=config, version_string="Synapse/tests", reactor=reactor,
)
# Install @cache_in_self attributes
for key, val in kwargs.items():
setattr(hs, key, val)
# Mock TLS
hs.tls_server_context_factory = Mock()
hs.tls_client_options_factory = Mock()
hs.setup()
if homeserver_to_use == TestHomeServer:
hs.setup_background_tasks()
if isinstance(db_engine, PostgresEngine):
database = hs.get_datastores().databases[0]
# We need to do cleanup on PostgreSQL
def cleanup():
import psycopg2
# Close all the db pools
database._db_pool.close()
dropped = False
# Drop the test database
db_conn = db_engine.module.connect(
database=POSTGRES_BASE_DB,
user=POSTGRES_USER,
host=POSTGRES_HOST,
password=POSTGRES_PASSWORD,
)
db_conn.autocommit = True
cur = db_conn.cursor()
# Try a few times to drop the DB. Some things may hold on to the
# database for a few more seconds due to flakiness, preventing
# us from dropping it when the test is over. If we can't drop
# it, warn and move on.
for x in range(5):
try:
cur.execute("DROP DATABASE IF EXISTS %s;" % (test_db,))
db_conn.commit()
dropped = True
except psycopg2.OperationalError as e:
warnings.warn(
"Couldn't drop old db: " + str(e), category=UserWarning
)
time.sleep(0.5)
cur.close()
db_conn.close()
if not dropped:
warnings.warn("Failed to drop old DB.", category=UserWarning)
if not LEAVE_DB:
# Register the cleanup hook
cleanup_func(cleanup)
# bcrypt is far too slow to be doing in unit tests
# Need to let the HS build an auth handler and then mess with it
# because AuthHandler's constructor requires the HS, so we can't make one
# beforehand and pass it in to the HS's constructor (chicken / egg)
async def hash(p):
return hashlib.md5(p.encode("utf8")).hexdigest()
hs.get_auth_handler().hash = hash
async def validate_hash(p, h):
return hashlib.md5(p.encode("utf8")).hexdigest() == h
hs.get_auth_handler().validate_hash = validate_hash
fed = kwargs.get("resource_for_federation", None)
if fed:
register_federation_servlets(hs, fed)
return hs
def register_federation_servlets(hs, resource):
federation_server.register_servlets(
hs,
resource=resource,
authenticator=federation_server.Authenticator(hs),
ratelimiter=FederationRateLimiter(
hs.get_clock(), config=hs.config.rc_federation
),
)
def get_mock_call_args(pattern_func, mock_func):
""" Return the arguments the mock function was called with interpreted
by the pattern functions argument list.
"""
invoked_args, invoked_kargs = mock_func.call_args
return getcallargs(pattern_func, *invoked_args, **invoked_kargs)
def mock_getRawHeaders(headers=None):
headers = headers if headers is not None else {}
def getRawHeaders(name, default=None):
return headers.get(name, default)
return getRawHeaders
# This is a mock /resource/ not an entire server
class MockHttpResource(HttpServer):
def __init__(self, prefix=""):
self.callbacks = [] # 3-tuple of method/pattern/function
self.prefix = prefix
def trigger_get(self, path):
return self.trigger(b"GET", path, None)
@patch("twisted.web.http.Request")
@defer.inlineCallbacks
def trigger(
self, http_method, path, content, mock_request, federation_auth_origin=None
):
""" Fire an HTTP event.
Args:
http_method : The HTTP method
path : The HTTP path
content : The HTTP body
mock_request : Mocked request to pass to the event so it can get
content.
federation_auth_origin (bytes|None): domain to authenticate as, for federation
Returns:
A tuple of (code, response)
Raises:
KeyError If no event is found which will handle the path.
"""
path = self.prefix + path
# annoyingly we return a twisted http request which has chained calls
# to get at the http content, hence mock it here.
mock_content = Mock()
config = {"read.return_value": content}
mock_content.configure_mock(**config)
mock_request.content = mock_content
mock_request.method = http_method.encode("ascii")
mock_request.uri = path.encode("ascii")
mock_request.getClientIP.return_value = "-"
headers = {}
if federation_auth_origin is not None:
headers[b"Authorization"] = [
b"X-Matrix origin=%s,key=,sig=" % (federation_auth_origin,)
]
mock_request.requestHeaders.getRawHeaders = mock_getRawHeaders(headers)
# return the right path if the event requires it
mock_request.path = path
# add in query params to the right place
try:
mock_request.args = urlparse.parse_qs(path.split("?")[1])
mock_request.path = path.split("?")[0]
path = mock_request.path
except Exception:
pass
if isinstance(path, bytes):
path = path.decode("utf8")
for (method, pattern, func) in self.callbacks:
if http_method != method:
continue
matcher = pattern.match(path)
if matcher:
try:
args = [urlparse.unquote(u) for u in matcher.groups()]
(code, response) = yield defer.ensureDeferred(
func(mock_request, *args)
)
return code, response
except CodeMessageException as e:
return (e.code, cs_error(e.msg, code=e.errcode))
raise KeyError("No event can handle %s" % path)
def register_paths(self, method, path_patterns, callback, servlet_name):
for path_pattern in path_patterns:
self.callbacks.append((method, path_pattern, callback))
class MockKey:
alg = "mock_alg"
version = "mock_version"
signature = b"\x9a\x87$"
@property
def verify_key(self):
return self
def sign(self, message):
return self
def verify(self, message, sig):
assert sig == b"\x9a\x87$"
def encode(self):
return b"<fake_encoded_key>"
class MockClock:
now = 1000
def __init__(self):
# list of lists of [absolute_time, callback, expired] in no particular
# order
self.timers = []
self.loopers = []
def time(self):
return self.now
def time_msec(self):
return self.time() * 1000
def call_later(self, delay, callback, *args, **kwargs):
ctx = current_context()
def wrapped_callback():
set_current_context(ctx)
callback(*args, **kwargs)
t = [self.now + delay, wrapped_callback, False]
self.timers.append(t)
return t
def looping_call(self, function, interval, *args, **kwargs):
self.loopers.append([function, interval / 1000.0, self.now, args, kwargs])
def cancel_call_later(self, timer, ignore_errs=False):
if timer[2]:
if not ignore_errs:
raise Exception("Cannot cancel an expired timer")
timer[2] = True
self.timers = [t for t in self.timers if t != timer]
# For unit testing
def advance_time(self, secs):
self.now += secs
timers = self.timers
self.timers = []
for t in timers:
time, callback, expired = t
if expired:
raise Exception("Timer already expired")
if self.now >= time:
t[2] = True
callback()
else:
self.timers.append(t)
for looped in self.loopers:
func, interval, last, args, kwargs = looped
if last + interval < self.now:
func(*args, **kwargs)
looped[2] = self.now
def advance_time_msec(self, ms):
self.advance_time(ms / 1000.0)
def time_bound_deferred(self, d, *args, **kwargs):
# We don't bother timing things out for now.
return d
def _format_call(args, kwargs):
return ", ".join(
["%r" % (a) for a in args] + ["%s=%r" % (k, v) for k, v in kwargs.items()]
)
class DeferredMockCallable:
"""A callable instance that stores a set of pending call expectations and
return values for them. It allows a unit test to assert that the given set
of function calls are eventually made, by awaiting on them to be called.
"""
def __init__(self):
self.expectations = []
self.calls = []
def __call__(self, *args, **kwargs):
self.calls.append((args, kwargs))
if not self.expectations:
raise ValueError(
"%r has no pending calls to handle call(%s)"
% (self, _format_call(args, kwargs))
)
for (call, result, d) in self.expectations:
if args == call[1] and kwargs == call[2]:
d.callback(None)
return result
failure = AssertionError(
"Was not expecting call(%s)" % (_format_call(args, kwargs))
)
for _, _, d in self.expectations:
try:
d.errback(failure)
except Exception:
pass
raise failure
def expect_call_and_return(self, call, result):
self.expectations.append((call, result, defer.Deferred()))
@defer.inlineCallbacks
def await_calls(self, timeout=1000):
deferred = defer.DeferredList(
[d for _, _, d in self.expectations], fireOnOneErrback=True
)
timer = reactor.callLater(
timeout / 1000,
deferred.errback,
AssertionError(
"%d pending calls left: %s"
% (
len([e for e in self.expectations if not e[2].called]),
[e for e in self.expectations if not e[2].called],
)
),
)
yield deferred
timer.cancel()
self.calls = []
def assert_had_no_calls(self):
if self.calls:
calls = self.calls
self.calls = []
raise AssertionError(
"Expected not to received any calls, got:\n"
+ "\n".join(["call(%s)" % _format_call(c[0], c[1]) for c in calls])
)
async def create_room(hs, room_id: str, creator_id: str):
"""Creates and persist a creation event for the given room
"""
persistence_store = hs.get_storage().persistence
store = hs.get_datastore()
event_builder_factory = hs.get_event_builder_factory()
event_creation_handler = hs.get_event_creation_handler()
await store.store_room(
room_id=room_id,
room_creator_user_id=creator_id,
is_public=False,
room_version=RoomVersions.V1,
)
builder = event_builder_factory.for_room_version(
RoomVersions.V1,
{
"type": EventTypes.Create,
"state_key": "",
"sender": creator_id,
"room_id": room_id,
"content": {},
},
)
event, context = await event_creation_handler.create_new_client_event(builder)
await persistence_store.persist_event(event, context)
| 32.201201 | 90 | 0.613075 |
acec757cbaeb789fc6913c9a6e92bc6462d79ab3 | 3,397 | py | Python | examples/pytorch/stgcn_wave/model.py | kingmbc/dgl | 831c0d29b28665f24f6a5b2539a4023a97a239cb | [
"Apache-2.0"
] | 1 | 2021-06-30T16:50:18.000Z | 2021-06-30T16:50:18.000Z | examples/pytorch/stgcn_wave/model.py | hetong007/dgl | 1bfc3118e4a542821c1415e376c026fe1dfd0b59 | [
"Apache-2.0"
] | null | null | null | examples/pytorch/stgcn_wave/model.py | hetong007/dgl | 1bfc3118e4a542821c1415e376c026fe1dfd0b59 | [
"Apache-2.0"
] | 2 | 2019-09-10T10:21:27.000Z | 2022-03-06T18:55:09.000Z | import math
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
from dgl.nn.pytorch import GraphConv
from dgl.nn.pytorch.conv import ChebConv
class TemporalConvLayer(nn.Module):
''' Temporal convolution layer.
arguments
---------
c_in : int
The number of input channels (features)
c_out : int
The number of output channels (features)
dia : int
The dilation size
'''
def __init__(self, c_in, c_out, dia = 1):
super(TemporalConvLayer, self).__init__()
self.c_out = c_out
self.c_in = c_in
self.conv = nn.Conv2d(c_in, c_out, (2, 1), 1, dilation = dia, padding = (0,0))
def forward(self, x):
return torch.relu(self.conv(x))
class SpatioConvLayer(nn.Module):
def __init__(self, c, Lk): # c : hidden dimension Lk: graph matrix
super(SpatioConvLayer, self).__init__()
self.g = Lk
self.gc = GraphConv(c, c, activation=F.relu)
# self.gc = ChebConv(c, c, 3)
def init(self):
stdv = 1. / math.sqrt(self.W.weight.size(1))
self.W.weight.data.uniform_(-stdv, stdv)
def forward(self, x):
x = x.transpose(0, 3)
x = x.transpose(1, 3)
output = self.gc(self.g, x)
output = output.transpose(1, 3)
output = output.transpose(0, 3)
return torch.relu(output)
class FullyConvLayer(nn.Module):
def __init__(self, c):
super(FullyConvLayer, self).__init__()
self.conv = nn.Conv2d(c, 1, 1)
def forward(self, x):
return self.conv(x)
class OutputLayer(nn.Module):
def __init__(self, c, T, n):
super(OutputLayer, self).__init__()
self.tconv1 = nn.Conv2d(c, c, (T, 1), 1, dilation = 1, padding = (0,0))
self.ln = nn.LayerNorm([n, c])
self.tconv2 = nn.Conv2d(c, c, (1, 1), 1, dilation = 1, padding = (0,0))
self.fc = FullyConvLayer(c)
def forward(self, x):
x_t1 = self.tconv1(x)
x_ln = self.ln(x_t1.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
x_t2 = self.tconv2(x_ln)
return self.fc(x_t2)
class STGCN_WAVE(nn.Module):
def __init__(self, c, T, n, Lk, p, num_layers, device, control_str = 'TNTSTNTST'):
super(STGCN_WAVE, self).__init__()
self.control_str = control_str # model structure controller
self.num_layers = len(control_str)
self.layers = []
cnt = 0
diapower = 0
for i in range(self.num_layers):
i_layer = control_str[i]
if i_layer == 'T': # Temporal Layer
self.layers.append(TemporalConvLayer(c[cnt], c[cnt + 1], dia = 2**diapower))
diapower += 1
cnt += 1
if i_layer == 'S': # Spatio Layer
self.layers.append(SpatioConvLayer(c[cnt], Lk))
if i_layer == 'N': # Norm Layer
self.layers.append(nn.LayerNorm([n,c[cnt]]))
self.output = OutputLayer(c[cnt], T + 1 - 2**(diapower), n)
for layer in self.layers:
layer = layer.to(device)
def forward(self, x):
for i in range(self.num_layers):
i_layer = self.control_str[i]
if i_layer == 'N':
x = self.layers[i](x.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
else:
x = self.layers[i](x)
return self.output(x)
| 33.303922 | 92 | 0.569326 |
acec75ccb157cc5ad7baa6e176fa495105b04858 | 10,555 | py | Python | digsby/src/gui/contactdialogs.py | ifwe/digsby | f5fe00244744aa131e07f09348d10563f3d8fa99 | [
"Python-2.0"
] | 35 | 2015-08-15T14:32:38.000Z | 2021-12-09T16:21:26.000Z | digsby/src/gui/contactdialogs.py | niterain/digsby | 16a62c7df1018a49eaa8151c0f8b881c7e252949 | [
"Python-2.0"
] | 4 | 2015-09-12T10:42:57.000Z | 2017-02-27T04:05:51.000Z | digsby/src/gui/contactdialogs.py | niterain/digsby | 16a62c7df1018a49eaa8151c0f8b881c7e252949 | [
"Python-2.0"
] | 15 | 2015-07-10T23:58:07.000Z | 2022-01-23T22:16:33.000Z | '''
GUI for editing contacts, metacontacts.
'''
from __future__ import with_statement
import wx
from wx import VERTICAL, HORIZONTAL, ALIGN_CENTER_HORIZONTAL, EXPAND, ALL, LEFT, RIGHT, TOP, BOTTOM,ALIGN_CENTER_VERTICAL,ALIGN_LEFT
TOPLESS = ALL & ~TOP
from gui.visuallisteditor import VisualListEditorList
from gui.toolbox import build_button_sizer, wx_prop
from gui.textutil import CopyFont
from gui.validators import LengthLimit
from util import Storage as S
from logging import getLogger; log =getLogger('contactdialogs'); info = log.info
from common import profile
from gettext import ngettext
REQUIRE_ALIAS = True
def get_profile():
from common import profile
return profile
def contact_string(c):
return '%s (%s)' % (c.name, c.protocol.name)
def account_string(a):
return '%s (%s)' % (a.name, a.protocol)
def send_files(parent, buddy, files):
'''
parent wxWindow parent
buddy buddy to call send_files on
files a list of file paths
'''
msg = ngettext(u'Would you like to send "{files[0]}" to {buddy_name:s}?',
u'Would you like to send {num_files:d} files to {buddy_name:s}?',
len(files)).format(files=files, num_files=len(files), buddy_name=buddy.name)
if wx.YES == wx.MessageBox(msg, _('Send Files'), style = wx.YES_NO, parent = parent):
for filename in files:
buddy.send_file(filename)
class ContactPanel(wx.Panel):
'GUI for adding a contact.'
def __init__(self, parent, to_group = None):
wx.Panel.__init__(self, parent)
self.construct()
self.layout()
# Listen for changes to the connected accounts list.
from common import profile
profile.account_manager.connected_accounts.add_observer(self.on_conns_changed)
self.on_conns_changed(profile.account_manager.connected_accounts, to_group)
def on_close(self):
profile.account_manager.connected_accounts.remove_observer(self.on_conns_changed)
def on_conns_changed(self, connected_accounts, *a):
'Updates the accounts choice.'
choice = self.acct_choice
sel = choice.GetStringSelection()
with choice.Frozen():
choice.Clear()
for acct in connected_accounts:
proto_str = account_string(acct)
choice.Append(proto_str)
choice.SetStringSelection(sel) if sel else choice.SetSelection(0)
def construct(self):
self.name_st = wx.StaticText(self, -1, _('Contact &Name:'))
self.name_txt = wx.TextCtrl(self, -1, validator=LengthLimit(255))
self.acct_st = wx.StaticText(self, -1, _('Accoun&t:'))
self.acct_choice = wx.Choice(self, -1)
self.get_acct = lambda: get_profile().account_manager.connected_accounts[self.acct_choice.Selection]
# Add and Cancel buttons
self.save = wx.Button(self, wx.ID_SAVE, _('&Add'))
self.save.SetDefault()
self.save.Bind(wx.EVT_BUTTON, self.Parent.on_save)
self.cancel = wx.Button(self, wx.ID_CANCEL, _('&Cancel'))
name = wx_prop('name_txt')
def get_info(self):
return S(name = self.name,
account = self.get_acct())
def layout(self):
self.Sizer = sz = wx.BoxSizer(wx.VERTICAL)
sz.Add(self.name_st, 0, wx.EXPAND | wx.ALL, 5)
sz.Add(self.name_txt, 0, wx.EXPAND | wx.ALL, 5)
sz.Add((0,5))
sz.Add(self.acct_st, 0, wx.EXPAND | wx.ALL, 5)
sz.Add(self.acct_choice, 0, wx.EXPAND | wx.ALL, 5)
# Add/Cancel
sz.Add(build_button_sizer(save=self.save, cancel=self.cancel),
0, wx.EXPAND | wx.SOUTH | wx.EAST | wx.WEST, 4)
class MetaListEditor(VisualListEditorList):
def __init__(self, parent, list2sort, listcallback = None):
VisualListEditorList.__init__(self, parent, list2sort, listcallback = listcallback)
def OnDrawItem(self,dc,rect,n):
dc.Font=self.Font
buddy = self.thelist[n]
icon = buddy.buddy_icon.Resized(16)
serv = buddy.serviceicon.Resized(16)
x = rect.x + 3
y = rect.y + 3
textrect = wx.Rect(x + 16 + 3,rect.y,rect.Width - x - 38,rect.Height)
dc.DrawLabel(buddy.name,textrect,ALIGN_CENTER_VERTICAL|ALIGN_LEFT)
dc.DrawBitmap(icon,x,y,True)
dc.DrawBitmap(serv,rect.x + rect.Width - 16 - 3,y,True)
class MetaContactPanel(wx.Panel):
'GUI for creating or appending to a metacontact.'
def __init__(self, parent, contacts = [], metacontact = None, order = None):
wx.Panel.__init__(self, parent)
self.contacts = contacts
self.metacontact = metacontact
self.order = order
self.construct()
self.layout()
def construct(self):
Text = lambda s: wx.StaticText(self,-1,_(s))
self.line1 = Text(_('Would you like to merge these contacts?'))
self.line1.Font = CopyFont(self.line1.Font,weight = wx.BOLD)
self.line2 = Text(_('They will appear as one item on your buddy list.'))
self.sep = wx.StaticLine(self,-1)
self.alias_label = wx.StaticText(self, -1, _('Alias:'))
self.alias_label.Font = CopyFont(self.alias_label.Font,weight = wx.BOLD)
# Decide on an alias: don't use the alias property from the metacontact
# because that falls through to the best available one.
alias = self.find_alias_suggestion()
self.alias_text = wx.TextCtrl(self, -1, alias if alias else '', validator=LengthLimit(255))
s = self.save = wx.Button(self, wx.ID_SAVE, _('&Save')) # save
s.SetDefault()
s.Bind(wx.EVT_BUTTON, self.Parent.on_save)
if REQUIRE_ALIAS:
self.alias_text.Bind(wx.EVT_TEXT, lambda e: self.save.Enable(self.alias_text.Value!=''))
self.save.Enable(self.alias_text.Value != '')
self.cancel = wx.Button(self, wx.ID_CANCEL, _('&Cancel')) # cancel
self.line4 = Text(_('Drag and drop to rearrange:'))
self.line4.Font = CopyFont(self.line4.Font,weight = wx.BOLD)
self.contacts_list = MetaListEditor(self,self.contacts,self.update_contacts_list)
def find_alias_suggestion(self):
'Returns a suggestion for the alias for this metacontact.'
if self.metacontact:
# Is this already a metacontact? If so, it already has an alias:
# use that.
return self.metacontact.alias
# Otherwise use the first available alias.
for contact in self.contacts:
a = profile.get_contact_info(contact, 'alias')
if a: return a
# No suggestion.
return ''
def update_contacts_list(self,contacts):
self.contacts = contacts
def layout(self):
self.Sizer = sz = wx.BoxSizer(VERTICAL)
h1 = wx.BoxSizer(VERTICAL)
h1.Add(self.line1,0,ALIGN_CENTER_HORIZONTAL)
h1.Add(self.line2,0,ALIGN_CENTER_HORIZONTAL|TOP,3)
h1.Add(self.sep,0,EXPAND|TOP,6)
h1.Add(self.alias_label,0,TOP,6)
h1.Add(self.alias_text,0,EXPAND|TOP,3)
h1.Add(self.line4,0,TOP,6)
h1.Add(self.contacts_list,1, EXPAND|TOP,3)
sz.Add(h1, 1, EXPAND|ALL,6)
# Save/Cancel
sz.Add(build_button_sizer(save=self.save, cancel=self.cancel),
0, EXPAND | TOPLESS, 4)
def commit(self):
'Commits changes.'
blist = get_profile().blist
mcs = blist.metacontacts
if self.metacontact:
self.metacontact.rename(self.alias)
mcs.edit(self.metacontact, self.contacts, grouppath = self.metacontact.mcinfo.groups)
return self.metacontact
else:
meta = mcs.create(self.alias, self.contacts, update = False)
meta = mcs.metacontact_objs[meta]
if self.order is not None:
order = [(c if c != '__meta__' else meta) for c in self.order]
blist.rearrange(*order)
return meta
alias = wx_prop('alias_text')
class ContactDialog(wx.Dialog):
def __init__(self, parent, to_group = None):
wx.Dialog.__init__(self, parent, title = _('Add Contact'))
self.contact_panel = ContactPanel(self, to_group)
self.Sizer = s = wx.BoxSizer(wx.VERTICAL)
s.Add(self.contact_panel, 1, wx.EXPAND)
self.Fit()
self.contact_panel.name_txt.SetFocus()
self.Centre()
def Prompt(self, callback):
try:
if wx.ID_SAVE == self.ShowModal():
callback(**self.contact_panel.get_info())
finally:
self.contact_panel.on_close()
self.Destroy()
def on_save(self, e):
self.SetReturnCode(wx.ID_SAVE)
if self.IsModal():
self.EndModal(wx.ID_SAVE)
class MetaContactDialog(wx.Dialog):
minsize = (290, 290)
def __init__(self, parent, contacts, metacontact = None, title=None, order = None):
wx.Dialog.__init__(self, parent, title=title or _('Merge Contacts'), pos=(400,200),
style = wx.DEFAULT_DIALOG_STYLE)
self.Sizer = s = wx.BoxSizer(wx.VERTICAL)
self.mc_panel = panel = MetaContactPanel(self, contacts, metacontact, order = order)
s.Add(panel, 1, wx.EXPAND)
# self.SetMinSize(self.minsize)
# self.Layout()
self.Fit()
@classmethod
def add_contact(cls, parent, metacontact, contact, position = -1):
'Creates and returns a dialog for adding a contact to a MetaContact.'
from contacts.metacontacts import MetaContact
if not isinstance(metacontact, MetaContact):
raise TypeError('parent (wxWindow), metacontact (MetaContact), '
'contact (Contact), [position (-1 < p < '
'len(metacontact))')
# Append the contact. (position -1 means at the end)
contacts = list(metacontact)
if position < 0: contacts.append(contact)
else: contacts.insert(position, contact)
info('contact order for dialog: %r', contacts)
title = _('Merge Contacts')
return cls(parent, contacts, metacontact, title = title)
def on_save(self, e):
self.SetReturnCode(wx.ID_SAVE)
if self.IsModal():
self.EndModal(wx.ID_SAVE)
def get_info(self):
return self.mc_panel.get_info()
def Prompt(self, ondone = None):
if wx.ID_SAVE == self.ShowModal():
result = self.mc_panel.commit()
if ondone: ondone(result)
| 32.57716 | 132 | 0.628517 |
acec75fa58d5c3f4bb4db88fc16772b71cf6ed18 | 270 | py | Python | tests/artificial/transf_Logit/trend_ConstantTrend/cycle_12/ar_12/test_artificial_32_Logit_ConstantTrend_12_12_20.py | jmabry/pyaf | afbc15a851a2445a7824bf255af612dc429265af | [
"BSD-3-Clause"
] | null | null | null | tests/artificial/transf_Logit/trend_ConstantTrend/cycle_12/ar_12/test_artificial_32_Logit_ConstantTrend_12_12_20.py | jmabry/pyaf | afbc15a851a2445a7824bf255af612dc429265af | [
"BSD-3-Clause"
] | 1 | 2019-11-30T23:39:38.000Z | 2019-12-01T04:34:35.000Z | tests/artificial/transf_Logit/trend_ConstantTrend/cycle_12/ar_12/test_artificial_32_Logit_ConstantTrend_12_12_20.py | jmabry/pyaf | afbc15a851a2445a7824bf255af612dc429265af | [
"BSD-3-Clause"
] | null | null | null | import pyaf.Bench.TS_datasets as tsds
import pyaf.tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "ConstantTrend", cycle_length = 12, transform = "Logit", sigma = 0.0, exog_count = 20, ar_order = 12); | 38.571429 | 165 | 0.733333 |
acec7708008ecc7b3ce44334e3c645653dd3e53a | 309 | py | Python | phm_start/setup.py | inomuh/phm_tools | 849de95081c5a3e9709697dfa1a9c9bea6c0ef99 | [
"Apache-2.0"
] | 12 | 2019-09-20T16:45:07.000Z | 2022-03-16T00:21:59.000Z | phm_start/setup.py | inomuh/phm_tools | 849de95081c5a3e9709697dfa1a9c9bea6c0ef99 | [
"Apache-2.0"
] | null | null | null | phm_start/setup.py | inomuh/phm_tools | 849de95081c5a3e9709697dfa1a9c9bea6c0ef99 | [
"Apache-2.0"
] | 6 | 2019-12-05T12:17:16.000Z | 2022-02-17T07:07:18.000Z | ## ! DO NOT MANUALLY INVOKE THIS setup.py, USE CATKIN INSTEAD
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
# fetch values from package.xml
setup_args = generate_distutils_setup(
packages=['phm_start'],
package_dir={'': 'src'},
)
setup(**setup_args)
| 23.769231 | 61 | 0.760518 |
acec77c98e9dde22241e1b4e2ec03f97e2bdf055 | 349 | py | Python | nlproar/explain/importance_measures/__init__.py | AndreasMadsen/nlp-roar-interpretability | ad30f756cd744dfb05d1b57de744c5ff60d9f20c | [
"MIT"
] | 17 | 2021-11-04T02:15:30.000Z | 2021-12-26T16:31:27.000Z | nlproar/explain/importance_measures/__init__.py | AndreasMadsen/nlp-roar-interpretability | ad30f756cd744dfb05d1b57de744c5ff60d9f20c | [
"MIT"
] | null | null | null | nlproar/explain/importance_measures/__init__.py | AndreasMadsen/nlp-roar-interpretability | ad30f756cd744dfb05d1b57de744c5ff60d9f20c | [
"MIT"
] | 1 | 2021-11-04T10:45:25.000Z | 2021-11-04T10:45:25.000Z |
from .attention import AttentionImportanceMeasure
from .gradient import GradientImportanceMeasure
from .integrated_gradient import IntegratedGradientImportanceMeasure
from .mutual_information import MutualInformationImportanceMeasure
from .random import RandomImportanceMeasure
from .input_times_gradient import InputTimesGradientImportanceMeasure
| 43.625 | 69 | 0.911175 |
acec78a445a987dd62ff83ab70e7da59167225b9 | 2,898 | py | Python | azure-mgmt-compute/azure/mgmt/compute/v2017_12_01/models/rolling_upgrade_status_info.py | v-Ajnava/azure-sdk-for-python | a1f6f80eb5869c5b710e8bfb66146546697e2a6f | [
"MIT"
] | 4 | 2016-06-17T23:25:29.000Z | 2022-03-30T22:37:45.000Z | azure-mgmt-compute/azure/mgmt/compute/v2017_12_01/models/rolling_upgrade_status_info.py | v-Ajnava/azure-sdk-for-python | a1f6f80eb5869c5b710e8bfb66146546697e2a6f | [
"MIT"
] | 2 | 2016-09-30T21:40:24.000Z | 2017-11-10T18:16:18.000Z | azure-mgmt-compute/azure/mgmt/compute/v2017_12_01/models/rolling_upgrade_status_info.py | v-Ajnava/azure-sdk-for-python | a1f6f80eb5869c5b710e8bfb66146546697e2a6f | [
"MIT"
] | 3 | 2016-05-03T20:49:46.000Z | 2017-10-05T21:05:27.000Z | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .resource import Resource
class RollingUpgradeStatusInfo(Resource):
"""The status of the latest virtual machine scale set rolling upgrade.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Resource Id
:vartype id: str
:ivar name: Resource name
:vartype name: str
:ivar type: Resource type
:vartype type: str
:param location: Resource location
:type location: str
:param tags: Resource tags
:type tags: dict[str, str]
:ivar policy: The rolling upgrade policies applied for this upgrade.
:vartype policy:
~azure.mgmt.compute.v2017_12_01.models.RollingUpgradePolicy
:ivar running_status: Information about the current running state of the
overall upgrade.
:vartype running_status:
~azure.mgmt.compute.v2017_12_01.models.RollingUpgradeRunningStatus
:ivar progress: Information about the number of virtual machine instances
in each upgrade state.
:vartype progress:
~azure.mgmt.compute.v2017_12_01.models.RollingUpgradeProgressInfo
:ivar error: Error details for this upgrade, if there are any.
:vartype error: ~azure.mgmt.compute.v2017_12_01.models.ApiError
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'location': {'required': True},
'policy': {'readonly': True},
'running_status': {'readonly': True},
'progress': {'readonly': True},
'error': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'policy': {'key': 'properties.policy', 'type': 'RollingUpgradePolicy'},
'running_status': {'key': 'properties.runningStatus', 'type': 'RollingUpgradeRunningStatus'},
'progress': {'key': 'properties.progress', 'type': 'RollingUpgradeProgressInfo'},
'error': {'key': 'properties.error', 'type': 'ApiError'},
}
def __init__(self, location, tags=None):
super(RollingUpgradeStatusInfo, self).__init__(location=location, tags=tags)
self.policy = None
self.running_status = None
self.progress = None
self.error = None
| 38.64 | 101 | 0.617322 |
acec798784771f8bbbe25a5240dbf4e5e263dce1 | 6,918 | py | Python | installer/core/kernel.py | Diffblue-benchmarks/pacbot | 4709eb11f87636bc42a52e7a76b740f9d76d156d | [
"Apache-2.0"
] | 1,165 | 2018-10-05T19:07:34.000Z | 2022-03-28T19:34:27.000Z | installer/core/kernel.py | Diffblue-benchmarks/pacbot | 4709eb11f87636bc42a52e7a76b740f9d76d156d | [
"Apache-2.0"
] | 334 | 2018-10-10T14:00:41.000Z | 2022-03-19T16:32:08.000Z | installer/core/kernel.py | Diffblue-benchmarks/pacbot | 4709eb11f87636bc42a52e7a76b740f9d76d156d | [
"Apache-2.0"
] | 268 | 2018-10-05T19:53:25.000Z | 2022-03-31T07:39:47.000Z | from core.command import Command
from core.config import Settings
from core.mixins import MsgMixin
from core.providers import Provider
from core.log import SysLog
from core.utils import run_command, exists_teraform_lock
from core import constants as K
import importlib
import sys
class Executor(MsgMixin):
"""
This executes the the command which is provided in the CLI
"""
def execute(self, command_class_instance):
"""
Initialize and execute the command using the command class object
Args:
command_class_instance (Command obj): This object is decides the logic behind running the command
"""
self.initialize()
self.execute_command(command_class_instance)
def initialize(self):
pass
def execute_command(self, command_class_instance):
"""
Execute the command using the command class object
Args:
command_class_instance (Command obj): This object is decides the logic behind running the command
"""
command_class_instance.execute(self.provider)
def do_pre_requisite_check(self):
"""
Before the execution starts, it checks for the pre-requisite. It would return either true or false
Returns:
Boolean: If the pre-requisite check passes then returns True else False
"""
if self.is_another_process_running():
return False
if self._check_tools_are_available() and self._check_python_packages_are_available():
if self.is_another_process_running():
return False
return True
return False
def is_another_process_running(self):
"""
This method checks whether another Command is running currently
Returns:
Boolean: If another process is running then it returns True else False
"""
if exists_teraform_lock():
self.warn_another_process_running()
return True
return False
def _check_tools_are_available(self):
"""
Based on the settings variable TOOLS_REQUIRED, this method do validate all the tools
Returns:
Boolean: Return True if all tools are available else False
"""
self.show_step_heading(K.TOOLS_CHECK_STARTED)
tools_required = Settings.TOOLS_REQUIRED
tools_available = True
for tool_name, command in tools_required.items():
error, msg, errmsg = run_command(command)
display_message = "Tool: %s, checking" % tool_name
status = K.NOT_FOUND if error or errmsg else K.FOUND
tools_available = False if error or errmsg else tools_available
self.show_step_inner_messaage(display_message, status, errmsg)
if not tools_available:
self.show_step_finish(K.ALL_TOOLS_NOT_AVAIALABLE, color=self.ERROR_ANSI)
return False
self.show_step_finish(K.TOOLS_CHECK_COMPLETED, color=self.GREEN_ANSI)
return True
def _check_python_packages_are_available(self):
"""
Based on the settings variable PYTHON_PACKAGES_REQUIRED, this method do validate all the python packages
Returns:
Boolean: Return True if all python packages are available else False
"""
self.show_step_heading(K.PIP_CHECK_STARTED)
error = False
for item in Settings.PYTHON_PACKAGES_REQUIRED:
success, err_msg = self._module_available(item)
status_msg = K.FOUND if success else K.NOT_FOUND
if not success:
error = True
display_msg = "Package: %s, Module: %s" % (item[0], item[1]) if type(item) is tuple else "Module: %s" % item
display_msg += ", checking"
self.show_step_inner_messaage(display_msg, status_msg, err_msg)
if error:
self.show_step_finish(K.PIP_INSTALL_MSG, color=self.ERROR_ANSI)
return False
self.show_step_finish(K.PIP_CHECK_COMPLETED, color=self.GREEN_ANSI)
return True
def _module_available(self, item):
"""
Based on the settings variable PYTHON_PACKAGES_REQUIRED, this method do validate all the python modules inside a package
Returns:
Boolean: Return True if all python modules are available else False
"""
module_name = item
try:
if type(item) is tuple:
module_name = item[0]
module = importlib.import_module(item[0])
if item[1] not in dir(module):
return False, "%s package doesn't have %s, " % item
else:
importlib.import_module(item)
except:
return False, None
return True, None
class Kernel(Command, Executor):
"""
Kernel module where the actual execution begins. Here system validation is done and settings/configurations are loaded.
Starts running command if everything is successful
Attributes:
provider (Provider obj): The provider object which can be AWS, Azure etc
"""
errors = []
def __init__(self, config_path):
"""
Constructor for the Kernel class, which do system validations and initialises Object attributes
Args:
config_path (str): This is the path to the main configuration/settings file
"""
self.load_settings(config_path)
provider_name = Settings.get('PROVIDER', None)
self.provider = Provider(provider_name)
self.do_system_validation()
super().__init__()
def do_system_validation(self):
"""Here the check for valid provider is done and passes the check if it is validelse exit the execution"""
if not self.provider.valid:
self.exit_with_provider_not_found()
def run(self, sys_args):
"""
Actual execution of the command is started from here
Args:
sys_args (dict): CLI Arguments supplied to the command
"""
self.show_loading_messsage()
Settings.set('running_command', ' '.join(sys_args))
try:
SysLog().debug_started(Settings.running_command)
if self.do_pre_requisite_check():
command_class_instance = self.get_command_class_instance(sys_args) # Get the command list and optional commands
self.execute(command_class_instance)
except Exception as e:
self.show_step_inner_error("Error occured, please check error log for more details")
SysLog().write_error_log(str(e))
def load_settings(self, config_path):
"""
Load all the main and local configurations into the system
Args:
config_path (str): This is the path to the main configuration/settings file
"""
Settings.load_setings(config_path)
| 35.476923 | 128 | 0.648598 |
acec79b3e7d336a98d878b5d18a58344013c9808 | 6,120 | py | Python | piccolo/apps/migrations/commands/backwards.py | antonio-one/piccolo | fd72c6064188a4139238cf70b416a0b3862e0da0 | [
"MIT"
] | 1 | 2021-08-22T03:29:08.000Z | 2021-08-22T03:29:08.000Z | piccolo/apps/migrations/commands/backwards.py | tonybaloney/piccolo | 61f2738996c7abe150ea1626ad352c576fe9b992 | [
"MIT"
] | null | null | null | piccolo/apps/migrations/commands/backwards.py | tonybaloney/piccolo | 61f2738996c7abe150ea1626ad352c576fe9b992 | [
"MIT"
] | null | null | null | from __future__ import annotations
import os
import sys
from piccolo.apps.migrations.auto import MigrationManager
from piccolo.apps.migrations.commands.base import (
BaseMigrationManager,
MigrationResult,
)
from piccolo.apps.migrations.tables import Migration
class BackwardsMigrationManager(BaseMigrationManager):
def __init__(
self,
app_name: str,
migration_id: str,
auto_agree: bool = False,
clean: bool = False,
):
self.migration_id = migration_id
self.app_name = app_name
self.auto_agree = auto_agree
self.clean = clean
super().__init__()
async def run(self) -> MigrationResult:
await self.create_migration_table()
app_modules = self.get_app_modules()
migration_modules = {}
for app_module in app_modules:
app_config = getattr(app_module, "APP_CONFIG")
if app_config.app_name == self.app_name:
migration_modules = self.get_migration_modules(
app_config.migrations_folder_path
)
break
ran_migration_ids = await Migration.get_migrations_which_ran(
app_name=self.app_name
)
if len(ran_migration_ids) == 0:
# Make sure a success is returned, as we don't want this
# to appear as an error in automated scripts.
message = "No migrations to reverse!"
print(message)
return MigrationResult(success=True, message=message)
#######################################################################
if self.migration_id == "all":
earliest_migration_id = ran_migration_ids[0]
elif self.migration_id == "1":
earliest_migration_id = ran_migration_ids[-1]
else:
earliest_migration_id = self.migration_id
if earliest_migration_id not in ran_migration_ids:
message = (
"Unrecognized migration name - must be one of "
f"{ran_migration_ids}"
)
print(message, file=sys.stderr)
return MigrationResult(success=False, message=message)
#######################################################################
latest_migration_id = ran_migration_ids[-1]
start_index = ran_migration_ids.index(earliest_migration_id)
end_index = ran_migration_ids.index(latest_migration_id) + 1
subset = ran_migration_ids[start_index:end_index]
reversed_migration_ids = list(reversed(subset))
#######################################################################
_continue = (
"y"
if self.auto_agree
else input(
"About to undo the following migrations:\n"
f"{reversed_migration_ids}\n"
"Enter y to continue.\n"
)
)
if _continue == "y":
print("Undoing migrations")
for migration_id in reversed_migration_ids:
print(f"Reversing {migration_id}")
migration_module = migration_modules[migration_id]
response = await migration_module.forwards()
if isinstance(response, MigrationManager):
await response.run_backwards()
await Migration.delete().where(
Migration.name == migration_id
).run()
if self.clean:
os.unlink(migration_module.__file__)
return MigrationResult(success=True)
else: # pragma: no cover
message = "Not proceeding."
print(message, file=sys.stderr)
return MigrationResult(success=False, message=message)
async def run_backwards(
app_name: str,
migration_id: str = "1",
auto_agree: bool = False,
clean: bool = False,
) -> MigrationResult:
if app_name == "all":
sorted_app_names = BaseMigrationManager().get_sorted_app_names()
sorted_app_names.reverse()
_continue = (
"y"
if auto_agree
else input(
"You're about to undo the migrations for the following apps:\n"
f"{sorted_app_names}\n"
"Are you sure you want to continue?\n"
"Enter y to continue.\n"
)
)
if _continue == "y":
for _app_name in sorted_app_names:
print(f"Undoing {_app_name}")
manager = BackwardsMigrationManager(
app_name=_app_name,
migration_id="all",
auto_agree=auto_agree,
)
await manager.run()
return MigrationResult(success=True)
else:
return MigrationResult(success=False, message="User cancelled")
else:
manager = BackwardsMigrationManager(
app_name=app_name,
migration_id=migration_id,
auto_agree=auto_agree,
clean=clean,
)
return await manager.run()
async def backwards(
app_name: str,
migration_id: str = "1",
auto_agree: bool = False,
clean: bool = False,
):
"""
Undo migrations up to a specific migration.
:param app_name:
The app to reverse migrations for. Specify a value of 'all' to reverse
migrations for all apps.
:param migration_id:
Migrations will be reversed up to and including this migration_id.
Specify a value of 'all' to undo all of the migrations. Specify a
value of '1' to undo the most recent migration.
:param auto_agree:
If true, automatically agree to any input prompts.
:param clean:
If true, the migration files which have been run backwards are deleted
from the disk after completing.
"""
response = await run_backwards(
app_name=app_name,
migration_id=migration_id,
auto_agree=auto_agree,
clean=clean,
)
if not response.success:
sys.exit(1)
| 32.041885 | 79 | 0.569935 |
acec79c103bf85e2d4929c4a46c9d49cd2c7f1d0 | 48,810 | py | Python | mypy/server/deps.py | anmolrajsoni15/mypy | 94059440a208b1d9b24dc5c621f3bfc96ce1741b | [
"PSF-2.0"
] | 1 | 2022-01-22T13:08:05.000Z | 2022-01-22T13:08:05.000Z | mypy/server/deps.py | anmolrajsoni15/mypy | 94059440a208b1d9b24dc5c621f3bfc96ce1741b | [
"PSF-2.0"
] | null | null | null | mypy/server/deps.py | anmolrajsoni15/mypy | 94059440a208b1d9b24dc5c621f3bfc96ce1741b | [
"PSF-2.0"
] | null | null | null | """Generate fine-grained dependencies for AST nodes, for use in the daemon mode.
Dependencies are stored in a map from *triggers* to *sets of affected locations*.
A trigger is a string that represents a program property that has changed, such
as the signature of a specific function. Triggers are written as '<...>' (angle
brackets). When a program property changes, we determine the relevant trigger(s)
and all affected locations. The latter are stale and will have to be reprocessed.
An affected location is a string than can refer to a *target* (a non-nested
function or method, or a module top level), a class, or a trigger (for
recursively triggering other triggers).
Here's an example representation of a simple dependency map (in format
"<trigger> -> locations"):
<m.A.g> -> m.f
<m.A> -> <m.f>, m.A, m.f
Assuming 'A' is a class, this means that
1) if a property of 'm.A.g', such as the signature, is changed, we need
to process target (function) 'm.f'
2) if the MRO or other significant property of class 'm.A' changes, we
need to process target 'm.f', the entire class 'm.A', and locations
triggered by trigger '<m.f>' (this explanation is a bit simplified;
see below for more details).
The triggers to fire are determined using mypy.server.astdiff.
Examples of triggers:
* '<mod.x>' represents a module attribute/function/class. If any externally
visible property of 'x' changes, this gets fired. For changes within
classes, only "big" changes cause the class to be triggered (such as a
change in MRO). Smaller changes, such as changes to some attributes, don't
trigger the entire class.
* '<mod.Cls.x>' represents the type and kind of attribute/method 'x' of
class 'mod.Cls'. This can also refer to an attribute inherited from a
base class (relevant if it's accessed through a value of type 'Cls'
instead of the base class type).
* '<package.mod>' represents the existence of module 'package.mod'. This
gets triggered if 'package.mod' is created or deleted, or if it gets
changed into something other than a module.
Examples of locations:
* 'mod' is the top level of module 'mod' (doesn't include any function bodies,
but includes class bodies not nested within a function).
* 'mod.f' is function 'f' in module 'mod' (module-level variables aren't separate
locations but are included in the module top level). Functions also include
any nested functions and classes -- such nested definitions aren't separate
locations, for simplicity of implementation.
* 'mod.Cls.f' is method 'f' of 'mod.Cls'. Non-method attributes aren't locations.
* 'mod.Cls' represents each method in class 'mod.Cls' + the top-level of the
module 'mod'. (To simplify the implementation, there is no location that only
includes the body of a class without the entire surrounding module top level.)
* Trigger '<...>' as a location is an indirect way of referring to to all
locations triggered by the trigger. These indirect locations keep the
dependency map smaller and easier to manage.
Triggers can be triggered by program changes such as these:
* Addition or deletion of an attribute (or module).
* Change of the kind of thing a name represents (such as a change from a function
to a class).
* Change of the static type of a name.
Changes in the body of a function that aren't reflected in the signature don't
cause the function to be triggered. More generally, we trigger only on changes
that may affect type checking results outside the module that contains the
change.
We don't generate dependencies from builtins and certain other stdlib modules,
since these change very rarely, and they would just increase the size of the
dependency map significantly without significant benefit.
Test cases for this module live in 'test-data/unit/deps*.test'.
"""
from typing import Dict, List, Set, Optional, Tuple
from typing_extensions import DefaultDict
from mypy.checkmember import bind_self
from mypy.nodes import (
Node, Expression, MypyFile, FuncDef, ClassDef, AssignmentStmt, NameExpr, MemberExpr, Import,
ImportFrom, CallExpr, CastExpr, TypeVarExpr, TypeApplication, IndexExpr, UnaryExpr, OpExpr,
ComparisonExpr, GeneratorExpr, DictionaryComprehension, StarExpr, PrintStmt, ForStmt, WithStmt,
TupleExpr, OperatorAssignmentStmt, DelStmt, YieldFromExpr, Decorator, Block,
TypeInfo, FuncBase, OverloadedFuncDef, RefExpr, SuperExpr, Var, NamedTupleExpr, TypedDictExpr,
LDEF, MDEF, GDEF, TypeAliasExpr, NewTypeExpr, ImportAll, EnumCallExpr, AwaitExpr
)
from mypy.operators import (
op_methods, reverse_op_methods, ops_with_inplace_method, unary_op_methods
)
from mypy.traverser import TraverserVisitor
from mypy.types import (
Type, Instance, AnyType, NoneType, TypeVisitor, CallableType, DeletedType, PartialType,
TupleType, TypeType, TypeVarType, TypedDictType, UnboundType, UninhabitedType, UnionType,
FunctionLike, Overloaded, TypeOfAny, LiteralType, ErasedType, get_proper_type, ProperType,
TypeAliasType, ParamSpecType
)
from mypy.server.trigger import make_trigger, make_wildcard_trigger
from mypy.util import correct_relative_import
from mypy.scope import Scope
from mypy.typestate import TypeState
from mypy.options import Options
def get_dependencies(target: MypyFile,
type_map: Dict[Expression, Type],
python_version: Tuple[int, int],
options: Options) -> Dict[str, Set[str]]:
"""Get all dependencies of a node, recursively."""
visitor = DependencyVisitor(type_map, python_version, target.alias_deps, options)
target.accept(visitor)
return visitor.map
def get_dependencies_of_target(module_id: str,
module_tree: MypyFile,
target: Node,
type_map: Dict[Expression, Type],
python_version: Tuple[int, int]) -> Dict[str, Set[str]]:
"""Get dependencies of a target -- don't recursive into nested targets."""
# TODO: Add tests for this function.
visitor = DependencyVisitor(type_map, python_version, module_tree.alias_deps)
with visitor.scope.module_scope(module_id):
if isinstance(target, MypyFile):
# Only get dependencies of the top-level of the module. Don't recurse into
# functions.
for defn in target.defs:
# TODO: Recurse into top-level statements and class bodies but skip functions.
if not isinstance(defn, (ClassDef, Decorator, FuncDef, OverloadedFuncDef)):
defn.accept(visitor)
elif isinstance(target, FuncBase) and target.info:
# It's a method.
# TODO: Methods in nested classes.
with visitor.scope.class_scope(target.info):
target.accept(visitor)
else:
target.accept(visitor)
return visitor.map
class DependencyVisitor(TraverserVisitor):
def __init__(self,
type_map: Dict[Expression, Type],
python_version: Tuple[int, int],
alias_deps: 'DefaultDict[str, Set[str]]',
options: Optional[Options] = None) -> None:
self.scope = Scope()
self.type_map = type_map
self.python2 = python_version[0] == 2
# This attribute holds a mapping from target to names of type aliases
# it depends on. These need to be processed specially, since they are
# only present in expanded form in symbol tables. For example, after:
# A = List[int]
# x: A
# The module symbol table will just have a Var `x` with type `List[int]`,
# and the dependency of `x` on `A` is lost. Therefore the alias dependencies
# are preserved at alias expansion points in `semanal.py`, stored as an attribute
# on MypyFile, and then passed here.
self.alias_deps = alias_deps
self.map: Dict[str, Set[str]] = {}
self.is_class = False
self.is_package_init_file = False
self.options = options
def visit_mypy_file(self, o: MypyFile) -> None:
with self.scope.module_scope(o.fullname):
self.is_package_init_file = o.is_package_init_file()
self.add_type_alias_deps(self.scope.current_target())
for trigger, targets in o.plugin_deps.items():
self.map.setdefault(trigger, set()).update(targets)
super().visit_mypy_file(o)
def visit_func_def(self, o: FuncDef) -> None:
with self.scope.function_scope(o):
target = self.scope.current_target()
if o.type:
if self.is_class and isinstance(o.type, FunctionLike):
signature: Type = bind_self(o.type)
else:
signature = o.type
for trigger in self.get_type_triggers(signature):
self.add_dependency(trigger)
self.add_dependency(trigger, target=make_trigger(target))
if o.info:
for base in non_trivial_bases(o.info):
# Base class __init__/__new__ doesn't generate a logical
# dependency since the override can be incompatible.
if not self.use_logical_deps() or o.name not in ('__init__', '__new__'):
self.add_dependency(make_trigger(base.fullname + '.' + o.name))
self.add_type_alias_deps(self.scope.current_target())
super().visit_func_def(o)
variants = set(o.expanded) - {o}
for ex in variants:
if isinstance(ex, FuncDef):
super().visit_func_def(ex)
def visit_decorator(self, o: Decorator) -> None:
if not self.use_logical_deps():
# We don't need to recheck outer scope for an overload, only overload itself.
# Also if any decorator is nested, it is not externally visible, so we don't need to
# generate dependency.
if not o.func.is_overload and self.scope.current_function_name() is None:
self.add_dependency(make_trigger(o.func.fullname))
else:
# Add logical dependencies from decorators to the function. For example,
# if we have
# @dec
# def func(): ...
# then if `dec` is unannotated, then it will "spoil" `func` and consequently
# all call sites, making them all `Any`.
for d in o.decorators:
tname: Optional[str] = None
if isinstance(d, RefExpr) and d.fullname is not None:
tname = d.fullname
if (isinstance(d, CallExpr) and isinstance(d.callee, RefExpr) and
d.callee.fullname is not None):
tname = d.callee.fullname
if tname is not None:
self.add_dependency(make_trigger(tname), make_trigger(o.func.fullname))
super().visit_decorator(o)
def visit_class_def(self, o: ClassDef) -> None:
with self.scope.class_scope(o.info):
target = self.scope.current_full_target()
self.add_dependency(make_trigger(target), target)
old_is_class = self.is_class
self.is_class = True
# Add dependencies to type variables of a generic class.
for tv in o.type_vars:
self.add_dependency(make_trigger(tv.fullname), target)
self.process_type_info(o.info)
super().visit_class_def(o)
self.is_class = old_is_class
def visit_newtype_expr(self, o: NewTypeExpr) -> None:
if o.info:
with self.scope.class_scope(o.info):
self.process_type_info(o.info)
def process_type_info(self, info: TypeInfo) -> None:
target = self.scope.current_full_target()
for base in info.bases:
self.add_type_dependencies(base, target=target)
if info.tuple_type:
self.add_type_dependencies(info.tuple_type, target=make_trigger(target))
if info.typeddict_type:
self.add_type_dependencies(info.typeddict_type, target=make_trigger(target))
if info.declared_metaclass:
self.add_type_dependencies(info.declared_metaclass, target=make_trigger(target))
if info.is_protocol:
for base_info in info.mro[:-1]:
# We add dependencies from whole MRO to cover explicit subprotocols.
# For example:
#
# class Super(Protocol):
# x: int
# class Sub(Super, Protocol):
# y: int
#
# In this example we add <Super[wildcard]> -> <Sub>, to invalidate Sub if
# a new member is added to Super.
self.add_dependency(make_wildcard_trigger(base_info.fullname),
target=make_trigger(target))
# More protocol dependencies are collected in TypeState._snapshot_protocol_deps
# after a full run or update is finished.
self.add_type_alias_deps(self.scope.current_target())
for name, node in info.names.items():
if isinstance(node.node, Var):
# Recheck Liskov if needed, self definitions are checked in the defining method
if node.node.is_initialized_in_class and has_user_bases(info):
self.add_dependency(make_trigger(info.fullname + '.' + name))
for base_info in non_trivial_bases(info):
# If the type of an attribute changes in a base class, we make references
# to the attribute in the subclass stale.
self.add_dependency(make_trigger(base_info.fullname + '.' + name),
target=make_trigger(info.fullname + '.' + name))
for base_info in non_trivial_bases(info):
for name, node in base_info.names.items():
if self.use_logical_deps():
# Skip logical dependency if an attribute is not overridden. For example,
# in case of:
# class Base:
# x = 1
# y = 2
# class Sub(Base):
# x = 3
# we skip <Base.y> -> <Child.y>, because even if `y` is unannotated it
# doesn't affect precision of Liskov checking.
if name not in info.names:
continue
# __init__ and __new__ can be overridden with different signatures, so no
# logical dependency.
if name in ('__init__', '__new__'):
continue
self.add_dependency(make_trigger(base_info.fullname + '.' + name),
target=make_trigger(info.fullname + '.' + name))
if not self.use_logical_deps():
# These dependencies are only useful for propagating changes --
# they aren't logical dependencies since __init__ and __new__ can be
# overridden with a different signature.
self.add_dependency(make_trigger(base_info.fullname + '.__init__'),
target=make_trigger(info.fullname + '.__init__'))
self.add_dependency(make_trigger(base_info.fullname + '.__new__'),
target=make_trigger(info.fullname + '.__new__'))
# If the set of abstract attributes change, this may invalidate class
# instantiation, or change the generated error message, since Python checks
# class abstract status when creating an instance.
self.add_dependency(make_trigger(base_info.fullname + '.(abstract)'),
target=make_trigger(info.fullname + '.__init__'))
# If the base class abstract attributes change, subclass abstract
# attributes need to be recalculated.
self.add_dependency(make_trigger(base_info.fullname + '.(abstract)'))
def visit_import(self, o: Import) -> None:
for id, as_id in o.ids:
self.add_dependency(make_trigger(id), self.scope.current_target())
def visit_import_from(self, o: ImportFrom) -> None:
if self.use_logical_deps():
# Just importing a name doesn't create a logical dependency.
return
module_id, _ = correct_relative_import(self.scope.current_module_id(),
o.relative,
o.id,
self.is_package_init_file)
self.add_dependency(make_trigger(module_id)) # needed if module is added/removed
for name, as_name in o.names:
self.add_dependency(make_trigger(module_id + '.' + name))
def visit_import_all(self, o: ImportAll) -> None:
module_id, _ = correct_relative_import(self.scope.current_module_id(),
o.relative,
o.id,
self.is_package_init_file)
# The current target needs to be rechecked if anything "significant" changes in the
# target module namespace (as the imported definitions will need to be updated).
self.add_dependency(make_wildcard_trigger(module_id))
def visit_block(self, o: Block) -> None:
if not o.is_unreachable:
super().visit_block(o)
def visit_assignment_stmt(self, o: AssignmentStmt) -> None:
rvalue = o.rvalue
if isinstance(rvalue, CallExpr) and isinstance(rvalue.analyzed, TypeVarExpr):
analyzed = rvalue.analyzed
self.add_type_dependencies(analyzed.upper_bound,
target=make_trigger(analyzed.fullname))
for val in analyzed.values:
self.add_type_dependencies(val, target=make_trigger(analyzed.fullname))
# We need to re-analyze the definition if bound or value is deleted.
super().visit_call_expr(rvalue)
elif isinstance(rvalue, CallExpr) and isinstance(rvalue.analyzed, NamedTupleExpr):
# Depend on types of named tuple items.
info = rvalue.analyzed.info
prefix = '%s.%s' % (self.scope.current_full_target(), info.name)
for name, symnode in info.names.items():
if not name.startswith('_') and isinstance(symnode.node, Var):
typ = symnode.node.type
if typ:
self.add_type_dependencies(typ)
self.add_type_dependencies(typ, target=make_trigger(prefix))
attr_target = make_trigger('%s.%s' % (prefix, name))
self.add_type_dependencies(typ, target=attr_target)
elif isinstance(rvalue, CallExpr) and isinstance(rvalue.analyzed, TypedDictExpr):
# Depend on the underlying typeddict type
info = rvalue.analyzed.info
assert info.typeddict_type is not None
prefix = '%s.%s' % (self.scope.current_full_target(), info.name)
self.add_type_dependencies(info.typeddict_type, target=make_trigger(prefix))
elif isinstance(rvalue, CallExpr) and isinstance(rvalue.analyzed, EnumCallExpr):
# Enum values are currently not checked, but for future we add the deps on them
for name, symnode in rvalue.analyzed.info.names.items():
if isinstance(symnode.node, Var) and symnode.node.type:
self.add_type_dependencies(symnode.node.type)
elif o.is_alias_def:
assert len(o.lvalues) == 1
lvalue = o.lvalues[0]
assert isinstance(lvalue, NameExpr)
typ = get_proper_type(self.type_map.get(lvalue))
if isinstance(typ, FunctionLike) and typ.is_type_obj():
class_name = typ.type_object().fullname
self.add_dependency(make_trigger(class_name + '.__init__'))
self.add_dependency(make_trigger(class_name + '.__new__'))
if isinstance(rvalue, IndexExpr) and isinstance(rvalue.analyzed, TypeAliasExpr):
self.add_type_dependencies(rvalue.analyzed.type)
elif typ:
self.add_type_dependencies(typ)
else:
# Normal assignment
super().visit_assignment_stmt(o)
for lvalue in o.lvalues:
self.process_lvalue(lvalue)
items = o.lvalues + [rvalue]
for i in range(len(items) - 1):
lvalue = items[i]
rvalue = items[i + 1]
if isinstance(lvalue, TupleExpr):
self.add_attribute_dependency_for_expr(rvalue, '__iter__')
if o.type:
self.add_type_dependencies(o.type)
if self.use_logical_deps() and o.unanalyzed_type is None:
# Special case: for definitions without an explicit type like this:
# x = func(...)
# we add a logical dependency <func> -> <x>, because if `func` is not annotated,
# then it will make all points of use of `x` unchecked.
if (isinstance(rvalue, CallExpr) and isinstance(rvalue.callee, RefExpr)
and rvalue.callee.fullname is not None):
fname: Optional[str] = None
if isinstance(rvalue.callee.node, TypeInfo):
# use actual __init__ as a dependency source
init = rvalue.callee.node.get('__init__')
if init and isinstance(init.node, FuncBase):
fname = init.node.fullname
else:
fname = rvalue.callee.fullname
if fname is None:
return
for lv in o.lvalues:
if isinstance(lv, RefExpr) and lv.fullname and lv.is_new_def:
if lv.kind == LDEF:
return # local definitions don't generate logical deps
self.add_dependency(make_trigger(fname), make_trigger(lv.fullname))
def process_lvalue(self, lvalue: Expression) -> None:
"""Generate additional dependencies for an lvalue."""
if isinstance(lvalue, IndexExpr):
self.add_operator_method_dependency(lvalue.base, '__setitem__')
elif isinstance(lvalue, NameExpr):
if lvalue.kind in (MDEF, GDEF):
# Assignment to an attribute in the class body, or direct assignment to a
# global variable.
lvalue_type = self.get_non_partial_lvalue_type(lvalue)
type_triggers = self.get_type_triggers(lvalue_type)
attr_trigger = make_trigger('%s.%s' % (self.scope.current_full_target(),
lvalue.name))
for type_trigger in type_triggers:
self.add_dependency(type_trigger, attr_trigger)
elif isinstance(lvalue, MemberExpr):
if self.is_self_member_ref(lvalue) and lvalue.is_new_def:
node = lvalue.node
if isinstance(node, Var):
info = node.info
if info and has_user_bases(info):
# Recheck Liskov for self definitions
self.add_dependency(make_trigger(info.fullname + '.' + lvalue.name))
if lvalue.kind is None:
# Reference to a non-module attribute
if lvalue.expr not in self.type_map:
# Unreachable assignment -> not checked so no dependencies to generate.
return
object_type = self.type_map[lvalue.expr]
lvalue_type = self.get_non_partial_lvalue_type(lvalue)
type_triggers = self.get_type_triggers(lvalue_type)
for attr_trigger in self.attribute_triggers(object_type, lvalue.name):
for type_trigger in type_triggers:
self.add_dependency(type_trigger, attr_trigger)
elif isinstance(lvalue, TupleExpr):
for item in lvalue.items:
self.process_lvalue(item)
elif isinstance(lvalue, StarExpr):
self.process_lvalue(lvalue.expr)
def is_self_member_ref(self, memberexpr: MemberExpr) -> bool:
"""Does memberexpr to refer to an attribute of self?"""
if not isinstance(memberexpr.expr, NameExpr):
return False
node = memberexpr.expr.node
return isinstance(node, Var) and node.is_self
def get_non_partial_lvalue_type(self, lvalue: RefExpr) -> Type:
if lvalue not in self.type_map:
# Likely a block considered unreachable during type checking.
return UninhabitedType()
lvalue_type = get_proper_type(self.type_map[lvalue])
if isinstance(lvalue_type, PartialType):
if isinstance(lvalue.node, Var) and lvalue.node.type:
lvalue_type = get_proper_type(lvalue.node.type)
else:
# Probably a secondary, non-definition assignment that doesn't
# result in a non-partial type. We won't be able to infer any
# dependencies from this so just return something. (The first,
# definition assignment with a partial type is handled
# differently, in the semantic analyzer.)
assert not lvalue.is_new_def
return UninhabitedType()
return lvalue_type
def visit_operator_assignment_stmt(self, o: OperatorAssignmentStmt) -> None:
super().visit_operator_assignment_stmt(o)
self.process_lvalue(o.lvalue)
method = op_methods[o.op]
self.add_attribute_dependency_for_expr(o.lvalue, method)
if o.op in ops_with_inplace_method:
inplace_method = '__i' + method[2:]
self.add_attribute_dependency_for_expr(o.lvalue, inplace_method)
def visit_for_stmt(self, o: ForStmt) -> None:
super().visit_for_stmt(o)
if not o.is_async:
# __getitem__ is only used if __iter__ is missing but for simplicity we
# just always depend on both.
self.add_attribute_dependency_for_expr(o.expr, '__iter__')
self.add_attribute_dependency_for_expr(o.expr, '__getitem__')
if o.inferred_iterator_type:
if self.python2:
method = 'next'
else:
method = '__next__'
self.add_attribute_dependency(o.inferred_iterator_type, method)
else:
self.add_attribute_dependency_for_expr(o.expr, '__aiter__')
if o.inferred_iterator_type:
self.add_attribute_dependency(o.inferred_iterator_type, '__anext__')
self.process_lvalue(o.index)
if isinstance(o.index, TupleExpr):
# Process multiple assignment to index variables.
item_type = o.inferred_item_type
if item_type:
# This is similar to above.
self.add_attribute_dependency(item_type, '__iter__')
self.add_attribute_dependency(item_type, '__getitem__')
if o.index_type:
self.add_type_dependencies(o.index_type)
def visit_with_stmt(self, o: WithStmt) -> None:
super().visit_with_stmt(o)
for e in o.expr:
if not o.is_async:
self.add_attribute_dependency_for_expr(e, '__enter__')
self.add_attribute_dependency_for_expr(e, '__exit__')
else:
self.add_attribute_dependency_for_expr(e, '__aenter__')
self.add_attribute_dependency_for_expr(e, '__aexit__')
for typ in o.analyzed_types:
self.add_type_dependencies(typ)
def visit_print_stmt(self, o: PrintStmt) -> None:
super().visit_print_stmt(o)
if o.target:
self.add_attribute_dependency_for_expr(o.target, 'write')
def visit_del_stmt(self, o: DelStmt) -> None:
super().visit_del_stmt(o)
if isinstance(o.expr, IndexExpr):
self.add_attribute_dependency_for_expr(o.expr.base, '__delitem__')
# Expressions
def process_global_ref_expr(self, o: RefExpr) -> None:
if o.fullname is not None:
self.add_dependency(make_trigger(o.fullname))
# If this is a reference to a type, generate a dependency to its
# constructor.
# IDEA: Avoid generating spurious dependencies for except statements,
# class attribute references, etc., if performance is a problem.
typ = get_proper_type(self.type_map.get(o))
if isinstance(typ, FunctionLike) and typ.is_type_obj():
class_name = typ.type_object().fullname
self.add_dependency(make_trigger(class_name + '.__init__'))
self.add_dependency(make_trigger(class_name + '.__new__'))
def visit_name_expr(self, o: NameExpr) -> None:
if o.kind == LDEF:
# We don't track dependencies to local variables, since they
# aren't externally visible.
return
if o.kind == MDEF:
# Direct reference to member is only possible in the scope that
# defined the name, so no dependency is required.
return
self.process_global_ref_expr(o)
def visit_member_expr(self, e: MemberExpr) -> None:
if isinstance(e.expr, RefExpr) and isinstance(e.expr.node, TypeInfo):
# Special case class attribute so that we don't depend on "__init__".
self.add_dependency(make_trigger(e.expr.node.fullname))
else:
super().visit_member_expr(e)
if e.kind is not None:
# Reference to a module attribute
self.process_global_ref_expr(e)
else:
# Reference to a non-module (or missing) attribute
if e.expr not in self.type_map:
# No type available -- this happens for unreachable code. Since it's unreachable,
# it wasn't type checked and we don't need to generate dependencies.
return
if isinstance(e.expr, RefExpr) and isinstance(e.expr.node, MypyFile):
# Special case: reference to a missing module attribute.
self.add_dependency(make_trigger(e.expr.node.fullname + '.' + e.name))
return
typ = get_proper_type(self.type_map[e.expr])
self.add_attribute_dependency(typ, e.name)
if self.use_logical_deps() and isinstance(typ, AnyType):
name = self.get_unimported_fullname(e, typ)
if name is not None:
# Generate a logical dependency from an unimported
# definition (which comes from a missing module).
# Example:
# import missing # "missing" not in build
#
# def g() -> None:
# missing.f() # Generate dependency from "missing.f"
self.add_dependency(make_trigger(name))
def get_unimported_fullname(self, e: MemberExpr, typ: AnyType) -> Optional[str]:
"""If e refers to an unimported definition, infer the fullname of this.
Return None if e doesn't refer to an unimported definition or if we can't
determine the name.
"""
suffix = ''
# Unwrap nested member expression to handle cases like "a.b.c.d" where
# "a.b" is a known reference to an unimported module. Find the base
# reference to an unimported module (such as "a.b") and the name suffix
# (such as "c.d") needed to build a full name.
while typ.type_of_any == TypeOfAny.from_another_any and isinstance(e.expr, MemberExpr):
suffix = '.' + e.name + suffix
e = e.expr
if e.expr not in self.type_map:
return None
obj_type = get_proper_type(self.type_map[e.expr])
if not isinstance(obj_type, AnyType):
# Can't find the base reference to the unimported module.
return None
typ = obj_type
if typ.type_of_any == TypeOfAny.from_unimported_type and typ.missing_import_name:
# Infer the full name of the unimported definition.
return typ.missing_import_name + '.' + e.name + suffix
return None
def visit_super_expr(self, e: SuperExpr) -> None:
# Arguments in "super(C, self)" won't generate useful logical deps.
if not self.use_logical_deps():
super().visit_super_expr(e)
if e.info is not None:
name = e.name
for base in non_trivial_bases(e.info):
self.add_dependency(make_trigger(base.fullname + '.' + name))
if name in base.names:
# No need to depend on further base classes, since we found
# the target. This is safe since if the target gets
# deleted or modified, we'll trigger it.
break
def visit_call_expr(self, e: CallExpr) -> None:
if isinstance(e.callee, RefExpr) and e.callee.fullname == 'builtins.isinstance':
self.process_isinstance_call(e)
else:
super().visit_call_expr(e)
typ = self.type_map.get(e.callee)
if typ is not None:
typ = get_proper_type(typ)
if not isinstance(typ, FunctionLike):
self.add_attribute_dependency(typ, '__call__')
def process_isinstance_call(self, e: CallExpr) -> None:
"""Process "isinstance(...)" in a way to avoid some extra dependencies."""
if len(e.args) == 2:
arg = e.args[1]
if (isinstance(arg, RefExpr)
and arg.kind == GDEF
and isinstance(arg.node, TypeInfo)
and arg.fullname):
# Special case to avoid redundant dependencies from "__init__".
self.add_dependency(make_trigger(arg.fullname))
return
# In uncommon cases generate normal dependencies. These will include
# spurious dependencies, but the performance impact is small.
super().visit_call_expr(e)
def visit_cast_expr(self, e: CastExpr) -> None:
super().visit_cast_expr(e)
self.add_type_dependencies(e.type)
def visit_type_application(self, e: TypeApplication) -> None:
super().visit_type_application(e)
for typ in e.types:
self.add_type_dependencies(typ)
def visit_index_expr(self, e: IndexExpr) -> None:
super().visit_index_expr(e)
self.add_operator_method_dependency(e.base, '__getitem__')
def visit_unary_expr(self, e: UnaryExpr) -> None:
super().visit_unary_expr(e)
if e.op not in unary_op_methods:
return
method = unary_op_methods[e.op]
self.add_operator_method_dependency(e.expr, method)
def visit_op_expr(self, e: OpExpr) -> None:
super().visit_op_expr(e)
self.process_binary_op(e.op, e.left, e.right)
def visit_comparison_expr(self, e: ComparisonExpr) -> None:
super().visit_comparison_expr(e)
for i, op in enumerate(e.operators):
left = e.operands[i]
right = e.operands[i + 1]
self.process_binary_op(op, left, right)
if self.python2 and op in ('==', '!=', '<', '<=', '>', '>='):
self.add_operator_method_dependency(left, '__cmp__')
self.add_operator_method_dependency(right, '__cmp__')
def process_binary_op(self, op: str, left: Expression, right: Expression) -> None:
method = op_methods.get(op)
if method:
if op == 'in':
self.add_operator_method_dependency(right, method)
else:
self.add_operator_method_dependency(left, method)
rev_method = reverse_op_methods.get(method)
if rev_method:
self.add_operator_method_dependency(right, rev_method)
def add_operator_method_dependency(self, e: Expression, method: str) -> None:
typ = get_proper_type(self.type_map.get(e))
if typ is not None:
self.add_operator_method_dependency_for_type(typ, method)
def add_operator_method_dependency_for_type(self, typ: ProperType, method: str) -> None:
# Note that operator methods can't be (non-metaclass) methods of type objects
# (that is, TypeType objects or Callables representing a type).
if isinstance(typ, TypeVarType):
typ = get_proper_type(typ.upper_bound)
if isinstance(typ, TupleType):
typ = typ.partial_fallback
if isinstance(typ, Instance):
trigger = make_trigger(typ.type.fullname + '.' + method)
self.add_dependency(trigger)
elif isinstance(typ, UnionType):
for item in typ.items:
self.add_operator_method_dependency_for_type(get_proper_type(item), method)
elif isinstance(typ, FunctionLike) and typ.is_type_obj():
self.add_operator_method_dependency_for_type(typ.fallback, method)
elif isinstance(typ, TypeType):
if isinstance(typ.item, Instance) and typ.item.type.metaclass_type is not None:
self.add_operator_method_dependency_for_type(typ.item.type.metaclass_type, method)
def visit_generator_expr(self, e: GeneratorExpr) -> None:
super().visit_generator_expr(e)
for seq in e.sequences:
self.add_iter_dependency(seq)
def visit_dictionary_comprehension(self, e: DictionaryComprehension) -> None:
super().visit_dictionary_comprehension(e)
for seq in e.sequences:
self.add_iter_dependency(seq)
def visit_star_expr(self, e: StarExpr) -> None:
super().visit_star_expr(e)
self.add_iter_dependency(e.expr)
def visit_yield_from_expr(self, e: YieldFromExpr) -> None:
super().visit_yield_from_expr(e)
self.add_iter_dependency(e.expr)
def visit_await_expr(self, e: AwaitExpr) -> None:
super().visit_await_expr(e)
self.add_attribute_dependency_for_expr(e.expr, '__await__')
# Helpers
def add_type_alias_deps(self, target: str) -> None:
# Type aliases are special, because some of the dependencies are calculated
# in semanal.py, before they are expanded.
if target in self.alias_deps:
for alias in self.alias_deps[target]:
self.add_dependency(make_trigger(alias))
def add_dependency(self, trigger: str, target: Optional[str] = None) -> None:
"""Add dependency from trigger to a target.
If the target is not given explicitly, use the current target.
"""
if trigger.startswith(('<builtins.', '<typing.',
'<mypy_extensions.', '<typing_extensions.')):
# Don't track dependencies to certain library modules to keep the size of
# the dependencies manageable. These dependencies should only
# change on mypy version updates, which will require a full rebuild
# anyway.
return
if target is None:
target = self.scope.current_target()
self.map.setdefault(trigger, set()).add(target)
def add_type_dependencies(self, typ: Type, target: Optional[str] = None) -> None:
"""Add dependencies to all components of a type.
Args:
target: If not None, override the default (current) target of the
generated dependency.
"""
for trigger in self.get_type_triggers(typ):
self.add_dependency(trigger, target)
def add_attribute_dependency(self, typ: Type, name: str) -> None:
"""Add dependencies for accessing a named attribute of a type."""
targets = self.attribute_triggers(typ, name)
for target in targets:
self.add_dependency(target)
def attribute_triggers(self, typ: Type, name: str) -> List[str]:
"""Return all triggers associated with the attribute of a type."""
typ = get_proper_type(typ)
if isinstance(typ, TypeVarType):
typ = get_proper_type(typ.upper_bound)
if isinstance(typ, TupleType):
typ = typ.partial_fallback
if isinstance(typ, Instance):
member = '%s.%s' % (typ.type.fullname, name)
return [make_trigger(member)]
elif isinstance(typ, FunctionLike) and typ.is_type_obj():
member = '%s.%s' % (typ.type_object().fullname, name)
triggers = [make_trigger(member)]
triggers.extend(self.attribute_triggers(typ.fallback, name))
return triggers
elif isinstance(typ, UnionType):
targets = []
for item in typ.items:
targets.extend(self.attribute_triggers(item, name))
return targets
elif isinstance(typ, TypeType):
triggers = self.attribute_triggers(typ.item, name)
if isinstance(typ.item, Instance) and typ.item.type.metaclass_type is not None:
triggers.append(make_trigger('%s.%s' %
(typ.item.type.metaclass_type.type.fullname,
name)))
return triggers
else:
return []
def add_attribute_dependency_for_expr(self, e: Expression, name: str) -> None:
typ = self.type_map.get(e)
if typ is not None:
self.add_attribute_dependency(typ, name)
def add_iter_dependency(self, node: Expression) -> None:
typ = self.type_map.get(node)
if typ:
self.add_attribute_dependency(typ, '__iter__')
def use_logical_deps(self) -> bool:
return self.options is not None and self.options.logical_deps
def get_type_triggers(self, typ: Type) -> List[str]:
return get_type_triggers(typ, self.use_logical_deps())
def get_type_triggers(typ: Type, use_logical_deps: bool) -> List[str]:
"""Return all triggers that correspond to a type becoming stale."""
return typ.accept(TypeTriggersVisitor(use_logical_deps))
class TypeTriggersVisitor(TypeVisitor[List[str]]):
def __init__(self, use_logical_deps: bool) -> None:
self.deps: List[str] = []
self.use_logical_deps = use_logical_deps
def get_type_triggers(self, typ: Type) -> List[str]:
return get_type_triggers(typ, self.use_logical_deps)
def visit_instance(self, typ: Instance) -> List[str]:
trigger = make_trigger(typ.type.fullname)
triggers = [trigger]
for arg in typ.args:
triggers.extend(self.get_type_triggers(arg))
if typ.last_known_value:
triggers.extend(self.get_type_triggers(typ.last_known_value))
return triggers
def visit_type_alias_type(self, typ: TypeAliasType) -> List[str]:
assert typ.alias is not None
trigger = make_trigger(typ.alias.fullname)
triggers = [trigger]
for arg in typ.args:
triggers.extend(self.get_type_triggers(arg))
# TODO: Add guard for infinite recursion here. Moreover, now that type aliases
# are its own kind of types we can simplify the logic to rely on intermediate
# dependencies (like for instance types).
triggers.extend(self.get_type_triggers(typ.alias.target))
return triggers
def visit_any(self, typ: AnyType) -> List[str]:
if typ.missing_import_name is not None:
return [make_trigger(typ.missing_import_name)]
return []
def visit_none_type(self, typ: NoneType) -> List[str]:
return []
def visit_callable_type(self, typ: CallableType) -> List[str]:
triggers = []
for arg in typ.arg_types:
triggers.extend(self.get_type_triggers(arg))
triggers.extend(self.get_type_triggers(typ.ret_type))
# fallback is a metaclass type for class objects, and is
# processed separately.
return triggers
def visit_overloaded(self, typ: Overloaded) -> List[str]:
triggers = []
for item in typ.items:
triggers.extend(self.get_type_triggers(item))
return triggers
def visit_erased_type(self, t: ErasedType) -> List[str]:
# This type should exist only temporarily during type inference
assert False, "Should not see an erased type here"
def visit_deleted_type(self, typ: DeletedType) -> List[str]:
return []
def visit_partial_type(self, typ: PartialType) -> List[str]:
assert False, "Should not see a partial type here"
def visit_tuple_type(self, typ: TupleType) -> List[str]:
triggers = []
for item in typ.items:
triggers.extend(self.get_type_triggers(item))
triggers.extend(self.get_type_triggers(typ.partial_fallback))
return triggers
def visit_type_type(self, typ: TypeType) -> List[str]:
triggers = self.get_type_triggers(typ.item)
if not self.use_logical_deps:
old_triggers = triggers[:]
for trigger in old_triggers:
triggers.append(trigger.rstrip('>') + '.__init__>')
triggers.append(trigger.rstrip('>') + '.__new__>')
return triggers
def visit_type_var(self, typ: TypeVarType) -> List[str]:
triggers = []
if typ.fullname:
triggers.append(make_trigger(typ.fullname))
if typ.upper_bound:
triggers.extend(self.get_type_triggers(typ.upper_bound))
for val in typ.values:
triggers.extend(self.get_type_triggers(val))
return triggers
def visit_param_spec(self, typ: ParamSpecType) -> List[str]:
triggers = []
if typ.fullname:
triggers.append(make_trigger(typ.fullname))
triggers.extend(self.get_type_triggers(typ.upper_bound))
return triggers
def visit_typeddict_type(self, typ: TypedDictType) -> List[str]:
triggers = []
for item in typ.items.values():
triggers.extend(self.get_type_triggers(item))
triggers.extend(self.get_type_triggers(typ.fallback))
return triggers
def visit_literal_type(self, typ: LiteralType) -> List[str]:
return self.get_type_triggers(typ.fallback)
def visit_unbound_type(self, typ: UnboundType) -> List[str]:
return []
def visit_uninhabited_type(self, typ: UninhabitedType) -> List[str]:
return []
def visit_union_type(self, typ: UnionType) -> List[str]:
triggers = []
for item in typ.items:
triggers.extend(self.get_type_triggers(item))
return triggers
def merge_dependencies(new_deps: Dict[str, Set[str]],
deps: Dict[str, Set[str]]) -> None:
for trigger, targets in new_deps.items():
deps.setdefault(trigger, set()).update(targets)
def non_trivial_bases(info: TypeInfo) -> List[TypeInfo]:
return [base for base in info.mro[1:]
if base.fullname != 'builtins.object']
def has_user_bases(info: TypeInfo) -> bool:
return any(base.module_name not in ('builtins', 'typing', 'enum') for base in info.mro[1:])
def dump_all_dependencies(modules: Dict[str, MypyFile],
type_map: Dict[Expression, Type],
python_version: Tuple[int, int],
options: Options) -> None:
"""Generate dependencies for all interesting modules and print them to stdout."""
all_deps: Dict[str, Set[str]] = {}
for id, node in modules.items():
# Uncomment for debugging:
# print('processing', id)
if id in ('builtins', 'typing') or '/typeshed/' in node.path:
continue
assert id == node.fullname
deps = get_dependencies(node, type_map, python_version, options)
for trigger, targets in deps.items():
all_deps.setdefault(trigger, set()).update(targets)
TypeState.add_all_protocol_deps(all_deps)
for trigger, targets in sorted(all_deps.items(), key=lambda x: x[0]):
print(trigger)
for target in sorted(targets):
print(' %s' % target)
| 47.852941 | 99 | 0.618623 |
acec7aca1816a4d33911c2a9fc28a1fc464e41ee | 18,328 | py | Python | examples/language_model/gpt-3/dygraph/dataset.py | tanhanzhuo/PaddleNLP | d0d20678f2bec820570b4f09ca49cd402d20c3b6 | [
"Apache-2.0"
] | 7,091 | 2021-02-05T13:56:25.000Z | 2022-03-31T11:42:50.000Z | examples/language_model/gpt-3/dygraph/dataset.py | tanhanzhuo/PaddleNLP | d0d20678f2bec820570b4f09ca49cd402d20c3b6 | [
"Apache-2.0"
] | 844 | 2021-02-10T01:09:29.000Z | 2022-03-31T12:12:58.000Z | examples/language_model/gpt-3/dygraph/dataset.py | tanhanzhuo/PaddleNLP | d0d20678f2bec820570b4f09ca49cd402d20c3b6 | [
"Apache-2.0"
] | 1,035 | 2021-02-05T14:26:48.000Z | 2022-03-31T11:42:57.000Z | # Copyright (c) 2020, NVIDIA CORPORATION.
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import time
import os
import numpy as np
import paddle
from paddle.io import DataLoader, Dataset
from paddlenlp.data import Stack, Tuple, Pad
from paddlenlp.utils.log import logger
from paddlenlp.utils.batch_sampler import DistributedBatchSampler
def construct_samples_and_shuffle_data(name, data_prefix, documents, sizes,
num_samples, seq_length, seed,
build_data_file):
"""
documents: document index from 0 to len(docs)
sizes: the length list of all docs.
num_samples: total step*bs iterations of data.
seq_length: the sequence length.
sum(sizes) = tokens_per_epoch
data_nums = num_samples * micro_batch_size
num_epochs = (data_nums + 1) // sum(sizes)
len(doc_idx) = num_epochs * sum(sizes)
"""
# Number of tokens in each epoch and number of required epochs.
tokens_per_epoch = _num_tokens(documents, sizes)
num_epochs = _num_epochs(tokens_per_epoch, seq_length, num_samples)
# Rng state
np_rng = np.random.RandomState(seed=seed)
# Filename of the index mappings.
_filename = data_prefix
_filename += '_{}_indexmap'.format(name)
_filename += '_{}ns'.format(num_samples)
_filename += '_{}sl'.format(seq_length)
doc_idx_filename = _filename + '_doc_idx.npy'
sample_idx_filename = _filename + '_sample_idx.npy'
shuffle_idx_filename = _filename + '_shuffle_idx.npy'
# Sava random state
savedState = np_rng.get_state()
# Build the indexed mapping if not exist.
if build_data_file:
if (not os.path.isfile(doc_idx_filename)) or \
(not os.path.isfile(sample_idx_filename)) or \
(not os.path.isfile(shuffle_idx_filename)):
if num_epochs == 1:
separate_last_epoch = False
else:
num_samples_from_epochs_minus_one = (
(num_epochs - 1) * tokens_per_epoch - 1) // seq_length
last_epoch_num_samples = num_samples - \
num_samples_from_epochs_minus_one
assert last_epoch_num_samples >= 0, \
'last epoch number of samples should be non-negative.'
num_samples_per_epoch = (tokens_per_epoch - 1) // seq_length
assert last_epoch_num_samples < (num_samples_per_epoch + 1), \
'last epoch number of samples exceeded max value.'
separate_last_epoch = (
last_epoch_num_samples < int(0.80 * num_samples_per_epoch))
# Note. len(doc_idx) = num_epochs * len(doc)
start_time = time.time()
doc_idx = _build_doc_idx(documents, num_epochs, np_rng,
separate_last_epoch)
np.save(doc_idx_filename, doc_idx, allow_pickle=True)
print(' > elasped time to build and save doc-idx mapping '
'(seconds): {:4f}'.format(time.time() - start_time))
# sample-idx. pos of each seq_len of data.
start_time = time.time()
assert doc_idx.dtype == np.int32
assert sizes.dtype == np.int32
import data_tools.helpers as helpers
sample_idx = helpers.build_sample_idx(sizes, doc_idx, seq_length,
num_epochs, tokens_per_epoch)
# sample_idx = _build_sample_idx(sizes, doc_idx, seq_length,
# num_epochs, tokens_per_epoch)
np.save(sample_idx_filename, sample_idx, allow_pickle=True)
print(' > elasped time to build and save sample-idx mapping '
'(seconds): {:4f}'.format(time.time() - start_time))
# shuffle-idx.
start_time = time.time()
if separate_last_epoch:
num_samples_ = num_samples_from_epochs_minus_one
else:
num_samples_ = sample_idx.shape[0] - 1
# Shuffle all seq len data.
shuffle_idx = _build_shuffle_idx(num_samples_,
sample_idx.shape[0] - 1, np_rng)
np.save(shuffle_idx_filename, shuffle_idx, allow_pickle=True)
print(' > elasped time to build and save shuffle-idx mapping'
' (seconds): {:4f}'.format(time.time() - start_time))
else:
while True:
if (not os.path.isfile(doc_idx_filename)) or \
(not os.path.isfile(sample_idx_filename)) or \
(not os.path.isfile(shuffle_idx_filename)):
time.sleep(3)
else:
try:
np.load(
shuffle_idx_filename, allow_pickle=True, mmap_mode='r')
break
except Exception as e:
print(
"%s file is still writing or damaged, please wait a moment."
% shuffle_idx_filename)
time.sleep(3)
# Restore random state
np_rng.set_state(savedState)
if paddle.distributed.get_world_size() > 1:
if paddle.fluid.framework.in_dygraph_mode():
paddle.distributed.barrier()
# Load mappings.
doc_idx = np.load(doc_idx_filename, allow_pickle=True, mmap_mode='r')
sample_idx = np.load(sample_idx_filename, allow_pickle=True, mmap_mode='r')
shuffle_idx = np.load(
shuffle_idx_filename, allow_pickle=True, mmap_mode='r')
return doc_idx, sample_idx, shuffle_idx
def _num_tokens(documents, lens):
"""Total number of tokens in the dataset."""
return np.sum(lens[documents])
def _num_epochs(tokens_per_epoch, seq_length, num_samples):
"""Based on number of samples and sequence lenght, calculate how many
epochs will be needed."""
num_epochs = 0
total_tokens = 0
while True:
num_epochs += 1
total_tokens += tokens_per_epoch
if ((total_tokens - 1) // seq_length) >= num_samples:
return num_epochs
def _build_doc_idx(documents, num_epochs, np_rng, separate_last_epoch):
"""
Build an array with length = number-of-epochs * number-of-documents.
Each index is mapped to a corresponding document.
"""
if not separate_last_epoch or num_epochs == 1:
doc_idx = np.mgrid[0:num_epochs, 0:len(documents)][1]
doc_idx[:] = documents
# The documents repeat num_epochs times.
doc_idx = doc_idx.reshape(-1)
doc_idx = doc_idx.astype(np.int32)
return doc_idx
doc_idx_first = _build_doc_idx(documents, num_epochs - 1, np_rng, False)
doc_idx_last = _build_doc_idx(documents, 1, np_rng, False)
return np.concatenate((doc_idx_first, doc_idx_last))
def _build_sample_idx(sizes, doc_idx, seq_length, num_epochs, tokens_per_epoch):
"""
num_samples + 1, pos of bs data
the distance between two points for sample idx is bs tokens.
"""
num_samples = (num_epochs * tokens_per_epoch - 1) // seq_length
sample_idx = np.zeros([int(num_samples) + 1, 2], dtype=np.int32)
sample_index = 0
doc_idx_index = 0
doc_offset = 0
sample_idx[sample_index][0] = doc_idx_index
sample_idx[sample_index][1] = doc_offset
sample_index += 1
while sample_index <= num_samples:
remaining_seq_length = seq_length + 1
while remaining_seq_length != 0:
doc_id = doc_idx[doc_idx_index]
doc_length = sizes[doc_id] - doc_offset
remaining_seq_length -= doc_length
if remaining_seq_length <= 0:
doc_offset += (remaining_seq_length + doc_length - 1)
remaining_seq_length = 0
else:
doc_idx_index += 1
doc_offset = 0
sample_idx[sample_index][0] = doc_idx_index
sample_idx[sample_index][1] = doc_offset
sample_index += 1
return sample_idx
def _build_shuffle_idx(num_samples, total_size, np_rng):
dtype_ = np.uint32
if total_size >= (np.iinfo(np.uint32).max - 1):
dtype_ = np.int64
shuffle_idx_first = np.arange(
start=0, stop=num_samples, step=1, dtype=dtype_)
np_rng.shuffle(shuffle_idx_first)
if num_samples == total_size:
return shuffle_idx_first
shuffle_idx_last = np.arange(
start=num_samples, stop=total_size, step=1, dtype=dtype_)
np_rng.shuffle(shuffle_idx_last)
return np.concatenate((shuffle_idx_first, shuffle_idx_last))
def get_train_valid_test_split_(splits_string, size):
""" Get dataset splits from comma or '/' separated string list."""
splits = []
if splits_string.find(',') != -1:
splits = [float(s) for s in splits_string.split(',')]
elif splits_string.find('/') != -1:
splits = [float(s) for s in splits_string.split('/')]
else:
splits = [float(splits_string)]
while len(splits) < 3:
splits.append(0.)
splits = splits[:3]
splits_sum = sum(splits)
assert splits_sum > 0.0
splits = [split / splits_sum for split in splits]
splits_index = [0]
for index, split in enumerate(splits):
splits_index.append(splits_index[index] + int(
round(split * float(size))))
diff = splits_index[-1] - size
for index in range(1, len(splits_index)):
splits_index[index] -= diff
assert len(splits_index) == 4
assert splits_index[-1] == size
return splits_index
def create_pretrained_dataset(args,
input_path,
local_rank,
data_world_rank,
data_world_size,
eos_id,
worker_init=None,
max_seq_len=1024,
places=None,
data_holders=None):
if local_rank == 0:
start_time = time.time()
print('> compiling dataset index builder ...')
from data_tools.dataset_utils import compile_helper
compile_helper()
print(
'>>> done with dataset index builder. Compilation time: {:.3f} '
'seconds'.format(time.time() - start_time),
flush=True)
device_world_size = paddle.distributed.get_world_size()
device_world_rank = paddle.distributed.get_rank()
logger.info(
"The distributed run, total device num:{}, distinct dataflow num:{}.".
format(device_world_size, data_world_size))
assert len(input_path) == 1, "GPT only support one dataset for now."
input_prefix = input_path[0]
if os.path.isfile(input_prefix + "_ids.npz"):
logger.warning(
"You are using compatible dataset, please make new dataset as the readme!"
)
process_datas = np.load(
input_prefix + "_ids.npz", mmap_mode="r+", allow_pickle=True)
sample_ids = process_datas["ids"]
sample_lens = process_datas["lens"].astype("int32")
else:
for suffix in ["_ids.npy", "_idx.npz"]:
if not os.path.isfile(input_prefix + suffix):
raise ValueError("File Not found, %s" % (path + suffix))
sample_ids = np.load(
input_prefix + "_ids.npy", mmap_mode="r", allow_pickle=True)
# All documment ids, extend as 1-D array.
process_datas = np.load(input_prefix + "_idx.npz")
# The len(sample_lens) num of docs
# The sum(sample_lens) should equal len(sample_ids)
sample_lens = process_datas["lens"]
splits = get_train_valid_test_split_(args.split, len(sample_lens))
assert len(sample_lens) >= splits[
-1], "The document nums should larger than max of splits, but %s < %s" % (
len(sample_lens), splits[-1])
def build_dataset(index, name, num_samples):
dataset = GPTDataset(
file_path=input_prefix,
build_data_file=local_rank == 0,
name="gpt_" + name,
max_seq_len=max_seq_len,
num_samples=num_samples,
documents=np.arange(splits[index], splits[index + 1]),
sample_ids=sample_ids,
sample_lens=sample_lens,
eos_id=eos_id,
seed=args.seed)
batch_sampler = DistributedBatchSampler(
dataset,
batch_size=args.local_batch_size,
num_replicas=data_world_size,
rank=data_world_rank,
shuffle=False,
drop_last=True)
data_loader = DataLoader(
dataset=dataset,
places=places,
feed_list=data_holders,
batch_sampler=batch_sampler,
num_workers=1,
worker_init_fn=worker_init,
# collate_fn=Tuple(Stack(), Stack(), Stack(), Stack(), Stack()),
collate_fn=Tuple(Stack(), Stack(), Stack(), Stack()),
return_list=False)
return data_loader
# Note, data should be broardcast to all devices.
# for train, valid, test, the distinct data num is data_world_size
train_data_loader = build_dataset(0, "train", args.local_batch_size *
args.max_steps * data_world_size)
valid_data_loader = build_dataset(1, "valid", args.local_batch_size *
(args.max_steps // args.eval_freq + 1) *
args.eval_iters * data_world_size)
test_data_loader = build_dataset(2, "test", args.local_batch_size *
args.test_iters * data_world_size)
return train_data_loader, valid_data_loader, test_data_loader
class GPTDataset(paddle.io.Dataset):
def __init__(self,
file_path,
num_samples,
eos_id,
sample_ids,
sample_lens,
documents=None,
build_data_file=False,
name="gpt",
max_seq_len=1024,
seed=1234):
self.file_path = file_path
self.max_seq_len = max_seq_len
self.name = name
self.eos_id = eos_id
self.sample_ids = sample_ids
self.sample_lens = sample_lens
if documents is None:
document_ids = np.arange(0, self.sample_lens.shape[0])
else:
document_ids = documents
self.doc_idx, self.sample_idx, self.shuffle_idx = \
construct_samples_and_shuffle_data(self.name, self.file_path, document_ids,\
self.sample_lens, num_samples, max_seq_len, seed, build_data_file)
# The doc cumsum start pos
self.start_pos = [0] + np.cumsum(self.sample_lens).tolist()
def _construct_sample(self, tokens):
tokens = np.array(tokens).astype("int64").tolist()
labels = tokens[1:]
tokens = tokens[:-1]
seq_length = len(tokens)
# Attention mask for the attention calulate
# attention_mask = np.tri(seq_length, seq_length).reshape((1, seq_length,
# seq_length))
# The pad and eos tokens do not contribute the loss
loss_mask = np.ones(seq_length, dtype="float32")
loss_mask[np.where(np.array(tokens) == self.eos_id)] = 0.0
position_ids = np.arange(0, seq_length, dtype="int64")
# attention_mask = (attention_mask - 1.0) * 1e9
# attention_mask = attention_mask.astype("float32")
# return [tokens, loss_mask, attention_mask, position_ids, labels]
return [tokens, loss_mask, position_ids, labels]
def _get_single_sample_from_idx(self, doc_index_f, doc_index_l, offset_f,
offset_l):
"""
The input means:
doc_index_f: data from the first doc.
doc_index_l: data from the last doc.
offset_f: offset of the first doc.
offset_l: offset of the last doc.
"""
# Data from the sample doc. just select the needed ids.
if doc_index_f == doc_index_l:
current_start_pos = self.start_pos[self.doc_idx[doc_index_f]]
return self.sample_ids[current_start_pos+offset_f:\
current_start_pos+offset_l+1].tolist()
# Data from multi docs.
else:
current_start_pos = self.start_pos[self.doc_idx[doc_index_f]]
next_start_pos = self.start_pos[self.doc_idx[doc_index_f] + 1]
tokens = self.sample_ids[current_start_pos + offset_f:
next_start_pos].tolist()
for i in range(doc_index_f + 1, doc_index_l):
current_start_pos = self.start_pos[self.doc_idx[i]]
next_start_pos = self.start_pos[self.doc_idx[i] + 1]
tokens.extend(self.sample_ids[current_start_pos:next_start_pos]
.tolist())
last_start_pos = self.start_pos[self.doc_idx[doc_index_l]]
tokens.extend(self.sample_ids[last_start_pos:last_start_pos +
offset_l + 1].tolist())
return tokens
def __getitem__(self, index):
idx = self.shuffle_idx[index]
# Start and end documents and offsets.
doc_index_f = self.sample_idx[idx][0]
doc_index_l = self.sample_idx[idx + 1][0]
offset_f = self.sample_idx[idx][1]
offset_l = self.sample_idx[idx + 1][1]
tokens = self._get_single_sample_from_idx(doc_index_f, doc_index_l,
offset_f, offset_l)
return self._construct_sample(tokens)
def __len__(self):
return self.sample_idx.shape[0] - 1
| 39.930283 | 88 | 0.605576 |
acec7b7020e49c600071a98639d94c8e983a6ae6 | 1,476 | py | Python | sparkplug/executor.py | k-fish/sparkplug | 43f3aa0d68a980b65609125595d0e26cca438733 | [
"MIT"
] | null | null | null | sparkplug/executor.py | k-fish/sparkplug | 43f3aa0d68a980b65609125595d0e26cca438733 | [
"MIT"
] | null | null | null | sparkplug/executor.py | k-fish/sparkplug | 43f3aa0d68a980b65609125595d0e26cca438733 | [
"MIT"
] | null | null | null | import os
import signal
import time
import multiprocessing
def direct(f, *args, **kwargs):
"""Runs a task in the current process. This is a very thin wrapper around
a direct function call."""
return f(*args, **kwargs)
class Subprocess(object):
sleep = 3600
"""Runs a task in N subprocesses. The current process is suspended (using
sleep) until an exception is raised on this process."""
def __init__(self, process_count):
self.process_count = process_count
def __call__(self, f, *args, **kwargs):
def add_worker_number(original_kwargs, index):
return dict(original_kwargs, **dict(worker_number=index))
processes = [
multiprocessing.Process(target=f, args=args, kwargs=add_worker_number(kwargs, index))
for index in xrange(self.process_count)
]
try:
for process in processes:
process.start()
while True:
time.sleep(self.sleep)
finally:
# process.terminate() would send SIGTERM and abruptly terminate
# all children. SIGINT is a little more graceful; it gives each
# process a chance to finish what it's doing (or abort, more
# likely) and hang up.
for process in processes:
os.kill(process.pid, signal.SIGINT)
for process in processes:
process.join()
| 32.086957 | 97 | 0.601626 |
acec7bb52c587808ffb00cf57a47d7ed57c78083 | 830 | py | Python | PyScripts(elseIsTkinter)/ex32.py | Dario213/My-Python-Scripts | dee96e84e8a892e7a72f96c47a1f161e068572cb | [
"Apache-2.0"
] | null | null | null | PyScripts(elseIsTkinter)/ex32.py | Dario213/My-Python-Scripts | dee96e84e8a892e7a72f96c47a1f161e068572cb | [
"Apache-2.0"
] | null | null | null | PyScripts(elseIsTkinter)/ex32.py | Dario213/My-Python-Scripts | dee96e84e8a892e7a72f96c47a1f161e068572cb | [
"Apache-2.0"
] | null | null | null | the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print(f"This is count {number}")
# same as above
for fruit in fruits:
print(f"A fruit of type: {fruit}")
# also we can go through mixed lists too
# notice we have to use {} since we don't know what's in it
for i in change:
print(f"I got {i}")
# we can also build lists, first start with an empty one
elements = []
#Then use the range function to do 0 to 5 counts
for i in range(0, 6):
print(f"Adding {i} to the list.")
# append is a function that lists understand
elements.append(i)
# Now we can print them out too
for i in elements:
print(f"Element was: {i}")
| 27.666667 | 60 | 0.637349 |
acec7c04fc2ebb782220f7d61111b2c9945cf70c | 884 | py | Python | Chapter10/c10_26_binomialAmericanCall.py | John-ye666/Python-for-Finance-Second-Edition | dabef09bcdd7b0ec2934774741bd0a7e1950de73 | [
"MIT"
] | 236 | 2017-07-02T03:06:54.000Z | 2022-03-31T03:15:33.000Z | Chapter10/c10_26_binomialAmericanCall.py | John-ye666/Python-for-Finance-Second-Edition | dabef09bcdd7b0ec2934774741bd0a7e1950de73 | [
"MIT"
] | null | null | null | Chapter10/c10_26_binomialAmericanCall.py | John-ye666/Python-for-Finance-Second-Edition | dabef09bcdd7b0ec2934774741bd0a7e1950de73 | [
"MIT"
] | 139 | 2017-06-30T10:28:16.000Z | 2022-01-19T19:43:34.000Z | # -*- coding: utf-8 -*-
"""
Name : c10_26_binomialAmericanCall.py
Book : Python for Finance (2nd ed.)
Publisher: Packt Publishing Ltd.
Author : Yuxing Yan
Date : 6/6/2017
email : yany@canisius.edu
paulyxy@hotmail.com
"""
def binomialAmericanCall(s,x,T,r,sigma,n=100):
from math import exp,sqrt
import numpy as np
deltaT = T /n
u = exp(sigma * sqrt(deltaT))
d = 1.0 / u
a = exp(r * deltaT)
p = (a - d) / (u - d)
v = [[0.0 for j in np.arange(i + 1)] for i in np.arange(n + 1)]
for j in np.arange(n+1):
v[n][j] = max(s * u**j * d**(n - j) - x, 0.0)
for i in np.arange(n-1, -1, -1):
for j in np.arange(i + 1):
v1=exp(-r*deltaT)*(p*v[i+1][j+1]+(1.0-p)*v[i+1][j])
v2=max(v[i][j]-x,0) # early exercise
v[i][j]=max(v1,v2)
return v[0][0]
| 27.625 | 68 | 0.501131 |
acec7c4a9040db6f16bf0dd37de76acf18b3fe06 | 7,682 | py | Python | example/vfs.py | hitakaken/ifplus | 8354eeceea8abcbcaeb5dcd1c11eef69cbef6557 | [
"MIT"
] | null | null | null | example/vfs.py | hitakaken/ifplus | 8354eeceea8abcbcaeb5dcd1c11eef69cbef6557 | [
"MIT"
] | null | null | null | example/vfs.py | hitakaken/ifplus | 8354eeceea8abcbcaeb5dcd1c11eef69cbef6557 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
import datetime
import time
import calendar
from bson import ObjectId
import pymongo
now = datetime.datetime.utcnow()
print time.mktime(now.timetuple())
print int(calendar.timegm(now.timetuple()) * 1000 + now.microsecond / 1000)
files = [
{
"name": "新能源汽车",
"acl": [{"sid": "r:7b49ef92-b9cb-4388-b5a7-a261b79ac5fa", "mask": -2088599552}, ],
"uid": "u:7bd71624-a961-47a8-bea0-d601625b9941",
"gid": "r:7b49ef92-b9cb-4388-b5a7-a261b79ac5fa",
"xattrs": {
"system": {"source": "mssql://dongge:dongge@192.168.0.2:57993/dbname=sh&table= Modules&ModuleID=470"},
"dc": {}},
"uuid": "97523ACC-FD8E-4809-BF7C-E475795E758B",
"parent": "278E0D1E-0099-4505-BDB3-1CB296FDBD4A",
"ancestors": ["上海行业情报服务网", "情报产品", "简报", "《第一情报·新能源汽车》"],
"mode": -2147466772,
"create": "2010-08-31T11:25:52.000Z",
"atime": "2016-11-01T11:25:52.000Z",
"ctime": "2010-08-31T11:25:52.000Z",
"mtime": "2010-08-31T11:25:52.000Z",
"dev": None,
"nlink": 1,
"size": 0
},
{
"name": "上海行业情报服务网",
"acl": [{"sid": "r:7b49ef92-b9cb-4388-b5a7-a261b79ac5fa", "mask": -2088599552}],
"uid": "u:7bd71624-a961-47a8-bea0-d601625b9941",
"gid": "r:7b49ef92-b9cb-4388-b5a7-a261b79ac5fa",
"xattrs": {"system": {"source": "mssql://dongge:dongge@192.168.0.2:57993/dbname=sh&table=Portals&PortalID=0"},
"dc": {"description": "上海行业情报服务网", "subject": "科技查新,专利检索,专利地图", "language": "zh-CN"}},
"uuid": "E92CC368-53AD-45AF-9899-BA790D276A38",
"parent": None,
"ancestors": [],
"mode": 0x80000000 | 0o040750,
"create": "2010-08-31T11:25:52.000Z",
"atime": "2016-11-01T11:25:52.000Z",
"ctime": "2010-08-31T11:25:52.000Z",
"mtime": "2010-08-31T11:25:52.000Z",
"dev": None,
"nlink": 1,
"size": 0
},
{
"name": "2010年08期",
"acl": [{"sid": "r:7b49ef92-b9cb-4388-b5a7-a261b79ac5fa", "mask": -2088599552}],
"uid": "u:ce414832-e0f3-4a78-82f6-d1daa221d147",
"gid": "r:7b49ef92-b9cb-4388-b5a7-a261b79ac5fa",
"xattrs": {"system":
{"source": "mssql://dongge:dongge@192.168.0.2:57993/dbname?table= C_info&InfoID=5294"},
"hits": {"p": 87},
"dc": {"description": "", "subject": ["新能源汽车"],
"source": "上海科学技术情报研究所"},
"bibo": {"shortTitle": "最新资讯",
"authorList": ["祝毓", "庄盛", "路炜"]},
"user": {"ggfs": "摘编"}},
"uuid": "136EC70D-05FC-4731-A2E8-3A80239DF201",
"parent": "97523ACC-FD8E-4809-BF7C-E475795E758B",
"ancestors": ["上海行业情报服务网", "情报产品", "简报", "《第一情报·新能源汽车》", "新能源汽车"],
"mode": -2147466772,
"creator": "u:ce414832-e0f3-4a78-82f6-d1daa221d147",
"create": "2010-08-31T11:25:52.000Z",
"atime": "2016-11-01T11:25:52.000Z",
"ctime": "2010-08-31T11:25:52.000Z",
"mtime": "2010-08-31T11:25:52.000Z",
"dev": None,
"nlink": 1,
"size": 0
},
{
"name": "《第一情报·新能源汽车》",
"acl": [{"sid": "r:7b49ef92-b9cb-4388-b5a7-a261b79ac5fa", "mask": -2088599552}],
"uid": "u:7bd71624-a961-47a8-bea0-d601625b9941",
"gid": "r:7b49ef92-b9cb-4388-b5a7-a261b79ac5fa",
"xattrs": {"system": {"source": "mssql://dongge:dongge@192.168.0.2:57993/dbname=sh&table=Tabs&TabID=125"},
"dc": {
"description": "低碳、新能源、哥本哈根无疑是2009 年度的热门话题。作为节能减排的重要领域之一,新能源汽车也当之无愧地成为“耀眼的明星”。尽管对于新能源汽车的发展,业内存在不同的声音,但可以肯定的是,传统汽车的升级换代和技术革新已经势不可挡。<br> 低碳、新能源、哥本哈根无疑是2009 年度的热门话题。作为节能减排的重要领域之一,新能源汽车也当之无愧地成为“耀眼的明星”。尽管对于新能源汽车的发展,业内存在不同的声音,但可以肯定的是,传统汽车的升级换代和技术革新已经势不可挡。 《第一情报·新能源汽车》的创刊,旨在提供国内外新能源汽车领域的最新发展动态和政策导向,切实发挥预警、竞合、战略的“第一情报”功能。简报为月刊形式,每月末发布。",
"subject": ["新能源", "汽车", "混合动力", "生物燃料", "燃料电池"]
}
},
"uuid": "278E0D1E-0099-4505-BDB3-1CB296FDBD4A",
"parent": "57EF5EA0-3CC1-4154-950A-DE14A1664CA6",
"ancestors": ["上海行业情报服务网", "情报产品", "简报"],
"mode": -2147466772,
"create": "2010-08-31T11:25:52.000Z",
"atime": "2016-11-01T11:25:52.000Z",
"ctime": "2010-08-31T11:25:52.000Z",
"mtime": "2010-08-31T11:25:52.000Z",
"dev": None,
"nlink": 1,
"size": 0
},
{
"name": "情报产品",
"acl": [{"sid": "r:7b49ef92-b9cb-4388-b5a7-a261b79ac5fa", "mask": -2088599552}],
"uid": "u:7bd71624-a961-47a8-bea0-d601625b9941",
"gid": "r:7b49ef92-b9cb-4388-b5a7-a261b79ac5fa",
"xattrs": {"system": {"source": "mssql://dongge:dongge@192.168.0.2:57993/dbname=sh&table=Tabs&TabID=64"},
"dc": {"description": "", "subject": ""}},
"uuid": "2E06A99B-5017-400B-95C3-2A433AEB11AA",
"parent": "E92CC368-53AD-45AF-9899-BA790D276A38",
"ancestors": ["上海行业情报服务网"],
"mode": -2147466772,
"create": "2010-08-31T11:25:52.000Z",
"atime": "2016-11-01T11:25:52.000Z",
"ctime": "2010-08-31T11:25:52.000Z",
"mtime": "2010-08-31T11:25:52.000Z",
"dev": None,
"nlink": 1,
"size": 0
},
{
"name": "简报",
"acl": [{"sid": "r:7b49ef92-b9cb-4388-b5a7-a261b79ac5fa", "mask": -2088599552}],
"uid": "u:7bd71624-a961-47a8-bea0-d601625b9941",
"gid": "r:7b49ef92-b9cb-4388-b5a7-a261b79ac5fa",
"xattrs": {"system": {"source": "mssql://dongge:dongge@192.168.0.2:57993/dbname=sh&table=Tabs&TabID=111"},
"dc": {"description": "", "subject": ""}},
"uuid": "57EF5EA0-3CC1-4154-950A-DE14A1664CA6",
"parent": "2E06A99B-5017-400B-95C3-2A433AEB11AA",
"ancestors": ["上海行业情报服务网", "情报产品"],
"mode": -2147466772,
"create": "2010-08-31T11:25:52.000Z",
"atime": "2016-11-01T11:25:52.000Z",
"ctime": "2010-08-31T11:25:52.000Z",
"mtime": "2010-08-31T11:25:52.000Z",
"dev": None,
"nlink": 1,
"size": 0
}
]
ids = {}
global_id = ObjectId("58532cfb33d581e6b16f5412")
global_ancestors = ['data', 'www.hyqb.sh.cn']
for file_obj in files:
ids[file_obj['uuid']] = ObjectId()
for file_obj in files:
file_obj['_id'] = ids[file_obj['uuid']]
if file_obj['parent'] is not None:
file_obj['parent'] = ids[file_obj['parent']]
del file_obj['uuid']
file_obj['ancestors'] = global_ancestors + file_obj['ancestors']
client = pymongo.MongoClient('10.1.80.180',27017)
db = client.istis
# db.files.insert_many(files)
documents = db.files.find({'ancestors.0':'data', 'ancestors.1':'www.hyqb.sh.cn'})
for document in documents:
# update_document = {}
# update_document[u'atime'] = datetime.datetime.strptime(document[u'atime'], '%Y-%m-%dT%H:%M:%S.%fZ')
# update_document[u'ctime'] = datetime.datetime.strptime(document[u'ctime'], '%Y-%m-%dT%H:%M:%S.%fZ')
# update_document[u'mtime'] = datetime.datetime.strptime(document[u'mtime'], '%Y-%m-%dT%H:%M:%S.%fZ')
# update_document[u'create'] = datetime.datetime.strptime(document[u'create'], '%Y-%m-%dT%H:%M:%S.%fZ')
# update_document[u'uid'] = u'u:30db792e-3f41-4773-ae0d-f3916111f73d'
# update_document[u'gid'] = u'r:a3ff2bae-4a11-49b0-8319-cee2ce0dc578'
# update_document[u'acl.0.sid'] = u'r:a3ff2bae-4a11-49b0-8319-cee2ce0dc578'
# db.files.update_one({u'_id': document['_id']}, {u'$set': update_document})
if document[u'parent'] is None:
db.files.update_one({u'_id': document[u'_id']}, {u'$set': {u'parent': global_id}}) | 44.149425 | 356 | 0.565738 |
acec7d3a1155407aac96e034228b3f742cddd958 | 25,802 | py | Python | sensitiviy_study_over_meshes_optimized.py | aflahelouneg/inverse_identification_soft_tissue | e9c7a1c8a09d07d39906ee89a3836dfd1b045092 | [
"MIT"
] | 8 | 2020-03-30T17:12:18.000Z | 2021-12-02T01:31:32.000Z | sensitiviy_study_over_meshes_optimized.py | aflahelouneg/inverse_identification_soft_tissue | e9c7a1c8a09d07d39906ee89a3836dfd1b045092 | [
"MIT"
] | null | null | null | sensitiviy_study_over_meshes_optimized.py | aflahelouneg/inverse_identification_soft_tissue | e9c7a1c8a09d07d39906ee89a3836dfd1b045092 | [
"MIT"
] | 4 | 2020-10-07T21:57:03.000Z | 2022-01-11T19:28:08.000Z | '''
problems/healthy_skin_fixed_pads/runner.py
Problem
-------
Healthy skin extension
Boundary conditions:
--------------------
right pad: fixed displacements
left pad: fixed displacements
Maybe should start with some prestress because at zero displacement, the force
is not zero
'''
from dolfin import *
import dolfin
import time
import os
import shutil
import sys
import logging
import importlib
import numpy as np
import scipy.linalg as linalg
import matplotlib.pyplot as plt
from importlib import reload
from pprint import pprint
import config
from invsolve import project
from invsolve import measure
from invsolve import invsolve
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# dolfin.set_log_level(INFO)
# dolfin.set_log_active(True)
reload = importlib.reload
### Problem Configuration Parameters
RUN_AS_TEST = True
PLOT_RESULTS = True
FIX_BOUNDARY = False
OBSERVE_LAST_MEASUREMENT = False # otherwise, all measurement times
### Problem Specific Imports
### Get measurements
if RUN_AS_TEST:
import keloid_skin_FEM_weakly_nonlinear_lagrange2
#import keloid_skin_test_3000
#import keloid_skin_test_540
u_msr_dom_func_original = keloid_skin_FEM_weakly_nonlinear_lagrange2.out['u_msr_dom_func']
u_msr_dom_vals = None
x_msr_dom_vals = None
ux_msr_pad_vals = keloid_skin_FEM_weakly_nonlinear_lagrange2.out['ux_msr_pad_left_vals']
fx_msr_pad_vals = keloid_skin_FEM_weakly_nonlinear_lagrange2.out['fx_msr_pad_left_vals']
V_generator = keloid_skin_FEM_weakly_nonlinear_lagrange2.out['Vector Function Space']
dx_material_generator = keloid_skin_FEM_weakly_nonlinear_lagrange2.out['FEM domain']
if RUN_AS_TEST:
msr_pad_one_ux = ux_msr_pad_vals
msr_pad_one_fx = fx_msr_pad_vals
### ---------------------------
### Generating data with noise
### Noised data factories
def generate_noisy_displacement (u_msr_origin, V, std_u):
u_msr_noisy = u_msr_origin.copy(deepcopy=True)
x0_ZOI = 32.0
x1_ZOI = 68.0
y0_ZOI = 8.0
y1_ZOI = 32.0
dof_idx = []
dof_map_coordinates = V.tabulate_dof_coordinates()
n_indices = len(dof_map_coordinates)
for i in range(n_indices):
if ( x0_ZOI < dof_map_coordinates[i][0] < x1_ZOI and y0_ZOI < dof_map_coordinates[i][1] < y1_ZOI):
dof_idx.append(i)
u_msr_noisy.vector()[dof_idx] += np.random.normal(0, std_u, np.size(dof_idx))
return u_msr_noisy
def relative_error_force(f, f_ref):
df = np.abs(np.array(f) - np.array(f_ref))
error_f = np.sqrt(np.dot(df,df))/np.sqrt(np.dot(f_ref,f_ref))
return error_f
### ---------------------------
def compute_max_w_msr_dic (u_msr, dx_material):
total_displacement = []
for u_msr_i in u_msr:
total_displacement.append(np.sqrt(assemble(dot(u_msr_i, u_msr_i)*dx_material[0])) +\
np.sqrt(assemble(dot(u_msr_i, u_msr_i)*dx_material[1]))
)
print(total_displacement[-1])
return max(total_displacement)
# Standard variations on displacement and raction force
std_u = [0.0, 0.04, 0.12, 0.20]
std_f = [0.0, 0.002, 0.006, 0.01]
### Import mesh
import keloid_skin_mesh_optimized
from keloid_skin_mesh_optimized import (
mesh_domain,
markers_domain,
markers_boundary,
id_markers_domain,
id_markers_boundary)
### Reload some module if needed
reload(config)
reload(invsolve.config)
### Define the Material Model
def grad_reduc(X):
# Transform the deformation gradient tenso 'F' to a 3D tensor
e = grad(X)
return as_tensor([[e[0, 0], e[0, 1], 0],
[e[1, 0], e[1, 1], 0],
[0, 0, 0]])
def dim_reduc(X):
# Transform a 3D tensor to 2D
return as_tensor([[X[0, 0], X[0, 1]],
[X[1, 0], X[1, 1]]])
def Psi_(u, material_parameters):
'''Strain energy density'''
I = Identity(3)
F = variable(I + grad_reduc(u))
C = F.T*F
# E = 0.5*(C-I)
B = F*F.T
J = det(F)
I1 = tr(C)
I2 = 0.5*(tr(C)**2 - tr(C*C))
I3 = det(C)
IB = tr(B)
mu = material_parameters['mu']
jm = material_parameters['jm']
psi = -0.5*mu*(jm*ln(1 - (IB - 3)/jm) + 2*ln(J)) # Gent compressible
PK1 = diff(psi, F)
PK2 = dot(inv(F), PK1)
return psi, PK1, PK2
def Pi_(u, mp_sub, dx_sub): # f_msr, dx_msr_f):
'''Potential energy
Parameters
----------
u : dolfin.Function
The displacement field, a vector values function.
mp_sub : iterable of dict's whose values are dolfin.Constant's
Material parameters for each material subdomain.
dx_sub: iterable of dolfin.Measure's
Material integration subdomains.
Returns
-------
Pi : ufl.Form
The potential energy of the hyper-elastic solid
'''
W_int = W_ext = 0
# deformation energy
for mp_sub_i, dx_sub_i in zip(mp_sub, dx_sub):
psi, *_ = Psi_(u, mp_sub_i)
W_int += psi * dx_sub_i
# # external load potential
# for f_msr_i, dx_msr_i in zip(f_msr, dx_msr_f):
# W_ext += dot(u, f_msr_i) * dx_msr_i
Pi = W_int - W_ext
return Pi
### Define the Cost Functional
def J_u_(u, u_msr, dx_msr, w_msr=None):
'''Cost functional.
J^{(k)}(u^{(k)}, u_msr^{(k)}) :=
\frac{1}{2} \int_{\Gamma_\mathrm{msr}} (u^{(k)} - u_msr^{(k)})^2 \, dx
The weights can be precomputed
This weight needs to be a dolfin.Constant that is assigned a pre-computed
value for each time. This can be done in the `observatio_setter`.
On the other hand, the weight must be differnetiable integral wrt some
parameter, (most likely measurement) so, the weight should be a ufl.Form.
What if the weight is not a ufl.Form; maye it's just a constant that
depends on the measurement, like a quantity of interset.
Parameters
----------
u : dolfin.Function
Model solution, e.g. displacement field
u_msr : iterable of dolfin.Expression's
Expermental measurements, e.g. 1DIC measurements
dx_msr : iterable of dolfin.Measure's
Integration domain, e.g. DIC measurement surface
Returns
-------
J : ufl.Form
The measure of the model cost, a cost functional.
'''
J = 0
if w_msr is None:
w_msr = (1,) * len(dx_msr)
for w_msr_i, u_msr_i, dx_msr_i in zip(w_msr, u_msr, dx_msr):
J += (u - u_msr_i)**2 / w_msr_i * dx_msr_i
return J
### Define the Constraint Equation
def C_fx_(f, f_msr, dx_msr, w_msr=None):
'''Constraint equation to impose on cost functional.
Reaction force in x-direction.
'''
C = 0
if w_msr is None:
w_msr = (1,) * len(dx_msr)
for w_msr_i, f_msr_i, dx_msr_i in zip(w_msr, f_msr, dx_msr):
C += (f[0] - f_msr_i[0]) / w_msr_i * dx_msr_i
# C += (f[0] - f_msr_i[0])**2 / w_msr_i * dx_msr_i
return C
def C_f_(f, f_msr, dx_msr, w_msr=None):
'''Constraint equation to impose on cost functional.
Net reaction force.
'''
C = 0
if w_msr is None:
w_msr = (1,) * len(dx_msr)
for w_msr_i, f_msr_i, dx_msr_i in zip(w_msr, f_msr, dx_msr):
# C += (sqrt(f**2)-sqrt(f_msr_i**2)) / w_msr_i * dx_msr_i
C+=1
return C
### Integration domains
dx_material = [
dolfin.Measure('dx',
domain=mesh_domain,
subdomain_data=markers_domain,
subdomain_id=(
id_markers_domain['keloid_measure'],
)
),
dolfin.Measure('dx',
domain=mesh_domain,
subdomain_data=markers_domain,
subdomain_id=(
id_markers_domain['healthy'],
id_markers_domain['healthy_measure'],
)
),
]
dx_measure = [
dolfin.Measure('dx',
domain=mesh_domain,
subdomain_data=markers_domain,
subdomain_id=(
id_markers_domain['keloid_measure'],
id_markers_domain['healthy_measure'],
)
),
]
ds_boundary_pad_one = dolfin.Measure('ds',
domain=mesh_domain,
subdomain_data=markers_boundary,
subdomain_id=(id_markers_boundary['pad_one_sensor'],))
ds_measure = [ds_boundary_pad_one]
dx_mat = dx_material
dx_msr_dom = dx_measure
ds_msr_pad = ds_measure
### To check if the external pad is well identified.
ds_boundary_pad_one_external = dolfin.Measure('ds',
domain=mesh_domain,
subdomain_data=markers_boundary,
subdomain_id=(id_markers_boundary['pad_one'],))
print('Sensor pad surface integration length', dolfin.assemble(1*ds_measure[0]))
print('External pad perimeter', dolfin.assemble(1*ds_boundary_pad_one_external))
if RUN_AS_TEST:
logger.warning('Assuming measurement domain to be the material domain.')
dx_msr_dom = dx_mat
### Function spaces
V = VectorFunctionSpace(mesh_domain, 'CG', 2)
V_msr_u = VectorFunctionSpace(mesh_domain, 'CG', 2)
### Dirichlet Boundary Conditions
bcs = []
uD_msr_pad_one = Expression(('ux','uy'), ux=0.0, uy=0.0, degree=0)
uD_msr_pad_two = Expression(('ux','uy'), ux=0.0, uy=0.0, degree=0)
bcs = [DirichletBC(V, uD_msr_pad_one, markers_boundary, id_markers_boundary['pad_one']),
DirichletBC(V, uD_msr_pad_one, markers_boundary, id_markers_boundary['pad_one_sensor']),
DirichletBC(V, uD_msr_pad_two, markers_boundary, id_markers_boundary['pad_two'])
]
EPS_DOLFIN = 1e-14
def bottom_boundary(x, on_boundary):
return on_boundary and near(x[1], -5, EPS_DOLFIN)
def top_boundary(x, on_boundary):
return on_boundary and near(x[1], 45, EPS_DOLFIN)
def left_boundary(x, on_boundary):
return on_boundary and near(x[0], 0, EPS_DOLFIN)
def right_boundary(x, on_boundary):
return on_boundary and near(x[0], 100, EPS_DOLFIN)
if FIX_BOUNDARY:
uD_x = Constant(0.0)
uD_y = Constant(0.0)
V_x, V_y = V.split()
bcs.extend([
DirichletBC(V_y, uD_y, bottom_boundary),
DirichletBC(V_y, uD_y, top_boundary),
DirichletBC(V_x, uD_x, left_boundary),
DirichletBC(V_x, uD_x, right_boundary),
])
msr_pad_one_fx_exact = np.array(fx_msr_pad_vals)
assert msr_pad_one_fx_exact.ndim == 1
### Model
u = Function(V)
if FIX_BOUNDARY:
material_parameters = [
{'mu': Constant(0),
'jm': Constant(0)},
{'mu': Constant(0),
'jm': Constant(0)}]
else:
material_parameters = [
{'mu': Constant(0),
'jm': Constant(0)},
{'mu': Constant(0),
'jm': Constant(0)}]
Pi = Pi_(u, material_parameters, dx_material)
def measurement_setter(t=None):
'''This function will be called inside the `InverseSolver` for each
solution time `t`. The purpose of this function is to set the values
of the measurements.
'''
if t is None: return
if t == -1: t = t_msr[-1]
# set dirichlet BC to measurement
uD_msr_pad_one.ux = ux_msr_pad_vals[t]
print(uD_msr_pad_one.ux)
# set displacement measurement
if isinstance(t, int):
for u_msr_i in u_msr:
u_msr_i.set_measurement_index(t)
print('set displacement measurement done for t=', t)
else:
for u_msr_i in u_msr:
u_msr_i.set_measurement_time(t)
print('set displacement measurement done for t=', t)
if isinstance(t, int):
for f_msr_i in f_msr:
f_msr_i.set_measurement_index(t)
print('set force measurement done for t=', t)
else:
for f_msr_i in f_msr:
f_msr_i.set_measurement_time(t)
print('set force measurement done for t=', t)
# TODO: This needs to be precomputed
# set cost weights for the displacement measurement
for var_w_i, form_w_msr_i in zip(var_w_msr_dic, form_w_msr_dic):
k = (id(var_w_i), t)
if k in previously_assembled_forms:
assemble_form_w_msr_i = previously_assembled_forms[k]
else:
assemble_form_w_msr_i = form_w_msr_dic_max
previously_assembled_forms[k] = assemble_form_w_msr_i
# assemble_form_w_msr_i = assemble(form_w_msr_i)
var_w_i.assign(assemble_form_w_msr_i)
# set cost weights for the force measurement
for var_w_i, form_w_msr_i in zip(var_w_msr_pad, form_w_msr_pad):
k = (id(var_w_i), t)
if k in previously_assembled_forms:
assemble_form_w_msr_i = previously_assembled_forms[k]
else:
assemble_form_w_msr_i = form_w_msr_force_max
previously_assembled_forms[k] = assemble_form_w_msr_i
# assemble_form_w_msr_i = assemble(form_w_msr_i)
var_w_i.assign(assemble_form_w_msr_i)
# set cost weight derivative values for the displacement measurement
for var_dwdv_msr_i, form_dwdv_msr_i in zip(var_dwdu_msr_dic, form_dwdu_msr_dic):
k = (id(var_w_i), t)
if k in previously_assembled_forms:
assemble_form_dwdv_msr_i = previously_assembled_forms[k]
else:
assemble_form_dwdv_msr_i = assemble(form_dwdv_msr_i)
previously_assembled_forms[k] = assemble_form_dwdv_msr_i
# assemble_form_dwdv_msr_i = assemble(form_dwdv_msr_i)
var_dwdv_msr_i.assign(assemble_form_dwdv_msr_i)
# set cost weight derivative values for the force measurement
for var_dwdv_msr_i, form_dwdv_msr_i in zip(var_dwdf_msr_pad, form_dwdf_msr_pad):
k = (id(var_w_i), t)
if k in previously_assembled_forms:
assemble_form_dwdv_msr_i = previously_assembled_forms[k]
else:
assemble_form_dwdv_msr_i = assemble(form_dwdv_msr_i)
previously_assembled_forms[k] = assemble_form_dwdv_msr_i
# assemble_form_dwdv_msr_i = assemble(form_dwdv_msr_i)
var_dwdv_msr_i.assign(assemble_form_dwdv_msr_i)
### Printing converging paramters for each standard variation set
result_parameters_file = open('identified_parameters_with_noise.txt', 'w')
for std_u_i, val_u in enumerate(std_u):
for std_f_i, val_f in enumerate(std_f):
print('Inverse identification for standard variations: ', val_u, '--', val_f)
n_msr_noisy = len(u_msr_dom_func_original)
t_msr_noisy = tuple(range(0,n_msr_noisy))
# Applying noises
u_msr_noisy = []
fx_msr_pad_left_noisy = []
for i, t in enumerate(t_msr_noisy):
u_msr_noisy.append(u_msr_dom_func_original[i].copy(deepcopy=True))
fx_msr_pad_left_noisy.append(fx_msr_pad_vals[i])
if t != 0:
if std_u[std_u_i] != 0.0 :
u_msr_noisy[-1] = generate_noisy_displacement(u_msr_dom_func_original[i], V_generator, val_u)
if std_f[std_f_i] != 0.0 :
fx_msr_pad_left_noisy[-1] += np.random.normal(0, val_f)
file = File("results/noisy_displacement/" + str(val_u) + '_' + str(val_f) + "/displacement_"+str(t_msr_noisy[t])+".pvd");
file << u_msr_noisy[-1]
# Computing relative errors between original and noisy data
U_rel_err = []
U_abs_err = []
U_ref_assembled = []
u_diff = Function(V_generator)
for t in tuple(range(1,n_msr_noisy)):
print("Computing relative errors in \"restricted\" ZOI case: ", t, '/', t_msr_noisy[-1], 'done')
u_diff = u_msr_noisy[t] - u_msr_dom_func_original[t]
diff_disp = dolfin.project(u_diff, V_generator)
U_abs_err.append(np.sqrt(assemble(dot(u_diff,u_diff)*dx_material_generator[0])+\
assemble(dot(u_diff,u_diff)*dx_material_generator[1])))
U_ref_assembled.append(np.sqrt(assemble(dot(u_msr_dom_func_original[t],u_msr_dom_func_original[t])*dx_material_generator[0])+\
assemble(dot(u_msr_dom_func_original[t],u_msr_dom_func_original[t])*dx_material_generator[1])))
U_rel_err.append(U_abs_err[-1]/U_ref_assembled[-1])
diff_disp.vector()[:] = abs(diff_disp.vector()[:])
print('Relative errors |reference u - dummy u| is: \n', U_rel_err)
U_abs_err_all_times = sum(U_abs_err)/sum(U_ref_assembled)
print('Total relative error |reference u - dummy u| is: \n', U_abs_err_all_times)
F_rel_err = relative_error_force(fx_msr_pad_left_noisy, fx_msr_pad_vals)
print('Total relative error |reference f - dummy f| is: ', F_rel_err)
if PLOT_RESULTS:
plot_path = 'results/plots/' + str(val_u) + '_' + str(val_f)
if os.path.exists(plot_path):
shutil.rmtree(plot_path)
os.makedirs ('results/plots/' + str(val_u) + '_' + str(val_f))
if PLOT_RESULTS:
figname = 'Reaction force vs. x-displacement'
plt.figure(figname)
plt.clf()
FENICS_ux_msr_pad_left_abs = np.abs(np.array(ux_msr_pad_vals))
FENICS_fx_msr_pad_left_abs = np.abs(np.array(fx_msr_pad_vals))
FENICS_fx_msr_pad_left_noisy_abs = np.abs(np.array(fx_msr_pad_left_noisy))
plt.rc('xtick', labelsize=12)
plt.rc('ytick', labelsize=12)
plt.plot(FENICS_ux_msr_pad_left_abs, FENICS_fx_msr_pad_left_abs, 'b-.')
plt.plot(FENICS_ux_msr_pad_left_abs, FENICS_fx_msr_pad_left_noisy_abs, 'r.')
plt.legend(['Reference','Dummy data'])
plt.xlabel('Pad displacement [mm]')
plt.ylabel('Reaction force [N]')
plt.title(figname)
plt.savefig('results/plots/' + str(val_u) + '_' + str(val_f) +'/noised_FU_curve.png')
plt.savefig('results/plots/' + str(val_u) + '_' + str(val_f) +'/noised_FU_curve.eps')
### Project generated data on identification mesh
u_msr_dom_func = []
for u_i in u_msr_noisy:
u_msr_dom_func.append(dolfin.project(u_i, V_msr_u))
### Create Measurement Expressions from Data
if RUN_AS_TEST:
n_msr_dic = len(u_msr_dom_func)
n_msr_pad = len(fx_msr_pad_left_noisy)
assert n_msr_dic == n_msr_pad
n_msr = n_msr_dic
t_msr = tuple(range(0,n_msr))
if RUN_AS_TEST:
u_msr = u_msr_dom_func
f_msr = np.zeros((n_msr_pad, 2), float)
f_msr[:,0] = fx_msr_pad_left_noisy # no y-component
f_msr /= assemble(1*ds_measure[0])
u_msr_dic = measure.MeasurementExpression(u_msr, t_msr, degree=2)
f_msr_pad = measure.MeasurementExpression(f_msr, t_msr, degree=0)
# place similar measurements in some containers
u_msr = [u_msr_dic,]
f_msr = [f_msr_pad,]
### Weights for Normalizing Cost Terms
# i.e. the weights will go in the denominator
# TODO: Need an abstraction
# Weight as a `ufl.Form`
# NOTE: can be differentiated with respect to a `dummy_delta_*`
# NOTE: shall not multiply anyother `ufl.Form`
noise_delta_u_msr = [Constant(0) for _ in u_msr]
noise_delta_f_msr = [Constant(0) for _ in f_msr]
eps_w_msr_dic = Constant(1e-4) # ensure positive denominator in cost
eps_w_msr_pad = Constant(1e-4) # ensure positive denominator in cost
form_w_msr_dic = [ (eps_w_msr_dic + u_msr_i**2) * dx_msr_i
for u_msr_i, dx_msr_i in zip(u_msr, dx_measure)]
form_w_msr_pad = [ (eps_w_msr_pad + sqrt(f_msr_i**2)) * dx_msr_i
for f_msr_i, dx_msr_i in zip(f_msr, ds_measure)]
form_dwdu_msr_dic = [ diff(w_msr_i, d_msr_i)
for w_msr_i, d_msr_i in zip(form_w_msr_dic, noise_delta_u_msr)]
form_dwdf_msr_pad = [ diff(w_msr_i, d_msr_i)
for w_msr_i, d_msr_i in zip(form_w_msr_pad, noise_delta_f_msr)]
# Weight as a `Constant` variable
# NOTE: can left-multiply a `ufl.Form`
# NOTE: can not be differentiated with respect to a `dummy_delta_*`
# NOTE: values must be assigned inside `measurement_setter`, e.g.
# var_w_msr_dic[i].assign(assemble(form_w_msr_dic[i]))
# var_w_msr_pad[i].assign(assemble(form_w_msr_pad[i]))
var_w_msr_dic = [Constant(0.0) for _ in dx_measure]
var_w_msr_pad = [Constant(0.0) for _ in ds_measure]
var_dwdu_msr_dic = [Constant(0.0) for _ in dx_measure]
var_dwdf_msr_pad = [Constant(0.0) for _ in ds_measure]
# Compute max of displacement
form_w_msr_dic_max = compute_max_w_msr_dic(u_msr_dom_func, dx_material)
# Compute max of reaction force
form_w_msr_force_max = max(np.abs(fx_msr_pad_left_noisy))
### Model Cost
J_u = J_u_(u, u_msr, dx_measure, var_w_msr_dic)
### Model Cost Constraint
# NOTE:
# T = dot(P,N) # numerical force
# R = f_msr[0] # measured reaction
N = FacetNormal(mesh_domain)
psi_keloid, P_keloid, S_keloid = Psi_(u, material_parameters[0])
psi_healthy, P_healthy, S_healthy = Psi_(u, material_parameters[1])
f = dolfin.dot(dim_reduc(P_keloid), N)
C_f = C_fx_(f, f_msr, ds_measure, var_w_msr_pad)
constraint_multiplier = Constant(-1e-6)
J_f = constraint_multiplier * C_f
### Inverse Solver Arguments
class model:
u = u
Pi = Pi
bcs = bcs
model_cost = J_u + J_f
model_parameters = [
material_parameters,
constraint_multiplier]
observation_times = t_msr
previously_assembled_forms = {}
### Initialize Inverse Solver
ip = invsolve.InverseSolver( model_cost, model, model_parameters, J_u, C_f,
observation_times=None, measurement_setter=None)
ip.assign_observation_times(observation_times)
ip.assign_measurement_setter(measurement_setter)
t_obs = t_msr # TEST
m_initial = [0.049, 0.19,
0.015, 0.39,
1e-04]
# Solving for the mean model parameters.
u.vector()[:] = 0.
ip.assign_model_parameters(m_initial)
try:
num_iters, has_converged = ip.minimize_cost_forall(t_obs,
sensitivity_method='default', approximate_D2JDm2='default')
except:
has_converged = False
if not has_converged:
logger.warning('Inverse solver did not converge.')
m_forall = ip.view_model_parameters_as_list()
if not has_converged:
print('has not converged')
result_parameters_file.write('Did not converged for std_u = ' + str(val_u) + 'and std_f = '+ str(val_f) + '\n')
else:
print('has converged')
result_parameters_file.write(str(val_f) + ', ' + str(F_rel_err) + ', ' +\
str(val_u) + ', ' + str(U_abs_err_all_times) + ', ' +\
str(m_forall[0:4])[1:-1] + '\n')
### Observe Model Cost
u.vector()[:] = 0.
J_obs, Ju_obs, Jf_obs = ip.observe_model_cost_seperate()
Jf_obs = np.abs(Jf_obs)
if PLOT_RESULTS :
figname = 'Observed Cost for each observation time'
fh = plt.figure(figname)
ax = fh.add_subplot(111)
ax.clear()
ax.plot(t_obs, Ju_obs, 'r-o', markerfacecolor='w')
ax.plot(t_obs, Jf_obs, 'b-o', markerfacecolor='w')
ax.plot(t_obs, J_obs, 'k--', markerfacecolor='w')
ax.legend(['Cost of displacements mismatch',
'Cost of reaction forces mismatch',
'Total cost'])
plt.rc('xtick', labelsize=12)
plt.rc('ytick', labelsize=12)
ax.set_title(figname)
ax.set_xlabel('Observation time, t ')
ax.set_ylabel('Cost functional value, J(t)')
plt.savefig('results/plots/' + str(val_u) + '_' + str(val_f) +'/obs_cost_for_each_obs_time.png')
plt.savefig('results/plots/' + str(val_u) + '_' + str(val_f) +'/obs_cost_for_each_obs_time.eps')
### Compute observed pad reaction force from displacement control
n_obs = n_msr_dic
i_obs = list(range(n_obs))
msr_pad_one_ux_abs = np.abs(msr_pad_one_ux)
msr_pad_one_fx_abs = np.abs(fx_msr_pad_left_noisy)
msr_pad_one_fx_exact_abs = np.abs(msr_pad_one_fx)
obs_pad_one_ux_abs = []
obs_pad_one_fx_abs = []
u.vector()[:] = 0.
for i in i_obs:
uD_msr_pad_one.ux = msr_pad_one_ux[i]
ip.solve_nonlinear_problem()
obs_pad_one_ux_abs.append(abs(uD_msr_pad_one.ux))
obs_pad_one_fx_abs.append(abs(assemble(f[0]*ds_measure[0])))
u_msr_noisy_ref = dolfin.project(u_msr_noisy[-1], V)
u_diff_inverse_solution = u_msr_noisy_ref - u
diff_disp_inverse_solution = dolfin.project(u_diff_inverse_solution, V)
file = File("results/plots/" + str(val_u) + '_' + str(val_f) +"/inverse_solution_last_observation_time.pvd");
file << diff_disp_inverse_solution
if PLOT_RESULTS:
figname = 'Pad Reaction Force vs. Displacement (inverse solution)'
fh = plt.figure(figname)
ax = fh.add_subplot(111)
ax.clear()
ax.plot(msr_pad_one_ux_abs, msr_pad_one_fx_abs, 'k.', linewidth=2)
ax.plot(msr_pad_one_ux_abs, msr_pad_one_fx_exact_abs, 'b', linewidth=2)
ax.plot(obs_pad_one_ux_abs, obs_pad_one_fx_abs, 'r--', linewidth=2)
ax.legend(['Dummy data', 'Reference', 'Inverse solution'])
ax.set_title(figname)
ax.set_xlabel('Pad displacement (mm)')
ax.set_ylabel('Pad reaction force (N)')
plt.savefig('results/plots/' + str(val_u) + '_' + str(val_f) +'/inverse_solution.png')
plt.savefig('results/plots/' + str(val_u) + '_' + str(val_f) +'/inverse_solution.eps')
result_parameters_file.close()
| 29.932715 | 138 | 0.637547 |
acec7da21c41a973de9920cd3786e2595a1cae2a | 1,926 | py | Python | yt/tests/test_funcs.py | FeiLi5/git-github.com-yt-project-yt | 0c6cf75351b91e4da80f6a0207ebbcb73dd72a59 | [
"BSD-3-Clause-Clear"
] | 2 | 2021-03-02T18:59:49.000Z | 2021-03-02T18:59:50.000Z | yt/tests/test_funcs.py | FeiLi5/git-github.com-yt-project-yt | 0c6cf75351b91e4da80f6a0207ebbcb73dd72a59 | [
"BSD-3-Clause-Clear"
] | 4 | 2018-04-13T23:03:42.000Z | 2018-05-08T17:50:43.000Z | yt/tests/test_funcs.py | FeiLi5/git-github.com-yt-project-yt | 0c6cf75351b91e4da80f6a0207ebbcb73dd72a59 | [
"BSD-3-Clause-Clear"
] | 2 | 2020-05-16T15:29:37.000Z | 2020-06-22T10:17:08.000Z | """
Tests for yt.funcs
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2018, yt Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
from nose.tools import assert_raises
from yt import YTQuantity
from yt.funcs import validate_axis, validate_center
from yt.testing import assert_equal, fake_amr_ds
def test_validate_axis():
validate_axis(None, 0)
validate_axis(None, 'X')
ds = fake_amr_ds(geometry="cylindrical")
ds.slice("Theta", 0.25)
with assert_raises(TypeError) as ex:
# default geometry is cartesian
ds = fake_amr_ds()
ds.slice("r", 0.25)
desired = ("Expected axis of int or char type (can be "
"[0, 'x', 'X', 1, 'y', 'Y', 2, 'z', 'Z']), received 'r'.")
assert_equal(str(ex.exception)[:40], desired[:40])
def test_validate_center():
validate_center("max")
validate_center("MIN_")
with assert_raises(TypeError) as ex:
validate_center("avg")
desired = ("Expected 'center' to be in ['c', 'center', 'm', 'max', 'min'] "
"or the prefix to be 'max_'/'min_', received 'avg'.")
assert_equal(str(ex.exception), desired)
validate_center(YTQuantity(0.25, 'cm'))
validate_center([0.25, 0.25, 0.25])
class CustomCenter:
def __init__(self, center):
self.center = center
with assert_raises(TypeError) as ex:
validate_center(CustomCenter(10))
desired = ("Expected 'center' to be a numeric object of type "
"list/tuple/np.ndarray/YTArray/YTQuantity, received "
"'yt.tests.test_funcs.test_validate_center.<locals>."
"CustomCenter'.")
assert_equal(str(ex.exception)[:50], desired[:50])
| 33.789474 | 79 | 0.590343 |
acec7e0e00544ad1c7d001e6aa4d49824e1de511 | 2,742 | py | Python | third-party/llvm/llvm-src/tools/clang/bindings/python/examples/cindex/cindex-dump.py | SamuelHoward/chapel | f1b927b5abaf6210ec05347c88d5f15c17b7ea47 | [
"ECL-2.0",
"Apache-2.0"
] | 115 | 2018-02-01T18:56:44.000Z | 2022-03-21T13:23:00.000Z | third-party/llvm/llvm-src/tools/clang/bindings/python/examples/cindex/cindex-dump.py | SamuelHoward/chapel | f1b927b5abaf6210ec05347c88d5f15c17b7ea47 | [
"ECL-2.0",
"Apache-2.0"
] | 27 | 2018-09-17T17:49:49.000Z | 2021-11-03T04:31:51.000Z | third-party/llvm/llvm-src/tools/clang/bindings/python/examples/cindex/cindex-dump.py | SamuelHoward/chapel | f1b927b5abaf6210ec05347c88d5f15c17b7ea47 | [
"ECL-2.0",
"Apache-2.0"
] | 55 | 2018-02-01T07:11:49.000Z | 2022-03-04T01:20:23.000Z | #!/usr/bin/env python
#===- cindex-dump.py - cindex/Python Source Dump -------------*- python -*--===#
#
# The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License. See LICENSE.TXT for details.
#
#===------------------------------------------------------------------------===#
"""
A simple command line tool for dumping a source file using the Clang Index
Library.
"""
def get_diag_info(diag):
return { 'severity' : diag.severity,
'location' : diag.location,
'spelling' : diag.spelling,
'ranges' : diag.ranges,
'fixits' : diag.fixits }
def get_cursor_id(cursor, cursor_list = []):
if not opts.showIDs:
return None
if cursor is None:
return None
# FIXME: This is really slow. It would be nice if the index API exposed
# something that let us hash cursors.
for i,c in enumerate(cursor_list):
if cursor == c:
return i
cursor_list.append(cursor)
return len(cursor_list) - 1
def get_info(node, depth=0):
if opts.maxDepth is not None and depth >= opts.maxDepth:
children = None
else:
children = [get_info(c, depth+1)
for c in node.get_children()]
return { 'id' : get_cursor_id(node),
'kind' : node.kind,
'usr' : node.get_usr(),
'spelling' : node.spelling,
'location' : node.location,
'extent.start' : node.extent.start,
'extent.end' : node.extent.end,
'is_definition' : node.is_definition(),
'definition id' : get_cursor_id(node.get_definition()),
'children' : children }
def main():
from clang.cindex import Index
from pprint import pprint
from optparse import OptionParser, OptionGroup
global opts
parser = OptionParser("usage: %prog [options] {filename} [clang-args*]")
parser.add_option("", "--show-ids", dest="showIDs",
help="Compute cursor IDs (very slow)",
action="store_true", default=False)
parser.add_option("", "--max-depth", dest="maxDepth",
help="Limit cursor expansion to depth N",
metavar="N", type=int, default=None)
parser.disable_interspersed_args()
(opts, args) = parser.parse_args()
if len(args) == 0:
parser.error('invalid number arguments')
index = Index.create()
tu = index.parse(None, args)
if not tu:
parser.error("unable to load input")
pprint(('diags', [get_diag_info(d) for d in tu.diagnostics]))
pprint(('nodes', get_info(tu.cursor)))
if __name__ == '__main__':
main()
| 31.159091 | 80 | 0.571845 |
acec7e70b3e4e38fb67187aebbabdcaa69a645f7 | 14,853 | py | Python | apps/useradmin/src/useradmin/forms.py | t3hi3x/hue | 36d71c1a8dd978b899ef2dc3eef8887b68fd99a8 | [
"Apache-2.0"
] | 1 | 2020-04-10T07:54:39.000Z | 2020-04-10T07:54:39.000Z | apps/useradmin/src/useradmin/forms.py | t3hi3x/hue | 36d71c1a8dd978b899ef2dc3eef8887b68fd99a8 | [
"Apache-2.0"
] | null | null | null | apps/useradmin/src/useradmin/forms.py | t3hi3x/hue | 36d71c1a8dd978b899ef2dc3eef8887b68fd99a8 | [
"Apache-2.0"
] | 1 | 2019-07-31T15:00:30.000Z | 2019-07-31T15:00:30.000Z | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import re
import django.contrib.auth.forms
from django import forms
from django.contrib.auth.models import User, Group
from django.forms.util import ErrorList
from django.utils.translation import ugettext as _, ugettext_lazy as _t
from desktop import conf as desktop_conf
from desktop.lib.django_util import get_username_re_rule, get_groupname_re_rule
from useradmin.models import GroupPermission, HuePermission
from useradmin.models import get_default_user_group
from useradmin.password_policy import get_password_validators
LOG = logging.getLogger(__name__)
def get_server_choices():
if desktop_conf.LDAP.LDAP_SERVERS.get():
return [(ldap_server_record_key, ldap_server_record_key) for ldap_server_record_key in desktop_conf.LDAP.LDAP_SERVERS.get()]
else:
return []
def validate_dn(dn):
assert dn is not None, _('Full Distinguished Name required.')
def validate_username(username_pattern):
validator = re.compile(r"^%s$" % get_username_re_rule())
assert username_pattern is not None, _('Username is required.')
assert len(username_pattern) <= 30, _('Username must be fewer than 30 characters.')
assert validator.match(username_pattern), _("Username must not contain whitespaces and ':'")
def validate_groupname(groupname_pattern):
validator = re.compile(r"^%s$" % get_groupname_re_rule())
assert groupname_pattern is not None, _('Group name required.')
assert len(groupname_pattern) <= 80, _('Group name must be 80 characters or fewer.')
assert validator.match(groupname_pattern), _("Group name can be any character as long as it's 80 characters or fewer.")
class UserChangeForm(django.contrib.auth.forms.UserChangeForm):
"""
This is similar, but not quite the same as djagno.contrib.auth.forms.UserChangeForm
and UserCreationForm.
"""
username = forms.RegexField(
label=_t("Username"),
max_length=30,
regex='^%s$' % (get_username_re_rule(),),
help_text = _t("Required. 30 characters or fewer. No whitespaces or colons."),
error_messages = {'invalid': _t("Whitespaces and ':' not allowed") })
password1 = forms.CharField(label=_t("Password"),
widget=forms.
PasswordInput,
required=False,
validators=get_password_validators())
password2 = forms.CharField(label=_t("Password confirmation"),
widget=forms.PasswordInput,
required=False,
validators=get_password_validators())
password_old = forms.CharField(label=_t("Previous Password"), widget=forms.PasswordInput, required=False)
ensure_home_directory = forms.BooleanField(label=_t("Create home directory"),
help_text=_t("Create home directory if one doesn't already exist."),
initial=True,
required=False)
class Meta(django.contrib.auth.forms.UserChangeForm.Meta):
fields = ["username", "first_name", "last_name", "email", "ensure_home_directory"]
def __init__(self, *args, **kwargs):
super(UserChangeForm, self).__init__(*args, **kwargs)
if self.instance.id:
self.fields['username'].widget.attrs['readonly'] = True
if desktop_conf.AUTH.BACKEND.get() == 'desktop.auth.backend.LdapBackend':
self.fields['password1'].widget.attrs['readonly'] = True
self.fields['password2'].widget.attrs['readonly'] = True
self.fields['password_old'].widget.attrs['readonly'] = True
def clean_password(self):
return self.cleaned_data["password"]
def clean_password2(self):
password1 = self.cleaned_data.get("password1", "")
password2 = self.cleaned_data["password2"]
if password1 != password2:
raise forms.ValidationError(_t("Passwords do not match."))
return password2
def clean_password1(self):
password = self.cleaned_data.get("password1", "")
if self.instance.id is None and password == "":
raise forms.ValidationError(_("You must specify a password when creating a new user."))
return self.cleaned_data.get("password1", "")
def clean_password_old(self):
if self.instance.id is not None:
password1 = self.cleaned_data.get("password1", "")
password_old = self.cleaned_data.get("password_old", "")
if password1 != '' and not self.instance.check_password(password_old):
raise forms.ValidationError(_("The old password does not match the current password."))
return self.cleaned_data.get("password_old", "")
def save(self, commit=True):
"""
Update password if it's set.
"""
user = super(UserChangeForm, self).save(commit=False)
if self.cleaned_data["password1"]:
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
# groups must be saved after the user
self.save_m2m()
return user
class SuperUserChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta):
fields = ["username", "is_active"] + UserChangeForm.Meta.fields + ["is_superuser", "groups"]
def __init__(self, *args, **kwargs):
super(SuperUserChangeForm, self).__init__(*args, **kwargs)
if self.instance.id:
# If the user exists already, we'll use its current group memberships
self.initial['groups'] = set(self.instance.groups.all())
else:
# If his is a new user, suggest the default group
default_group = get_default_user_group()
if default_group is not None:
self.initial['groups'] = set([default_group])
else:
self.initial['groups'] = []
class AddLdapUsersForm(forms.Form):
username_pattern = forms.CharField(
label=_t("Username"),
help_text=_t("Required. 30 characters or fewer with username. 64 characters or fewer with DN. No whitespaces or colons."),
error_messages={'invalid': _t("Whitespaces and ':' not allowed")})
dn = forms.BooleanField(label=_t("Distinguished name"),
help_text=_t("Whether or not the user should be imported by "
"distinguished name."),
initial=False,
required=False)
ensure_home_directory = forms.BooleanField(label=_t("Create home directory"),
help_text=_t("Create home directory for user if one doesn't already exist."),
initial=True,
required=False)
def __init__(self, *args, **kwargs):
super(AddLdapUsersForm, self).__init__(*args, **kwargs)
if get_server_choices():
self.fields['server'] = forms.ChoiceField(choices=get_server_choices(), required=True)
def clean(self):
cleaned_data = super(AddLdapUsersForm, self).clean()
username_pattern = cleaned_data.get("username_pattern")
dn = cleaned_data.get("dn")
try:
if dn:
validate_dn(username_pattern)
else:
validate_username(username_pattern)
except AssertionError, e:
errors = self._errors.setdefault('username_pattern', ErrorList())
errors.append(e.message)
raise forms.ValidationError(e.message)
return cleaned_data
class AddLdapGroupsForm(forms.Form):
groupname_pattern = forms.CharField(
label=_t("Name"),
max_length=256,
help_text=_t("Required. 256 characters or fewer."),
error_messages={'invalid': _t("256 characters or fewer.") })
dn = forms.BooleanField(label=_t("Distinguished name"),
help_text=_t("Whether or not the group should be imported by "
"distinguished name."),
initial=False,
required=False)
import_members = forms.BooleanField(label=_t('Import new members'),
help_text=_t('Import unimported or new users from the group.'),
initial=False,
required=False)
ensure_home_directories = forms.BooleanField(label=_t('Create home directories'),
help_text=_t('Create home directories for every member imported, if members are being imported.'),
initial=True,
required=False)
import_members_recursive = forms.BooleanField(label=_t('Import new members from all subgroups'),
help_text=_t('Import unimported or new users from the all subgroups.'),
initial=False,
required=False)
def __init__(self, *args, **kwargs):
super(AddLdapGroupsForm, self).__init__(*args, **kwargs)
if get_server_choices():
self.fields['server'] = forms.ChoiceField(choices=get_server_choices(), required=True)
def clean(self):
cleaned_data = super(AddLdapGroupsForm, self).clean()
groupname_pattern = cleaned_data.get("groupname_pattern")
dn = cleaned_data.get("dn")
try:
if dn:
validate_dn(groupname_pattern)
else:
validate_groupname(groupname_pattern)
except AssertionError, e:
errors = self._errors.setdefault('groupname_pattern', ErrorList())
errors.append(e.message)
raise forms.ValidationError(e.message)
return cleaned_data
class GroupEditForm(forms.ModelForm):
"""
Form to manipulate a group. This manages the group name and its membership.
"""
GROUPNAME = re.compile('^%s$' % get_groupname_re_rule())
class Meta:
model = Group
fields = ("name",)
def clean_name(self):
# Note that the superclass doesn't have a clean_name method.
data = self.cleaned_data["name"]
if not self.GROUPNAME.match(data):
raise forms.ValidationError(_("Group name may only contain letters, " +
"numbers, hyphens or underscores."))
return data
def __init__(self, *args, **kwargs):
super(GroupEditForm, self).__init__(*args, **kwargs)
if self.instance.id:
self.fields['name'].widget.attrs['readonly'] = True
initial_members = User.objects.filter(groups=self.instance).order_by('username')
initial_perms = HuePermission.objects.filter(grouppermission__group=self.instance).order_by('app','description')
else:
initial_members = []
initial_perms = []
self.fields["members"] = _make_model_field(_("members"), initial_members, User.objects.order_by('username'))
self.fields["permissions"] = _make_model_field(_("permissions"), initial_perms, HuePermission.objects.order_by('app','description'))
def _compute_diff(self, field_name):
current = set(self.fields[field_name].initial_objs)
updated = set(self.cleaned_data[field_name])
delete = current.difference(updated)
add = updated.difference(current)
return delete, add
def save(self):
super(GroupEditForm, self).save()
self._save_members()
self._save_permissions()
def _save_members(self):
delete_membership, add_membership = self._compute_diff("members")
for user in delete_membership:
user.groups.remove(self.instance)
user.save()
for user in add_membership:
user.groups.add(self.instance)
user.save()
def _save_permissions(self):
delete_permission, add_permission = self._compute_diff("permissions")
for perm in delete_permission:
GroupPermission.objects.get(group=self.instance, hue_permission=perm).delete()
for perm in add_permission:
GroupPermission.objects.create(group=self.instance, hue_permission=perm)
class PermissionsEditForm(forms.ModelForm):
"""
Form to manage the set of groups that have a particular permission.
"""
class Meta:
model = Group
fields = ()
def __init__(self, *args, **kwargs):
super(PermissionsEditForm, self).__init__(*args, **kwargs)
if self.instance.id:
initial_groups = Group.objects.filter(grouppermission__hue_permission=self.instance).order_by('name')
else:
initial_groups = []
self.fields["groups"] = _make_model_field(_("groups"), initial_groups, Group.objects.order_by('name'))
def _compute_diff(self, field_name):
current = set(self.fields[field_name].initial_objs)
updated = set(self.cleaned_data[field_name])
delete = current.difference(updated)
add = updated.difference(current)
return delete, add
def save(self):
self._save_permissions()
def _save_permissions(self):
delete_group, add_group = self._compute_diff("groups")
for group in delete_group:
GroupPermission.objects.get(group=group, hue_permission=self.instance).delete()
for group in add_group:
GroupPermission.objects.create(group=group, hue_permission=self.instance)
def _make_model_field(label, initial, choices, multi=True):
""" Creates multiple choice field with given query object as choices. """
if multi:
field = forms.models.ModelMultipleChoiceField(choices, required=False)
field.initial_objs = initial
field.initial = [ obj.pk for obj in initial ]
field.label = label
else:
field = forms.models.ModelChoiceField(choices, required=False)
field.initial_obj = initial
if initial:
field.initial = initial.pk
return field
class SyncLdapUsersGroupsForm(forms.Form):
ensure_home_directory = forms.BooleanField(label=_t("Create Home Directories"),
help_text=_t("Create home directory for every user, if one doesn't already exist."),
initial=True,
required=False)
def __init__(self, *args, **kwargs):
super(SyncLdapUsersGroupsForm, self).__init__(*args, **kwargs)
if get_server_choices():
self.fields['server'] = forms.ChoiceField(choices=get_server_choices(), required=True)
| 40.581967 | 146 | 0.664714 |
acec7f172d94933b3a48c28f2160f2f6d3c770bb | 3,618 | py | Python | src/sentry/models/grouptagvalue.py | seukjung/sentry-custom | c5f6bb2019aef3caff7f3e2b619f7a70f2b9b963 | [
"BSD-3-Clause"
] | null | null | null | src/sentry/models/grouptagvalue.py | seukjung/sentry-custom | c5f6bb2019aef3caff7f3e2b619f7a70f2b9b963 | [
"BSD-3-Clause"
] | 6 | 2019-12-29T00:50:11.000Z | 2022-02-10T13:27:24.000Z | src/sentry/models/grouptagvalue.py | seukjung/sentry-custom | c5f6bb2019aef3caff7f3e2b619f7a70f2b9b963 | [
"BSD-3-Clause"
] | null | null | null | """
sentry.models.grouptagvalue
~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from datetime import timedelta
from django.db import connections, models, router
from django.db.models import Sum
from django.utils import timezone
from sentry.constants import MAX_TAG_KEY_LENGTH, MAX_TAG_VALUE_LENGTH
from sentry.db.models import (
Model, BoundedPositiveIntegerField, BaseManager,
sane_repr
)
from sentry.utils import db
class GroupTagValue(Model):
"""
Stores the total number of messages seen by a group matching
the given filter.
"""
__core__ = False
project_id = BoundedPositiveIntegerField(null=True)
group_id = BoundedPositiveIntegerField()
times_seen = BoundedPositiveIntegerField(default=0)
key = models.CharField(max_length=MAX_TAG_KEY_LENGTH)
value = models.CharField(max_length=MAX_TAG_VALUE_LENGTH)
last_seen = models.DateTimeField(
default=timezone.now, db_index=True, null=True)
first_seen = models.DateTimeField(
default=timezone.now, db_index=True, null=True)
objects = BaseManager()
class Meta:
app_label = 'sentry'
db_table = 'sentry_messagefiltervalue'
unique_together = (
('group_id', 'key', 'value'),
)
index_together = (
('project_id', 'key', 'value', 'last_seen'),
)
__repr__ = sane_repr('project_id', 'group_id', 'key', 'value')
def save(self, *args, **kwargs):
if not self.first_seen:
self.first_seen = self.last_seen
super(GroupTag, self).save(*args, **kwargs)
@classmethod
def get_value_count(cls, group_id, key):
if db.is_postgres():
# This doesnt guarantee percentage is accurate, but it does ensure
# that the query has a maximum cost
using = router.db_for_read(cls)
cursor = connections[using].cursor()
cursor.execute("""
SELECT SUM(t)
FROM (
SELECT times_seen as t
FROM sentry_messagefiltervalue
WHERE group_id = %s
AND key = %s
ORDER BY last_seen DESC
LIMIT 10000
) as a
""", [group_id, key])
return cursor.fetchone()[0] or 0
cutoff = timezone.now() - timedelta(days=7)
return cls.objects.filter(
group_id=group_id,
key=key,
last_seen__gte=cutoff,
).aggregate(t=Sum('times_seen'))['t']
@classmethod
def get_top_values(cls, group_id, key, limit=3):
if db.is_postgres():
# This doesnt guarantee percentage is accurate, but it does ensure
# that the query has a maximum cost
return list(cls.objects.raw("""
SELECT *
FROM (
SELECT *
FROM sentry_messagefiltervalue
WHERE group_id = %%s
AND key = %%s
ORDER BY last_seen DESC
LIMIT 10000
) as a
ORDER BY times_seen DESC
LIMIT %d
""" % limit, [group_id, key]))
cutoff = timezone.now() - timedelta(days=7)
return list(cls.objects.filter(
group_id=group_id,
key=key,
last_seen__gte=cutoff,
).order_by('-times_seen')[:limit])
GroupTag = GroupTagValue
| 32.017699 | 78 | 0.58209 |
acec80a8496d4229bfd72d6bb1a2fe587ce8ac53 | 270 | py | Python | mittalapp/mittal_app/doctype/test_mittalapp/test_test_mittalapp.py | vineet79/mittalapp | bb8911c9267c27e4cb5ada91011fa32c9b4a2e60 | [
"MIT"
] | null | null | null | mittalapp/mittal_app/doctype/test_mittalapp/test_test_mittalapp.py | vineet79/mittalapp | bb8911c9267c27e4cb5ada91011fa32c9b4a2e60 | [
"MIT"
] | null | null | null | mittalapp/mittal_app/doctype/test_mittalapp/test_test_mittalapp.py | vineet79/mittalapp | bb8911c9267c27e4cb5ada91011fa32c9b4a2e60 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vineet and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
# test_records = frappe.get_test_records('test mittalapp')
class Testtestmittalapp(unittest.TestCase):
pass
| 20.769231 | 58 | 0.774074 |
acec80d15939a7acd314f053075e2ae6e353fa2b | 22,102 | py | Python | annot/fishDB_pub.py | seita42/fish-patterns | 3c88d3a6d9f73c380847af46e65df99e62255702 | [
"MIT"
] | 1 | 2021-01-08T11:41:38.000Z | 2021-01-08T11:41:38.000Z | annot/fishDB_pub.py | seita42/fish-patterns | 3c88d3a6d9f73c380847af46e65df99e62255702 | [
"MIT"
] | null | null | null | annot/fishDB_pub.py | seita42/fish-patterns | 3c88d3a6d9f73c380847af46e65df99e62255702 | [
"MIT"
] | 1 | 2021-06-17T09:04:43.000Z | 2021-06-17T09:04:43.000Z | from flask import Flask, render_template, redirect, url_for, g, request
import pandas as pd
import sqlite3
import datetime
import random
app = Flask(__name__)
#### DB for pattern annotation
# DATABASE = 'fishDB_pub.db'
DATABASE = 'fishDB_pub_empty.db'
TABLE = 'fishdb'
#### Annotator's name
# ANNOTATOR = 'seita'
ANNOTATOR = 'anonymous'
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect(DATABASE)
db.row_factory = sqlite3.Row
return db
def query_db(query, args=(), one=False):
cur = get_db().execute(query, args)
rv = cur.fetchall()
cur.close()
return (rv[0] if rv else None) if one else rv
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
#### Dictionary for Japanese name
with app.app_context():
sql_str = 'SELECT DISTINCT family, jpn_fam FROM fishdb'
jpn_fams = dict(query_db(sql_str))
sql_str = 'SELECT DISTINCT species, jpn_name FROM fishdb'
jpn_names = dict(query_db(sql_str))
#### for time recording
start_time = datetime.datetime.now()
current_sp = 0
sp100_mode = False
SP100_NUM = 100
#### for auto mode
random_fam = False
current_fam = ""
#### where to go back?
next_url = ""
@app.route('/')
def hello():
return redirect(url_for('show_fam_list'))
@app.route('/fam_list')
def show_fam_list():
sort = request.args.get('sort', default=0, type=int)
sql_str = 'SELECT family, jpn_fam, genus, ' \
'COUNT(DISTINCT (CASE WHEN is_checked=1 THEN species ELSE NULL END)) AS sp_chk_num, ' \
'COUNT(DISTINCT species) AS sp_num ' \
'FROM fishdb GROUP BY genus'
sql_str = 'SELECT family, jpn_fam, ' \
'COUNT(CASE WHEN sp_chk_num = sp_num THEN genus ELSE NULL END) AS gen_comp_num, ' \
'COUNT(genus) AS gen_num, ' \
'SUM(sp_chk_num) AS sp_chk_num, ' \
'SUM(sp_num) AS sp_num ' \
'FROM (' + sql_str + ') GROUP BY family'
if (sort==0): ### A-Z
sql_str += ' ORDER BY family ASC'
elif (sort==1): ### gen_num ASC
sql_str += ' ORDER BY gen_num ASC'
elif (sort==2): ### gen_num DESC
sql_str += ' ORDER BY gen_num DESC'
fam_gen = query_db(sql_str)
sum_gen_comp_num = sum([row['gen_comp_num'] for row in fam_gen])
sum_gen_num = sum([row['gen_num'] for row in fam_gen])
sum_sp_chk_num = sum([row['sp_chk_num'] for row in fam_gen])
sum_sp_num = sum([row['sp_num'] for row in fam_gen])
return render_template('fam_list.html',
sum_gen_comp_num = sum_gen_comp_num,
sum_gen_num = sum_gen_num,
sum_sp_chk_num = sum_sp_chk_num,
sum_sp_num = sum_sp_num,
fam_gen = fam_gen,
sp100_mode = sp100_mode,
current_sp = current_sp)
@app.route('/gen_list/<fam>')
def show_gen_list(fam):
sort = request.args.get('sort', default=0, type=int)
jpn_fam = jpn_fams[fam]
### Sometimes the same genus can be found in different families...
### Counting all of them based on the genus list
### get genus list
sql_str = 'SELECT genus FROM fishdb WHERE family = ? GROUP BY genus'
gen_list = [row[0] for row in query_db(sql_str, [fam])]
### get sp_num
format_str = ','.join(list('?' * len(gen_list)))
sql_str = 'SELECT genus, ' \
'COUNT(DISTINCT species) AS sp_num, ' \
'COUNT(DISTINCT CASE WHEN is_checked=1 THEN species ELSE NULL END) AS sp_chk_num ' \
'FROM fishdb WHERE genus IN({}) GROUP BY genus'.format(format_str)
if (sort==0): ### A-Z
sql_str += ' ORDER BY genus ASC'
elif (sort==1): ### gen_num ASC
sql_str += ' ORDER BY sp_num ASC'
elif (sort==2): ### gen_num DESC
sql_str += ' ORDER BY sp_num DESC'
gen_sp = query_db(sql_str, gen_list)
return render_template('gen_list.html', fam=fam, jpn_fam=jpn_fam, gen_sp=gen_sp, sp100_mode=sp100_mode, current_sp=current_sp)
@app.route('/sp_list/<gen>')
def show_sp_list(gen):
### Sometimes the same species can be found in different families...
### Counting all of them
sql_str = 'SELECT DISTINCT family, jpn_fam FROM fishdb WHERE genus = ? GROUP BY family, jpn_fam'
fams = query_db(sql_str, [gen])
sql_str = 'SELECT species, jpn_name, ' \
'COUNT(img_file) AS pic_num, ' \
'COUNT(CASE WHEN is_checked=1 THEN img_file ELSE NULL END) AS pic_chk_num, ' \
'COUNT(mono=1 OR NULL) AS mono_num, ' \
'COUNT(area_fill=1 OR NULL) AS area_fill_num, ' \
'COUNT(stripe_vert=1 OR NULL) AS stripe_vert_num, ' \
'COUNT(stripe_horz=1 OR NULL) AS stripe_horz_num, ' \
'COUNT(stripe_diag=1 OR NULL) AS stripe_diag_num, ' \
'COUNT(stripe_maze=1 OR NULL) AS stripe_maze_num, ' \
'COUNT(spot_dark=1 OR NULL) AS spot_dark_num, ' \
'COUNT(spot_light=1 OR NULL) AS spot_light_num, ' \
'COUNT(eyespot=1 OR NULL) AS eyespot_num, ' \
'COUNT(saddle=1 OR NULL) AS saddle_num, ' \
'COUNT(blotch=1 OR NULL) AS blotch_num, ' \
'COUNT(no_use=1 OR NULL) AS no_use_num ' \
'FROM fishdb WHERE genus = ? GROUP BY species, jpn_name'
sp_pic = query_db(sql_str, [gen])
return render_template('sp_list.html', fams=fams, gen=gen, sp_pic=sp_pic, sp100_mode=sp100_mode, current_sp=current_sp)
@app.route('/pic_list/<sp>')
def show_pic_list(sp):
global next_url
next_url = request.args.get('next_url', default="", type=str) ### where to go back?
jpn_name = jpn_names[sp]
gen = sp.split()[0]
### Sometimes the same species can be found in different families...
### Counting all of them
sql_str = 'SELECT DISTINCT family, jpn_fam FROM fishdb WHERE genus = ? GROUP BY family, jpn_fam'
fams = query_db(sql_str, [gen])
sql_str = 'SELECT img_file, img_file_path, is_checked,' \
'mono, area_fill, ' \
'stripe_vert, stripe_horz, stripe_diag, stripe_maze, ' \
'spot_dark, spot_light, eyespot, saddle, blotch, no_use, ' \
'datetime(timestamp) as timestamp, annotator ' \
'FROM fishdb WHERE species = ? ORDER BY is_checked DESC'
pic_path = query_db(sql_str, [sp])
if (len(pic_path)==1): ### only one image -> directly to annotate_pic
if next_url == "":
next_url = url_for('show_sp_list', gen=gen)
return redirect(url_for('annotate_pic', img_file=pic_path[0]['img_file']))
else:
if next_url == "":
next_url = url_for('show_sp_list', gen=gen)
return render_template('pic_list.html', fams=fams, gen=gen, sp=sp, jpn_name=jpn_name, pic_path=pic_path, next_url=next_url, sp100_mode=sp100_mode, current_sp=current_sp)
def get_annotation(img_file):
annotation = get_db().execute(
'SELECT family, genus, species, jpn_name, db, img_file_path, '
' mono, area_fill, '
' stripe_vert, stripe_horz, stripe_diag, stripe_maze, '
' spot_dark, spot_light, eyespot, saddle, blotch, no_use'
' FROM fishdb'
' WHERE img_file = ?',
(img_file,)
).fetchone()
if annotation is None:
abort(404, "Annotation for file {0} doesn't exist.".format(img_file))
return annotation
@app.route('/annotate_pic/<img_file>', methods=('GET', 'POST'))
def annotate_pic(img_file):
global current_sp
print(next_url)
annotation = get_annotation(img_file)
if request.method == 'POST':
mono, area_fill = 0, 0
stripe_vert, stripe_horz, stripe_diag, stripe_maze = 0, 0, 0, 0
spot_dark, spot_light, eyespot, saddle, blotch, no_use = 0, 0, 0, 0, 0, 0
is_checked = 0
if request.form.get('mono'):
mono = 1
if request.form.get('area_fill'):
area_fill = 1
if request.form.get('stripe_vert'):
stripe_vert = 1
if request.form.get('stripe_horz'):
stripe_horz = 1
if request.form.get('stripe_diag'):
stripe_diag = 1
if request.form.get('stripe_maze'):
stripe_maze = 1
if request.form.get('spot_dark'):
spot_dark = 1
if request.form.get('spot_light'):
spot_light = 1
if request.form.get('eyespot'):
eyespot = 1
if request.form.get('saddle'):
saddle = 1
if request.form.get('blotch'):
blotch = 1
if request.form.get('no_use'):
no_use = 1
if (mono or area_fill or \
stripe_vert or stripe_horz or stripe_diag or stripe_maze or \
spot_dark or spot_light or eyespot or saddle or blotch or no_use):
is_checked = 1
db = get_db()
now = datetime.datetime.now()
db.execute(
'UPDATE fishdb SET '
' mono = ?, '
' area_fill = ?, '
' stripe_vert = ?, '
' stripe_horz = ?, '
' stripe_diag = ?, '
' stripe_maze = ?, '
' spot_dark = ?, '
' spot_light = ?, '
' eyespot = ?, '
' saddle = ?, '
' blotch = ?, '
' no_use = ?, '
' is_checked = ?, '
' timestamp = ?, '
' annotator = ? '
' WHERE img_file = ?',
(mono, area_fill, stripe_vert, stripe_horz, stripe_diag, stripe_maze, \
spot_dark, spot_light, eyespot, saddle, blotch, no_use, is_checked, \
now, ANNOTATOR, img_file)
)
db.commit()
#### for time recording
current_sp += 1
print("current_sp: ", current_sp)
if (sp100_mode and current_sp >= SP100_NUM):
return redirect(url_for('sp100', command='lap',
next_url=next_url,
fam=[annotation['family']],
gen=[annotation['genus']]))
if "search" in next_url:
return redirect(next_url+"#"+img_file)
else:
return redirect(next_url+"#"+annotation['species'])
else:
sql_str = 'SELECT DISTINCT family, jpn_fam FROM fishdb WHERE genus = ? GROUP BY family, jpn_fam'
fams = query_db(sql_str, [annotation['genus']])
return render_template('annotate_pic.html', fams=fams, img_file=img_file, annotation=annotation, sp100_mode=sp100_mode, current_sp=current_sp)
@app.route('/query')
def query():
return render_template('query.html')
@app.route('/search')
def search():
global next_url
is_checked = request.args.get('is_checked', default=1, type=int)
mono = request.args.get('mono', default=-1, type=int)
area_fill = request.args.get('area_fill', default=-1, type=int)
stripe_any = request.args.get('stripe_any', default=-1, type=int)
stripe_dir = request.args.get('stripe_dir', default=-1, type=int)
stripe_vert = request.args.get('stripe_vert', default=-1, type=int)
stripe_horz = request.args.get('stripe_horz', default=-1, type=int)
stripe_diag = request.args.get('stripe_diag', default=-1, type=int)
stripe_maze = request.args.get('stripe_maze', default=-1, type=int)
spot_any = request.args.get('spot_any', default=-1, type=int)
spot_noeye = request.args.get('spot_noeye', default=-1, type=int)
spot_dark = request.args.get('spot_dark', default=-1, type=int)
spot_light = request.args.get('spot_light', default=-1, type=int)
eyespot = request.args.get('eyespot', default=-1, type=int)
saddle = request.args.get('saddle', default=-1, type=int)
blotch = request.args.get('blotch', default=-1, type=int)
no_use = request.args.get('no_use', default=-1, type=int)
gen = request.args.get('gen', default="", type=str)
fam = request.args.get('fam', default="", type=str)
timestamp = request.args.get('timestamp', default="", type=str)
annotator = request.args.get('annotator', default="", type=str)
sql_str = 'SELECT family, jpn_fam, genus, species, jpn_name, img_file, img_file_path, ' \
'mono, area_fill, ' \
'stripe_vert, stripe_horz, stripe_diag, stripe_maze, ' \
'spot_dark, spot_light, eyespot, saddle, blotch, no_use ' \
'FROM fishdb '
where_str = 'WHERE is_checked=? '
if (mono == 0): where_str += 'AND mono = 0 '
if (mono == 1): where_str += 'AND mono = 1 '
if (area_fill == 0): where_str += 'AND area_fill = 0 '
if (area_fill == 1): where_str += 'AND area_fill = 1 '
if (stripe_any == 0): where_str += 'AND (stripe_vert=0 AND stripe_horz=0 AND stripe_diag=0 AND stripe_maze=0) '
if (stripe_any == 1): where_str += 'AND (stripe_vert=1 OR stripe_horz=1 OR stripe_diag=1 OR stripe_maze=1) '
if (stripe_dir == 0): where_str += 'AND (stripe_vert=0 AND stripe_horz=0 AND stripe_diag=0) '
if (stripe_dir == 1): where_str += 'AND (stripe_vert=1 OR stripe_horz=1 OR stripe_diag=1) '
if (stripe_vert == 0): where_str += 'AND stripe_vert = 0 '
if (stripe_vert == 1): where_str += 'AND stripe_vert = 1 '
if (stripe_horz == 0): where_str += 'AND stripe_horz = 0 '
if (stripe_horz == 1): where_str += 'AND stripe_horz = 1 '
if (stripe_diag == 0): where_str += 'AND stripe_diag = 0 '
if (stripe_diag == 1): where_str += 'AND stripe_diag = 1 '
if (stripe_maze == 0): where_str += 'AND stripe_maze = 0 '
if (stripe_maze == 1): where_str += 'AND stripe_maze = 1 '
if (spot_any == 0): where_str += 'AND (spot_dark=0 AND spot_light=0 AND eyespot=0 AND saddle=0) '
if (spot_any == 1): where_str += 'AND (spot_dark=1 OR spot_light=1 OR eyespot=1 OR saddle=1) '
if (spot_noeye == 0): where_str += 'AND (spot_dark=0 AND spot_light=0) '
if (spot_noeye == 1): where_str += 'AND (spot_dark=1 OR spot_light=1) '
if (spot_dark == 0): where_str += 'AND spot_dark = 0 '
if (spot_dark == 1): where_str += 'AND spot_dark = 1 '
if (spot_light == 0): where_str += 'AND spot_light = 0 '
if (spot_light == 1): where_str += 'AND spot_light = 1 '
if (eyespot == 0): where_str += 'AND eyespot = 0 '
if (eyespot == 1): where_str += 'AND eyespot = 1 '
if (saddle == 0): where_str += 'AND saddle = 0 '
if (saddle == 1): where_str += 'AND saddle = 1 '
if (blotch == 0): where_str += 'AND blotch = 0 '
if (blotch == 1): where_str += 'AND blotch = 1 '
if (no_use == 0): where_str += 'AND no_use = 0 '
if (no_use == 1): where_str += 'AND no_use = 1 '
if (fam != ""): where_str += 'AND family = "' + fam + '" '
if (gen != ""): where_str += 'AND genus = "' + gen + '" '
order_str = 'ORDER BY family, genus, species'
search_result = query_db(sql_str + where_str + order_str,
[is_checked])
hit_fam_num = len(set([row['family'] for row in search_result]))
hit_gen_num = len(set([row['genus'] for row in search_result]))
hit_sp_num = len(set([row['species'] for row in search_result]))
next_url = request.full_path
print(next_url)
return render_template('search_results.html', hit_fam_num=hit_fam_num, hit_gen_num=hit_gen_num, hit_sp_num=hit_sp_num,
hit_num=len(search_result), search_result=search_result, sp100_mode=sp100_mode, current_sp=current_sp)
@app.route('/status')
def status():
pass
"""
@app.route('/auto_fam')
def auto_fam():
global random_fam
global current_fam
fam = request.args.get('fam', default="", type=str)
if (fam == ""):
random_fam = True
### family, gen_comp_num, gen_num (gen_comp_num < gen_num)
sql_str = 'SELECT family, genus, ' \
'COUNT(DISTINCT (CASE WHEN is_checked=1 THEN species ELSE NULL END)) AS sp_chk_num, ' \
'COUNT(DISTINCT species) AS sp_num ' \
'FROM fishdb GROUP BY genus'
sql_fam = 'SELECT family, ' \
'COUNT(CASE WHEN sp_chk_num = sp_num THEN genus ELSE NULL END) AS gen_comp_num, ' \
'COUNT(genus) AS gen_num ' \
'FROM (' + sql_str + ') ' \
'GROUP BY family ' \
'HAVING (gen_comp_num < gen_num)'
fam_gen_num = query_db(sql_fam)
### min of gen_comp_num
gen_comp_num_min = min([row['gen_comp_num'] for row in fam_gen_num])
print("gen_comp_num_min = ", gen_comp_num_min)
### list of families to be checked
fam_to_be_chk = []
for row in fam_gen_num:
if ((row['gen_comp_num'] == gen_comp_num_min) and (row['gen_comp_num'] < row['gen_num'])):
fam_to_be_chk.append(row['family'])
random_fam = random.choice(fam_to_be_chk)
print("random_fam = ", random_fam)
current_fam = random_fam
else:
random_fam = False
current_fam = fam
return redirect(url_for('auto_gen', fam=current_fam))
@app.route('/auto_gen/<fam>')
def auto_gen(fam):
### get the list of genera within family
sql_gen = 'SELECT DISTINCT genus FROM fishdb ' \
'WHERE family="' + fam + '"'
### genus WHERE (sp_chk_num < sp_num) ORDER BY sp_num
sql_gen = 'SELECT genus, '\
'COUNT(DISTINCT (CASE WHEN is_checked=1 THEN species ELSE NULL END)) AS sp_chk_num, ' \
'COUNT(DISTINCT species) AS sp_num ' \
'FROM fishdb ' \
'WHERE (genus in (' + sql_gen + ')) ' \
'GROUP BY genus ' \
'HAVING ( sp_chk_num < sp_num ) ' \
'ORDER BY sp_num DESC'
# ### family, genus WHERE (sp_chk_num < sp_num) ORDER BY sp_num
# sql_str = 'SELECT family, genus, ' \
# 'COUNT(DISTINCT (CASE WHEN is_checked=1 THEN species ELSE NULL END)) AS sp_chk_num, ' \
# 'COUNT(DISTINCT species) AS sp_num ' \
# 'FROM fishdb WHERE family="' + random_fam + '" GROUP BY genus'
# sql_gen = 'SELECT genus, sp_chk_num, sp_num ' \
# 'FROM (' + sql_str + ') ' \
# 'WHERE (sp_chk_num < sp_num) ' \
# 'ORDER BY family, sp_num DESC'
print(sql_gen)
gen_sp_num = query_db(sql_gen)
gen_to_be_chk = [row['genus'] for row in gen_sp_num]
gen_sp_chk_num = [row['sp_chk_num'] for row in gen_sp_num]
gen_sp_num = [row['sp_num'] for row in gen_sp_num]
print("gen_to_be_chk:")
print(gen_to_be_chk)
print(gen_sp_chk_num)
print(gen_sp_num)
if (len(gen_to_be_chk) > 0):
return redirect(url_for('auto_sp', gen=gen_to_be_chk[0]))
else:
if (random_fam):
return redirect(url_for('auto_fam', fam=""))
else:
return redirect(url_for('show_gen_list', fam=fam))
@app.route('/auto_sp/<gen>')
def auto_sp(gen):
global next_url
sql_str = 'SELECT species, ' \
'COUNT(CASE WHEN is_checked=1 THEN img_file ELSE NULL END) AS pic_chk_num ' \
'FROM fishdb WHERE genus = ? GROUP BY species'
sql_sp = 'SELECT species ' \
'FROM (' + sql_str + ') '\
'WHERE (pic_chk_num = 0)'
sp_not_chk = query_db(sql_sp, [gen])
sp_to_be_chk = [row['species'] for row in sp_not_chk]
print(sp_to_be_chk)
next_url = request.full_path
if (len(sp_to_be_chk) > 0):
return redirect(url_for('show_pic_list', sp=sp_to_be_chk[0], next_url=next_url))
else:
if (random_fam):
return redirect(url_for('auto_fam', fam=""))
else:
return redirect(url_for('auto_gen', fam=current_fam))
@app.route('/sp100/<command>')
def sp100(command):
global start_time
global current_sp
global sp100_mode
global next_url
fam = request.args.get('fam', default="", type=str)
gen = request.args.get('gen', default="", type=str)
next_url = request.args.get('next_url', default="", type=str)
if (command == "start"):
start_time = datetime.datetime.now()
current_sp = 0
sp100_mode = True
print(sp100_mode)
print(request.referrer)
return redirect(request.referrer)
if (command == "lap"):
now = datetime.datetime.now()
record_time = now - start_time
start_time = datetime.datetime.now()
current_sp = 0
sql_str = 'INSERT INTO sp100(timestamp, record) VALUES(?, ?)'
query_db(sql_str, (str(now), str(record_time)))
get_db().commit()
sql_str = 'SELECT timestamp, record FROM sp100 ORDER BY record'
sp100 = query_db(sql_str)
df_sp100 = pd.read_sql(sql_str, get_db())
my_rank = df_sp100[df_sp100.record==str(record_time)].index[0] + 1
return render_template('sp100.html', fam=fam, gen=gen, next_url=next_url, my_rank=my_rank, sp100=sp100)
if (command == "stop"):
sp100_mode = False
print(sp100_mode)
print(request.referrer)
return redirect(request.referrer)
@app.route('/stats')
def stats():
global next_url
fam = request.args.get('fam', default="", type=str)
gen = request.args.get('gen', default="", type=str)
next_url = request.args.get('next_url', default="", type=str)
sql_str = 'SELECT timestamp, record FROM sp100 ORDER BY record'
sp100 = query_db(sql_str)
sql_str = 'SELECT timestamp, record FROM sp100 ORDER BY timestamp DESC'
sp100_2 = query_db(sql_str)
return render_template('stats.html', fam=fam, gen=gen, next_url=request.referrer, sp100=sp100, sp100_2=sp100_2)
"""
if __name__ == "__main__":
# app.run(debug=True)
app.run(debug=True, host='0.0.0.0')
| 37.021776 | 177 | 0.592164 |
acec822642181756b367a60a7341cad04386d1c4 | 17,668 | py | Python | python/drydock_provisioner/drivers/oob/redfish_driver/actions/oob.py | Vjrx/airship-drydock | 315fb9864e6d55a66d5266f76c160be55d22c98b | [
"Apache-2.0"
] | 14 | 2018-05-19T11:58:22.000Z | 2019-05-10T12:31:36.000Z | python/drydock_provisioner/drivers/oob/redfish_driver/actions/oob.py | Vjrx/airship-drydock | 315fb9864e6d55a66d5266f76c160be55d22c98b | [
"Apache-2.0"
] | 10 | 2019-11-12T17:21:16.000Z | 2021-11-10T18:16:06.000Z | python/drydock_provisioner/drivers/oob/redfish_driver/actions/oob.py | Vjrx/airship-drydock | 315fb9864e6d55a66d5266f76c160be55d22c98b | [
"Apache-2.0"
] | 11 | 2018-06-05T16:21:18.000Z | 2019-04-03T11:44:34.000Z | # Copyright 2018 AT&T Intellectual Property. All other rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Driver for controlling OOB interface via Redfish.
Based on Redfish Rest API specification.
"""
import time
from oslo_config import cfg
from drydock_provisioner.orchestrator.actions.orchestrator import BaseAction
from drydock_provisioner.drivers.oob.redfish_driver.client import RedfishException
from drydock_provisioner.drivers.oob.redfish_driver.client import RedfishSession
import drydock_provisioner.error as errors
import drydock_provisioner.objects.fields as hd_fields
class RedfishBaseAction(BaseAction):
"""Base action for Redfish executed actions."""
def get_redfish_session(self, node):
"""Initialize a Redfish session to the node.
:param node: instance of objects.BaremetalNode
:return: An instance of client.RedfishSession initialized to node's Redfish interface
"""
if node.oob_type != 'redfish':
raise errors.DriverError("Node OOB type is not Redfish")
oob_network = node.oob_parameters['network']
oob_address = node.get_network_address(oob_network)
if oob_address is None:
raise errors.DriverError(
"Node %s has no OOB Redfish address" % (node.name))
oob_account = node.oob_parameters['account']
oob_credential = node.oob_parameters['credential']
self.logger.debug("Starting Redfish session to %s with %s" %
(oob_address, oob_account))
try:
redfish_obj = RedfishSession(host=oob_address,
account=oob_account,
password=oob_credential,
use_ssl=cfg.CONF.redfish_driver.use_ssl,
connection_retries=cfg.CONF.redfish_driver.max_retries)
except (RedfishException, errors.DriverError) as iex:
self.logger.error(
"Error initializing Redfish session for node %s" % node.name)
self.logger.error("Redfish Exception: %s" % str(iex))
redfish_obj = None
return redfish_obj
def exec_redfish_command(self, node, session, func, *args):
"""Call a Redfish command after establishing a session.
:param node: Instance of objects.BaremetalNode to execute against
:param session: Redfish session
:param func: The redfish Command method to call
:param args: The args to pass the func
"""
try:
self.logger.debug("Calling Redfish command %s on %s" %
(func.__name__, node.name))
response = func(session, *args)
return response
except RedfishException as iex:
self.logger.error(
"Error executing Redfish command %s for node %s" % (func.__name__, node.name))
self.logger.error("Redfish Exception: %s" % str(iex))
raise errors.DriverError("Redfish command failed.")
class ValidateOobServices(RedfishBaseAction):
"""Action to validate OOB services are available."""
def start(self):
self.task.add_status_msg(
msg="OOB does not require services.",
error=False,
ctx='NA',
ctx_type='NA')
self.task.set_status(hd_fields.TaskStatus.Complete)
self.task.success()
self.task.save()
return
class ConfigNodePxe(RedfishBaseAction):
"""Action to configure PXE booting via OOB."""
def start(self):
self.task.set_status(hd_fields.TaskStatus.Running)
self.task.save()
node_list = self.orchestrator.get_target_nodes(self.task)
for n in node_list:
self.task.add_status_msg(
msg="Redfish doesn't configure PXE options.",
error=True,
ctx=n.name,
ctx_type='node')
self.task.set_status(hd_fields.TaskStatus.Complete)
self.task.failure()
self.task.save()
return
class SetNodeBoot(RedfishBaseAction):
"""Action to configure a node to PXE boot."""
def start(self):
self.task.set_status(hd_fields.TaskStatus.Running)
self.task.save()
node_list = self.orchestrator.get_target_nodes(self.task)
for n in node_list:
self.logger.debug("Setting bootdev to PXE for %s" % n.name)
self.task.add_status_msg(
msg="Setting node to PXE boot.",
error=False,
ctx=n.name,
ctx_type='node')
bootdev = None
try:
session = self.get_redfish_session(n)
bootdev = self.exec_redfish_command(n, session, RedfishSession.get_bootdev)
if bootdev.get('bootdev', '') != 'Pxe':
self.exec_redfish_command(n, session, RedfishSession.set_bootdev, 'Pxe')
bootdev = self.exec_redfish_command(n, session, RedfishSession.get_bootdev)
session.close_session()
except errors.DriverError:
pass
if bootdev is not None and (bootdev.get('bootdev',
'') == 'Pxe'):
self.task.add_status_msg(
msg="Set bootdev to PXE.",
error=False,
ctx=n.name,
ctx_type='node')
self.logger.debug("%s reports bootdev of network" % n.name)
self.task.success(focus=n.name)
else:
self.task.add_status_msg(
msg="Unable to set bootdev to PXE.",
error=True,
ctx=n.name,
ctx_type='node')
self.task.failure(focus=n.name)
self.logger.warning(
"Unable to set node %s to PXE boot." % (n.name))
self.task.set_status(hd_fields.TaskStatus.Complete)
self.task.save()
return
class PowerOffNode(RedfishBaseAction):
"""Action to power off a node via Redfish."""
def start(self):
self.task.set_status(hd_fields.TaskStatus.Running)
self.task.save()
node_list = self.orchestrator.get_target_nodes(self.task)
for n in node_list:
self.logger.debug("Sending set_power = off command to %s" % n.name)
self.task.add_status_msg(
msg="Sending set_power = off command.",
error=False,
ctx=n.name,
ctx_type='node')
session = self.get_redfish_session(n)
# If power is already off, continue with the next node
power_state = self.exec_redfish_command(n, RedfishSession.get_power)
if power_state is not None and (power_state.get(
'powerstate', '') == 'Off'):
self.task.add_status_msg(
msg="Node reports power off.",
error=False,
ctx=n.name,
ctx_type='node')
self.logger.debug(
"Node %s reports powerstate already off. No action required" % n.name)
self.task.success(focus=n.name)
continue
self.exec_redfish_command(n, session, RedfishSession.set_power, 'ForceOff')
attempts = cfg.CONF.redfish_driver.power_state_change_max_retries
while attempts > 0:
self.logger.debug("Polling powerstate waiting for success.")
power_state = self.exec_redfish_command(n, RedfishSession.get_power)
if power_state is not None and (power_state.get(
'powerstate', '') == 'Off'):
self.task.add_status_msg(
msg="Node reports power off.",
error=False,
ctx=n.name,
ctx_type='node')
self.logger.debug(
"Node %s reports powerstate of off" % n.name)
self.task.success(focus=n.name)
break
time.sleep(cfg.CONF.redfish_driver.power_state_change_retry_interval)
attempts = attempts - 1
if power_state is not None and (power_state.get('powerstate', '')
!= 'Off'):
self.task.add_status_msg(
msg="Node failed to power off.",
error=True,
ctx=n.name,
ctx_type='node')
self.logger.error("Giving up on Redfish command to %s" % n.name)
self.task.failure(focus=n.name)
session.close_session()
self.task.set_status(hd_fields.TaskStatus.Complete)
self.task.save()
return
class PowerOnNode(RedfishBaseAction):
"""Action to power on a node via Redfish."""
def start(self):
self.task.set_status(hd_fields.TaskStatus.Running)
self.task.save()
node_list = self.orchestrator.get_target_nodes(self.task)
for n in node_list:
self.logger.debug("Sending set_power = on command to %s" % n.name)
self.task.add_status_msg(
msg="Sending set_power = on command.",
error=False,
ctx=n.name,
ctx_type='node')
session = self.get_redfish_session(n)
# If power is already on, continue with the next node
power_state = self.exec_redfish_command(n, RedfishSession.get_power)
if power_state is not None and (power_state.get(
'powerstate', '') == 'On'):
self.task.add_status_msg(
msg="Node reports power on.",
error=False,
ctx=n.name,
ctx_type='node')
self.logger.debug(
"Node %s reports powerstate already on. No action required" % n.name)
self.task.success(focus=n.name)
continue
self.exec_redfish_command(n, session, RedfishSession.set_power, 'On')
attempts = cfg.CONF.redfish_driver.power_state_change_max_retries
while attempts > 0:
self.logger.debug("Polling powerstate waiting for success.")
power_state = self.exec_redfish_command(n, session, RedfishSession.get_power)
if power_state is not None and (power_state.get(
'powerstate', '') == 'On'):
self.logger.debug(
"Node %s reports powerstate of on" % n.name)
self.task.add_status_msg(
msg="Node reports power on.",
error=False,
ctx=n.name,
ctx_type='node')
self.task.success(focus=n.name)
break
time.sleep(cfg.CONF.redfish_driver.power_state_change_retry_interval)
attempts = attempts - 1
if power_state is not None and (power_state.get('powerstate', '')
!= 'On'):
self.task.add_status_msg(
msg="Node failed to power on.",
error=True,
ctx=n.name,
ctx_type='node')
self.logger.error("Giving up on Redfish command to %s" % n.name)
self.task.failure(focus=n.name)
session.close_session()
self.task.set_status(hd_fields.TaskStatus.Complete)
self.task.save()
return
class PowerCycleNode(RedfishBaseAction):
"""Action to hard powercycle a node via Redfish."""
def start(self):
self.task.set_status(hd_fields.TaskStatus.Running)
self.task.save()
node_list = self.orchestrator.get_target_nodes(self.task)
for n in node_list:
self.logger.debug("Sending set_power = off command to %s" % n.name)
self.task.add_status_msg(
msg="Power cycling node via Redfish.",
error=False,
ctx=n.name,
ctx_type='node')
session = self.get_redfish_session(n)
self.exec_redfish_command(n, session, RedfishSession.set_power, 'ForceOff')
# Wait for power state of off before booting back up
attempts = cfg.CONF.redfish_driver.power_state_change_max_retries
while attempts > 0:
power_state = self.exec_redfish_command(n, session, RedfishSession.get_power)
if power_state is not None and power_state.get(
'powerstate', '') == 'Off':
self.logger.debug("%s reports powerstate of off" % n.name)
break
elif power_state is None:
self.logger.debug(
"No response on Redfish power query to %s" % n.name)
time.sleep(cfg.CONF.redfish_driver.power_state_change_retry_interval)
attempts = attempts - 1
if power_state.get('powerstate', '') != 'Off':
self.task.add_status_msg(
msg="Failed to power down during power cycle.",
error=True,
ctx=n.name,
ctx_type='node')
self.logger.warning(
"Failed powering down node %s during power cycle task" %
n.name)
self.task.failure(focus=n.name)
break
self.logger.debug("Sending set_power = on command to %s" % n.name)
self.exec_redfish_command(n, session, RedfishSession.set_power, 'On')
attempts = cfg.CONF.redfish_driver.power_state_change_max_retries
while attempts > 0:
power_state = self.exec_redfish_command(n, session, RedfishSession.get_power)
if power_state is not None and power_state.get(
'powerstate', '') == 'On':
self.logger.debug("%s reports powerstate of on" % n.name)
break
elif power_state is None:
self.logger.debug(
"No response on Redfish power query to %s" % n.name)
time.sleep(cfg.CONF.redfish_driver.power_state_change_retry_interval)
attempts = attempts - 1
if power_state is not None and (power_state.get('powerstate',
'') == 'On'):
self.task.add_status_msg(
msg="Node power cycle complete.",
error=False,
ctx=n.name,
ctx_type='node')
self.task.success(focus=n.name)
else:
self.task.add_status_msg(
msg="Failed to power up during power cycle.",
error=True,
ctx=n.name,
ctx_type='node')
self.logger.warning(
"Failed powering up node %s during power cycle task" %
n.name)
self.task.failure(focus=n.name)
session.close_session()
self.task.set_status(hd_fields.TaskStatus.Complete)
self.task.save()
return
class InterrogateOob(RedfishBaseAction):
"""Action to complete a basic interrogation of the node Redfish interface."""
def start(self):
self.task.set_status(hd_fields.TaskStatus.Running)
self.task.save()
node_list = self.orchestrator.get_target_nodes(self.task)
for n in node_list:
try:
self.logger.debug(
"Interrogating node %s Redfish interface." % n.name)
session = self.get_redfish_session(n)
powerstate = self.exec_redfish_command(n, session, RedfishSession.get_power)
session.close_session()
if powerstate is None:
raise errors.DriverError()
self.task.add_status_msg(
msg="Redfish interface interrogation yielded powerstate %s" %
powerstate.get('powerstate'),
error=False,
ctx=n.name,
ctx_type='node')
self.task.success(focus=n.name)
except errors.DriverError:
self.logger.debug(
"Interrogating node %s Redfish interface failed." % n.name)
self.task.add_status_msg(
msg="Redfish interface interrogation failed.",
error=True,
ctx=n.name,
ctx_type='node')
self.task.failure(focus=n.name)
self.task.set_status(hd_fields.TaskStatus.Complete)
self.task.save()
return
| 39.792793 | 96 | 0.554053 |
acec825a02bb235b716e66c29a0d50193114eb4e | 4,335 | py | Python | src/settings/components/base.py | pradipta/back-end | 05895b051afc4c8e0cb17db708063d80102e9de5 | [
"MIT"
] | 17 | 2019-05-11T22:15:34.000Z | 2022-03-26T22:45:33.000Z | src/settings/components/base.py | pradipta/back-end | 05895b051afc4c8e0cb17db708063d80102e9de5 | [
"MIT"
] | 390 | 2019-05-23T10:48:57.000Z | 2021-12-17T21:01:43.000Z | src/settings/components/base.py | pradipta/back-end | 05895b051afc4c8e0cb17db708063d80102e9de5 | [
"MIT"
] | 40 | 2019-05-21T14:41:57.000Z | 2021-01-30T13:39:38.000Z | from settings.components import BASE_DIR, config
SECRET_KEY = config("SECRET_KEY", default="SUPA_SECRET")
TESTING = False
# Application definition
INSTALLED_APPS = [
# Our apps
"core.apps.CoreConfig",
"api.apps.ApiConfig",
"frontend.apps.FrontendConfig",
# Django Suit Admin Console
# https://django-suit.readthedocs.io
"suit",
# Default Django apps:
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"django.contrib.sites",
# Django anymail
# https://anymail.readthedocs.io/en/stable/
"anymail",
# django-background-tasks
# https://django-background-tasks.readthedocs.io/en/latest/
"background_task",
# django-suit-daterange-filter
# https://github.com/f213/django-suit-daterange-filter
"date_range_filter",
# django-rest-framework
# https://www.django-rest-framework.org/
"rest_framework",
"rest_framework.authtoken",
"rest_auth.registration",
# django-rest-auth
# https://django-rest-auth.readthedocs.io/en/latest/
"rest_auth",
# django-allauth
# https://django-allauth.readthedocs.io/en/latest/installation.html
"allauth",
"allauth.account",
"allauth.socialaccount",
"allauth.socialaccount.providers.google",
"allauth.socialaccount.providers.facebook",
"allauth.socialaccount.providers.github",
# django-storages
# https://django-storages.readthedocs.io/en/latest/
"storages",
# django-cors-headers
# https://github.com/ottoyiu/django-cors-headers
"corsheaders",
# drf-yasg : Yet another Swagger generator
# https://drf-yasg.readthedocs.io/en/stable/readme.html
"drf_yasg",
# temp frontend apps
"widget_tweaks",
"snowpenguin.django.recaptcha2",
# django-health-check
# https://django-health-check.readthedocs.io/en/latest/
"health_check", # required
"health_check.db", # stock Django health checkers
]
ROOT_URLCONF = "operationcode_backend.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [BASE_DIR.joinpath("core", "templates")],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
]
},
}
]
WSGI_APPLICATION = "operationcode_backend.wsgi.application"
DATABASES = {
"default": {
"ENGINE": config("DB_ENGINE", default="django.db.backends.sqlite3"),
"NAME": config("DB_NAME", default=str(BASE_DIR.joinpath("db.sqlite3"))),
"USER": config("DB_USER", default=""),
"PASSWORD": config("DB_PASSWORD", default=""),
"HOST": config("DB_HOST", default=""),
"PORT": config("DB_PORT", default=""),
}
}
# Django Suit (Admin Console)
# https://django-suit.readthedocs.io
SUIT_CONFIG = {
"MENU": (
{
"label": "Users",
"icon": "icon-user",
"models": (
"auth.user",
"core.profile",
"auth.group",
"account.emailaddress",
),
},
{"app": "socialaccount", "icon": "icon-thumbs-up"},
"sites",
"-",
"api",
{"app": "background_task", "icon": "icon-tasks"},
)
}
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_L10N = True
USE_TZ = True
ATOMIC_REQUESTS = True
EMAIL_BACKEND = config(
"EMAIL_BACKEND", default="django.core.mail.backends.console.EmailBackend"
)
DEFAULT_FROM_EMAIL = "noreply@operationcode.org"
SERVER_EMAIL = "noreplyerrors@operationcode.org"
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = "/static/"
MEDIA_URL = "/media/"
STATIC_ROOT = BASE_DIR.joinpath("static")
MEDIA_ROOT = BASE_DIR.joinpath("media")
SITE_ID = config("SITE_ID", default=3)
ACCOUNT_ADAPTER = "core.adapters.AccountAdapter"
ACCOUNT_USERNAME_REQUIRED = False
| 29.896552 | 80 | 0.644521 |
acec8270d4e326b49957245fa72bd997a356dfd9 | 1,217 | py | Python | rasa/core/cli/test.py | jeanveau/rasa_core | 953d54f057c19ef10b9c71cb8fcfc2d13dbefc65 | [
"Apache-2.0"
] | 2,433 | 2017-10-04T13:08:05.000Z | 2022-03-13T14:59:26.000Z | rasa/core/cli/test.py | jeanveau/rasa_core | 953d54f057c19ef10b9c71cb8fcfc2d13dbefc65 | [
"Apache-2.0"
] | 1,684 | 2017-10-04T13:04:44.000Z | 2019-05-31T20:48:49.000Z | rasa/core/cli/test.py | jeanveau/rasa_core | 953d54f057c19ef10b9c71cb8fcfc2d13dbefc65 | [
"Apache-2.0"
] | 1,229 | 2017-10-04T20:23:59.000Z | 2022-03-11T02:49:13.000Z | from rasa.core.cli import arguments
def add_evaluation_arguments(parser):
parser.add_argument(
'-m', '--max_stories',
type=int,
help="maximum number of stories to test on")
parser.add_argument(
'-u', '--nlu',
type=str,
help="nlu model to run with the server. None for regex interpreter")
parser.add_argument(
'-o', '--output',
type=str,
default="results",
help="output path for the any files created from the evaluation")
parser.add_argument(
'--e2e', '--end-to-end',
action='store_true',
help="Run an end-to-end evaluation for combined action and "
"intent prediction. Requires a story file in end-to-end "
"format.")
parser.add_argument(
'--endpoints',
default=None,
help="Configuration file for the connectors as a yml file")
parser.add_argument(
'--fail_on_prediction_errors',
action='store_true',
help="If a prediction error is encountered, an exception "
"is thrown. This can be used to validate stories during "
"tests, e.g. on travis.")
arguments.add_core_model_arg(parser)
| 33.805556 | 76 | 0.606409 |
acec8435727dfe95a8ff732a7e094454424bd1f7 | 824 | py | Python | lib/userFunction/dataCreator2.py | ronnygeo/YelpSocialEffects | 55315af989be97c2785ee50c7accf5372ed06bce | [
"Unlicense",
"MIT"
] | null | null | null | lib/userFunction/dataCreator2.py | ronnygeo/YelpSocialEffects | 55315af989be97c2785ee50c7accf5372ed06bce | [
"Unlicense",
"MIT"
] | null | null | null | lib/userFunction/dataCreator2.py | ronnygeo/YelpSocialEffects | 55315af989be97c2785ee50c7accf5372ed06bce | [
"Unlicense",
"MIT"
] | null | null | null | from mongoOperations import getUsers, getUsersFromUserFriends, getUsersFromUserFriendsAsc
from userExtract import extractFriends
from locationEstimation import getUserLocation
import ujson
users = getUsersFromUserFriendsAsc(1)
res = []
usersCount = users.count()
for user in users:
data = {}
userId = user['user_id']
data = getUserLocation(userId)
data["user_id"] = userId
data["friends"] = []
i = 0
for f in user["friends"]:
if f != userId:
friend = {}
friend = getUserLocation(f)
# friend["user_id"] = f
# print friend
data["friends"].append(friend)
res.append(data)
# from pymongo import MongoClient
#
# client = MongoClient()
#
# db = client['yelp']
#
# db.user_test.insert_many(res)
#
with open('../../static/json/user_friends_location_data.json', 'w+') as outfile:
ujson.dump(res, outfile)
| 23.542857 | 89 | 0.716019 |
acec843b6dc475da04a03e818148e9f8511e7cae | 1,706 | py | Python | Data-Sources/arXiv.org/projects-using-arXiv-api/bibcure/doi2bib/doi2bib/crossref.py | briancabbott/xtrax | 3bfcbe1c2f5c355b886d8171481a604cca7f4f16 | [
"MIT"
] | 2 | 2020-02-07T17:32:14.000Z | 2022-02-08T09:14:01.000Z | Data-Sources/arXiv.org/projects-using-arXiv-api/bibcure/doi2bib/doi2bib/crossref.py | briancabbott/xtrax | 3bfcbe1c2f5c355b886d8171481a604cca7f4f16 | [
"MIT"
] | null | null | null | Data-Sources/arXiv.org/projects-using-arXiv-api/bibcure/doi2bib/doi2bib/crossref.py | briancabbott/xtrax | 3bfcbe1c2f5c355b886d8171481a604cca7f4f16 | [
"MIT"
] | null | null | null | """
crossref integration
===========================
The core module
"""
from __future__ import unicode_literals, print_function, absolute_import
from builtins import str
import requests
import re
bare_url = "http://api.crossref.org/"
def get_bib(doi):
"""
Parameters
----------
doi: str
Returns
-------
found: bool
bib: str
"""
url = "{}works/{}/transform/application/x-bibtex"
url = url.format(bare_url, doi)
r = requests.get(url)
found = False if r.status_code != 200 else True
bib = r.content
bib = str(bib, "utf-8")
return found, bib
def get_json(doi):
"""
Parameters
----------
doi: str
Returns
-------
found: bool
item: dict
Response from crossref
"""
url = "{}works/{}"
url = url.format(bare_url, doi)
r = requests.get(url)
found = False if r.status_code != 200 else True
item = r.json()
return found, item
def get_bib_from_doi(doi, abbrev_journal=True):
"""
Parameters
----------
doi: str
abbrev_journal: bool
If True try to abbreviate the journal name
Returns
-------
found: bool
bib: str
The bibtex string
"""
found, bib = get_bib(doi)
if found and abbrev_journal:
found, item = get_json(doi)
if found:
abbreviated_journal = item["message"]["short-container-title"][0].strip()
if abbreviated_journal:
bib = re.sub(
r"journal = \{[^>]*?\}",
"journal = {" + abbreviated_journal + "}",
bib)
return found, bib
| 19.168539 | 85 | 0.52286 |
acec84f00002cd8a56fbbcafdb1dc1866afdd226 | 805 | bzl | Python | bazel/third_party/generate_header.bzl | msercheli/openexr | 9912f6b3886f6c695547747d70e19b98c0e38d59 | [
"BSD-3-Clause"
] | 587 | 2015-01-04T09:56:19.000Z | 2019-11-21T13:23:33.000Z | bazel/third_party/generate_header.bzl | msercheli/openexr | 9912f6b3886f6c695547747d70e19b98c0e38d59 | [
"BSD-3-Clause"
] | 391 | 2018-07-31T21:28:52.000Z | 2022-03-28T16:51:18.000Z | bazel/third_party/generate_header.bzl | msercheli/openexr | 9912f6b3886f6c695547747d70e19b98c0e38d59 | [
"BSD-3-Clause"
] | 297 | 2015-01-11T12:06:42.000Z | 2019-11-19T21:59:57.000Z | # SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) Contributors to the OpenEXR Project.
def _generate_header_impl(ctx):
out = ctx.actions.declare_file(ctx.label.name)
ctx.actions.expand_template(
output = out,
template = ctx.file.template,
substitutions = ctx.attr.substitutions,
)
return [CcInfo(
compilation_context = cc_common.create_compilation_context(
includes = depset([out.dirname]),
headers = depset([out]),
),
)]
generate_header = rule(
implementation = _generate_header_impl,
attrs = {
"substitutions": attr.string_dict(
mandatory = True,
),
"template": attr.label(
allow_single_file = [".h.in"],
mandatory = True,
),
},
)
| 26.833333 | 67 | 0.598758 |
acec850f02c2da39a1a9b1a4bfc03a2dc2bd6286 | 27,238 | py | Python | python/pyspark/streaming/dstream.py | seahusbanf/spark_source_code | ba0beff63a4959759b414044604e3a1bd0c6491f | [
"BSD-3-Clause-Open-MPI",
"PSF-2.0",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"MIT-0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | 53 | 2016-04-22T03:57:05.000Z | 2020-08-11T02:54:15.000Z | python/pyspark/streaming/dstream.py | seahusbanf/spark_source_code | ba0beff63a4959759b414044604e3a1bd0c6491f | [
"BSD-3-Clause-Open-MPI",
"PSF-2.0",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"MIT-0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | 15 | 2017-03-06T20:54:46.000Z | 2022-01-21T23:23:02.000Z | python/pyspark/streaming/dstream.py | seahusbanf/spark_source_code | ba0beff63a4959759b414044604e3a1bd0c6491f | [
"BSD-3-Clause-Open-MPI",
"PSF-2.0",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"MIT-0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | 42 | 2016-04-22T03:56:50.000Z | 2020-11-23T09:32:25.000Z | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import sys
import operator
import time
from itertools import chain
from datetime import datetime
if sys.version < "3":
from itertools import imap as map, ifilter as filter
from py4j.protocol import Py4JJavaError
from pyspark import RDD
from pyspark.storagelevel import StorageLevel
from pyspark.streaming.util import rddToFileName, TransformFunction
from pyspark.rdd import portable_hash
from pyspark.resultiterable import ResultIterable
__all__ = ["DStream"]
class DStream(object):
"""
A Discretized Stream (DStream), the basic abstraction in Spark Streaming,
is a continuous sequence of RDDs (of the same type) representing a
continuous stream of data (see L{RDD} in the Spark core documentation
for more details on RDDs).
DStreams can either be created from live data (such as, data from TCP
sockets, Kafka, Flume, etc.) using a L{StreamingContext} or it can be
generated by transforming existing DStreams using operations such as
`map`, `window` and `reduceByKeyAndWindow`. While a Spark Streaming
program is running, each DStream periodically generates a RDD, either
from live data or by transforming the RDD generated by a parent DStream.
DStreams internally is characterized by a few basic properties:
- A list of other DStreams that the DStream depends on
- A time interval at which the DStream generates an RDD
- A function that is used to generate an RDD after each time interval
"""
def __init__(self, jdstream, ssc, jrdd_deserializer):
self._jdstream = jdstream
self._ssc = ssc
self._sc = ssc._sc
self._jrdd_deserializer = jrdd_deserializer
self.is_cached = False
self.is_checkpointed = False
def context(self):
"""
Return the StreamingContext associated with this DStream
"""
return self._ssc
def count(self):
"""
Return a new DStream in which each RDD has a single element
generated by counting each RDD of this DStream.
"""
return self.mapPartitions(lambda i: [sum(1 for _ in i)]).reduce(operator.add)
def filter(self, f):
"""
Return a new DStream containing only the elements that satisfy predicate.
"""
def func(iterator):
return filter(f, iterator)
return self.mapPartitions(func, True)
def flatMap(self, f, preservesPartitioning=False):
"""
Return a new DStream by applying a function to all elements of
this DStream, and then flattening the results
"""
def func(s, iterator):
return chain.from_iterable(map(f, iterator))
return self.mapPartitionsWithIndex(func, preservesPartitioning)
def map(self, f, preservesPartitioning=False):
"""
Return a new DStream by applying a function to each element of DStream.
"""
def func(iterator):
return map(f, iterator)
return self.mapPartitions(func, preservesPartitioning)
def mapPartitions(self, f, preservesPartitioning=False):
"""
Return a new DStream in which each RDD is generated by applying
mapPartitions() to each RDDs of this DStream.
"""
def func(s, iterator):
return f(iterator)
return self.mapPartitionsWithIndex(func, preservesPartitioning)
def mapPartitionsWithIndex(self, f, preservesPartitioning=False):
"""
Return a new DStream in which each RDD is generated by applying
mapPartitionsWithIndex() to each RDDs of this DStream.
"""
return self.transform(lambda rdd: rdd.mapPartitionsWithIndex(f, preservesPartitioning))
def reduce(self, func):
"""
Return a new DStream in which each RDD has a single element
generated by reducing each RDD of this DStream.
"""
return self.map(lambda x: (None, x)).reduceByKey(func, 1).map(lambda x: x[1])
def reduceByKey(self, func, numPartitions=None):
"""
Return a new DStream by applying reduceByKey to each RDD.
"""
if numPartitions is None:
numPartitions = self._sc.defaultParallelism
return self.combineByKey(lambda x: x, func, func, numPartitions)
def combineByKey(self, createCombiner, mergeValue, mergeCombiners,
numPartitions=None):
"""
Return a new DStream by applying combineByKey to each RDD.
"""
if numPartitions is None:
numPartitions = self._sc.defaultParallelism
def func(rdd):
return rdd.combineByKey(createCombiner, mergeValue, mergeCombiners, numPartitions)
return self.transform(func)
def partitionBy(self, numPartitions, partitionFunc=portable_hash):
"""
Return a copy of the DStream in which each RDD are partitioned
using the specified partitioner.
"""
return self.transform(lambda rdd: rdd.partitionBy(numPartitions, partitionFunc))
def foreachRDD(self, func):
"""
Apply a function to each RDD in this DStream.
"""
if func.__code__.co_argcount == 1:
old_func = func
func = lambda t, rdd: old_func(rdd)
jfunc = TransformFunction(self._sc, func, self._jrdd_deserializer)
api = self._ssc._jvm.PythonDStream
api.callForeachRDD(self._jdstream, jfunc)
def pprint(self, num=10):
"""
Print the first num elements of each RDD generated in this DStream.
@param num: the number of elements from the first will be printed.
"""
def takeAndPrint(time, rdd):
taken = rdd.take(num + 1)
print("-------------------------------------------")
print("Time: %s" % time)
print("-------------------------------------------")
for record in taken[:num]:
print(record)
if len(taken) > num:
print("...")
print("")
self.foreachRDD(takeAndPrint)
def mapValues(self, f):
"""
Return a new DStream by applying a map function to the value of
each key-value pairs in this DStream without changing the key.
"""
map_values_fn = lambda kv: (kv[0], f(kv[1]))
return self.map(map_values_fn, preservesPartitioning=True)
def flatMapValues(self, f):
"""
Return a new DStream by applying a flatmap function to the value
of each key-value pairs in this DStream without changing the key.
"""
flat_map_fn = lambda kv: ((kv[0], x) for x in f(kv[1]))
return self.flatMap(flat_map_fn, preservesPartitioning=True)
def glom(self):
"""
Return a new DStream in which RDD is generated by applying glom()
to RDD of this DStream.
"""
def func(iterator):
yield list(iterator)
return self.mapPartitions(func)
def cache(self):
"""
Persist the RDDs of this DStream with the default storage level
(C{MEMORY_ONLY_SER}).
"""
self.is_cached = True
self.persist(StorageLevel.MEMORY_ONLY_SER)
return self
def persist(self, storageLevel):
"""
Persist the RDDs of this DStream with the given storage level
"""
self.is_cached = True
javaStorageLevel = self._sc._getJavaStorageLevel(storageLevel)
self._jdstream.persist(javaStorageLevel)
return self
def checkpoint(self, interval):
"""
Enable periodic checkpointing of RDDs of this DStream
@param interval: time in seconds, after each period of that, generated
RDD will be checkpointed
"""
self.is_checkpointed = True
self._jdstream.checkpoint(self._ssc._jduration(interval))
return self
def groupByKey(self, numPartitions=None):
"""
Return a new DStream by applying groupByKey on each RDD.
"""
if numPartitions is None:
numPartitions = self._sc.defaultParallelism
return self.transform(lambda rdd: rdd.groupByKey(numPartitions))
def countByValue(self):
"""
Return a new DStream in which each RDD contains the counts of each
distinct value in each RDD of this DStream.
"""
return self.map(lambda x: (x, None)).reduceByKey(lambda x, y: None).count()
def saveAsTextFiles(self, prefix, suffix=None):
"""
Save each RDD in this DStream as at text file, using string
representation of elements.
"""
def saveAsTextFile(t, rdd):
path = rddToFileName(prefix, suffix, t)
try:
rdd.saveAsTextFile(path)
except Py4JJavaError as e:
# after recovered from checkpointing, the foreachRDD may
# be called twice
if 'FileAlreadyExistsException' not in str(e):
raise
return self.foreachRDD(saveAsTextFile)
# TODO: uncomment this until we have ssc.pickleFileStream()
# def saveAsPickleFiles(self, prefix, suffix=None):
# """
# Save each RDD in this DStream as at binary file, the elements are
# serialized by pickle.
# """
# def saveAsPickleFile(t, rdd):
# path = rddToFileName(prefix, suffix, t)
# try:
# rdd.saveAsPickleFile(path)
# except Py4JJavaError as e:
# # after recovered from checkpointing, the foreachRDD may
# # be called twice
# if 'FileAlreadyExistsException' not in str(e):
# raise
# return self.foreachRDD(saveAsPickleFile)
def transform(self, func):
"""
Return a new DStream in which each RDD is generated by applying a function
on each RDD of this DStream.
`func` can have one argument of `rdd`, or have two arguments of
(`time`, `rdd`)
"""
if func.__code__.co_argcount == 1:
oldfunc = func
func = lambda t, rdd: oldfunc(rdd)
assert func.__code__.co_argcount == 2, "func should take one or two arguments"
return TransformedDStream(self, func)
def transformWith(self, func, other, keepSerializer=False):
"""
Return a new DStream in which each RDD is generated by applying a function
on each RDD of this DStream and 'other' DStream.
`func` can have two arguments of (`rdd_a`, `rdd_b`) or have three
arguments of (`time`, `rdd_a`, `rdd_b`)
"""
if func.__code__.co_argcount == 2:
oldfunc = func
func = lambda t, a, b: oldfunc(a, b)
assert func.__code__.co_argcount == 3, "func should take two or three arguments"
jfunc = TransformFunction(self._sc, func, self._jrdd_deserializer, other._jrdd_deserializer)
dstream = self._sc._jvm.PythonTransformed2DStream(self._jdstream.dstream(),
other._jdstream.dstream(), jfunc)
jrdd_serializer = self._jrdd_deserializer if keepSerializer else self._sc.serializer
return DStream(dstream.asJavaDStream(), self._ssc, jrdd_serializer)
def repartition(self, numPartitions):
"""
Return a new DStream with an increased or decreased level of parallelism.
"""
return self.transform(lambda rdd: rdd.repartition(numPartitions))
@property
def _slideDuration(self):
"""
Return the slideDuration in seconds of this DStream
"""
return self._jdstream.dstream().slideDuration().milliseconds() / 1000.0
def union(self, other):
"""
Return a new DStream by unifying data of another DStream with this DStream.
@param other: Another DStream having the same interval (i.e., slideDuration)
as this DStream.
"""
if self._slideDuration != other._slideDuration:
raise ValueError("the two DStream should have same slide duration")
return self.transformWith(lambda a, b: a.union(b), other, True)
def cogroup(self, other, numPartitions=None):
"""
Return a new DStream by applying 'cogroup' between RDDs of this
DStream and `other` DStream.
Hash partitioning is used to generate the RDDs with `numPartitions` partitions.
"""
if numPartitions is None:
numPartitions = self._sc.defaultParallelism
return self.transformWith(lambda a, b: a.cogroup(b, numPartitions), other)
def join(self, other, numPartitions=None):
"""
Return a new DStream by applying 'join' between RDDs of this DStream and
`other` DStream.
Hash partitioning is used to generate the RDDs with `numPartitions`
partitions.
"""
if numPartitions is None:
numPartitions = self._sc.defaultParallelism
return self.transformWith(lambda a, b: a.join(b, numPartitions), other)
def leftOuterJoin(self, other, numPartitions=None):
"""
Return a new DStream by applying 'left outer join' between RDDs of this DStream and
`other` DStream.
Hash partitioning is used to generate the RDDs with `numPartitions`
partitions.
"""
if numPartitions is None:
numPartitions = self._sc.defaultParallelism
return self.transformWith(lambda a, b: a.leftOuterJoin(b, numPartitions), other)
def rightOuterJoin(self, other, numPartitions=None):
"""
Return a new DStream by applying 'right outer join' between RDDs of this DStream and
`other` DStream.
Hash partitioning is used to generate the RDDs with `numPartitions`
partitions.
"""
if numPartitions is None:
numPartitions = self._sc.defaultParallelism
return self.transformWith(lambda a, b: a.rightOuterJoin(b, numPartitions), other)
def fullOuterJoin(self, other, numPartitions=None):
"""
Return a new DStream by applying 'full outer join' between RDDs of this DStream and
`other` DStream.
Hash partitioning is used to generate the RDDs with `numPartitions`
partitions.
"""
if numPartitions is None:
numPartitions = self._sc.defaultParallelism
return self.transformWith(lambda a, b: a.fullOuterJoin(b, numPartitions), other)
def _jtime(self, timestamp):
""" Convert datetime or unix_timestamp into Time
"""
if isinstance(timestamp, datetime):
timestamp = time.mktime(timestamp.timetuple())
return self._sc._jvm.Time(long(timestamp * 1000))
def slice(self, begin, end):
"""
Return all the RDDs between 'begin' to 'end' (both included)
`begin`, `end` could be datetime.datetime() or unix_timestamp
"""
jrdds = self._jdstream.slice(self._jtime(begin), self._jtime(end))
return [RDD(jrdd, self._sc, self._jrdd_deserializer) for jrdd in jrdds]
def _validate_window_param(self, window, slide):
duration = self._jdstream.dstream().slideDuration().milliseconds()
if int(window * 1000) % duration != 0:
raise ValueError("windowDuration must be multiple of the slide duration (%d ms)"
% duration)
if slide and int(slide * 1000) % duration != 0:
raise ValueError("slideDuration must be multiple of the slide duration (%d ms)"
% duration)
def window(self, windowDuration, slideDuration=None):
"""
Return a new DStream in which each RDD contains all the elements in seen in a
sliding window of time over this DStream.
@param windowDuration: width of the window; must be a multiple of this DStream's
batching interval
@param slideDuration: sliding interval of the window (i.e., the interval after which
the new DStream will generate RDDs); must be a multiple of this
DStream's batching interval
"""
self._validate_window_param(windowDuration, slideDuration)
d = self._ssc._jduration(windowDuration)
if slideDuration is None:
return DStream(self._jdstream.window(d), self._ssc, self._jrdd_deserializer)
s = self._ssc._jduration(slideDuration)
return DStream(self._jdstream.window(d, s), self._ssc, self._jrdd_deserializer)
def reduceByWindow(self, reduceFunc, invReduceFunc, windowDuration, slideDuration):
"""
Return a new DStream in which each RDD has a single element generated by reducing all
elements in a sliding window over this DStream.
if `invReduceFunc` is not None, the reduction is done incrementally
using the old window's reduced value :
1. reduce the new values that entered the window (e.g., adding new counts)
2. "inverse reduce" the old values that left the window (e.g., subtracting old counts)
This is more efficient than `invReduceFunc` is None.
@param reduceFunc: associative reduce function
@param invReduceFunc: inverse reduce function of `reduceFunc`
@param windowDuration: width of the window; must be a multiple of this DStream's
batching interval
@param slideDuration: sliding interval of the window (i.e., the interval after which
the new DStream will generate RDDs); must be a multiple of this
DStream's batching interval
"""
keyed = self.map(lambda x: (1, x))
reduced = keyed.reduceByKeyAndWindow(reduceFunc, invReduceFunc,
windowDuration, slideDuration, 1)
return reduced.map(lambda kv: kv[1])
def countByWindow(self, windowDuration, slideDuration):
"""
Return a new DStream in which each RDD has a single element generated
by counting the number of elements in a window over this DStream.
windowDuration and slideDuration are as defined in the window() operation.
This is equivalent to window(windowDuration, slideDuration).count(),
but will be more efficient if window is large.
"""
return self.map(lambda x: 1).reduceByWindow(operator.add, operator.sub,
windowDuration, slideDuration)
def countByValueAndWindow(self, windowDuration, slideDuration, numPartitions=None):
"""
Return a new DStream in which each RDD contains the count of distinct elements in
RDDs in a sliding window over this DStream.
@param windowDuration: width of the window; must be a multiple of this DStream's
batching interval
@param slideDuration: sliding interval of the window (i.e., the interval after which
the new DStream will generate RDDs); must be a multiple of this
DStream's batching interval
@param numPartitions: number of partitions of each RDD in the new DStream.
"""
keyed = self.map(lambda x: (x, 1))
counted = keyed.reduceByKeyAndWindow(operator.add, operator.sub,
windowDuration, slideDuration, numPartitions)
return counted.filter(lambda kv: kv[1] > 0).count()
def groupByKeyAndWindow(self, windowDuration, slideDuration, numPartitions=None):
"""
Return a new DStream by applying `groupByKey` over a sliding window.
Similar to `DStream.groupByKey()`, but applies it over a sliding window.
@param windowDuration: width of the window; must be a multiple of this DStream's
batching interval
@param slideDuration: sliding interval of the window (i.e., the interval after which
the new DStream will generate RDDs); must be a multiple of this
DStream's batching interval
@param numPartitions: Number of partitions of each RDD in the new DStream.
"""
ls = self.mapValues(lambda x: [x])
grouped = ls.reduceByKeyAndWindow(lambda a, b: a.extend(b) or a, lambda a, b: a[len(b):],
windowDuration, slideDuration, numPartitions)
return grouped.mapValues(ResultIterable)
def reduceByKeyAndWindow(self, func, invFunc, windowDuration, slideDuration=None,
numPartitions=None, filterFunc=None):
"""
Return a new DStream by applying incremental `reduceByKey` over a sliding window.
The reduced value of over a new window is calculated using the old window's reduce value :
1. reduce the new values that entered the window (e.g., adding new counts)
2. "inverse reduce" the old values that left the window (e.g., subtracting old counts)
`invFunc` can be None, then it will reduce all the RDDs in window, could be slower
than having `invFunc`.
@param func: associative reduce function
@param invFunc: inverse function of `reduceFunc`
@param windowDuration: width of the window; must be a multiple of this DStream's
batching interval
@param slideDuration: sliding interval of the window (i.e., the interval after which
the new DStream will generate RDDs); must be a multiple of this
DStream's batching interval
@param numPartitions: number of partitions of each RDD in the new DStream.
@param filterFunc: function to filter expired key-value pairs;
only pairs that satisfy the function are retained
set this to null if you do not want to filter
"""
self._validate_window_param(windowDuration, slideDuration)
if numPartitions is None:
numPartitions = self._sc.defaultParallelism
reduced = self.reduceByKey(func, numPartitions)
def reduceFunc(t, a, b):
b = b.reduceByKey(func, numPartitions)
r = a.union(b).reduceByKey(func, numPartitions) if a else b
if filterFunc:
r = r.filter(filterFunc)
return r
def invReduceFunc(t, a, b):
b = b.reduceByKey(func, numPartitions)
joined = a.leftOuterJoin(b, numPartitions)
return joined.mapValues(lambda kv: invFunc(kv[0], kv[1])
if kv[1] is not None else kv[0])
jreduceFunc = TransformFunction(self._sc, reduceFunc, reduced._jrdd_deserializer)
if invFunc:
jinvReduceFunc = TransformFunction(self._sc, invReduceFunc, reduced._jrdd_deserializer)
else:
jinvReduceFunc = None
if slideDuration is None:
slideDuration = self._slideDuration
dstream = self._sc._jvm.PythonReducedWindowedDStream(reduced._jdstream.dstream(),
jreduceFunc, jinvReduceFunc,
self._ssc._jduration(windowDuration),
self._ssc._jduration(slideDuration))
return DStream(dstream.asJavaDStream(), self._ssc, self._sc.serializer)
def updateStateByKey(self, updateFunc, numPartitions=None):
"""
Return a new "state" DStream where the state for each key is updated by applying
the given function on the previous state of the key and the new values of the key.
@param updateFunc: State update function. If this function returns None, then
corresponding state key-value pair will be eliminated.
"""
if numPartitions is None:
numPartitions = self._sc.defaultParallelism
def reduceFunc(t, a, b):
if a is None:
g = b.groupByKey(numPartitions).mapValues(lambda vs: (list(vs), None))
else:
g = a.cogroup(b.partitionBy(numPartitions), numPartitions)
g = g.mapValues(lambda ab: (list(ab[1]), list(ab[0])[0] if len(ab[0]) else None))
state = g.mapValues(lambda vs_s: updateFunc(vs_s[0], vs_s[1]))
return state.filter(lambda k_v: k_v[1] is not None)
jreduceFunc = TransformFunction(self._sc, reduceFunc,
self._sc.serializer, self._jrdd_deserializer)
dstream = self._sc._jvm.PythonStateDStream(self._jdstream.dstream(), jreduceFunc)
return DStream(dstream.asJavaDStream(), self._ssc, self._sc.serializer)
class TransformedDStream(DStream):
"""
TransformedDStream is an DStream generated by an Python function
transforming each RDD of an DStream to another RDDs.
Multiple continuous transformations of DStream can be combined into
one transformation.
"""
def __init__(self, prev, func):
self._ssc = prev._ssc
self._sc = self._ssc._sc
self._jrdd_deserializer = self._sc.serializer
self.is_cached = False
self.is_checkpointed = False
self._jdstream_val = None
# Using type() to avoid folding the functions and compacting the DStreams which is not
# not strictly a object of TransformedDStream.
# Changed here is to avoid bug in KafkaTransformedDStream when calling offsetRanges().
if (type(prev) is TransformedDStream and
not prev.is_cached and not prev.is_checkpointed):
prev_func = prev.func
self.func = lambda t, rdd: func(t, prev_func(t, rdd))
self.prev = prev.prev
else:
self.prev = prev
self.func = func
@property
def _jdstream(self):
if self._jdstream_val is not None:
return self._jdstream_val
jfunc = TransformFunction(self._sc, self.func, self.prev._jrdd_deserializer)
dstream = self._sc._jvm.PythonTransformedDStream(self.prev._jdstream.dstream(), jfunc)
self._jdstream_val = dstream.asJavaDStream()
return self._jdstream_val
| 42.962145 | 100 | 0.62846 |
acec864491a35b040b4eb3ff2000432af57fa1d5 | 1,917 | py | Python | openhivenpy/types/__init__.py | FrostbyteBot/hiven.py | 1a2831cf4e0512cc8dd2b8f8f5d04b582158a21e | [
"MIT"
] | 9 | 2020-11-13T19:07:54.000Z | 2021-01-30T23:12:57.000Z | openhivenpy/types/__init__.py | FrostbyteBot/hiven.py | 1a2831cf4e0512cc8dd2b8f8f5d04b582158a21e | [
"MIT"
] | 46 | 2020-11-05T20:32:41.000Z | 2021-04-03T22:48:18.000Z | openhivenpy/types/__init__.py | FrostbyteBot/openhiven.py | 1a2831cf4e0512cc8dd2b8f8f5d04b582158a21e | [
"MIT"
] | 2 | 2020-12-19T14:27:07.000Z | 2021-01-29T10:52:33.000Z | """
Module for all data classes that represent Hiven Objects.
---
Under MIT License
Copyright © 2020 - 2021 Luna Klatzer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
# Used for type hinting and not having to use annotations for the objects
from __future__ import annotations
__all__ = [
'TextRoom',
'LazyHouse', 'House',
'PrivateRoom', 'PrivateGroupRoom',
'LazyUser', 'User',
'Message', 'DeletedMessage',
'Context',
'Member',
'UserTyping',
'Attachment',
'Feed',
'Entity',
'Invite',
'Mention',
'Embed',
'Relationship'
]
from .attachment import *
from .context import *
from .embed import *
from .entity import *
from .feed import *
from .house import *
from .invite import *
from .member import *
from .mention import *
from .message import *
from .private_room import *
from .relationship import *
from .textroom import *
from .user import *
from .usertyping import *
| 29.492308 | 78 | 0.744914 |
acec8658c120041856b9e794091c15375a619484 | 640 | py | Python | test/test_add_group.py | agakax/qa-courses-python-training | d523d5543c947ed449cd2d1109cac2eeac390f7b | [
"Apache-2.0"
] | null | null | null | test/test_add_group.py | agakax/qa-courses-python-training | d523d5543c947ed449cd2d1109cac2eeac390f7b | [
"Apache-2.0"
] | null | null | null | test/test_add_group.py | agakax/qa-courses-python-training | d523d5543c947ed449cd2d1109cac2eeac390f7b | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
from model.group import Group
def test_add_group(app, db, json_groups, check_ui):
group = json_groups
old_groups = db.get_group_list()
app.group.create(group)
new_groups = db.get_group_list()
old_groups.append(group)
assert sorted(old_groups, key=Group.id_or_max) == sorted(new_groups, key=Group.id_or_max)
if check_ui:
assert sorted((map(lambda x: clean(x), new_groups)), key=Group.id_or_max) == \
sorted((map(lambda x: clean(x), app.group.get_group_list())), key=Group.id_or_max)
def clean(group):
return Group(id_group=group.id, name=group.name.strip())
| 33.684211 | 97 | 0.685938 |
acec8689f8da9b4ea80fcbaa1792e551b8443f49 | 95,629 | py | Python | env/lib/python3.8/site-packages/reportlab/platypus/flowables.py | Tuitoek/Golden- | e8afa1b57b558450c90eedf12b3ef6a35e8f98a4 | [
"MIT"
] | null | null | null | env/lib/python3.8/site-packages/reportlab/platypus/flowables.py | Tuitoek/Golden- | e8afa1b57b558450c90eedf12b3ef6a35e8f98a4 | [
"MIT"
] | null | null | null | env/lib/python3.8/site-packages/reportlab/platypus/flowables.py | Tuitoek/Golden- | e8afa1b57b558450c90eedf12b3ef6a35e8f98a4 | [
"MIT"
] | null | null | null | #Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/platypus/flowables.py
__version__='3.3.0'
__doc__="""
A flowable is a "floating element" in a document whose exact position is determined by the
other elements that precede it, such as a paragraph, a diagram interspersed between paragraphs,
a section header, etcetera. Examples of non-flowables include page numbering annotations,
headers, footers, fixed diagrams or logos, among others.
Flowables are defined here as objects which know how to determine their size and which
can draw themselves onto a page with respect to a relative "origin" position determined
at a higher level. The object's draw() method should assume that (0,0) corresponds to the
bottom left corner of the enclosing rectangle that will contain the object. The attributes
vAlign and hAlign may be used by 'packers' as hints as to how the object should be placed.
Some Flowables also know how to "split themselves". For example a
long paragraph might split itself between one page and the next.
Packers should set the canv attribute during wrap, split & draw operations to allow
the flowable to work out sizes etc in the proper context.
The "text" of a document usually consists mainly of a sequence of flowables which
flow into a document from top to bottom (with column and page breaks controlled by
higher level components).
"""
import os
from copy import deepcopy, copy
from reportlab.lib.colors import red, gray, lightgrey
from reportlab.lib.rl_accel import fp_str
from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT, TA_JUSTIFY
from reportlab.lib.styles import _baseFontName
from reportlab.lib.utils import strTypes, rl_safe_exec
from reportlab.lib.abag import ABag
from reportlab.pdfbase import pdfutils
from reportlab.pdfbase.pdfmetrics import stringWidth
from reportlab.rl_config import _FUZZ, overlapAttachedSpace, ignoreContainerActions, listWrapOnFakeWidth
from reportlab import xrange
import collections
__all__ = '''AnchorFlowable BalancedColumns BulletDrawer CallerMacro CondPageBreak DDIndenter DocAssert
DocAssign DocExec DocIf DocPara DocWhile FailOnDraw FailOnWrap Flowable FrameBG FrameSplitter
HRFlowable Image ImageAndFlowables KeepInFrame KeepTogether LIIndenter ListFlowable ListItem
Macro NullDraw PTOContainer PageBreak PageBreakIfNotEmpty ParagraphAndImage Preformatted
SetPageTopFlowables SetTopFlowables SlowPageBreak Spacer TopPadder TraceInfo UseUpSpace XBox
splitLine splitLines'''.split()
class TraceInfo:
"Holder for info about where an object originated"
def __init__(self):
self.srcFile = '(unknown)'
self.startLineNo = -1
self.startLinePos = -1
self.endLineNo = -1
self.endLinePos = -1
#############################################################
# Flowable Objects - a base class and a few examples.
# One is just a box to get some metrics. We also have
# a paragraph, an image and a special 'page break'
# object which fills the space.
#############################################################
class Flowable:
"""Abstract base class for things to be drawn. Key concepts:
1. It knows its size
2. It draws in its own coordinate system (this requires the
base API to provide a translate() function.
"""
_fixedWidth = 0 #assume wrap results depend on arguments?
_fixedHeight = 0
def __init__(self):
self.width = 0
self.height = 0
self.wrapped = 0
#these are hints to packers/frames as to how the floable should be positioned
self.hAlign = 'LEFT' #CENTER/CENTRE or RIGHT
self.vAlign = 'BOTTOM' #MIDDLE or TOP
#optional holder for trace info
self._traceInfo = None
self._showBoundary = None
#many flowables handle text and must be processed in the
#absence of a canvas. tagging them with their encoding
#helps us to get conversions right. Use Python codec names.
self.encoding = None
def _drawOn(self,canv):
'''ensure canv is set on and then draw'''
self.canv = canv
self.draw()#this is the bit you overload
del self.canv
def _hAlignAdjust(self,x,sW=0):
if sW and hasattr(self,'hAlign'):
a = self.hAlign
if a in ('CENTER','CENTRE', TA_CENTER):
x += 0.5*sW
elif a in ('RIGHT',TA_RIGHT):
x += sW
elif a not in ('LEFT',TA_LEFT):
raise ValueError("Bad hAlign value "+str(a))
return x
def drawOn(self, canvas, x, y, _sW=0):
"Tell it to draw itself on the canvas. Do not override"
x = self._hAlignAdjust(x,_sW)
canvas.saveState()
canvas.translate(x, y)
self._drawOn(canvas)
if hasattr(self, '_showBoundary') and self._showBoundary:
#diagnostic tool support
canvas.setStrokeColor(gray)
canvas.rect(0,0,self.width, self.height)
canvas.restoreState()
def wrapOn(self, canv, aW, aH):
'''intended for use by packers allows setting the canvas on
during the actual wrap'''
self.canv = canv
w, h = self.wrap(aW,aH)
del self.canv
return w, h
def wrap(self, availWidth, availHeight):
"""This will be called by the enclosing frame before objects
are asked their size, drawn or whatever. It returns the
size actually used."""
return (self.width, self.height)
def minWidth(self):
"""This should return the minimum required width"""
return getattr(self,'_minWidth',self.width)
def splitOn(self, canv, aW, aH):
'''intended for use by packers allows setting the canvas on
during the actual split'''
self.canv = canv
S = self.split(aW,aH)
del self.canv
return S
def split(self, availWidth, availheight):
"""This will be called by more sophisticated frames when
wrap fails. Stupid flowables should return []. Clever flowables
should split themselves and return a list of flowables.
If they decide that nothing useful can be fitted in the
available space (e.g. if you have a table and not enough
space for the first row), also return []"""
return []
def getKeepWithNext(self):
"""returns boolean determining whether the next flowable should stay with this one"""
if hasattr(self,'keepWithNext'): return self.keepWithNext
elif hasattr(self,'style') and hasattr(self.style,'keepWithNext'): return self.style.keepWithNext
else: return 0
def getSpaceAfter(self):
"""returns how much space should follow this item if another item follows on the same page."""
if hasattr(self,'spaceAfter'): return self.spaceAfter
elif hasattr(self,'style') and hasattr(self.style,'spaceAfter'): return self.style.spaceAfter
else: return 0
def getSpaceBefore(self):
"""returns how much space should precede this item if another item precedess on the same page."""
if hasattr(self,'spaceBefore'): return self.spaceBefore
elif hasattr(self,'style') and hasattr(self.style,'spaceBefore'): return self.style.spaceBefore
else: return 0
def isIndexing(self):
"""Hook for IndexingFlowables - things which have cross references"""
return 0
def identity(self, maxLen=None):
'''
This method should attempt to return a string that can be used to identify
a particular flowable uniquely. The result can then be used for debugging
and or error printouts
'''
if hasattr(self, 'getPlainText'):
r = self.getPlainText(identify=1)
elif hasattr(self, 'text'):
r = str(self.text)
else:
r = '...'
if r and maxLen:
r = r[:maxLen]
return "<%s at %s%s>%s" % (self.__class__.__name__, hex(id(self)), self._frameName(), r)
@property
def _doctemplate(self):
return getattr(getattr(self,'canv',None),'_doctemplate',None)
def _doctemplateAttr(self,a):
return getattr(self._doctemplate,a,None)
def _frameName(self):
f = getattr(self,'_frame',None)
if not f: f = self._doctemplateAttr('frame')
if f and f.id: return ' frame=%s' % f.id
return ''
class XBox(Flowable):
"""Example flowable - a box with an x through it and a caption.
This has a known size, so does not need to respond to wrap()."""
def __init__(self, width, height, text = 'A Box'):
Flowable.__init__(self)
self.width = width
self.height = height
self.text = text
def __repr__(self):
return "XBox(w=%s, h=%s, t=%s)" % (self.width, self.height, self.text)
def draw(self):
self.canv.rect(0, 0, self.width, self.height)
self.canv.line(0, 0, self.width, self.height)
self.canv.line(0, self.height, self.width, 0)
#centre the text
self.canv.setFont(_baseFontName,12)
self.canv.drawCentredString(0.5*self.width, 0.5*self.height, self.text)
def _trimEmptyLines(lines):
#don't want the first or last to be empty
while len(lines) and lines[0].strip() == '':
lines = lines[1:]
while len(lines) and lines[-1].strip() == '':
lines = lines[:-1]
return lines
def _dedenter(text,dedent=0):
'''
tidy up text - carefully, it is probably code. If people want to
indent code within a source script, you can supply an arg to dedent
and it will chop off that many character, otherwise it leaves
left edge intact.
'''
lines = text.split('\n')
if dedent>0:
templines = _trimEmptyLines(lines)
lines = []
for line in templines:
line = line[dedent:].rstrip()
lines.append(line)
else:
lines = _trimEmptyLines(lines)
return lines
SPLIT_CHARS = "[{( ,.;:/\\-"
def splitLines(lines, maximum_length, split_characters, new_line_characters):
if split_characters is None:
split_characters = SPLIT_CHARS
if new_line_characters is None:
new_line_characters = ""
# Return a table of lines
lines_splitted = []
for line in lines:
if len(line) > maximum_length:
splitLine(line, lines_splitted, maximum_length, \
split_characters, new_line_characters)
else:
lines_splitted.append(line)
return lines_splitted
def splitLine(line_to_split, lines_splitted, maximum_length, \
split_characters, new_line_characters):
# Used to implement the characters added
#at the beginning of each new line created
first_line = True
# Check if the text can be splitted
while line_to_split and len(line_to_split)>0:
# Index of the character where we can split
split_index = 0
# Check if the line length still exceeds the maximum length
if len(line_to_split) <= maximum_length:
# Return the remaining of the line
split_index = len(line_to_split)
else:
# Iterate for each character of the line
for line_index in range(maximum_length):
# Check if the character is in the list
# of allowed characters to split on
if line_to_split[line_index] in split_characters:
split_index = line_index + 1
# If the end of the line was reached
# with no character to split on
if split_index==0:
split_index = line_index + 1
if first_line:
lines_splitted.append(line_to_split[0:split_index])
first_line = False
maximum_length -= len(new_line_characters)
else:
lines_splitted.append(new_line_characters + \
line_to_split[0:split_index])
# Remaining text to split
line_to_split = line_to_split[split_index:]
class Preformatted(Flowable):
"""This is like the HTML <PRE> tag.
It attempts to display text exactly as you typed it in a fixed width "typewriter" font.
By default the line breaks are exactly where you put them, and it will not be wrapped.
You can optionally define a maximum line length and the code will be wrapped; and
extra characters to be inserted at the beginning of each wrapped line (e.g. '> ').
"""
def __init__(self, text, style, bulletText = None, dedent=0, maxLineLength=None, splitChars=None, newLineChars=""):
"""text is the text to display. If dedent is set then common leading space
will be chopped off the front (for example if the entire text is indented
6 spaces or more then each line will have 6 spaces removed from the front).
"""
self.style = style
self.bulletText = bulletText
self.lines = _dedenter(text,dedent)
if text and maxLineLength:
self.lines = splitLines(
self.lines,
maxLineLength,
splitChars,
newLineChars
)
def __repr__(self):
bT = self.bulletText
H = "Preformatted("
if bT is not None:
H = "Preformatted(bulletText=%s," % repr(bT)
return "%s'''\\ \n%s''')" % (H, '\n'.join(self.lines))
def wrap(self, availWidth, availHeight):
self.width = availWidth
self.height = self.style.leading*len(self.lines)
return (self.width, self.height)
def minWidth(self):
style = self.style
fontSize = style.fontSize
fontName = style.fontName
return max([stringWidth(line,fontName,fontSize) for line in self.lines])
def split(self, availWidth, availHeight):
#returns two Preformatted objects
#not sure why they can be called with a negative height
if availHeight < self.style.leading:
return []
linesThatFit = int(availHeight * 1.0 / self.style.leading)
text1 = '\n'.join(self.lines[0:linesThatFit])
text2 = '\n'.join(self.lines[linesThatFit:])
style = self.style
if style.firstLineIndent != 0:
style = deepcopy(style)
style.firstLineIndent = 0
return [Preformatted(text1, self.style), Preformatted(text2, style)]
def draw(self):
#call another method for historical reasons. Besides, I
#suspect I will be playing with alternate drawing routines
#so not doing it here makes it easier to switch.
cur_x = self.style.leftIndent
cur_y = self.height - self.style.fontSize
self.canv.addLiteral('%PreformattedPara')
if self.style.textColor:
self.canv.setFillColor(self.style.textColor)
tx = self.canv.beginText(cur_x, cur_y)
#set up the font etc.
tx.setFont( self.style.fontName,
self.style.fontSize,
self.style.leading)
for text in self.lines:
tx.textLine(text)
self.canv.drawText(tx)
class Image(Flowable):
"""an image (digital picture). Formats supported by PIL/Java 1.4 (the Python/Java Imaging Library
are supported. Images as flowables may be aligned horizontally in the
frame with the hAlign parameter - accepted values are 'CENTER',
'LEFT' or 'RIGHT' with 'CENTER' being the default.
We allow for two kinds of lazyness to allow for many images in a document
which could lead to file handle starvation.
lazy=1 don't open image until required.
lazy=2 open image when required then shut it.
"""
_fixedWidth = 1
_fixedHeight = 1
def __init__(self, filename, width=None, height=None, kind='direct',
mask="auto", lazy=1, hAlign='CENTER', useDPI=False):
"""If size to draw at not specified, get it from the image."""
self.hAlign = hAlign
self._mask = mask
fp = hasattr(filename,'read')
self._drawing = None
if fp:
self._file = filename
self.filename = repr(filename)
elif hasattr(filename,'_renderPy'):
self._drawing = filename
self.filename=repr(filename)
self._file = None
self._img = None
fp = True
else:
self._file = self.filename = filename
self._dpi = useDPI
if not fp and os.path.splitext(filename)[1] in ['.jpg', '.JPG', '.jpeg', '.JPEG']:
# if it is a JPEG, will be inlined within the file -
# but we still need to know its size now
from reportlab.lib.utils import open_for_read
f = open_for_read(filename, 'b')
try:
try:
info = pdfutils.readJPEGInfo(f)
except:
#couldn't read as a JPEG, try like normal
self._setup(width,height,kind,lazy)
return
finally:
f.close()
self.imageWidth = info[0]
self.imageHeight = info[1]
if useDPI:
self._dpi = info[3]
self._img = None
self._setup(width,height,kind,0)
elif fp:
self._setup(width,height,kind,0)
else:
self._setup(width,height,kind,lazy)
def _dpiAdjust(self):
dpi = self._dpi
if dpi:
if dpi[0]!=72: self.imageWidth *= 72.0 / dpi[0]
if dpi[1]!=72: self.imageHeight *= 72.0 / dpi[1]
def _setup(self,width,height,kind,lazy):
self._lazy = lazy
self._width = width
self._height = height
self._kind = kind
if lazy<=0: self._setup_inner()
def _setup_inner(self):
width = self._width
height = self._height
kind = self._kind
img = self._img
if img:
self.imageWidth, self.imageHeight = img.getSize()
if self._dpi and hasattr(img,'_image'):
self._dpi = img._image.info.get('dpi',(72,72))
elif self._drawing:
self.imageWidth, self.imageHeight = self._drawing.width,self._drawing.height
self._dpi = False
self._dpiAdjust()
if self._lazy>=2: del self._img
if kind in ['direct','absolute']:
self.drawWidth = width or self.imageWidth
self.drawHeight = height or self.imageHeight
elif kind in ['percentage','%']:
self.drawWidth = self.imageWidth*width*0.01
self.drawHeight = self.imageHeight*height*0.01
elif kind in ['bound','proportional']:
factor = min(float(width)/self.imageWidth,float(height)/self.imageHeight)
self.drawWidth = self.imageWidth*factor
self.drawHeight = self.imageHeight*factor
def _restrictSize(self,aW,aH):
if self.drawWidth>aW+_FUZZ or self.drawHeight>aH+_FUZZ:
self._oldDrawSize = self.drawWidth, self.drawHeight
factor = min(float(aW)/self.drawWidth,float(aH)/self.drawHeight)
self.drawWidth *= factor
self.drawHeight *= factor
return self.drawWidth, self.drawHeight
def _unRestrictSize(self):
dwh = getattr(self,'_oldDrawSize',None)
if dwh:
self.drawWidth, self.drawHeight = dwh
def __getattr__(self,a):
if a=='_img':
from reportlab.lib.utils import ImageReader #this may raise an error
self._img = ImageReader(self._file)
if not isinstance(self._file,strTypes):
self._file = None
if self._lazy>=2: self._lazy = 1 #here we're assuming we cannot read again
return self._img
elif a in ('drawWidth','drawHeight','imageWidth','imageHeight'):
self._setup_inner()
return self.__dict__[a]
raise AttributeError("<Image @ 0x%x>.%s" % (id(self),a))
def wrap(self, availWidth, availHeight):
#the caller may decide it does not fit.
return self.drawWidth, self.drawHeight
def draw(self):
dx = getattr(self,'_offs_x',0)
dy = getattr(self,'_offs_y',0)
d = self._drawing
if d:
sx = self.drawWidth / float(self.imageWidth)
sy = self.drawHeight / float(self.imageHeight)
otrans = d.transform
try:
d.scale(sx,sy)
d.drawOn(self.canv,dx,dy)
finally:
d.transform = otrans
else:
lazy = self._lazy
if lazy>=2: self._lazy = 1
self.canv.drawImage( self._img or self.filename,
dx,
dy,
self.drawWidth,
self.drawHeight,
mask=self._mask,
)
if lazy>=2:
self._img = self._file = None
self._lazy = lazy
def identity(self,maxLen=None):
r = Flowable.identity(self,maxLen)
if r[-4:]=='>...' and isinstance(self.filename,str):
r = "%s filename=%s>" % (r[:-4],self.filename)
return r
class NullDraw(Flowable):
def draw(self):
pass
class Spacer(NullDraw):
"""A spacer just takes up space and doesn't draw anything - it guarantees
a gap between objects."""
_fixedWidth = 1
_fixedHeight = 1
def __init__(self, width, height, isGlue=False):
self.width = width
if isGlue:
self.height = 1e-4
self.spacebefore = height
self.height = height
def __repr__(self):
return "%s(%s, %s)" % (self.__class__.__name__,self.width, self.height)
class UseUpSpace(NullDraw):
def __init__(self):
pass
def __repr__(self):
return "%s()" % self.__class__.__name__
def wrap(self, availWidth, availHeight):
self.width = availWidth
self.height = availHeight
return (availWidth,availHeight-1e-8) #step back a point
class PageBreak(UseUpSpace):
locChanger=1
"""Move on to the next page in the document.
This works by consuming all remaining space in the frame!"""
def __init__(self,nextTemplate=None):
self.nextTemplate = nextTemplate
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__,repr(self.nextTemplate) if self.nextTemplate else '')
class SlowPageBreak(PageBreak):
pass
class PageBreakIfNotEmpty(PageBreak):
pass
class CondPageBreak(Spacer):
locChanger=1
"""use up a frame if not enough vertical space effectively CondFrameBreak"""
def __init__(self, height):
self.height = height
def __repr__(self):
return "CondPageBreak(%s)" %(self.height,)
def wrap(self, availWidth, availHeight):
if availHeight<self.height:
f = self._doctemplateAttr('frame')
if not f: return availWidth, availHeight
from reportlab.platypus.doctemplate import FrameBreak
f.add_generated_content(FrameBreak)
return 0, 0
def identity(self,maxLen=None):
return repr(self).replace(')',',frame=%s)'%self._frameName())
def _listWrapOn(F,availWidth,canv,mergeSpace=1,obj=None,dims=None,fakeWidth=None):
'''return max width, required height for a list of flowables F'''
doct = getattr(canv,'_doctemplate',None)
cframe = getattr(doct,'frame',None)
if fakeWidth is None:
fakeWidth = listWrapOnFakeWidth
if cframe:
from reportlab.platypus.doctemplate import _addGeneratedContent, Indenter
doct_frame = cframe
cframe = doct.frame = deepcopy(doct_frame)
cframe._generated_content = None
del cframe._generated_content
try:
W = 0
H = 0
pS = 0
atTop = 1
F = F[:]
while F:
f = F.pop(0)
if hasattr(f,'frameAction'):
from reportlab.platypus.doctemplate import Indenter
if isinstance(f,Indenter):
availWidth -= f.left+f.right
continue
w,h = f.wrapOn(canv,availWidth,0xfffffff)
if dims is not None: dims.append((w,h))
if cframe:
_addGeneratedContent(F,cframe)
if w<=_FUZZ or h<=_FUZZ: continue
W = max(W,min(w,availWidth) if fakeWidth else w)
H += h
if not atTop:
h = f.getSpaceBefore()
if mergeSpace:
if getattr(f,'_SPACETRANSFER',False):
h = pS
h = max(h-pS,0)
H += h
else:
if obj is not None: obj._spaceBefore = f.getSpaceBefore()
atTop = 0
s = f.getSpaceAfter()
if getattr(f,'_SPACETRANSFER',False):
s = pS
pS = s
H += pS
if obj is not None: obj._spaceAfter = pS
return W, H-pS
finally:
if cframe:
doct.frame = doct_frame
def _flowableSublist(V):
"if it isn't a list or tuple, wrap it in a list"
if not isinstance(V,(list,tuple)): V = V is not None and [V] or []
from reportlab.platypus.doctemplate import LCActionFlowable
assert not [x for x in V if isinstance(x,LCActionFlowable)],'LCActionFlowables not allowed in sublists'
return V
class _ContainerSpace: #Abstract some common container like behaviour
def getSpaceBefore(self,content=None):
for c in (self._content if content is None else content):
if not hasattr(c,'frameAction'):
return c.getSpaceBefore()
return 0
def getSpaceAfter(self,content=None):
for c in reversed(self._content if content is None else content):
if not hasattr(c,'frameAction'):
return c.getSpaceAfter()
return 0
class KeepTogether(_ContainerSpace,Flowable):
splitAtTop = False
def __init__(self,flowables,maxHeight=None):
if not hasattr(KeepTogether,'NullActionFlowable'):
#cache these on the class
from reportlab.platypus.doctemplate import NullActionFlowable
from reportlab.platypus.doctemplate import FrameBreak
from reportlab.lib.utils import annotateException
KeepTogether.NullActionFlowable = NullActionFlowable
KeepTogether.FrameBreak = FrameBreak
KeepTogether.annotateException = annotateException
if not flowables:
flowables = [self.NullActionFlowable()]
self._content = _flowableSublist(flowables)
self._maxHeight = maxHeight
def __repr__(self):
f = self._content
L = list(map(repr,f))
L = "\n"+"\n".join(L)
L = L.replace("\n", "\n ")
return "%s(%s,maxHeight=%s)" % (self.__class__.__name__,L,self._maxHeight)
def wrap(self, aW, aH):
dims = []
try:
W,H = _listWrapOn(self._content,aW,self.canv,dims=dims)
except:
self.annotateException('\nraised by class %s(%s)@0x%8.8x wrap\n' % (self.__class__.__name__,self.__class__.__module__,id(self)))
self._H = H
self._H0 = dims and dims[0][1] or 0
self._wrapInfo = aW,aH
return W, 0xffffff # force a split
def split(self, aW, aH):
if getattr(self,'_wrapInfo',None)!=(aW,aH): self.wrap(aW,aH)
S = self._content[:]
cf = atTop = getattr(self,'_frame',None)
if cf:
atTop = getattr(cf,'_atTop',None)
cAW = cf._width
cAH = cf._height
C0 = self._H>aH and (not self._maxHeight or aH>self._maxHeight)
C1 = (self._H0>aH) or C0 and atTop
if C0 or C1:
fb = False
panf = self._doctemplateAttr('_peekNextFrame')
if cf and panf:
nf = panf()
nAW = nf._width
nAH = nf._height
if C0 and not (self.splitAtTop and atTop):
fb = not (atTop and cf and nf and cAW>=nAW and cAH>=nAH)
elif nf and nAW>=cf._width and nAH>=self._H:
fb = True
S.insert(0,(self.FrameBreak if fb else self.NullActionFlowable)())
return S
def identity(self, maxLen=None):
msg = "<%s at %s%s> containing :%s" % (self.__class__.__name__,hex(id(self)),self._frameName(),"\n".join([f.identity() for f in self._content]))
if maxLen:
return msg[0:maxLen]
else:
return msg
class KeepTogetherSplitAtTop(KeepTogether):
'''
Same as KeepTogether, but it will split content immediately if it cannot
fit at the top of a frame.
'''
splitAtTop = True
class Macro(Flowable):
"""This is not actually drawn (i.e. it has zero height)
but is executed when it would fit in the frame. Allows direct
access to the canvas through the object 'canvas'"""
def __init__(self, command):
self.command = command
def __repr__(self):
return "Macro(%s)" % repr(self.command)
def wrap(self, availWidth, availHeight):
return (0,0)
def draw(self):
rl_safe_exec(self.command, g=None, l={'canvas':self.canv})
def _nullCallable(*args,**kwds):
pass
class CallerMacro(Flowable):
'''
like Macro, but with callable command(s)
drawCallable(self)
wrapCallable(self,aW,aH)
'''
def __init__(self, drawCallable=None, wrapCallable=None):
self._drawCallable = drawCallable or _nullCallable
self._wrapCallable = wrapCallable or _nullCallable
def __repr__(self):
return "CallerMacro(%r,%r)" % (self._drawCallable,self._wrapCallable)
def wrap(self, aW, aH):
self._wrapCallable(self,aW,aH)
return (0,0)
def draw(self):
self._drawCallable(self)
class ParagraphAndImage(Flowable):
'''combine a Paragraph and an Image'''
def __init__(self,P,I,xpad=3,ypad=3,side='right'):
self.P = P
self.I = I
self.xpad = xpad
self.ypad = ypad
self._side = side
def getSpaceBefore(self):
return max(self.P.getSpaceBefore(),self.I.getSpaceBefore())
def getSpaceAfter(self):
return max(self.P.getSpaceAfter(),self.I.getSpaceAfter())
def wrap(self,availWidth,availHeight):
wI, hI = self.I.wrap(availWidth,availHeight)
self.wI = wI
self.hI = hI
# work out widths array for breaking
self.width = availWidth
P = self.P
style = P.style
xpad = self.xpad
ypad = self.ypad
leading = style.leading
leftIndent = style.leftIndent
later_widths = availWidth - leftIndent - style.rightIndent
intermediate_widths = later_widths - xpad - wI
first_line_width = intermediate_widths - style.firstLineIndent
P.width = 0
nIW = int((hI+ypad)/(leading*1.0))
P.blPara = P.breakLines([first_line_width] + nIW*[intermediate_widths]+[later_widths])
if self._side=='left':
self._offsets = [wI+xpad]*(1+nIW)+[0]
P.height = len(P.blPara.lines)*leading
self.height = max(hI,P.height)
return (self.width, self.height)
def split(self,availWidth, availHeight):
P, wI, hI, ypad = self.P, self.wI, self.hI, self.ypad
if hI+ypad>availHeight or len(P.frags)<=0: return []
S = P.split(availWidth,availHeight)
if not S: return S
P = self.P = S[0]
del S[0]
style = P.style
P.height = len(self.P.blPara.lines)*style.leading
self.height = max(hI,P.height)
return [self]+S
def draw(self):
canv = self.canv
if self._side=='left':
self.I.drawOn(canv,0,self.height-self.hI-self.ypad)
self.P._offsets = self._offsets
try:
self.P.drawOn(canv,0,0)
finally:
del self.P._offsets
else:
self.I.drawOn(canv,self.width-self.wI-self.xpad,self.height-self.hI-self.ypad)
self.P.drawOn(canv,0,0)
class FailOnWrap(NullDraw):
def wrap(self, availWidth, availHeight):
raise ValueError("FailOnWrap flowable wrapped and failing as ordered!")
class FailOnDraw(Flowable):
def wrap(self, availWidth, availHeight):
return 0,0
def draw(self):
raise ValueError("FailOnDraw flowable drawn, and failing as ordered!")
class HRFlowable(Flowable):
'''Like the hr tag'''
def __init__(self,
width="80%",
thickness=1,
lineCap='round',
color=lightgrey,
spaceBefore=1, spaceAfter=1,
hAlign='CENTER', vAlign='BOTTOM',
dash=None):
Flowable.__init__(self)
self.width = width
self.lineWidth = thickness
self.lineCap=lineCap
self.spaceBefore = spaceBefore
self.spaceAfter = spaceAfter
self.color = color
self.hAlign = hAlign
self.vAlign = vAlign
self.dash = dash
def __repr__(self):
return "HRFlowable(width=%s, height=%s)" % (self.width, self.height)
def wrap(self, availWidth, availHeight):
w = self.width
if isinstance(w,strTypes):
w = w.strip()
if w.endswith('%'): w = availWidth*float(w[:-1])*0.01
else: w = float(w)
w = min(w,availWidth)
self._width = w
return w, self.lineWidth
def draw(self):
canv = self.canv
canv.saveState()
canv.setLineWidth(self.lineWidth)
canv.setLineCap({'butt':0,'round':1, 'square': 2}[self.lineCap.lower()])
canv.setStrokeColor(self.color)
if self.dash: canv.setDash(self.dash)
canv.line(0, 0, self._width, self.height)
canv.restoreState()
class _PTOInfo:
def __init__(self,trailer,header):
self.trailer = _flowableSublist(trailer)
self.header = _flowableSublist(header)
def cdeepcopy(obj):
if hasattr(obj,'deepcopy'):
return obj.deepcopy()
else:
return deepcopy(obj)
class _Container(_ContainerSpace): #Abstract some common container like behaviour
def drawOn(self, canv, x, y, _sW=0, scale=1.0, content=None, aW=None):
'''we simulate being added to a frame'''
from reportlab.platypus.doctemplate import ActionFlowable, Indenter
x0 = x
y0 = y
pS = 0
if aW is None: aW = self.width
aW *= scale
if content is None:
content = self._content
x = self._hAlignAdjust(x,_sW*scale)
y += self.height*scale
yt = y
frame = getattr(self,'_frame',None)
for c in content:
if not ignoreContainerActions and isinstance(c,ActionFlowable):
c.apply(canv._doctemplate)
continue
if isinstance(c,Indenter):
x += c.left*scale
aW -= (c.left+c.right)*scale
continue
w, h = c.wrapOn(canv,aW,0xfffffff)
if (w<_FUZZ or h<_FUZZ) and not getattr(c,'_ZEROSIZE',None): continue
if yt!=y:
s = c.getSpaceBefore()
if not getattr(c,'_SPACETRANSFER',False):
h += max(s-pS,0)
y -= h
s = c.getSpaceAfter()
if getattr(c,'_SPACETRANSFER',False):
s = pS
pS = s
fbg = getattr(frame,'_frameBGs',None)
if fbg and fbg[-1].active:
bg = fbg[-1]
fbgl = bg.left
fbgr = bg.right
bgm = bg.start
fbw = scale*(frame._width-fbgl-fbgr)
fbx = x0+scale*(fbgl-frame._leftPadding)
fbh = y + h + pS
fby = max(y0,y-pS)
fbh = max(0,fbh-fby)
bg.render(canv,frame,fbx,fby,fbw,fbh)
c._frame = frame
c.drawOn(canv,x,y,_sW=aW-w)
if c is not content[-1] and not getattr(c,'_SPACETRANSFER',None):
y -= pS
del c._frame
def copyContent(self,content=None):
C = [].append
for c in (content or self._content):
C(cdeepcopy(c))
self._content = C.__self__
class PTOContainer(_Container,Flowable):
'''PTOContainer(contentList,trailerList,headerList)
A container for flowables decorated with trailer & header lists.
If the split operation would be called then the trailer and header
lists are injected before and after the split. This allows specialist
"please turn over" and "continued from previous" like behaviours.'''
def __init__(self,content,trailer=None,header=None):
I = _PTOInfo(trailer,header)
self._content = C = []
for _ in _flowableSublist(content):
if isinstance(_,PTOContainer):
C.extend(_._content)
else:
C.append(_)
if not hasattr(_,'_ptoinfo'): _._ptoinfo = I
def wrap(self,availWidth,availHeight):
self.width, self.height = _listWrapOn(self._content,availWidth,self.canv)
return self.width,self.height
def split(self, availWidth, availHeight):
from reportlab.platypus.doctemplate import Indenter
if availHeight<0: return []
canv = self.canv
C = self._content
x = i = H = pS = hx = 0
n = len(C)
I2W = {}
dLeft = dRight = 0
for x in xrange(n):
c = C[x]
I = c._ptoinfo
if I not in I2W.keys():
T = I.trailer
Hdr = I.header
tW, tH = _listWrapOn(T, availWidth, self.canv)
if len(T): #trailer may have no content
tSB = T[0].getSpaceBefore()
else:
tSB = 0
I2W[I] = T,tW,tH,tSB
else:
T,tW,tH,tSB = I2W[I]
_, h = c.wrapOn(canv,availWidth,0xfffffff)
if isinstance(c,Indenter):
dw = c.left+c.right
dLeft += c.left
dRight += c.right
availWidth -= dw
pS = 0
hx = 0
else:
if x:
hx = max(c.getSpaceBefore()-pS,0)
h += hx
pS = c.getSpaceAfter()
H += h+pS
tHS = tH+max(tSB,pS)
if H+tHS>=availHeight-_FUZZ: break
i += 1
#first retract last thing we tried
H -= (h+pS)
#attempt a sub split on the last one we have
aH = (availHeight-H-tHS-hx)*0.99999
if aH>=0.05*availHeight:
SS = c.splitOn(canv,availWidth,aH)
else:
SS = []
if abs(dLeft)+abs(dRight)>1e-8:
R1I = [Indenter(-dLeft,-dRight)]
R2I = [Indenter(dLeft,dRight)]
else:
R1I = R2I = []
if not SS:
j = i
while i>1 and C[i-1].getKeepWithNext():
i -= 1
C[i].keepWithNext = 0
if i==1 and C[0].getKeepWithNext():
#robin's black sheep
i = j
C[0].keepWithNext = 0
F = [UseUpSpace()]
if len(SS)>1:
R1 = C[:i]+SS[:1]+R1I+T+F
R2 = Hdr+R2I+SS[1:]+C[i+1:]
elif not i:
return []
else:
R1 = C[:i]+R1I+T+F
R2 = Hdr+R2I+C[i:]
T = R1 + [PTOContainer(R2,[copy(x) for x in I.trailer],[copy(x) for x in I.header])]
return T
#utility functions used by KeepInFrame
def _hmodel(s0,s1,h0,h1):
# calculate the parameters in the model
# h = a/s**2 + b/s
a11 = 1./s0**2
a12 = 1./s0
a21 = 1./s1**2
a22 = 1./s1
det = a11*a22-a12*a21
b11 = a22/det
b12 = -a12/det
b21 = -a21/det
b22 = a11/det
a = b11*h0+b12*h1
b = b21*h0+b22*h1
return a,b
def _qsolve(h,ab):
'''solve the model v = a/s**2 + b/s for an s which gives us v==h'''
a,b = ab
if abs(a)<=_FUZZ:
return b/h
t = 0.5*b/a
from math import sqrt
f = -h/a
r = t*t-f
if r<0: return None
r = sqrt(r)
if t>=0:
s1 = -t - r
else:
s1 = -t + r
s2 = f/s1
return max(1./s1, 1./s2)
class KeepInFrame(_Container,Flowable):
def __init__(self, maxWidth, maxHeight, content=[], mergeSpace=1, mode='shrink', name='',hAlign='LEFT',vAlign='BOTTOM', fakeWidth=None):
'''mode describes the action to take when overflowing
error raise an error in the normal way
continue ignore ie just draw it and report maxWidth, maxHeight
shrink shrinkToFit
truncate fit as much as possible
set fakeWidth to False to make _listWrapOn do the 'right' thing
'''
self.name = name
self.maxWidth = maxWidth
self.maxHeight = maxHeight
self.mode = mode
assert mode in ('error','overflow','shrink','truncate'), '%s invalid mode value %s' % (self.identity(),mode)
assert maxHeight>=0, '%s invalid maxHeight value %s' % (self.identity(),maxHeight)
if mergeSpace is None: mergeSpace = overlapAttachedSpace
self.mergespace = mergeSpace
self._content = content or []
self.vAlign = vAlign
self.hAlign = hAlign
self.fakeWidth = fakeWidth
def _getAvailableWidth(self):
return self.maxWidth - self._leftExtraIndent - self._rightExtraIndent
def identity(self, maxLen=None):
return "<%s at %s%s%s> size=%sx%s" % (self.__class__.__name__, hex(id(self)), self._frameName(),
getattr(self,'name','') and (' name="%s"'% getattr(self,'name','')) or '',
getattr(self,'maxWidth','') and (' maxWidth=%s'%fp_str(getattr(self,'maxWidth',0))) or '',
getattr(self,'maxHeight','')and (' maxHeight=%s' % fp_str(getattr(self,'maxHeight')))or '')
def wrap(self,availWidth,availHeight):
from reportlab.platypus.doctemplate import LayoutError
mode = self.mode
maxWidth = float(min(self.maxWidth or availWidth,availWidth))
maxHeight = float(min(self.maxHeight or availHeight,availHeight))
fakeWidth = self.fakeWidth
W, H = _listWrapOn(self._content,maxWidth,self.canv, fakeWidth=fakeWidth)
if (mode=='error' and (W>maxWidth+_FUZZ or H>maxHeight+_FUZZ)):
ident = 'content %sx%s too large for %s' % (W,H,self.identity(30))
#leave to keep apart from the raise
raise LayoutError(ident)
elif W<=maxWidth+_FUZZ and H<=maxHeight+_FUZZ:
self.width = W-_FUZZ #we take what we get
self.height = H-_FUZZ
elif mode in ('overflow','truncate'): #we lie
self.width = min(maxWidth,W)-_FUZZ
self.height = min(maxHeight,H)-_FUZZ
else:
def func(x):
x = float(x)
W, H = _listWrapOn(self._content,x*maxWidth,self.canv, fakeWidth=fakeWidth)
W /= x
H /= x
return W, H
W0 = W
H0 = H
s0 = 1
if W>maxWidth+_FUZZ:
#squeeze out the excess width and or Height
s1 = W/maxWidth #linear model
W, H = func(s1)
if H<=maxHeight+_FUZZ:
self.width = W-_FUZZ
self.height = H-_FUZZ
self._scale = s1
return W,H
s0 = s1
H0 = H
W0 = W
s1 = H/maxHeight
W, H = func(s1)
self.width = W-_FUZZ
self.height = H-_FUZZ
self._scale = s1
if H<min(0.95*maxHeight,maxHeight-10) or H>=maxHeight+_FUZZ:
#the standard case W should be OK, H is short we want
#to find the smallest s with H<=maxHeight
H1 = H
for f in 0, 0.01, 0.05, 0.10, 0.15:
#apply the quadratic model
s = _qsolve(maxHeight*(1-f),_hmodel(s0,s1,H0,H1))
W, H = func(s)
if H<=maxHeight+_FUZZ and W<=maxWidth+_FUZZ:
self.width = W-_FUZZ
self.height = H-_FUZZ
self._scale = s
break
return self.width, self.height
def drawOn(self, canv, x, y, _sW=0):
scale = getattr(self,'_scale',1.0)
truncate = self.mode=='truncate'
ss = scale!=1.0 or truncate
if ss:
canv.saveState()
if truncate:
p = canv.beginPath()
p.rect(x, y, self.width,self.height)
canv.clipPath(p,stroke=0)
else:
canv.translate(x,y)
x=y=0
canv.scale(1.0/scale, 1.0/scale)
_Container.drawOn(self, canv, x, y, _sW=_sW, scale=scale)
if ss: canv.restoreState()
class _FindSplitterMixin:
def _findSplit(self,canv,availWidth,availHeight,mergeSpace=1,obj=None,content=None,paraFix=True):
'''return max width, required height for a list of flowables F'''
W = 0
H = 0
pS = sB = 0
atTop = 1
F = self._getContent(content)
for i,f in enumerate(F):
if hasattr(f,'frameAction'):
from reportlab.platypus.doctemplate import Indenter
if isinstance(f,Indenter):
availWidth -= f.left+f.right
continue
w,h = f.wrapOn(canv,availWidth,0xfffffff)
if w<=_FUZZ or h<=_FUZZ: continue
W = max(W,w)
if not atTop:
s = f.getSpaceBefore()
if mergeSpace: s = max(s-pS,0)
H += s
else:
if obj is not None: obj._spaceBefore = f.getSpaceBefore()
atTop = 0
if H>=availHeight or w>availWidth:
return W, availHeight, F[:i],F[i:]
H += h
if H>availHeight:
aH = availHeight-(H-h)
if paraFix:
from reportlab.platypus.paragraph import Paragraph
if isinstance(f,(Paragraph,Preformatted)):
leading = f.style.leading
nH = leading*int(aH/float(leading))+_FUZZ
if nH<aH: nH += leading
availHeight += nH-aH
aH = nH
S = cdeepcopy(f).splitOn(canv,availWidth,aH)
if not S:
return W, availHeight, F[:i],F[i:]
else:
return W,availHeight,F[:i]+S[:1],S[1:]+F[i+1:]
pS = f.getSpaceAfter()
H += pS
if obj is not None: obj._spaceAfter = pS
return W, H-pS, F, []
def _getContent(self,content=None):
F = []
C = content if content is not None else self._content
for f in C:
if isinstance(f,ListFlowable):
F.extend(self._getContent(f._content))
else:
F.append(f)
return F
class ImageAndFlowables(_Container,_FindSplitterMixin,Flowable):
'''combine a list of flowables and an Image'''
def __init__(self,I,F,imageLeftPadding=0,imageRightPadding=3,imageTopPadding=0,imageBottomPadding=3,
imageSide='right', imageHref=None):
self._content = _flowableSublist(F)
self._I = I
self._irpad = imageRightPadding
self._ilpad = imageLeftPadding
self._ibpad = imageBottomPadding
self._itpad = imageTopPadding
self._side = imageSide
self.imageHref = imageHref
def deepcopy(self):
c = copy(self) #shallow
self._reset()
c.copyContent() #partially deep?
return c
def getSpaceAfter(self):
if hasattr(self,'_C1'):
C = self._C1
elif hasattr(self,'_C0'):
C = self._C0
else:
C = self._content
return _Container.getSpaceAfter(self,C)
def getSpaceBefore(self):
return max(self._I.getSpaceBefore(),_Container.getSpaceBefore(self))
def _reset(self):
for a in ('_wrapArgs','_C0','_C1'):
try:
delattr(self,a)
except:
pass
def wrap(self,availWidth,availHeight):
canv = self.canv
I = self._I
if hasattr(self,'_wrapArgs'):
if self._wrapArgs==(availWidth,availHeight) and getattr(I,'_oldDrawSize',None) is None:
return self.width,self.height
self._reset()
I._unRestrictSize()
self._wrapArgs = availWidth, availHeight
I.wrap(availWidth,availHeight)
wI, hI = I._restrictSize(availWidth,availHeight)
self._wI = wI
self._hI = hI
ilpad = self._ilpad
irpad = self._irpad
ibpad = self._ibpad
itpad = self._itpad
self._iW = iW = availWidth - irpad - wI - ilpad
aH = itpad + hI + ibpad
if iW>_FUZZ:
W,H0,self._C0,self._C1 = self._findSplit(canv,iW,aH)
else:
W = availWidth
H0 = 0
if W>iW+_FUZZ:
self._C0 = []
self._C1 = self._content
aH = self._aH = max(aH,H0)
self.width = availWidth
if not self._C1:
self.height = aH
else:
W1,H1 = _listWrapOn(self._C1,availWidth,canv)
self.height = aH+H1
return self.width, self.height
def split(self,availWidth, availHeight):
if hasattr(self,'_wrapArgs'):
I = self._I
if self._wrapArgs!=(availWidth,availHeight) or getattr(I,'_oldDrawSize',None) is not None:
self._reset()
I._unRestrictSize()
W,H=self.wrap(availWidth,availHeight)
if self._aH>availHeight: return []
C1 = self._C1
if C1:
S = C1[0].split(availWidth,availHeight-self._aH)
if not S:
_C1 = []
else:
_C1 = [S[0]]
C1 = S[1:]+C1[1:]
else:
_C1 = []
return [ImageAndFlowables(
self._I,
self._C0+_C1,
imageLeftPadding=self._ilpad,
imageRightPadding=self._irpad,
imageTopPadding=self._itpad,
imageBottomPadding=self._ibpad,
imageSide=self._side, imageHref=self.imageHref)
]+C1
def drawOn(self, canv, x, y, _sW=0):
if self._side=='left':
Ix = x + self._ilpad
Fx = Ix+ self._irpad + self._wI
else:
Ix = x + self.width-self._wI-self._irpad
Fx = x
self._I.drawOn(canv,Ix,y+self.height-self._itpad-self._hI)
if self.imageHref:
canv.linkURL(self.imageHref, (Ix, y+self.height-self._itpad-self._hI, Ix + self._wI, y+self.height), relative=1)
if self._C0:
_Container.drawOn(self, canv, Fx, y, content=self._C0, aW=self._iW)
if self._C1:
aW, aH = self._wrapArgs
_Container.drawOn(self, canv, x, y-self._aH,content=self._C1, aW=aW)
class _AbsRect(NullDraw):
_ZEROSIZE=1
_SPACETRANSFER = True
def __init__(self,x,y,width,height,strokeWidth=0,strokeColor=None,fillColor=None,strokeDashArray=None):
self._x = x
self._y = y
self._width = width
self._height = height
self._strokeColor = strokeColor
self._fillColor = fillColor
self._strokeWidth = strokeWidth
self._strokeDashArray = strokeDashArray
def wrap(self, availWidth, availHeight):
return 0,0
def drawOn(self, canv, x, y, _sW=0):
if self._width>_FUZZ and self._height>_FUZZ:
st = self._strokeColor and self._strokeWidth is not None and self._strokeWidth>=0
if st or self._fillColor:
canv.saveState()
if st:
canv.setStrokeColor(self._strokeColor)
canv.setLineWidth(self._strokeWidth)
if self._fillColor:
canv.setFillColor(self._fillColor)
canv.rect(self._x,self._y,self._width,self._height,stroke=1 if st else 0, fill=1 if self._fillColor else 0)
canv.restoreState()
class _ExtendBG(NullDraw):
_ZEROSIZE=1
_SPACETRANSFER = True
def __init__(self,y,height,bg,frame):
self._y = y
self._height = height
self._bg = bg
def wrap(self, availWidth, availHeight):
return 0,0
def frameAction(self, frame):
bg = self._bg
fby = self._y
fbh = self._height
fbgl = bg.left
fbw = frame._width - fbgl - bg.right
fbx = frame._x1 - fbgl
canv = self.canv
pn = canv.getPageNumber()
bg.render(canv,frame,fbx,fby,fbw,fbh)
class _AbsLine(NullDraw):
_ZEROSIZE=1
_SPACETRANSFER = True
def __init__(self,x,y,x1,y1,strokeWidth=0,strokeColor=None,strokeDashArray=None):
self._x = x
self._y = y
self._x1 = x1
self._y1 = y1
self._strokeColor = strokeColor
self._strokeWidth = strokeWidth
self._strokeDashArray = strokeDashArray
def wrap(self, availWidth, availHeight):
return 0,0
def drawOn(self, canv, x, y, _sW=0):
if self._strokeColor and self._strokeWidth is not None and self._strokeWidth>=0:
canv.saveState()
canv.setStrokeColor(self._strokeColor)
canv.setLineWidth(self._strokeWidth)
canv.line(self._x,self._y,self._x1,self._y1)
canv.restoreState()
class BalancedColumns(_FindSplitterMixin,NullDraw):
'''combine a list of flowables and an Image'''
def __init__(self, F, nCols=2, needed=72, spaceBefore=0, spaceAfter=0, showBoundary=None,
leftPadding=None, innerPadding=None, rightPadding=None, topPadding=None, bottomPadding=None,
name='', endSlack=0.1,
boxStrokeColor=None,
boxStrokeWidth=0,
boxFillColor=None,
boxMargin=None,
vLinesStrokeColor=None,
vLinesStrokeWidth=None,
):
self.name = name or 'BalancedColumns-%d' % id(self)
if nCols <2:
raise ValueError('nCols should be at least 2 not %r in %s' % (nCols,self.identitity()))
self._content = _flowableSublist(F)
self._nCols = nCols
self.spaceAfter = spaceAfter
self._leftPadding = leftPadding
self._innerPadding = innerPadding
self._rightPadding = rightPadding
self._topPadding = topPadding
self._bottomPadding = bottomPadding
self.spaceBefore = spaceBefore
self._needed = needed - _FUZZ
self.showBoundary = showBoundary
self.endSlack = endSlack #what we might allow as a lastcolumn overrun
self._boxStrokeColor = boxStrokeColor
self._boxStrokeWidth = boxStrokeWidth
self._boxFillColor = boxFillColor
self._boxMargin = boxMargin
self._vLinesStrokeColor = vLinesStrokeColor
self._vLinesStrokeWidth = vLinesStrokeWidth
def identity(self, maxLen=None):
return "<%s nCols=%r at %s%s%s>" % (self.__class__.__name__, self._nCols, hex(id(self)), self._frameName(),
getattr(self,'name','') and (' name="%s"'% getattr(self,'name','')) or '',
)
def getSpaceAfter(self):
return self.spaceAfter
def getSpaceBefore(self):
return self.spaceBefore
def _generated_content(self,aW,aH):
G = []
frame = self._frame
from reportlab.platypus.doctemplate import CurrentFrameFlowable,LayoutError, ActionFlowable, Indenter
from reportlab.platypus.frames import Frame
from reportlab.platypus.doctemplate import FrameBreak
lpad = frame._leftPadding if self._leftPadding is None else self._leftPadding
rpad = frame._rightPadding if self._rightPadding is None else self._rightPadding
tpad = frame._topPadding if self._topPadding is None else self._topPadding
bpad = frame._bottomPadding if self._bottomPadding is None else self._bottomPadding
leftExtraIndent = frame._leftExtraIndent
rightExtraIndent = frame._rightExtraIndent
gap = max(lpad,rpad) if self._innerPadding is None else self._innerPadding
hgap = gap*0.5
canv = self.canv
nCols = self._nCols
cw = (aW - gap*(nCols-1) - lpad - rpad)/float(nCols)
aH0 = aH
aH -= tpad + bpad
W,H0,_C0,C2 = self._findSplit(canv,cw,nCols*aH,paraFix=False)
if not _C0:
raise ValueError(
"%s cannot make initial split aW=%r aH=%r ie cw=%r ah=%r\ncontent=%s" % (
self.identity(),aW,aH,cw,nCols*aH,
[f.__class__.__name__ for f in self._content],
))
_fres = {}
def splitFunc(ah,endSlack=0):
if ah not in _fres:
c = []
w = 0
h = 0
cn = None
icheck = nCols-2 if endSlack else -1
for i in xrange(nCols):
wi, hi, c0, c1 = self._findSplit(canv,cw,ah,content=cn,paraFix=False)
w = max(w,wi)
h = max(h,hi)
c.append(c0)
if i==icheck:
wc, hc, cc0, cc1 = self._findSplit(canv,cw,2*ah,content=c1,paraFix=False)
if hc<=(1+endSlack)*ah:
c.append(c1)
h = ah-1e-6
cn = []
break
cn = c1
_fres[ah] = ah+100000*int(cn!=[]),cn==[],(w,h,c,cn)
return _fres[ah][2]
endSlack = 0
if C2:
H = aH
else:
#we are short so use H0 to figure out what to use
import math
def func(ah):
splitFunc(ah)
return _fres[ah][0]
def gss(f, a, b, tol=1, gr=(math.sqrt(5) + 1) / 2):
c = b - (b - a) / gr
d = a + (b - a) / gr
while abs(a - b) > tol:
if f(c) < f(d):
b = d
else:
a = c
# we recompute both c and d here to avoid loss of precision which may lead to incorrect results or infinite loop
c = b - (b - a) / gr
d = a + (b - a) / gr
F = [(x,tf,v) for x,tf,v in _fres.values() if tf]
if F:
F.sort()
return F[0][2]
return None
H = min(int(H0/float(nCols)+self.spaceAfter*0.4),aH)
splitFunc(H)
if not _fres[H][1]:
H = gss(func,H,aH)
if H:
W, H0, _C0, C2 = H
H = H0
endSlack = False
else:
H = aH
endSlack = self.endSlack
else:
H1 = H0/float(nCols)
splitFunc(H1)
if not _fres[H1][1]:
H = gss(func,H,aH)
if H:
W, H0, _C0, C2 = H
H = H0
endSlack = False
else:
H = aH
endSlack = self.endSlack
assert not C2, "unexpected non-empty C2"
W1, H1, C, C1 = splitFunc(H, endSlack)
_fres.clear()
if C[0]==[] and C[1]==[] and C1:
#no split situation
C, C1 = [C1,C[1]], C[0]
x1 = frame._x1
y1 = frame._y1
fw = frame._width
ftop = y1+bpad+tpad+aH
fh = H1 + bpad + tpad
y2 = ftop - fh
dx = aW / float(nCols)
if leftExtraIndent or rightExtraIndent:
indenter0 = Indenter(-leftExtraIndent,-rightExtraIndent)
indenter1 = Indenter(leftExtraIndent,rightExtraIndent)
else:
indenter0 = indenter1 = None
showBoundary=self.showBoundary if self.showBoundary is not None else frame.showBoundary
obx = x1+leftExtraIndent+frame._leftPadding
F = [Frame(obx+i*dx,y2,dx,fh,
leftPadding=lpad if not i else hgap, bottomPadding=bpad,
rightPadding=rpad if i==nCols-1 else hgap, topPadding=tpad,
id='%s-%d' %(self.name,i),
showBoundary=showBoundary,
overlapAttachedSpace=frame._oASpace,
_debug=frame._debug) for i in xrange(nCols)]
#we are going to modify the current template
T=self._doctemplateAttr('pageTemplate')
if T is None:
raise LayoutError('%s used in non-doctemplate environment' % self.identity())
BGs = getattr(frame,'_frameBGs',None)
xbg = bg = BGs[-1] if BGs else None
class TAction(ActionFlowable):
'''a special Action flowable that sets stuff on the doc template T'''
def __init__(self, bgs=[],F=[],f=None):
Flowable.__init__(self)
self.bgs = bgs
self.F = F
self.f = f
def apply(self,doc,T=T):
T.frames = self.F
frame._frameBGs = self.bgs
doc.handle_currentFrame(self.f.id)
frame._frameBGs = self.bgs
if bg:
#G.append(Spacer(1e-5,1e-5))
#G[-1].__id__ = 'spacer0'
xbg = _ExtendBG(y2,fh,bg,frame)
G.append(xbg)
oldFrames = T.frames
G.append(TAction([],F,F[0]))
if indenter0: G.append(indenter0)
doBox = (self._boxStrokeColor and self._boxStrokeWidth and self._boxStrokeWidth>=0) or self._boxFillColor
doVLines = self._vLinesStrokeColor and self._vLinesStrokeWidth and self._vLinesStrokeWidth>=0
if doBox or doVLines:
obm = self._boxMargin
if not obm: obm = (0,0,0,0)
if len(obm)==1:
obmt = obml = obmr = obmb = obm[0]
elif len(obm)==2:
obmt = obmb = obm[0]
obml = obmr = obm[1]
elif len(obm)==3:
obmt = obm[0]
obml = obmr = obm[1]
obmb = obm[2]
elif len(obm)==4:
obmt = obm[0]
obmr = obm[1]
obmb = obm[2]
obml = obm[3]
else:
raise ValueError('Invalid value %s for boxMargin' % repr(obm))
obx1 = obx - obml
obx2 = F[-1]._x1+F[-1]._width + obmr
oby2 = y2-obmb
obh = fh+obmt+obmb
oby1 = oby2+obh
if doBox:
box = _AbsRect(obx1,oby2, obx2-obx1, obh,
fillColor=self._boxFillColor,
strokeColor=self._boxStrokeColor,
strokeWidth=self._boxStrokeWidth,
)
if doVLines:
vLines = []
for i in xrange(1,nCols):
vlx = 0.5*(F[i]._x1 + F[i-1]._x1+F[i-1]._width)
vLines.append(_AbsLine(vlx,oby2,vlx,oby1,strokeWidth=self._vLinesStrokeWidth,strokeColor=self._vLinesStrokeColor))
else:
oby1 = ftop
oby2 = y2
if doBox: G.append(box)
if doVLines: G.extend(vLines)
sa = self.getSpaceAfter()
for i in xrange(nCols):
Ci = C[i]
if Ci:
Ci = KeepInFrame(W1,H1,Ci,mode='shrink')
sa = max(sa,Ci.getSpaceAfter())
G.append(Ci)
if i!=nCols-1:
G.append(FrameBreak)
G.append(TAction(BGs,oldFrames,frame))
if xbg:
if C1: sa = 0
xbg._y = min(y2,oby2) - sa
xbg._height = max(ftop,oby1) - xbg._y
if indenter1: G.append(indenter1)
if C1:
G.append(
BalancedColumns(C1, nCols=nCols,
needed=self._needed, spaceBefore=self.spaceBefore, spaceAfter=self.spaceAfter,
showBoundary=self.showBoundary,
leftPadding=self._leftPadding,
innerPadding=self._innerPadding,
rightPadding=self._rightPadding,
topPadding=self._topPadding,
bottomPadding=self._bottomPadding,
name=self.name+'-1', endSlack=self.endSlack,
boxStrokeColor=self._boxStrokeColor,
boxStrokeWidth=self._boxStrokeWidth,
boxFillColor=self._boxFillColor,
boxMargin=self._boxMargin,
vLinesStrokeColor=self._vLinesStrokeColor,
vLinesStrokeWidth=self._vLinesStrokeWidth,
)
)
return fh, G
def wrap(self,aW,aH):
#here's where we mess with everything
if aH<self.spaceBefore+self._needed-_FUZZ:
#we are going straight to the nextTemplate with no attempt to modify the frames
G = [PageBreak(), self]
H1 = 0
else:
H1, G = self._generated_content(aW,aH)
self._frame.add_generated_content(*G)
return 0,min(H1,aH)
class AnchorFlowable(Spacer):
'''create a bookmark in the pdf'''
_ZEROSIZE=1
_SPACETRANSFER = True
def __init__(self,name):
Spacer.__init__(self,0,0)
self._name = name
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__,self._name)
def wrap(self,aW,aH):
return 0,0
def draw(self):
self.canv.bookmarkHorizontal(self._name,0,0)
class _FBGBag(ABag):
def matches(self,frame,canv):
fid = id(frame)
return ((isinstance(self.fid,list) and fid in self.fid or fid==self.fid)
and id(canv)==self.cid and self.pn==canv.getPageNumber())
def getDims(self,canv):
self._inst = canv._code[self.codePos].split()
return map(float,self._inst[1:5])
def setDims(self,canv,x,y,w,h):
self._inst[1:5] = [fp_str(x,y,w,h)]
canv._code[self.codePos] = ' '.join(self._inst)
def render(self,canv,frame,fbx,fby,fbw,fbh):
if abs(fbw)>_FUZZ and abs(fbh)>_FUZZ:
pn = canv.getPageNumber()
if self.fid==id(frame) and self.cid==id(canv) and self.pn==pn:
ox,oy,ow,oh = self.getDims(canv)
self.setDims(canv,ox,fby,ow,oh+oy-fby)
else:
canv.saveState()
fbgc = self.fillColor
if fbgc:
canv.setFillColor(fbgc)
sw = self.strokeWidth
sc = None if sw is None or sw<0 else self.strokeColor
if sc:
canv.setStrokeColor(sc)
canv.setLineWidth(sw)
da = self.strokeDashArray
if da:
canv.setDash(da)
self.fid = id(frame)
self.cid = id(canv)
self.pn = pn
self.codePos = len(canv._code)
canv.rect(fbx,fby,fbw,fbh,stroke=1 if sc else 0,fill=1 if fbgc else 0)
canv.restoreState()
class FrameBG(AnchorFlowable):
"""Start or stop coloring the frame background
left & right are distances from the edge of the frame to start stop colouring.
if start in ('frame','frame-permanent') then the background is filled from here to the bottom of the frame and immediately discarded
for the frame case.
"""
_ZEROSIZE=1
def __init__(self, color=None, left=0, right=0, start=True, strokeWidth=None, strokeColor=None, strokeDashArray=None):
Spacer.__init__(self,0,0)
self.start = start
if start:
from reportlab.platypus.doctemplate import _evalMeasurement
self.left = _evalMeasurement(left)
self.right = _evalMeasurement(right)
self.color = color
self.strokeWidth = strokeWidth
self.strokeColor = strokeColor
self.strokeDashArray = strokeDashArray
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__,', '.join(['%s=%r' % (i,getattr(self,i,None)) for i in 'start color left right'.split()]))
def draw(self):
frame = getattr(self,'_frame',None)
if frame is None: return
if self.start:
sc = self.strokeColor
sw = self.strokeWidth
sw = -1 if sw is None else sw
frame._frameBGs.append(
_FBGBag(left=self.left,
right=self.right,
fillColor=self.color,
start=self.start if self.start in ('frame','frame-permanent') else None,
strokeColor=self.strokeColor,
strokeWidth=self.strokeWidth,
strokeDashArray=self.strokeDashArray,
fid = 0,
cid = 0,
pn = -1,
codePos = None,
active=True,
))
elif frame._frameBGs:
frame._frameBGs.pop()
class FrameSplitter(NullDraw):
'''When encountered this flowable should either switch directly to nextTemplate
if remaining space in the current frame is less than gap+required or it should
temporarily modify the current template to have the frames from nextTemplate
that are listed in nextFrames and switch to the first of those frames.
'''
_ZEROSIZE=1
def __init__(self, nextTemplate, nextFrames=[], gap=10, required=72, adjustHeight=True):
self.nextTemplate = nextTemplate
self.nextFrames = nextFrames or []
self.gap = gap
self.required = required
self.adjustHeight = adjustHeight
def wrap(self,aW,aH):
frame = self._frame
from reportlab.platypus.doctemplate import NextPageTemplate,CurrentFrameFlowable,LayoutError
G=[NextPageTemplate(self.nextTemplate)]
if aH<self.gap+self.required-_FUZZ:
#we are going straight to the nextTemplate with no attempt to modify the frames
G.append(PageBreak())
else:
#we are going to modify the incoming templates
templates = self._doctemplateAttr('pageTemplates')
if templates is None:
raise LayoutError('%s called in non-doctemplate environment'%self.identity())
T=[t for t in templates if t.id==self.nextTemplate]
if not T:
raise LayoutError('%s.nextTemplate=%s not found' % (self.identity(),self.nextTemplate))
T=T[0]
F=[f for f in T.frames if f.id in self.nextFrames]
N=[f.id for f in F]
N=[f for f in self.nextFrames if f not in N]
if N:
raise LayoutError('%s frames=%r not found in pageTemplate(%s)\n%r has frames %r' % (self.identity(),N,T.id,T,[f.id for f in T.frames]))
T=self._doctemplateAttr('pageTemplate')
def unwrap(canv,doc,T=T,onPage=T.onPage,oldFrames=T.frames):
T.frames=oldFrames
T.onPage=onPage
onPage(canv,doc)
T.onPage=unwrap
h=aH-self.gap
for i,f in enumerate(F):
f=copy(f)
if self.adjustHeight: f.height=h
f._reset()
F[i]=f
T.frames=F
G.append(CurrentFrameFlowable(F[0].id))
frame.add_generated_content(*G)
return 0,0
from reportlab.lib.sequencer import _type2formatter
_bulletNames = dict(
bulletchar=u'\u2022', #usually a small circle
circle=u'\u25cf', #circle as high as the font
square=u'\u25a0',
disc=u'\u25cb',
diamond=u'\u25c6',
diamondwx=u'\u2756',
rarrowhead=u'\u27a4',
sparkle=u'\u2747',
squarelrs=u'\u274f',
blackstar=u'\u2605',
)
def _bulletFormat(value,type='1',format=None):
if type=='bullet':
s = _bulletNames.get(value,value)
else:
s = _type2formatter[type](int(value))
if format:
if isinstance(format,strTypes):
s = format % s
elif callable(format):
s = format(s)
else:
raise ValueError('unexpected BulletDrawer format %r' % format)
return s
class BulletDrawer:
def __init__(self,
value='0',
bulletAlign='left',
bulletType='1',
bulletColor='black',
bulletFontName='Helvetica',
bulletFontSize=12,
bulletOffsetY=0,
bulletDedent=0,
bulletDir='ltr',
bulletFormat=None,
):
self.value = value
self._bulletAlign = bulletAlign
self._bulletType = bulletType
self._bulletColor = bulletColor
self._bulletFontName = bulletFontName
self._bulletFontSize = bulletFontSize
self._bulletOffsetY = bulletOffsetY
self._bulletDedent = bulletDedent
self._bulletDir = bulletDir
self._bulletFormat = bulletFormat
def drawOn(self,indenter,canv,x,y,_sW=0):
value = self.value
if not value: return
canv.saveState()
canv.translate(x, y)
y = indenter.height-self._bulletFontSize+self._bulletOffsetY
if self._bulletDir=='rtl':
x = indenter.width - indenter._rightIndent + self._bulletDedent
else:
x = indenter._leftIndent - self._bulletDedent
canv.setFont(self._bulletFontName,self._bulletFontSize)
canv.setFillColor(self._bulletColor)
bulletAlign = self._bulletAlign
value = _bulletFormat(value,self._bulletType,self._bulletFormat)
if bulletAlign=='left':
canv.drawString(x,y,value)
elif bulletAlign=='right':
canv.drawRightString(x,y,value)
elif bulletAlign in ('center','centre'):
canv.drawCentredString(x,y,value)
elif bulletAlign.startswith('numeric') or bulletAlign.startswith('decimal'):
pc = bulletAlign[7:].strip() or '.'
canv.drawAlignedString(x,y,value,pc)
else:
raise ValueError('Invalid bulletAlign: %r' % bulletAlign)
canv.restoreState()
def _computeBulletWidth(b,value):
value = _bulletFormat(value,b._bulletType,b._bulletFormat)
return stringWidth(value,b._bulletFontName,b._bulletFontSize)
class DDIndenter(Flowable):
_IndenterAttrs = '_flowable _leftIndent _rightIndent width height'.split()
def __init__(self,flowable,leftIndent=0,rightIndent=0):
self._flowable = flowable
self._leftIndent = leftIndent
self._rightIndent = rightIndent
self.width = None
self.height = None
def split(self, aW, aH):
S = self._flowable.split(aW-self._leftIndent-self._rightIndent, aH)
return [
DDIndenter(s,
leftIndent=self._leftIndent,
rightIndent=self._rightIndent,
) for s in S
]
def drawOn(self, canv, x, y, _sW=0):
self._flowable.drawOn(canv,x+self._leftIndent,y,max(0,_sW-self._leftIndent-self._rightIndent))
def wrap(self, aW, aH):
w,h = self._flowable.wrap(aW-self._leftIndent-self._rightIndent, aH)
self.width = w+self._leftIndent+self._rightIndent
self.height = h
return self.width,h
def __getattr__(self,a):
if a in self._IndenterAttrs:
try:
return self.__dict__[a]
except KeyError:
if a not in ('spaceBefore','spaceAfter'):
raise AttributeError('%r has no attribute %s' % (self,a))
return getattr(self._flowable,a)
def __setattr__(self,a,v):
if a in self._IndenterAttrs:
self.__dict__[a] = v
else:
setattr(self._flowable,a,v)
def __delattr__(self,a):
if a in self._IndenterAttrs:
del self.__dict__[a]
else:
delattr(self._flowable,a)
def identity(self,maxLen=None):
return '%s containing %s' % (self.__class__.__name__,self._flowable.identity(maxLen))
class LIIndenter(DDIndenter):
_IndenterAttrs = '_flowable _bullet _leftIndent _rightIndent width height spaceBefore spaceAfter'.split()
def __init__(self,flowable,leftIndent=0,rightIndent=0,bullet=None, spaceBefore=None, spaceAfter=None):
self._flowable = flowable
self._bullet = bullet
self._leftIndent = leftIndent
self._rightIndent = rightIndent
self.width = None
self.height = None
if spaceBefore is not None:
self.spaceBefore = spaceBefore
if spaceAfter is not None:
self.spaceAfter = spaceAfter
def split(self, aW, aH):
S = self._flowable.split(aW-self._leftIndent-self._rightIndent, aH)
return [
LIIndenter(s,
leftIndent=self._leftIndent,
rightIndent=self._rightIndent,
bullet = (s is S[0] and self._bullet or None),
) for s in S
]
def drawOn(self, canv, x, y, _sW=0):
if self._bullet:
self._bullet.drawOn(self,canv,x,y,0)
self._flowable.drawOn(canv,x+self._leftIndent,y,max(0,_sW-self._leftIndent-self._rightIndent))
from reportlab.lib.styles import ListStyle
class ListItem:
def __init__(self,
flowables, #the initial flowables
style=None,
#leftIndent=18,
#rightIndent=0,
#spaceBefore=None,
#spaceAfter=None,
#bulletType='1',
#bulletColor='black',
#bulletFontName='Helvetica',
#bulletFontSize=12,
#bulletOffsetY=0,
#bulletDedent='auto',
#bulletDir='ltr',
#bulletFormat=None,
**kwds
):
if not isinstance(flowables,(list,tuple)):
flowables = (flowables,)
self._flowables = flowables
params = self._params = {}
if style:
if not isinstance(style,ListStyle):
raise ValueError('%s style argument (%r) not a ListStyle' % (self.__class__.__name__,style))
self._style = style
for k in ListStyle.defaults:
if k in kwds:
v = kwds.get(k)
elif style:
v = getattr(style,k)
else:
continue
params[k] = v
for k in ('value', 'spaceBefore','spaceAfter'):
v = kwds.get(k,getattr(style,k,None))
if v is not None:
params[k] = v
class _LIParams:
def __init__(self,flowable,params,value,first):
self.flowable = flowable
self.params = params
self.value = value
self.first= first
class ListFlowable(_Container,Flowable):
_numberStyles = '1aAiI'
def __init__(self,
flowables, #the initial flowables
start=None,
style=None,
#leftIndent=18,
#rightIndent=0,
#spaceBefore=None,
#spaceAfter=None,
#bulletType='1',
#bulletColor='black',
#bulletFontName='Helvetica',
#bulletFontSize=12,
#bulletOffsetY=0,
#bulletDedent='auto',
#bulletDir='ltr',
#bulletFormat=None,
**kwds
):
self._flowables = flowables
if style:
if not isinstance(style,ListStyle):
raise ValueError('%s style argument not a ListStyle' % self.__class__.__name__)
self.style = style
for k,v in ListStyle.defaults.items():
setattr(self,'_'+k,kwds.get(k,getattr(style,k,v)))
for k in ('spaceBefore','spaceAfter'):
v = kwds.get(k,getattr(style,k,None))
if v is not None:
setattr(self,k,v)
auto = False
if start is None:
start = getattr(self,'_start',None)
if start is None:
if self._bulletType=='bullet':
start = 'bulletchar'
auto = True
else:
start = self._bulletType
auto = True
if self._bulletType!='bullet':
if auto:
for v in start:
if v not in self._numberStyles:
raise ValueError('invalid start=%r or bullettype=%r' % (start,self._bulletType))
else:
for v in self._bulletType:
if v not in self._numberStyles:
raise ValueError('invalid bullettype=%r' % self._bulletType)
self._start = start
self._auto = auto or isinstance(start,(list,tuple))
self._list_content = None
self._dims = None
@property
def _content(self):
if self._list_content is None:
self._list_content = self._getContent()
del self._flowables
return self._list_content
def wrap(self,aW,aH):
if self._dims!=aW:
self.width, self.height = _listWrapOn(self._content,aW,self.canv)
self._dims = aW
return self.width,self.height
def split(self,aW,aH):
return self._content
def _flowablesIter(self):
for f in self._flowables:
if isinstance(f,(list,tuple)):
if f:
for i, z in enumerate(f):
yield i==0 and not isinstance(z,LIIndenter), z
elif isinstance(f,ListItem):
params = f._params
if not params:
#meerkat simples just a list like object
for i, z in enumerate(f._flowables):
if isinstance(z,LIIndenter):
raise ValueError('LIIndenter not allowed in ListItem')
yield i==0, z
else:
params = params.copy()
value = params.pop('value',None)
spaceBefore = params.pop('spaceBefore',None)
spaceAfter = params.pop('spaceAfter',None)
n = len(f._flowables) - 1
for i, z in enumerate(f._flowables):
P = params.copy()
if not i and spaceBefore is not None:
P['spaceBefore'] = spaceBefore
if i==n and spaceAfter is not None:
P['spaceAfter'] = spaceAfter
if i: value=None
yield 0, _LIParams(z,P,value,i==0)
else:
yield not isinstance(f,LIIndenter), f
def _makeLIIndenter(self,flowable, bullet, params=None):
if params:
leftIndent = params.get('leftIndent',self._leftIndent)
rightIndent = params.get('rightIndent',self._rightIndent)
spaceBefore = params.get('spaceBefore',None)
spaceAfter = params.get('spaceAfter',None)
return LIIndenter(flowable,leftIndent,rightIndent,bullet,spaceBefore=spaceBefore,spaceAfter=spaceAfter)
else:
return LIIndenter(flowable,self._leftIndent,self._rightIndent,bullet)
def _makeBullet(self,value,params=None):
if params is None:
def getp(a):
return getattr(self,'_'+a)
else:
style = getattr(params,'style',None)
def getp(a):
if a in params: return params[a]
if style and a in style.__dict__: return getattr(self,a)
return getattr(self,'_'+a)
return BulletDrawer(
value=value,
bulletAlign=getp('bulletAlign'),
bulletType=getp('bulletType'),
bulletColor=getp('bulletColor'),
bulletFontName=getp('bulletFontName'),
bulletFontSize=getp('bulletFontSize'),
bulletOffsetY=getp('bulletOffsetY'),
bulletDedent=getp('calcBulletDedent'),
bulletDir=getp('bulletDir'),
bulletFormat=getp('bulletFormat'),
)
def _getContent(self):
bt = self._bulletType
value = self._start
if isinstance(value,(list,tuple)):
values = value
value = values[0]
else:
values = [value]
autov = values[0]
inc = int(bt in '1aAiI')
if inc:
try:
value = int(value)
except:
value = 1
bd = self._bulletDedent
if bd=='auto':
align = self._bulletAlign
dir = self._bulletDir
if dir=='ltr' and align=='left':
bd = self._leftIndent
elif align=='right':
bd = self._rightIndent
else:
#we need to work out the maximum width of any of the labels
tvalue = value
maxW = 0
for d,f in self._flowablesIter():
if d:
maxW = max(maxW,_computeBulletWidth(self,tvalue))
if inc: tvalue += inc
elif isinstance(f,LIIndenter):
b = f._bullet
if b:
if b.bulletType==bt:
maxW = max(maxW,_computeBulletWidth(b,b.value))
tvalue = int(b.value)
else:
maxW = max(maxW,_computeBulletWidth(self,tvalue))
if inc: tvalue += inc
if dir=='ltr':
if align=='right':
bd = self._leftIndent - maxW
else:
bd = self._leftIndent - maxW*0.5
elif align=='left':
bd = self._rightIndent - maxW
else:
bd = self._rightIndent - maxW*0.5
self._calcBulletDedent = bd
S = []
aS = S.append
i=0
for d,f in self._flowablesIter():
if isinstance(f,ListFlowable):
fstart = f._start
if isinstance(fstart,(list,tuple)):
fstart = fstart[0]
if fstart in values:
#my kind of ListFlowable
if f._auto:
autov = values.index(autov)+1
f._start = values[autov:]+values[:autov]
autov = f._start[0]
if inc: f._bulletType = autov
else:
autov = fstart
fparams = {}
if not i:
i += 1
spaceBefore = getattr(self,'spaceBefore',None)
if spaceBefore is not None:
fparams['spaceBefore'] = spaceBefore
if d:
aS(self._makeLIIndenter(f,bullet=self._makeBullet(value),params=fparams))
if inc: value += inc
elif isinstance(f,LIIndenter):
b = f._bullet
if b:
if b.bulletType!=bt:
raise ValueError('Included LIIndenter bulletType=%s != OrderedList bulletType=%s' % (b.bulletType,bt))
value = int(b.value)
else:
f._bullet = self._makeBullet(value,params=getattr(f,'params',None))
if fparams:
f.__dict__['spaceBefore'] = max(f.__dict__.get('spaceBefore',0),spaceBefore)
aS(f)
if inc: value += inc
elif isinstance(f,_LIParams):
fparams.update(f.params)
z = self._makeLIIndenter(f.flowable,bullet=None,params=fparams)
if f.first:
if f.value is not None:
value = f.value
if inc: value = int(value)
z._bullet = self._makeBullet(value,f.params)
if inc: value += inc
aS(z)
else:
aS(self._makeLIIndenter(f,bullet=None,params=fparams))
spaceAfter = getattr(self,'spaceAfter',None)
if spaceAfter is not None:
f=S[-1]
f.__dict__['spaceAfter'] = max(f.__dict__.get('spaceAfter',0),spaceAfter)
return S
class TopPadder(Flowable):
'''wrap a single flowable so that its first bit will be
padded to fill out the space so that it appears at the
bottom of its frame'''
def __init__(self,f):
self.__dict__['_TopPadder__f'] = f
def wrap(self,aW,aH):
w,h = self.__f.wrap(aW,aH)
self.__dict__['_TopPadder__dh'] = aH-h
return w,h
def split(self,aW,aH):
S = self.__f.split(aW,aH)
if len(S)>1:
S[0] = TopPadder(S[0])
return S
def drawOn(self, canvas, x, y, _sW=0):
self.__f.drawOn(canvas,x,y-max(0,self.__dh-1e-8),_sW)
def __setattr__(self,a,v):
setattr(self.__f,a,v)
def __getattr__(self,a):
return getattr(self.__f,a)
def __delattr__(self,a):
delattr(self.__f,a)
class DocAssign(NullDraw):
'''At wrap time this flowable evaluates var=expr in the doctemplate namespace'''
_ZEROSIZE=1
def __init__(self,var,expr,life='forever'):
Flowable.__init__(self)
self.args = var,expr,life
def funcWrap(self,aW,aH):
NS=self._doctemplateAttr('_nameSpace')
NS.update(dict(availableWidth=aW,availableHeight=aH))
try:
return self.func()
finally:
for k in 'availableWidth','availableHeight':
try:
del NS[k]
except:
pass
def func(self):
return self._doctemplateAttr('d'+self.__class__.__name__[1:])(*self.args)
def wrap(self,aW,aH):
self.funcWrap(aW,aH)
return 0,0
class DocExec(DocAssign):
'''at wrap time exec stmt in doc._nameSpace'''
def __init__(self,stmt,lifetime='forever'):
Flowable.__init__(self)
self.args=stmt,lifetime
class DocPara(DocAssign):
'''at wrap time create a paragraph with the value of expr as text
if format is specified it should use %(__expr__)s for string interpolation
of the expression expr (if any). It may also use %(name)s interpolations
for other variables in the namespace.
suitable defaults will be used if style and klass are None
'''
def __init__(self,expr,format=None,style=None,klass=None,escape=True):
Flowable.__init__(self)
self.expr=expr
self.format=format
self.style=style
self.klass=klass
self.escape=escape
def func(self):
expr = self.expr
if expr:
if not isinstance(expr,str): expr = str(expr)
return self._doctemplateAttr('docEval')(expr)
def add_content(self,*args):
self._doctemplateAttr('frame').add_generated_content(*args)
def get_value(self,aW,aH):
value = self.funcWrap(aW,aH)
if self.format:
NS=self._doctemplateAttr('_nameSpace').copy()
NS.update(dict(availableWidth=aW,availableHeight=aH))
NS['__expr__'] = value
value = self.format % NS
else:
value = str(value)
return value
def wrap(self,aW,aH):
value = self.get_value(aW,aH)
P = self.klass
if not P:
from reportlab.platypus.paragraph import Paragraph as P
style = self.style
if not style:
from reportlab.lib.styles import getSampleStyleSheet
style=getSampleStyleSheet()['Code']
if self.escape:
from xml.sax.saxutils import escape
value=escape(value)
self.add_content(P(value,style=style))
return 0,0
class DocAssert(DocPara):
def __init__(self,cond,format=None):
Flowable.__init__(self)
self.expr=cond
self.format=format
def funcWrap(self,aW,aH):
self._cond = DocPara.funcWrap(self,aW,aH)
return self._cond
def wrap(self,aW,aH):
value = self.get_value(aW,aH)
if not bool(self._cond):
raise AssertionError(value)
return 0,0
class DocIf(DocPara):
def __init__(self,cond,thenBlock,elseBlock=[]):
Flowable.__init__(self)
self.expr = cond
self.blocks = elseBlock or [],thenBlock
def checkBlock(self,block):
if not isinstance(block,(list,tuple)):
block = (block,)
return block
def wrap(self,aW,aH):
self.add_content(*self.checkBlock(self.blocks[int(bool(self.funcWrap(aW,aH)))]))
return 0,0
class DocWhile(DocIf):
def __init__(self,cond,whileBlock):
Flowable.__init__(self)
self.expr = cond
self.block = self.checkBlock(whileBlock)
def wrap(self,aW,aH):
if bool(self.funcWrap(aW,aH)):
self.add_content(*(list(self.block)+[self]))
return 0,0
class SetTopFlowables(NullDraw):
_ZEROZSIZE = 1
def __init__(self,F,show=False):
self._F = F
self._show = show
def wrap(self,aW,aH):
doc = getattr(getattr(self,'canv',None),'_doctemplate',None)
if doc:
doc._topFlowables = self._F
if self._show and self._F:
doc.frame._generated_content = self._F
return 0,0
class SetPageTopFlowables(NullDraw):
_ZEROZSIZE = 1
def __init__(self,F,show=False):
self._F = F
self._show = show
def wrap(self,aW,aH):
doc = getattr(getattr(self,'canv',None),'_doctemplate',None)
if doc:
doc._pageTopFlowables = self._F
if self._show and self._F:
doc.frame._generated_content = self._F
return 0,0
| 36.950927 | 152 | 0.556432 |
acec87911b63da121c8ec43adb4181850d65ee8d | 2,093 | py | Python | pypcd/version.py | bmankirLinker/pypcd | 3cfef33a89430848880a112c818b1a9596df3318 | [
"MIT"
] | 17 | 2019-01-04T13:54:02.000Z | 2022-03-29T04:05:32.000Z | pypcd/version.py | bmankirLinker/pypcd | 3cfef33a89430848880a112c818b1a9596df3318 | [
"MIT"
] | 1 | 2020-12-21T07:54:55.000Z | 2020-12-21T07:54:55.000Z | pypcd/version.py | bmankirLinker/pypcd | 3cfef33a89430848880a112c818b1a9596df3318 | [
"MIT"
] | 26 | 2018-08-03T07:10:23.000Z | 2022-03-31T11:59:09.000Z | from os.path import join as pjoin
# Format expected by setup.py and doc/source/conf.py: string of form "X.Y.Z"
_version_major = 0
_version_minor = 1
_version_micro = 1 # use '' for first of series, number for 1 and above
_version_extra = None # Uncomment this for full releases
# Construct full version string from these.
_ver = [_version_major, _version_minor]
if _version_micro:
_ver.append(_version_micro)
if _version_extra:
_ver.append(_version_extra)
__version__ = '.'.join(map(str, _ver))
CLASSIFIERS = ["Development Status :: 3 - Alpha",
"Environment :: Console",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Scientific/Engineering"]
# Description should be a one-liner:
description = "Pure Python PCD reader/writer"
# Long description will go up on the pypi page
long_description = """\
pypcd
========
Pure Python reader/writer for the PCL ``pcd`` data format for point clouds.
Please go to the repository README_.
.. _README: https://github.com/dimatura/pypcd/blob/master/README.md
License
=======
``pypcd`` is licensed under the terms of the MIT license. See the file
"LICENSE" for information on the history of this software, terms & conditions
for usage, and a DISCLAIMER OF ALL WARRANTIES.
All trademarks referenced herein are property of their respective holders.
Copyright (c) 2015--, Daniel Maturana
"""
NAME = "pypcd"
MAINTAINER = "Daniel Maturana"
MAINTAINER_EMAIL = "dimatura@cmu.edu"
DESCRIPTION = description
LONG_DESCRIPTION = long_description
URL = "http://github.com/dimatura/pypcd"
DOWNLOAD_URL = ""
LICENSE = "MIT"
AUTHOR = "Daniel Maturana"
AUTHOR_EMAIL = "dimatura@cmu.edu"
PLATFORMS = "OS Independent"
MAJOR = _version_major
MINOR = _version_minor
MICRO = _version_micro
VERSION = __version__
PACKAGES = ['pypcd',
'pypcd.tests']
PACKAGE_DATA = {'pypcd': [pjoin('data', '*')]}
INSTALL_REQUIRES = ["numpy", "python-lzf"]
| 29.9 | 77 | 0.70473 |
acec8858b3176613951ced08dbea6d49b2334909 | 13,665 | py | Python | nsm/computer_factory.py | pcyin/neural-symbolic-machines | a552bf375dc2eb7b7e8d6003c180f016f076e1e5 | [
"Apache-2.0"
] | null | null | null | nsm/computer_factory.py | pcyin/neural-symbolic-machines | a552bf375dc2eb7b7e8d6003c180f016f076e1e5 | [
"Apache-2.0"
] | null | null | null | nsm/computer_factory.py | pcyin/neural-symbolic-machines | a552bf375dc2eb7b7e8d6003c180f016f076e1e5 | [
"Apache-2.0"
] | null | null | null | """Computers can read in tokens, parse them into a program, and execute it."""
from __future__ import print_function
from collections import OrderedDict
import re
import copy
import sys
import os
import data_utils
import pprint
END_TK = data_utils.END_TK # End of program token
ERROR_TK = '<ERROR>'
# SPECIAL_TKS = [END_TK, ERROR_TK, '(', ')']
SPECIAL_TKS = [ERROR_TK, '(', ')']
class LispInterpreter(object):
"""Interpreter reads in tokens, parse them into a program and execute it."""
def __init__(self, type_hierarchy, max_mem, max_n_exp, assisted=True):
"""
max_mem: maximum number of memory slots.
max_n_exp: maximum number of expressions.
assisted: whether to provide assistance to the programmer (used for neural programmer).
"""
# Create namespace.
self.namespace = Namespace()
self.assisted = assisted
# Configs.
# Functions used to call
# Signature: autocomplete(evaled_exp, valid_tokens, evaled_tokens)
# return a subset of valid_tokens that passed the
# filter. Used to implement filtering with denotation.
self.type_hierarchy = type_hierarchy
self.type_ancestry = create_type_ancestry(type_hierarchy)
self.max_mem = max_mem
self.max_n_exp = max_n_exp
# Initialize the parser state.
self.n_exp = 0
self.history = []
self.exp_stack = []
self.done = False
self.result = None
@property
def primitive_names(self):
primitive_names = []
for k, v in self.namespace.iteritems():
if ('property' in self.type_ancestry[v['type']] or
'primitive_function' in self.type_ancestry[v['type']]):
primitive_names.append(k)
return primitive_names
@property
def primitives(self):
primitives = []
for k, v in self.namespace.iteritems():
if ('property' in self.type_ancestry[v['type']] or
'primitive_function' in self.type_ancestry[v['type']]):
primitives.append(v)
return primitives
def add_constant(self, value, type, name=None):
"""Generate the code and variables to hold the constants."""
if name is None:
name = self.namespace.generate_new_name()
self.namespace[name] = dict(
value=value, type=type,
is_constant=True)
return name
def add_function(self, name, value, args, return_type,
autocomplete, type):
"""Add function into the namespace."""
if name in self.namespace:
raise ValueError('Name %s is already used.' % name)
else:
self.namespace[name] = dict(
value=value, type=type,
autocomplete=autocomplete,
return_type=return_type, args=args)
def autocomplete(self, exp, tokens, token_vals, namespace):
# func = exp[0]
# exp = [x['value'] for x in exp]
# token_vals = [x['value'] for x in token_vals]
# if func['type'] == 'global_primitive_function':
# return func['autocomplete'](
# exp, tokens, token_vals, namespace=namespace)
# else:
# return func['autocomplete'](exp, tokens, token_vals)
function = exp[0]
return function['autocomplete'](exp, tokens, token_vals)
def reset(self, only_reset_variables=False):
"""Reset all the interpreter state."""
if only_reset_variables:
self.namespace.reset_variables()
else:
self.namespace = Namespace()
self.history = []
self.n_exp = 0
self.exp_stack = []
self.done = False
self.result = None
def read_token_id(self, token_id):
token = self.rev_vocab[token_id]
return self.read_token(token)
def read_token(self, token):
"""Read in one token, parse and execute the expression if completed."""
if ((self.n_exp >= self.max_n_exp) or
(self.namespace.n_var >= self.max_mem)):
token = END_TK
new_exp = self.parse_step(token)
# If reads in end of program, then return the last value as result.
if token == END_TK:
self.done = True
self.result = self.namespace.get_last_value()
return self.result
elif new_exp:
if self.assisted:
name = self.namespace.generate_new_name()
result = self.eval(['define', name, new_exp])
self.n_exp += 1
# If there are errors in the execution, self.eval
# will return None. We can also give a separate negative
# reward for errors.
if result is None:
self.namespace.n_var -= 1
self.done = True
self.result = [ERROR_TK]
# result = self.eval(['define', name, ERROR_TK])
else:
result = self.eval(new_exp)
return result
else:
return None
def valid_tokens(self):
"""Return valid tokens for the next step for programmer to pick."""
# If already exceeded max memory or max expression
# limit, then must end the program.
if ((self.n_exp >= self.max_n_exp) or
(self.namespace.n_var >= self.max_mem)):
result = [END_TK]
# If last expression is finished, either start a new one
# or end the program.
elif not self.history:
result = ['(']
# If not in an expression, either start a new expression or end the program.
elif not self.exp_stack:
result = ['(', END_TK]
# If currently in an expression.
else:
exp = self.exp_stack[-1]
# If in the middle of a new expression.
if exp:
# Use number of arguments to check if all arguments are there.
head = exp[0]
args = self.namespace[head]['args']
pos = len(exp) - 1
if pos == len(args):
result = [')']
else:
result = self.namespace.valid_tokens(
args[pos], self.get_type_ancestors)
if self.autocomplete is not None:
valid_tokens = result
evaled_exp = [self.eval(item) for item in exp]
evaled_tokens = [self.eval(tk) for tk in valid_tokens]
result = self.autocomplete(
evaled_exp, valid_tokens, evaled_tokens, self.namespace)
# If at the beginning of a new expression.
else:
result = self.namespace.valid_tokens(
{'types': ['head']}, self.get_type_ancestors)
return result
def parse_step(self, token):
"""Run the parser for one step with given token which parses tokens into expressions."""
self.history.append(token)
if token == END_TK:
self.done = True
elif token == '(':
self.exp_stack.append([])
elif token == ')':
# One list is finished.
new_exp = self.exp_stack.pop()
if self.exp_stack:
self.exp_stack[-1].append(new_exp)
else:
self.exp_stack = []
return new_exp
elif self.exp_stack:
self.exp_stack[-1].append(token)
else:
# Atom expression.
return token
def tokenize(self, chars):
"""Convert a string of characters into a list of tokens."""
return chars.replace('(', ' ( ').replace(')', ' ) ').split()
def get_type_ancestors(self, type):
return self.type_ancestry[type]
def infer_type(self, return_type, arg_types):
"""Infer the type of the returned value of a function."""
if hasattr(return_type, '__call__'):
return return_type(*arg_types)
else:
return return_type
def eval(self, x, namespace=None):
"""Another layer above _eval to handle exceptions."""
try:
result = self._eval(x, namespace)
except Exception as e:
print('Error: ', e)
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
print('when evaluating ', x)
print(self.history)
pprint.pprint(self.namespace)
raise e
result = None
return result
def _eval(self, x, namespace=None):
"""Evaluate an expression in an namespace."""
if namespace is None:
namespace = self.namespace
if is_symbol(x): # variable reference
return namespace.get_object(x).copy()
elif x[0] == 'define': # (define name exp)
(_, name, exp) = x
obj = self._eval(exp, namespace)
namespace[name] = obj
return obj
else:
# Execute a function.
proc = self._eval(x[0], namespace)
args = [self._eval(exp, namespace) for exp in x[1:]]
arg_values = [arg['value'] for arg in args]
if proc['type'] == 'global_primitive_function':
arg_values += [self.namespace]
value = proc['value'](*(arg_values))
arg_types = [arg['type'] for arg in args]
type = self.infer_type(proc['return_type'], arg_types)
return {'value': value, 'type': type, 'is_constant': False}
def step(self, token):
"""Open AI gym inferface."""
result = self.read_token(token)
observation = token
reward = 0.0
done = self.done
if (result is None) or self.done:
write_pos = None
else:
write_pos = self.namespace.n_var - 1
info = {'result': result,
'write_pos': write_pos}
return observation, reward, done, info
def get_last_var_loc(self):
return self.namespace.n_var - 1
def interactive(self, prompt='> ', assisted=False):
"""A prompt-read-eval-print loop."""
print('Namespace:')
for key, val in self.namespace.items():
if val['type'] == 'primitive_function':
print('Function: {}'.format(key))
else:
print('Entity: {}, Value: {}'.format(key, val))
temp = self.assisted
# try:
self.assisted = assisted
while True:
# try:
query = raw_input(prompt).strip()
tokens = self.tokenize(query)
for tk in tokens:
result = self.read_token(tk)
print('Read in [{}], valid tokens: {}'.format(tk, self.valid_tokens()))
if result:
print(result['value'])
# except Exception as e:
# print(e)
# continue
# finally:
# self.assisted = temp
def has_extra_work(self):
"""Check if the current solution contains some extra/wasted work."""
all_var_names = ['v{}'.format(i)
for i in range(self.namespace.n_var)]
for var_name in all_var_names:
obj = self.namespace.get_object(var_name)
# If some variable is not given as constant, not used
# in other expressions and not the last one, then
# generating it is some extra work that should not be
# done.
if ((not obj['is_constant']) and
(var_name not in self.history) and
(var_name != self.namespace.last_var)):
return True
return False
def clone(self):
"""Make a copy of itself, used in search."""
new = LispInterpreter(
self.type_hierarchy, self.max_mem, self.max_n_exp, self.assisted)
new.history = self.history[:]
new.exp_stack = copy.deepcopy(self.exp_stack)
new.n_exp = self.n_exp
new.namespace = self.namespace.clone()
return new
def get_vocab(self):
mem_tokens = []
for i in range(self.max_mem):
mem_tokens.append('v{}'.format(i))
vocab = data_utils.Vocab(
self.namespace.get_all_names() + SPECIAL_TKS + mem_tokens)
return vocab
class Namespace(OrderedDict):
"""Namespace is a mapping from names to values.
Namespace maintains the mapping from names to their
values. It also generates new variable names for memory
slots (v0, v1...), and support finding a subset of
variables that fulfill some type constraints, (for
example, find all the functions or find all the entity
lists).
"""
def __init__(self, *args, **kwargs):
"""Initialize the namespace with a list of functions."""
# params = dict(zip(names, objs))
super(Namespace, self).__init__(*args, **kwargs)
self.n_var = 0
self.last_var = None
def clone(self):
new = Namespace(self)
new.n_var = self.n_var
new.last_var = self.last_var
return new
def generate_new_name(self):
"""Create and return a new variable."""
name = 'v{}'.format(self.n_var)
self.last_var = name
self.n_var += 1
return name
def valid_tokens(self, constraint, get_type_ancestors):
"""Return all the names/tokens that fulfill the constraint."""
return [k for k, v in self.iteritems()
if self._is_token_valid(v, constraint, get_type_ancestors)]
def _is_token_valid(self, token, constraint, get_type_ancestors):
"""Determine if the token fulfills the given constraint."""
type = token['type']
return set(get_type_ancestors(type) + [type]).intersection(constraint['types'])
def get_value(self, name):
return self[name]['value']
def get_object(self, name):
return self[name]
def get_last_value(self):
if self.last_var is None:
return None
else:
return self.get_value(self.last_var)
def get_all_names(self):
return self.keys()
def reset_variables(self):
for k in self.keys():
if re.match(r'v\d+', k):
del self[k]
self.n_var = 0
self.last_var = None
def is_symbol(x):
return isinstance(x, str) or isinstance(x, unicode)
def create_type_ancestry(type_tree):
type_ancestry = {}
for type, _ in type_tree.iteritems():
_get_type_ancestors(type, type_tree, type_ancestry)
return type_ancestry
def _get_type_ancestors(type, type_hrchy, type_ancestry):
"""Compute the ancestors of a type with memorization."""
if type in type_ancestry:
return type_ancestry[type]
else:
parents = type_hrchy[type]
result = parents[:]
for p in parents:
ancestors = _get_type_ancestors(p, type_hrchy, type_ancestry)
for a in ancestors:
if a not in result:
result.append(a)
type_ancestry[type] = result
return result
| 32.002342 | 92 | 0.637834 |
acec8912e6d5d5d4064d60ec5d630ff05a92d2ef | 1,750 | py | Python | el/utils/el.py | deepakxyz/Edna | 825393c6ca88bb31d35cc4c369ea7042b9048fcb | [
"MIT"
] | 2 | 2021-08-31T23:23:11.000Z | 2022-03-07T03:18:01.000Z | el/utils/el.py | deepakxyz/Elna | 825393c6ca88bb31d35cc4c369ea7042b9048fcb | [
"MIT"
] | null | null | null | el/utils/el.py | deepakxyz/Elna | 825393c6ca88bb31d35cc4c369ea7042b9048fcb | [
"MIT"
] | null | null | null | import os
import re
import logging
from el.config.GLOBALS import CONFIG_FILE_PATH
from el.utils.read_dump import read_json, read_yaml
class el:
# echo fucn to print and log information
@classmethod
def echo(cls,msg,lvl="INFO",log=False):
final_msg = (f"{lvl}: {msg}")
print(final_msg)
# change the current working directory
@classmethod
def cwd(cls,path):
os.chdir(path)
# os.system('/bin/zsh')
os.system('/bin/bash')
@classmethod
def log(cls, msg, level):
logging.basicConfig(level=logging.DEBUG, filename='test.log', format='%(asctime)s -%(levelname)s -- %(message)s')
logging.debug(f'Add {num1} + {num2} = {add_result}')
@staticmethod
def path(path):
dir_name , file_name = os.path.split(path)
last_folder, file = os.path.split(dir_name)
raw, ext = os.path.splitext(file_name)
path_out = [last_folder, file, raw, ext]
return path_out
def current_show(path):
i = os.path.split(path)
print(i)
class Path():
config = read_yaml(CONFIG_FILE_PATH)
show_base_path = config['base_show_path']
@classmethod
def show_name(cls,path):
if cls.show_base_path in path:
show_name = re.sub(cls.show_base_path, '', path)
show_name = show_name.split('/')
if len(show_name) <= 1:
return None
else:
show_name.pop(0)
output = os.path.join(cls.show_base_path, show_name[0])
return output
else:
el.echo('''
You are not the show level.
Use the command 'el goshow' to move to the show level.
''',lvl="ERROR")
| 26.119403 | 121 | 0.587429 |
acec8a482fc84d8f5a31544dd620ab52f7a27d69 | 3,019 | py | Python | test/functional/zapwallettxes.py | Gulden-Coin/gulden-official | fd9b07bb17a87bfbaab7b9c9a3415279fcb3c508 | [
"MIT"
] | null | null | null | test/functional/zapwallettxes.py | Gulden-Coin/gulden-official | fd9b07bb17a87bfbaab7b9c9a3415279fcb3c508 | [
"MIT"
] | null | null | null | test/functional/zapwallettxes.py | Gulden-Coin/gulden-official | fd9b07bb17a87bfbaab7b9c9a3415279fcb3c508 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the zapwallettxes functionality.
- start three GuldenD nodes
- create four transactions on node 0 - two are confirmed and two are
unconfirmed.
- restart node 1 and verify that both the confirmed and the unconfirmed
transactions are still available.
- restart node 0 and verify that the confirmed transactions are still
available, but that the unconfirmed transaction has been zapped.
"""
from test_framework.test_framework import GuldenTestFramework
from test_framework.util import *
class ZapWalletTXesTest (GuldenTestFramework):
def __init__(self):
super().__init__()
self.setup_clean_chain = True
self.num_nodes = 3
def setup_network(self):
super().setup_network()
connect_nodes_bi(self.nodes,0,2)
def run_test (self):
self.log.info("Mining blocks...")
self.nodes[0].generate(1)
self.sync_all()
self.nodes[1].generate(101)
self.sync_all()
assert_equal(self.nodes[0].getbalance(), 50)
txid0 = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 11)
txid1 = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 10)
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
txid2 = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 11)
txid3 = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 10)
tx0 = self.nodes[0].gettransaction(txid0)
assert_equal(tx0['txid'], txid0) #tx0 must be available (confirmed)
tx1 = self.nodes[0].gettransaction(txid1)
assert_equal(tx1['txid'], txid1) #tx1 must be available (confirmed)
tx2 = self.nodes[0].gettransaction(txid2)
assert_equal(tx2['txid'], txid2) #tx2 must be available (unconfirmed)
tx3 = self.nodes[0].gettransaction(txid3)
assert_equal(tx3['txid'], txid3) #tx3 must be available (unconfirmed)
#restart GuldenD
self.stop_node(0)
self.nodes[0] = self.start_node(0,self.options.tmpdir)
tx3 = self.nodes[0].gettransaction(txid3)
assert_equal(tx3['txid'], txid3) #tx must be available (unconfirmed)
self.stop_node(0)
#restart GuldenD with zapwallettxes
self.nodes[0] = self.start_node(0,self.options.tmpdir, ["-zapwallettxes=1"])
assert_raises(JSONRPCException, self.nodes[0].gettransaction, [txid3])
#there must be a expection because the unconfirmed wallettx0 must be gone by now
tx0 = self.nodes[0].gettransaction(txid0)
assert_equal(tx0['txid'], txid0) #tx0 (confirmed) must still be available because it was confirmed
if __name__ == '__main__':
ZapWalletTXesTest ().main ()
| 37.271605 | 106 | 0.661146 |
acec8a6146a86b69b488979c40cfa79014a4f136 | 9,282 | py | Python | kratos/tests/test_connectivity_preserve_modeler.py | AndreaVoltan/MyKratos7.0 | e977752722e8ef1b606f25618c4bf8fd04c434cc | [
"BSD-4-Clause"
] | 2 | 2020-04-30T19:13:08.000Z | 2021-04-14T19:40:47.000Z | kratos/tests/test_connectivity_preserve_modeler.py | AndreaVoltan/MyKratos7.0 | e977752722e8ef1b606f25618c4bf8fd04c434cc | [
"BSD-4-Clause"
] | 1 | 2020-04-30T19:19:09.000Z | 2020-05-02T14:22:36.000Z | kratos/tests/test_connectivity_preserve_modeler.py | AndreaVoltan/MyKratos7.0 | e977752722e8ef1b606f25618c4bf8fd04c434cc | [
"BSD-4-Clause"
] | 1 | 2020-06-12T08:51:24.000Z | 2020-06-12T08:51:24.000Z | from __future__ import print_function, absolute_import, division
import KratosMultiphysics.KratosUnittest as KratosUnittest
import KratosMultiphysics
class TestConnectivityPreserveModeler(KratosUnittest.TestCase):
def test_connectivity_preserve_modeler(self):
current_model = KratosMultiphysics.Model()
model_part1 = current_model.CreateModelPart("Main")
model_part1.AddNodalSolutionStepVariable(KratosMultiphysics.DISTANCE)
model_part1.CreateNewNode(1,0.0,0.1,0.2)
model_part1.CreateNewNode(2,2.0,0.1,0.2)
model_part1.CreateNewNode(3,1.0,1.1,0.2)
model_part1.CreateNewNode(4,2.0,3.1,10.2)
sub1 = model_part1.CreateSubModelPart("sub1")
sub2 = model_part1.CreateSubModelPart("sub2")
subsub1 = sub1.CreateSubModelPart("subsub1")
subsub1.AddNodes([1,2])
sub2.AddNodes([3])
model_part1.CreateNewElement("Element2D3N", 1, [1,2,3], model_part1.GetProperties()[1])
model_part1.CreateNewElement("Element2D3N", 2, [1,2,4], model_part1.GetProperties()[1])
model_part1.CreateNewCondition("Condition2D2N", 2, [2,4], model_part1.GetProperties()[1])
sub1.AddConditions([2])
current_model = KratosMultiphysics.Model()
new_model_part = current_model.CreateModelPart("Other")
modeler = KratosMultiphysics.ConnectivityPreserveModeler()
modeler.GenerateModelPart(model_part1, new_model_part, "Element2D3N", "Condition2D2N")
self.assertEqual(len(model_part1.Nodes) , len(new_model_part.Nodes))
self.assertEqual(len(model_part1.Conditions) , len(new_model_part.Conditions))
self.assertEqual(len(model_part1.Elements) , len(new_model_part.Elements))
##assign a value to an element in model_part1, the corresponding element in the other model part will not be changed
model_part1.Elements[1].SetValue(KratosMultiphysics.DISTANCE, 1.0)
self.assertEqual(model_part1.Elements[1].GetValue(KratosMultiphysics.DISTANCE) , 1.0)
self.assertEqual(new_model_part.Elements[1].GetValue(KratosMultiphysics.DISTANCE) , 0.0)
##assign a value to an element in model_part1, the corresponding element in the other model part will not be changed
model_part1.Conditions[1].SetValue(KratosMultiphysics.DISTANCE, 1.0)
self.assertEqual(model_part1.Conditions[1].GetValue(KratosMultiphysics.DISTANCE) , 1.0)
self.assertEqual(new_model_part.Conditions[1].GetValue(KratosMultiphysics.DISTANCE) , 0.0)
#assign a value to a node of new_model_part --> affects both model parts
new_model_part.Nodes[1].SetSolutionStepValue(KratosMultiphysics.DISTANCE,0,2.0)
self.assertEqual(model_part1.Nodes[1].GetSolutionStepValue(KratosMultiphysics.DISTANCE) , 2.0)
self.assertEqual(new_model_part.Nodes[1].GetSolutionStepValue(KratosMultiphysics.DISTANCE), 2.0)
#test if submodelparts are created correctly
for part in model_part1.SubModelParts:
new_part = new_model_part.GetSubModelPart(part.Name)
for node in part.Nodes:
self.assertTrue( node.Id in new_part.Nodes)
for cond in part.Conditions:
self.assertTrue( cond.Id in new_part.Conditions)
for elem in part.Elements:
self.assertTrue( elem.Id in new_part.Elements)
model_part1.GetSubModelPart("sub1").Conditions[2].SetValue(KratosMultiphysics.TEMPERATURE, 1234.0)
self.assertEqual(model_part1.Conditions[2].GetValue(KratosMultiphysics.TEMPERATURE), 1234.0)
self.assertEqual(model_part1.GetSubModelPart("sub1").Conditions[2].GetValue(KratosMultiphysics.TEMPERATURE), 1234.0)
self.assertEqual(new_model_part.Conditions[2].GetValue(KratosMultiphysics.TEMPERATURE), 0.0)
self.assertEqual(new_model_part.GetSubModelPart("sub1").Conditions[2].GetValue(KratosMultiphysics.TEMPERATURE), 0.0)
def test_repeated_call(self):
current_model = KratosMultiphysics.Model()
model_part1 = current_model.CreateModelPart("Main")
model_part1.AddNodalSolutionStepVariable(KratosMultiphysics.DISTANCE)
model_part1.CreateNewNode(1,0.0,0.1,0.2)
model_part1.CreateNewNode(2,2.0,0.1,0.2)
model_part1.CreateNewNode(3,1.0,1.1,0.2)
model_part1.CreateNewNode(4,2.0,3.1,10.2)
sub1 = model_part1.CreateSubModelPart("sub1")
subsub1 = sub1.CreateSubModelPart("subsub1")
subsub1.AddNodes([1,2])
model_part1.CreateNewElement("Element2D3N", 1, [1,2,3], model_part1.GetProperties()[1])
model_part1.CreateNewElement("Element2D3N", 2, [1,2,4], model_part1.GetProperties()[1])
model_part1.CreateNewCondition("Condition2D2N", 2, [2,4], model_part1.GetProperties()[1])
model_part1.CreateNewCondition("Condition2D2N", 1, [1,2], model_part1.GetProperties()[1])
sub1.AddConditions([2])
current_model = KratosMultiphysics.Model()
new_model_part = current_model.CreateModelPart("New1")
new_model_part2 = current_model.CreateModelPart("New2")
modeler = KratosMultiphysics.ConnectivityPreserveModeler()
modeler.GenerateModelPart(model_part1, new_model_part, "Element2D3N", "Condition2D2N")
self.assertEqual(len(model_part1.Nodes) , len(new_model_part.Nodes))
self.assertEqual(len(model_part1.Conditions) , len(new_model_part.Conditions))
self.assertEqual(len(model_part1.Elements) , len(new_model_part.Elements))
modeler.GenerateModelPart(model_part1, new_model_part2, "Element2D3N", "Condition2D2N")
self.assertEqual(len(model_part1.Nodes) , len(new_model_part2.Nodes))
self.assertEqual(len(model_part1.Conditions) , len(new_model_part2.Conditions))
self.assertEqual(len(model_part1.Elements) , len(new_model_part2.Elements))
modeler.GenerateModelPart(model_part1, new_model_part, "Element2D3N", "Condition2D2N")
self.assertEqual(len(model_part1.Nodes) , len(new_model_part.Nodes))
self.assertEqual(len(model_part1.Conditions) , len(new_model_part.Conditions))
self.assertEqual(len(model_part1.Elements) , len(new_model_part.Elements))
modeler.GenerateModelPart(model_part1, new_model_part2, "Element2D3N", "Condition2D2N")
self.assertEqual(len(model_part1.Nodes) , len(new_model_part2.Nodes))
self.assertEqual(len(model_part1.Conditions) , len(new_model_part2.Conditions))
self.assertEqual(len(model_part1.Elements) , len(new_model_part2.Elements))
self.assertEqual(len(model_part1.Nodes) , len(new_model_part.Nodes))
self.assertEqual(len(model_part1.Conditions) , len(new_model_part.Conditions))
self.assertEqual(len(model_part1.Elements) , len(new_model_part.Elements))
def test_variable_list_merging(self):
current_model = KratosMultiphysics.Model()
model_part1 = current_model.CreateModelPart("mp1")
model_part1.AddNodalSolutionStepVariable(KratosMultiphysics.DISTANCE)
model_part1.AddNodalSolutionStepVariable(KratosMultiphysics.DISPLACEMENT)
model_part2 = current_model.CreateModelPart("mp2")
model_part2.AddNodalSolutionStepVariable(KratosMultiphysics.TEMPERATURE)
model_part2.AddNodalSolutionStepVariable(KratosMultiphysics.VELOCITY)
#check before merging variable lists
self.assertTrue(model_part1.HasNodalSolutionStepVariable(KratosMultiphysics.DISTANCE))
self.assertTrue(model_part1.HasNodalSolutionStepVariable(KratosMultiphysics.DISPLACEMENT))
self.assertFalse(model_part1.HasNodalSolutionStepVariable(KratosMultiphysics.TEMPERATURE))
self.assertFalse(model_part1.HasNodalSolutionStepVariable(KratosMultiphysics.VELOCITY))
self.assertFalse(model_part2.HasNodalSolutionStepVariable(KratosMultiphysics.DISTANCE))
self.assertFalse(model_part2.HasNodalSolutionStepVariable(KratosMultiphysics.DISPLACEMENT))
self.assertTrue(model_part2.HasNodalSolutionStepVariable(KratosMultiphysics.TEMPERATURE))
self.assertTrue(model_part2.HasNodalSolutionStepVariable(KratosMultiphysics.VELOCITY))
KratosMultiphysics.MergeVariableListsUtility().Merge(model_part1, model_part2)
#check after merging variable lists
self.assertTrue(model_part1.HasNodalSolutionStepVariable(KratosMultiphysics.DISTANCE))
self.assertTrue(model_part1.HasNodalSolutionStepVariable(KratosMultiphysics.DISPLACEMENT))
self.assertTrue(model_part1.HasNodalSolutionStepVariable(KratosMultiphysics.TEMPERATURE))
self.assertTrue(model_part1.HasNodalSolutionStepVariable(KratosMultiphysics.VELOCITY))
self.assertTrue(model_part2.HasNodalSolutionStepVariable(KratosMultiphysics.DISTANCE))
self.assertTrue(model_part2.HasNodalSolutionStepVariable(KratosMultiphysics.DISPLACEMENT))
self.assertTrue(model_part2.HasNodalSolutionStepVariable(KratosMultiphysics.TEMPERATURE))
self.assertTrue(model_part2.HasNodalSolutionStepVariable(KratosMultiphysics.VELOCITY))
if __name__ == '__main__':
KratosUnittest.main()
| 58.0125 | 125 | 0.735725 |
acec8b5dc919cf2dbe3abdb84759ccc3665b0bfa | 19,394 | py | Python | STRATEGY/Cointegration.py | xtuyaowu/Pair-Trading-Reinforcement-Learning | 24b744224457efa2dfee23ed0c44ec393b37449a | [
"MIT"
] | null | null | null | STRATEGY/Cointegration.py | xtuyaowu/Pair-Trading-Reinforcement-Learning | 24b744224457efa2dfee23ed0c44ec393b37449a | [
"MIT"
] | null | null | null | STRATEGY/Cointegration.py | xtuyaowu/Pair-Trading-Reinforcement-Learning | 24b744224457efa2dfee23ed0c44ec393b37449a | [
"MIT"
] | null | null | null | # from statsmodels.tsa.stattools import coint
# from sklearn.linear_model import LinearRegression
# import pandas as pd
# import numpy as np
# import sys
# import random
# from MAIN.Basics import Strategy
#
#
# def get_src_cls(source_name):
# return getattr(sys.modules[__name__], source_name)
#
#
# class EGCointegration(Strategy):
#
# def __init__(self, x, y, on, col_name, is_cleaned=True):
# if is_cleaned is not True:
# x, y = EGCointegration.clean_data(x, y, on, col_name)
# self.timestamp = x[on].values
# self.x = x[col_name].values.reshape(-1, )
# self.y = y[col_name].values.reshape(-1, )
# self.beta = None
# self.resid_mean = None
# self.resid_std = None
# self.p = 0
# self._reward = 0
# self._record = None
#
# @property
# def reward(self):
# return self._reward
#
# @reward.setter
# def reward(self, value):
# self._reward = value
#
# @property
# def record(self):
# return self._record
#
# @record.setter
# def record(self, value):
# self._record = value
#
# @classmethod
# def clean_data(cls, x, y, on, col_name):
# x.replace([np.inf, -np.inf], np.nan, inplace=True)
# y.replace([np.inf, -np.inf], np.nan, inplace=True)
# merged_df = pd.merge(left=x, right=y, on=on, how='outer')
# clean_df = merged_df.loc[merged_df.notnull().all(axis=1), :]
# df_x = pd.DataFrame()
# df_y = pd.DataFrame()
# df_x[on] = clean_df[on].values
# df_y[on] = clean_df[on].values
# df_x[col_name] = clean_df[col_name + '_x'].values
# df_y[col_name] = clean_df[col_name + '_y'].values
# return df_x, df_y
#
# def cal_spread(self, x, y, is_norm):
# resid = y - x * self.beta
# resid = (resid - self.resid_mean) / self.resid_std if is_norm is True else resid
# return resid
#
# def get_sample(self, start, end):
# assert start < end <= len(self.x), 'Error:Invalid Indexing.'
# x_sample = self.x[start:end]
# y_sample = self.y[start:end]
# time_sample = self.timestamp[start:end]
# return x_sample, y_sample, time_sample
#
# @staticmethod
# def get_p_value(x, y):
# _, p_val, _ = coint(x, y)
# return p_val
#
# def run_ols(self, x, y):
# reg = LinearRegression().fit(x.reshape(-1, 1), y.reshape(-1, 1))
# self.beta = reg.coef_[0]
#
# def calibrate(self, start, end, cl):
# x, y, _ = self.get_sample(start, end)
# self.p = self.get_p_value(x, y)
# if self.p < cl:
# self.run_ols(x, y)
# resid = self.cal_spread(x, y, is_norm=False)
# self.resid_mean = resid.mean()
# self.resid_std = resid.std()
#
# def gen_signal(self, start, end, trade_th, stop_loss, transaction_cost):
# stop_loss = trade_th + stop_loss
# x, y, time = self.get_sample(start, end)
# spread = self.cal_spread(x, y, is_norm=True)
# price = self.cal_spread(x, y, is_norm=False)
#
# spread_t0 = spread[:-1]
# spread_t1 = spread[1:]
# price = price[1:]
# t_t1 = time[1:]
#
# ind_buy = np.logical_and(spread_t0 > -trade_th, spread_t1 <= -trade_th).reshape(-1, )
# ind_sell = np.logical_and(spread_t0 < trade_th, spread_t1 >= trade_th).reshape(-1, )
# ind_stop = np.logical_or(np.logical_or(np.logical_and(spread_t0 > -stop_loss, spread_t1 <= -stop_loss).reshape(-1, ),
# np.logical_and(spread_t0 < stop_loss, spread_t1 >= stop_loss).reshape(-1, )),
# np.logical_or(np.logical_and(spread_t0 > 0, spread_t1 <= 0).reshape(-1, ),
# np.logical_and(spread_t0 < 0, spread_t1 >= 0).reshape(-1, )))
#
# order = np.array([None] * len(t_t1))
# order[ind_buy] = 'Buy'
# order[ind_sell] = 'Sell'
# order[ind_stop] = 'Stop'
# order[-1] = 'Stop'
#
# ind_order = order != None
# time = t_t1[ind_order]
# price = price[ind_order]
# order = order[ind_order]
# x = x[1:][ind_order]
# y = y[1:][ind_order]
# gross_exp = y + abs(x) * self.beta
# cost = abs(gross_exp * transaction_cost)
# return time, price, order, gross_exp, cost
#
# @staticmethod
# def gen_trade_record(time, price, order, cost):
# if len(order) == 0:
# return None
#
# n_buy_sell = sum(order != 'Stop')
# trade_time = np.array([None] * n_buy_sell, object)
# trade_price = np.array([None] * n_buy_sell, float)
# trade_cost = np.array([None] * n_buy_sell, float)
# close_time = np.array([None] * n_buy_sell, object)
# close_price = np.array([None] * n_buy_sell, float)
# close_cost = np.array([None] * n_buy_sell, float)
# long_short = np.array([0] * n_buy_sell, int)
#
# current_holding = 0
# j = 0
#
# for i in range(len(order)):
# sign_holding = int(np.sign(current_holding))
# if order[i] == 'Buy':
# close_pos = (sign_holding < 0) * -current_holding
# close_time[j - close_pos:j] = time[i]
# close_price[j - close_pos:j] = price[i]
# close_cost[j - close_pos:j] = cost[i]
# trade_time[j] = time[i]
# trade_price[j] = price[i]
# long_short[j] = 1
# trade_cost[j] = cost[i]
# buy_sell = close_pos + 1
# current_holding = current_holding + buy_sell
# j += 1
# elif order[i] == 'Sell':
# close_pos = (sign_holding > 0) * -current_holding
# close_time[j + close_pos:j] = time[i]
# close_price[j + close_pos:j] = price[i]
# close_cost[j + close_pos:j] = cost[i]
# trade_time[j] = time[i]
# trade_price[j] = price[i]
# long_short[j] = -1
# trade_cost[j] = cost[i]
# buy_sell = close_pos - 1
# current_holding = current_holding + buy_sell
# j += 1
# else:
# close_pos = abs(current_holding)
# close_time[j - close_pos:j] = time[i]
# close_price[j - close_pos:j] = price[i]
# close_cost[j - close_pos:j] = cost[i]
# current_holding = 0
#
# profit = (close_price - trade_price) * long_short
# trade_record = {'trade_time' : trade_time,
# 'trade_price': trade_price,
# 'close_time' : close_time,
# 'close_price': close_price,
# 'long_short' : long_short,
# 'trade_cost' : trade_cost,
# 'close_cost' : close_cost,
# 'profit' : profit}
#
# return trade_record
#
# @staticmethod
# def get_indices(index, n_hist, n_forward):
# assert n_hist <= index, 'Error:Invalid number of historical observations.'
# start_hist = index - n_hist
# end_hist = index
# start_forward = index
# end_forward = index + n_forward
# return start_hist, end_hist, start_forward, end_forward
#
# def process(self, n_hist, n_forward, trade_th, stop_loss, cl, transaction_cost, index=None, **kwargs):
# index = random.randint(n_hist, len(self.x) - n_forward) if index is None else index
# start_hist, end_hist, start_forward, end_forward = self.get_indices(index, n_hist, n_forward)
# self.calibrate(start_hist, end_hist, cl)
# self.reward = 0
# self.record = None
# if self.p < cl:
# time, price, order, gross_exp, cost = self.gen_signal(start_forward, end_forward, trade_th, stop_loss, transaction_cost)
# trade_record = self.gen_trade_record(time, price, order, cost)
# returns = (trade_record['profit'] -
# trade_record['trade_cost'] -
# trade_record['close_cost']) / abs(trade_record['trade_price'])
# if (len(returns) > 0) and (np.any(np.isnan(returns)) is not True):
# self.reward = min(returns.mean(), 10)
# self.record = trade_record
from statsmodels.tsa.stattools import coint
from sklearn.linear_model import LinearRegression
import pandas as pd
import numpy as np
import sys
import random
random.seed(0)
from MAIN.Basics import Strategy
def get_src_cls(source_name):
return getattr(sys.modules[__name__], source_name)
class EGCointegration(Strategy):
def __init__(self, x, y, on, col_name, is_cleaned=True):
if is_cleaned is not True:
x, y = EGCointegration.clean_data(x, y, on, col_name)
self.timestamp = x[on].values
self.x = x[col_name].values.reshape(-1, )
self.y = y[col_name].values.reshape(-1, )
self.beta = None
self.resid_mean = None
self.resid_std = None
self.p = 0
self._reward = 0
self._record = None
self.MTR_variables = False
self.p_values_MTR = []
self.orders_MTR = []
self.spread_MTR = []
self.hist_pri_diff = (y['close'] - x['close']).mean()
@property
def reward(self):
return self._reward
@reward.setter
def reward(self, value):
self._reward = value
@property
def record(self):
return self._record
@record.setter
def record(self, value):
self._record = value
@classmethod
def clean_data(cls, x, y, on, col_name):
x.replace([np.inf, -np.inf], np.nan, inplace=True)
y.replace([np.inf, -np.inf], np.nan, inplace=True)
merged_df = pd.merge(left=x, right=y, on=on, how='outer')
clean_df = merged_df.loc[merged_df.notnull().all(axis=1), :]
df_x = pd.DataFrame()
df_y = pd.DataFrame()
df_x[on] = clean_df[on].values
df_y[on] = clean_df[on].values
df_x[col_name] = clean_df[col_name + '_x'].values
df_y[col_name] = clean_df[col_name + '_y'].values
return df_x, df_y
def cal_spread(self, x, y, is_norm):
resid = y - x * self.beta
resid = (resid - resid.mean()) / resid.std() if is_norm is True else resid # MTR
#resid = (resid - self.resid_mean) / self.resid_std if is_norm is True else resid # Latest version
return resid
def get_sample(self, start, end):
assert start < end <= len(self.x), 'Error:Invalid Indexing.'
x_sample = self.x[start:end]
y_sample = self.y[start:end]
time_sample = self.timestamp[start:end]
return x_sample, y_sample, time_sample
@staticmethod
def get_p_value(x, y):
_, p_val, _ = coint(x, y)
return p_val
def run_ols(self, x, y):
reg = LinearRegression().fit(x.reshape(-1, 1), y.reshape(-1, 1))
self.beta = reg.coef_[0]
def calibrate(self, start, end, cl):
x, y, _ = self.get_sample(start, end)
self.p = self.get_p_value(x, y)
if self.p < cl:
self.run_ols(x, y)
#resid = self.cal_spread(x, y, is_norm=False) # MTR
#self.resid_mean = resid.mean() # MTR
#self.resid_std = resid.std() # MTR
# If i want to calculate the historical spread, i can make a call to cal_spread here.
def gen_signal(self, start, end, trade_th, stop_loss, transaction_cost):
# self.gen_signal(start_forward, end_forward, trade_th, stop_loss, transaction_cost)
stop_loss = trade_th + stop_loss
x, y, time = self.get_sample(start, end)
spread = self.cal_spread(x, y, is_norm=True)
price = self.cal_spread(x, y, is_norm=False)
if self.MTR_variables:
self.spread_MTR.append(spread) # MTR
spread_t0 = spread[:-1]
spread_t1 = spread[1:]
price = price[1:]
t_t1 = time[1:]
# ind_buy/ind_sell: will be True at indexes at which a buy/sell (long/short) of spread is to be performed, otherwise False
ind_buy = np.logical_and(spread_t0 > -trade_th, spread_t1 <= -trade_th).reshape(-1, )
# spread_t0[i+1]<= -trade_th < spread_t0[i] : spread just passed the negative trading threshold from above
ind_sell = np.logical_and(spread_t0 < trade_th, spread_t1 >= trade_th).reshape(-1, )
# spread_t0[i] < trade_th <=spread_t0[i+1] : spread just passed the positive trading threshold from below
ind_stop = np.logical_or(np.logical_or(np.logical_and(spread_t0 > -stop_loss, spread_t1 <= -stop_loss).reshape(-1, ),
np.logical_and(spread_t0 < stop_loss, spread_t1 >= stop_loss).reshape(-1, )),
np.logical_or(np.logical_and(spread_t0 > 0, spread_t1 <= 0).reshape(-1, ),
np.logical_and(spread_t0 < 0, spread_t1 >= 0).reshape(-1, )))
################################################
# ind_stop
# Four logical_and s:
# (spread_t0[i+1] <= -stop_loss < spread_t0[i]) # spread just passed the negative stop threshold
# (spread_t0[i] < stop_loss <= spread_t0[i+1]) # spread just passed the positive stop threshold
# (spread_t0[i+1] <= 0 < spread_t0[i]) # spread just passed the mean from above
# (spread_t0[i] < 0 <= spread_t0[i+1]) # spread just passed the mean from below
# logical_or s: stop if any of the above conditions are met.
#
#
################################################
order = np.array([None] * len(t_t1))
order[ind_buy] = 'Buy'
order[ind_sell] = 'Sell'
order[ind_stop] = 'Stop'
order[-1] = 'Stop'
ind_order = order != None
time = t_t1[ind_order]
price = price[ind_order]
if self.MTR_variables:
self.orders_MTR.append(order)
order = order[ind_order]
x = x[1:][ind_order]
y = y[1:][ind_order]
gross_exp = y + abs(x) * self.beta
cost = abs(gross_exp * transaction_cost)
return time, price, order, gross_exp, cost
@staticmethod
def gen_trade_record(time, price, order, cost):
if len(order) == 0:
return None
n_buy_sell = sum(order != 'Stop')
trade_time = np.array([None] * n_buy_sell, object)
trade_price = np.array([None] * n_buy_sell, float)
trade_cost = np.array([None] * n_buy_sell, float)
close_time = np.array([None] * n_buy_sell, object)
close_price = np.array([None] * n_buy_sell, float)
close_cost = np.array([None] * n_buy_sell, float)
long_short = np.array([0] * n_buy_sell, int)
current_holding = 0
j = 0
for i in range(len(order)):
sign_holding = int(np.sign(current_holding))
# np.sign Returns an element-wise indication of the sign of a number.
if order[i] == 'Buy':
close_pos = (sign_holding < 0) * -current_holding
close_time[j - close_pos:j] = time[i]
close_price[j - close_pos:j] = price[i]
close_cost[j - close_pos:j] = cost[i]
trade_time[j] = time[i]
trade_price[j] = price[i]
long_short[j] = 1
trade_cost[j] = cost[i]
buy_sell = close_pos + 1
current_holding = current_holding + buy_sell
j += 1
elif order[i] == 'Sell':
close_pos = (sign_holding > 0) * -current_holding
close_time[j + close_pos:j] = time[i]
close_price[j + close_pos:j] = price[i]
close_cost[j + close_pos:j] = cost[i]
trade_time[j] = time[i]
trade_price[j] = price[i]
long_short[j] = -1
trade_cost[j] = cost[i]
buy_sell = close_pos - 1
current_holding = current_holding + buy_sell
j += 1
else:
close_pos = abs(current_holding)
close_time[j - close_pos:j] = time[i]
close_price[j - close_pos:j] = price[i]
close_cost[j - close_pos:j] = cost[i]
current_holding = 0
profit = (close_price - trade_price) * long_short
trade_record = {'trade_time' : trade_time,
'trade_price': trade_price,
'close_time' : close_time,
'close_price': close_price,
'long_short' : long_short,
'trade_cost' : trade_cost,
'close_cost' : close_cost,
'profit' : profit}
return trade_record
@staticmethod
def get_indices(index, n_hist, n_forward):
assert n_hist <= index, 'Error:Invalid number of historical observations.'
start_hist = index - n_hist
end_hist = index
start_forward = index
end_forward = index + n_forward
return start_hist, end_hist, start_forward, end_forward
def process(self, n_hist, n_forward, trade_th, stop_loss, cl, transaction_cost, index=None, **kwargs):
#index = random.randint(n_hist, len(self.x) - n_forward) if index is None else index
start_hist, end_hist, start_forward, end_forward = self.get_indices(index, n_hist, n_forward)
self.calibrate(start_hist, end_hist, cl)
self.reward = 0
self.record = None
if self.MTR_variables:
self.p_values_MTR.append(self.p)
if self.p < cl:
time, price, order, gross_exp, cost = self.gen_signal(start_forward, end_forward, trade_th, stop_loss, transaction_cost)
# The first index of trade_record will be start_forward + 1 because the time that gen_signal returns is t_t1[ind_order].
# and t_t1 = time[1:]
trade_record = self.gen_trade_record(time, price, order, cost)
returns = (trade_record['profit'] -
trade_record['trade_cost'] -
trade_record['close_cost']) / abs(trade_record['trade_price'])
if (len(returns) > 0) and (np.any(np.isnan(returns)) is not True):
#self.reward = min(returns.mean(), 10)
self.reward = returns.mean()
self.record = trade_record | 42.437637 | 134 | 0.53728 |
acec8c207a18d8e87a7bf4047e59d163d8b715c2 | 10,709 | py | Python | api/namex/models/request.py | ericminio/namex | 09da6b5f6476494d13ec2243934c51e0423340cd | [
"Apache-2.0"
] | null | null | null | api/namex/models/request.py | ericminio/namex | 09da6b5f6476494d13ec2243934c51e0423340cd | [
"Apache-2.0"
] | null | null | null | api/namex/models/request.py | ericminio/namex | 09da6b5f6476494d13ec2243934c51e0423340cd | [
"Apache-2.0"
] | null | null | null | """Request is the main business class that is the real top level object in the system
"""
from . import db, ma
from flask import current_app
from namex.exceptions import BusinessException
from sqlalchemy import Sequence
from sqlalchemy.orm import backref
from marshmallow import Schema, fields, post_load, post_dump
from .nwpta import PartnerNameSystem
from .user import User, UserSchema
from .comment import Comment, CommentSchema
from .applicant import Applicant
from .name import Name, NameSchema
from .state import State, StateSchema
from datetime import datetime
# create sequence if not exists nr_seq;
# noinspection PyPep8Naming
class Request(db.Model):
__tablename__ = 'requests'
# Field names use a JSON / JavaScript naming pattern,
# as opposed to the common python Snake_case
# core fields
id = db.Column(db.Integer, primary_key=True)
submittedDate = db.Column('submitted_date', db.DateTime, default=datetime.utcnow, index=True)
lastUpdate = db.Column('last_update', db.DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
nrNum = db.Column('nr_num', db.String(10), unique=True)
requestTypeCd = db.Column('request_type_cd', db.String(10))
priorityCd = db.Column('priority_cd', db.String(2))
priorityDate = db.Column('priority_date', db.DateTime(timezone=True))
expirationDate = db.Column('expiration_date', db.DateTime(timezone=True))
consentFlag = db.Column('consent_flag', db.String(1))
additionalInfo = db.Column('additional_info', db.String(150))
natureBusinessInfo = db.Column('nature_business_info', db.String(1000))
xproJurisdiction = db.Column('xpro_jurisdiction', db.String(40))
corpNum = db.Column('corp_num', db.String(20), default=None)
submitter_userid = db.Column('submitter_userid', db.Integer, db.ForeignKey('users.id'))
#legacy sync tracking
furnished = db.Column('furnished', db.String(1), default='N', index=True)
# Flag to indicate this NR has been reset. Cleared upon submission, so it is only true after
# reset before subsequent examination is complete.
hasBeenReset = db.Column('has_been_reset', db.Boolean, default=False)
# parent keys
userId = db.Column('user_id', db.Integer, db.ForeignKey('users.id'), index=True)
# legacy fields
requestId = db.Column('request_id', db.Integer)
previousRequestId = db.Column('previous_request_id', db.Integer)
submitCount = db.Column('submit_count', db.Integer)
nroLastUpdate = db.Column('nro_last_update', db.DateTime)
# Relationship State
stateCd = db.Column('state_cd', db.String(40), db.ForeignKey('states.cd'), index=True)
# previous state, used when editing NR in certain scenarios
previousStateCd = db.Column('prev_state_cd', db.String(40), nullable=True)
# Relationships - Users
activeUser = db.relationship('User', backref=backref('active_user', uselist=False), foreign_keys=[userId])
submitter = db.relationship('User', backref=backref('submitter', uselist=False), foreign_keys=[submitter_userid])
# Relationships - Names
names = db.relationship('Name', lazy='dynamic')
# Relationships - Applicants
applicants = db.relationship('Applicant', lazy='dynamic')
# Relationships - Examiner Comments
comments = db.relationship('Comment', lazy='dynamic', order_by="Comment.timestamp")
# Relationships - Examiner Comments
partnerNS = db.relationship('PartnerNameSystem', lazy='dynamic')
##### end of table definitions
REQUEST_FURNISHED = 'Y'
def __init__(self, *args, **kwargs):
pass
def json(self):
# get previous NR number from legacy requestId and previousRequestId fields
previousNr = None
if self.previousRequestId:
previousNr = self.query.filter_by(requestId=self.previousRequestId).first()
try:
# we just want the NR number, or null if it doesn't exist
previousNr = previousNr.nrNum
except:
previousNr = None
return {'id' : self.id,
'submittedDate' : self.submittedDate,
'lastUpdate' : self.lastUpdate,
'userId' : '' if (self.activeUser is None) else self.activeUser.username,
'submitter_userid' : '' if (self.submitter is None) else self.submitter.username,
'state' : self.stateCd,
'previousStateCd': self.previousStateCd,
'nrNum' : self.nrNum,
'consentFlag' : self.consentFlag,
'expirationDate' : self.expirationDate,
'requestTypeCd' : self.requestTypeCd,
'priorityCd' : self.priorityCd,
'priorityDate': self.priorityDate,
'xproJurisdiction' : self.xproJurisdiction,
'additionalInfo' : self.additionalInfo,
'natureBusinessInfo' : self.natureBusinessInfo,
'furnished': self.furnished if (self.furnished is not None) else 'N',
'hasBeenReset': self.hasBeenReset,
'previousRequestId': self.previousRequestId,
'previousNr': previousNr,
'submitCount': self.submitCount,
'corpNum': self.corpNum,
'names': [name.as_dict() for name in self.names.all()],
'applicants': '' if (self.applicants.one_or_none() is None) else self.applicants.one_or_none().as_dict(),
'comments': [comment.as_dict() for comment in self.comments.all()],
'nwpta': [partner_name.as_dict() for partner_name in self.partnerNS.all()]
}
@classmethod
def find_by_nr(cls, nr):
return cls.query.filter_by(nrNum=nr).one_or_none()
def save_to_db(self):
# if self.id is None:
# NR is not the primary key, but has to be a unique value.
# seq = Sequence('nr_seq')
# next_nr = db.engine.execute(seq)
# self.nr = 'NR{0:0>8}'.format(next_nr)
db.session.add(self)
db.session.commit()
def delete_from_db(self):
#TODO: Add listener onto the SQLALchemy event to block deletes
raise BusinessException({"code": "cannot_delete_nr",
"description":
"NRs cannot be deleted, maybe try cancelling instead"},
403)
@classmethod
def get_queued_oldest(cls, userObj):
"""Gets the Next NR# from the database
It sets the STATUS == INPROGRESS
and then returns the NR or
error out with a SQLAlchemy Error type
"""
existing_nr = Request.get_inprogress(userObj)
if existing_nr:
current_app.logger.info('Existing NR found, returning: {}'.format(existing_nr.nrNum))
return existing_nr, False
# this will error if there's nothing in the queue - likelihood ~ 0
r = db.session.query(Request).\
filter(Request.stateCd.in_([State.DRAFT])).\
order_by(Request.priorityCd.desc(), Request.submittedDate.asc()).\
with_for_update().first()
# this row is now locked
if not r:
raise BusinessException(None, 404)
# mark this as assigned to the user, masking it from others.
r.stateCd= State.INPROGRESS
r.userId = userObj.id
db.session.add(r)
db.session.commit()
return r, True
@classmethod
def get_inprogress(cls, userObj):
"""Gets the Next NR# from the database
where the STATUS == INPROGRESS
and assigned to the user
this assumes that a user can ONLY EVER have 1 Request in progress at a time.
"""
existing_nr = db.session.query(Request).\
filter(Request.userId == userObj.id, Request.stateCd == State.INPROGRESS).\
one_or_none()
return existing_nr
@classmethod
def find_name(cls, nr, choice):
return cls.query.filter_by(nrNum=nr).names.filter_by(choice=choice).one_or_none()
@classmethod
def validNRFormat(cls, nr):
'''NR should be of the format "NR 1234567"
'''
if len(nr) != 10 or nr[:2] != 'NR' or nr[2:3] != ' ':
return False
try:
num = int(nr[3:])
except:
return False
return True
class RequestsSchema(ma.ModelSchema):
class Meta:
model = Request
additional = ['stateCd']
names = ma.Nested(NameSchema, many=True)
activeUser = ma.Nested(UserSchema, many=False, only='username')
submitter = ma.Nested(UserSchema, many=False, only='username')
comments = ma.Nested(CommentSchema, many=True, only=['comment', 'examiner', 'timestamp'])
@post_dump
def clean_missing(self, data):
ret = data.copy()
for key in filter(lambda key: data[key] is None, data):
del ret[key]
return ret
class RequestsHeaderSchema(ma.ModelSchema):
class Meta:
model = Request
# sqla_session = db.scoped_session
# additional = ['stateCd']
fields = ('additionalInfo'
,'consentFlag'
,'corpNum'
,'expirationDate'
,'furnished'
,'hasBeenReset'
,'id'
,'natureBusinessInfo'
,'nrNum'
,'nroLastUpdate'
,'priorityCd'
,'requestTypeCd'
,'stateCd'
,'previousStateCd'
,'submitCount'
,'submittedDate'
,'xproJurisdiction'
)
class RequestsSearchSchema(ma.ModelSchema):
class Meta:
model = Request
# sqla_session = db.scoped_session
# additional = ['stateCd']
fields = ('additionalInfo'
,'comments'
,'consentFlag'
,'corpNum'
,'expirationDate'
,'furnished'
,'lastUpdate'
,'natureBusinessInfo'
,'nrNum'
,'nroLastUpdate'
,'priorityCd'
,'priorityDate'
,'requestTypeCd'
,'stateCd'
,'submitCount'
,'submittedDate'
,'xproJurisdiction'
,'names'
,'activeUser'
)
names = ma.Nested(NameSchema, many=True)
activeUser = ma.Nested(UserSchema, many=False, only='username')
comments = ma.Nested(CommentSchema, many=True, only=['comment', 'examiner', 'timestamp'])
| 38.66065 | 121 | 0.606312 |
acec8ca4bef68cbfa4f370898920bd4632e1ec1f | 9,553 | py | Python | checkerista/.env/Lib/site-packages/sqlparse/filters/reindent.py | LybaFatimaNasir/CS311S20PID02 | bc29a8c4c9ee508c74d231c015a57b1ca4dfcb39 | [
"MIT"
] | 746 | 2017-12-02T06:02:05.000Z | 2022-03-29T06:59:03.000Z | checkerista/.env/Lib/site-packages/sqlparse/filters/reindent.py | LybaFatimaNasir/CS311S20PID02 | bc29a8c4c9ee508c74d231c015a57b1ca4dfcb39 | [
"MIT"
] | 123 | 2019-09-10T14:48:01.000Z | 2019-11-28T21:24:06.000Z | checkerista/.env/Lib/site-packages/sqlparse/filters/reindent.py | LybaFatimaNasir/CS311S20PID02 | bc29a8c4c9ee508c74d231c015a57b1ca4dfcb39 | [
"MIT"
] | 363 | 2017-12-10T01:08:17.000Z | 2022-03-26T05:25:00.000Z | # -*- coding: utf-8 -*-
#
# Copyright (C) 2009-2018 the sqlparse authors and contributors
# <see AUTHORS file>
#
# This module is part of python-sqlparse and is released under
# the BSD License: https://opensource.org/licenses/BSD-3-Clause
from sqlparse import sql, tokens as T
from sqlparse.compat import text_type
from sqlparse.utils import offset, indent
class ReindentFilter(object):
def __init__(self, width=2, char=' ', wrap_after=0, n='\n',
comma_first=False, indent_after_first=False,
indent_columns=False):
self.n = n
self.width = width
self.char = char
self.indent = 1 if indent_after_first else 0
self.offset = 0
self.wrap_after = wrap_after
self.comma_first = comma_first
self.indent_columns = indent_columns
self._curr_stmt = None
self._last_stmt = None
self._last_func = None
def _flatten_up_to_token(self, token):
"""Yields all tokens up to token but excluding current."""
if token.is_group:
token = next(token.flatten())
for t in self._curr_stmt.flatten():
if t == token:
break
yield t
@property
def leading_ws(self):
return self.offset + self.indent * self.width
def _get_offset(self, token):
raw = u''.join(map(text_type, self._flatten_up_to_token(token)))
line = (raw or '\n').splitlines()[-1]
# Now take current offset into account and return relative offset.
return len(line) - len(self.char * self.leading_ws)
def nl(self, offset=0):
return sql.Token(
T.Whitespace,
self.n + self.char * max(0, self.leading_ws + offset))
def _next_token(self, tlist, idx=-1):
split_words = ('FROM', 'STRAIGHT_JOIN$', 'JOIN$', 'AND', 'OR',
'GROUP BY', 'ORDER BY', 'UNION', 'VALUES',
'SET', 'BETWEEN', 'EXCEPT', 'HAVING', 'LIMIT')
m_split = T.Keyword, split_words, True
tidx, token = tlist.token_next_by(m=m_split, idx=idx)
if token and token.normalized == 'BETWEEN':
tidx, token = self._next_token(tlist, tidx)
if token and token.normalized == 'AND':
tidx, token = self._next_token(tlist, tidx)
return tidx, token
def _split_kwds(self, tlist):
tidx, token = self._next_token(tlist)
while token:
pidx, prev_ = tlist.token_prev(tidx, skip_ws=False)
uprev = text_type(prev_)
if prev_ and prev_.is_whitespace:
del tlist.tokens[pidx]
tidx -= 1
if not (uprev.endswith('\n') or uprev.endswith('\r')):
tlist.insert_before(tidx, self.nl())
tidx += 1
tidx, token = self._next_token(tlist, tidx)
def _split_statements(self, tlist):
ttypes = T.Keyword.DML, T.Keyword.DDL
tidx, token = tlist.token_next_by(t=ttypes)
while token:
pidx, prev_ = tlist.token_prev(tidx, skip_ws=False)
if prev_ and prev_.is_whitespace:
del tlist.tokens[pidx]
tidx -= 1
# only break if it's not the first token
if prev_:
tlist.insert_before(tidx, self.nl())
tidx += 1
tidx, token = tlist.token_next_by(t=ttypes, idx=tidx)
def _process(self, tlist):
func_name = '_process_{cls}'.format(cls=type(tlist).__name__)
func = getattr(self, func_name.lower(), self._process_default)
func(tlist)
def _process_where(self, tlist):
tidx, token = tlist.token_next_by(m=(T.Keyword, 'WHERE'))
# issue121, errors in statement fixed??
tlist.insert_before(tidx, self.nl())
with indent(self):
self._process_default(tlist)
def _process_parenthesis(self, tlist):
ttypes = T.Keyword.DML, T.Keyword.DDL
_, is_dml_dll = tlist.token_next_by(t=ttypes)
fidx, first = tlist.token_next_by(m=sql.Parenthesis.M_OPEN)
with indent(self, 1 if is_dml_dll else 0):
tlist.tokens.insert(0, self.nl()) if is_dml_dll else None
with offset(self, self._get_offset(first) + 1):
self._process_default(tlist, not is_dml_dll)
def _process_function(self, tlist):
self._last_func = tlist[0]
self._process_default(tlist)
def _process_identifierlist(self, tlist):
identifiers = list(tlist.get_identifiers())
if self.indent_columns:
first = next(identifiers[0].flatten())
num_offset = 1 if self.char == '\t' else self.width
else:
first = next(identifiers.pop(0).flatten())
num_offset = 1 if self.char == '\t' else self._get_offset(first)
if not tlist.within(sql.Function) and not tlist.within(sql.Values):
with offset(self, num_offset):
position = 0
for token in identifiers:
# Add 1 for the "," separator
position += len(token.value) + 1
if position > (self.wrap_after - self.offset):
adjust = 0
if self.comma_first:
adjust = -2
_, comma = tlist.token_prev(
tlist.token_index(token))
if comma is None:
continue
token = comma
tlist.insert_before(token, self.nl(offset=adjust))
if self.comma_first:
_, ws = tlist.token_next(
tlist.token_index(token), skip_ws=False)
if (ws is not None
and ws.ttype is not T.Text.Whitespace):
tlist.insert_after(
token, sql.Token(T.Whitespace, ' '))
position = 0
else:
# ensure whitespace
for token in tlist:
_, next_ws = tlist.token_next(
tlist.token_index(token), skip_ws=False)
if token.value == ',' and not next_ws.is_whitespace:
tlist.insert_after(
token, sql.Token(T.Whitespace, ' '))
end_at = self.offset + sum(len(i.value) + 1 for i in identifiers)
adjusted_offset = 0
if (self.wrap_after > 0
and end_at > (self.wrap_after - self.offset)
and self._last_func):
adjusted_offset = -len(self._last_func.value) - 1
with offset(self, adjusted_offset), indent(self):
if adjusted_offset < 0:
tlist.insert_before(identifiers[0], self.nl())
position = 0
for token in identifiers:
# Add 1 for the "," separator
position += len(token.value) + 1
if (self.wrap_after > 0
and position > (self.wrap_after - self.offset)):
adjust = 0
tlist.insert_before(token, self.nl(offset=adjust))
position = 0
self._process_default(tlist)
def _process_case(self, tlist):
iterable = iter(tlist.get_cases())
cond, _ = next(iterable)
first = next(cond[0].flatten())
with offset(self, self._get_offset(tlist[0])):
with offset(self, self._get_offset(first)):
for cond, value in iterable:
token = value[0] if cond is None else cond[0]
tlist.insert_before(token, self.nl())
# Line breaks on group level are done. let's add an offset of
# len "when ", "then ", "else "
with offset(self, len("WHEN ")):
self._process_default(tlist)
end_idx, end = tlist.token_next_by(m=sql.Case.M_CLOSE)
if end_idx is not None:
tlist.insert_before(end_idx, self.nl())
def _process_values(self, tlist):
tlist.insert_before(0, self.nl())
tidx, token = tlist.token_next_by(i=sql.Parenthesis)
first_token = token
while token:
ptidx, ptoken = tlist.token_next_by(m=(T.Punctuation, ','),
idx=tidx)
if ptoken:
if self.comma_first:
adjust = -2
offset = self._get_offset(first_token) + adjust
tlist.insert_before(ptoken, self.nl(offset))
else:
tlist.insert_after(ptoken,
self.nl(self._get_offset(token)))
tidx, token = tlist.token_next_by(i=sql.Parenthesis, idx=tidx)
def _process_default(self, tlist, stmts=True):
self._split_statements(tlist) if stmts else None
self._split_kwds(tlist)
for sgroup in tlist.get_sublists():
self._process(sgroup)
def process(self, stmt):
self._curr_stmt = stmt
self._process(stmt)
if self._last_stmt is not None:
nl = '\n' if text_type(self._last_stmt).endswith('\n') else '\n\n'
stmt.tokens.insert(0, sql.Token(T.Whitespace, nl))
self._last_stmt = stmt
return stmt
| 39.475207 | 78 | 0.539307 |
acec8d252b51859aef0e7d7d02905fcea35bfb44 | 3,334 | py | Python | devsearch/devsearch/settings.py | KivutiBrian/DevSearch | 925d214054e79a276083b4e15b2405605c4ca8b7 | [
"MIT"
] | null | null | null | devsearch/devsearch/settings.py | KivutiBrian/DevSearch | 925d214054e79a276083b4e15b2405605c4ca8b7 | [
"MIT"
] | null | null | null | devsearch/devsearch/settings.py | KivutiBrian/DevSearch | 925d214054e79a276083b4e15b2405605c4ca8b7 | [
"MIT"
] | null | null | null | """
Django settings for devsearch project.
Generated by 'django-admin startproject' using Django 4.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-$o0=qv!7tkk914u*w#=@s(qp(83pc3($=miqt#7@u4_!z9ewm-'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'projects.apps.ProjectsConfig'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'devsearch.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'devsearch.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
| 25.844961 | 91 | 0.69766 |
acec8d64040ae5777599978dcc7cc5f2a2e50ba1 | 801 | py | Python | src/flockwave/ext/errors.py | skybrush-io/flockwave-ext | 5a34c2df538edd7f521f8ff453e66f47aea62272 | [
"MIT"
] | null | null | null | src/flockwave/ext/errors.py | skybrush-io/flockwave-ext | 5a34c2df538edd7f521f8ff453e66f47aea62272 | [
"MIT"
] | null | null | null | src/flockwave/ext/errors.py | skybrush-io/flockwave-ext | 5a34c2df538edd7f521f8ff453e66f47aea62272 | [
"MIT"
] | null | null | null | __all__ = ("ExtensionError", "ApplicationExit", "NoSuchExtension", "NotSupportedError")
class ExtensionError(RuntimeError):
"""Superclass for errors related to the extension manager."""
pass
class ApplicationExit(ExtensionError):
"""Special exception that can be thrown from the `load()` or `unload()`
method of an extension to request the host application to exit.
"""
pass
class NoSuchExtension(ExtensionError):
"""Error thrown by the extension module finder when there is no extension
module for a given extension name.
"""
pass
class NotSupportedError(ExtensionError):
"""Special exception that can be thrown from the `unload()` method of an
extension to indicate that the extension is essential and cannot be unloaded.
"""
pass
| 25.03125 | 87 | 0.716604 |
acec8ea2f62250907226b606550036a71793fece | 2,815 | py | Python | src/metpy/constants/default.py | tjturnage/MetPy | 096be48de7f3ff895b689a881fe7b3b1acb4da12 | [
"BSD-3-Clause"
] | 1 | 2022-02-22T08:09:32.000Z | 2022-02-22T08:09:32.000Z | src/metpy/constants/default.py | tjturnage/MetPy | 096be48de7f3ff895b689a881fe7b3b1acb4da12 | [
"BSD-3-Clause"
] | 24 | 2022-02-01T08:03:22.000Z | 2022-03-29T12:36:34.000Z | src/metpy/constants/default.py | tjturnage/MetPy | 096be48de7f3ff895b689a881fe7b3b1acb4da12 | [
"BSD-3-Clause"
] | null | null | null | # Copyright (c) 2008,2015,2016,2018,2021 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Constant and thermophysical property values expressed as quantities."""
from ..package_tools import Exporter
from ..units import units
exporter = Exporter(globals())
# Export all the variables defined in this block
with exporter:
# Earth
earth_gravity = g = units.Quantity(9.80665, 'm / s^2')
Re = earth_avg_radius = units.Quantity(6371008.7714, 'm')
G = gravitational_constant = units.Quantity(6.67430e-11, 'm^3 / kg / s^2')
GM = geocentric_gravitational_constant = units.Quantity(3986005e8, 'm^3 / s^2')
omega = earth_avg_angular_vel = units.Quantity(7292115e-11, 'rad / s')
d = earth_sfc_avg_dist_sun = units.Quantity(149597870700., 'm')
S = earth_solar_irradiance = units.Quantity(1360.8, 'W / m^2')
delta = earth_max_declination = units.Quantity(23.45, 'degrees')
earth_orbit_eccentricity = units.Quantity(0.0167, 'dimensionless')
earth_mass = me = geocentric_gravitational_constant / gravitational_constant
# molar gas constant
R = units.Quantity(8.314462618, 'J / mol / K')
# Water
Mw = water_molecular_weight = units.Quantity(18.015268, 'g / mol')
Rv = water_gas_constant = R / Mw
rho_l = density_water = units.Quantity(999.97495, 'kg / m^3')
wv_specific_heat_ratio = units.Quantity(1.330, 'dimensionless')
Cp_v = wv_specific_heat_press = (
wv_specific_heat_ratio * Rv / (wv_specific_heat_ratio - 1)
)
Cv_v = wv_specific_heat_vol = Cp_v / wv_specific_heat_ratio
Cp_l = water_specific_heat = units.Quantity(4.2194, 'kJ / kg / K')
Lv = water_heat_vaporization = units.Quantity(2.50084e6, 'J / kg')
Lf = water_heat_fusion = units.Quantity(3.337e5, 'J / kg')
Cp_i = ice_specific_heat = units.Quantity(2090, 'J / kg / K')
rho_i = density_ice = units.Quantity(917, 'kg / m^3')
sat_pressure_0c = units.Quantity(6.112, 'millibar')
# Dry air
Md = dry_air_molecular_weight = units.Quantity(28.96546e-3, 'kg / mol')
Rd = dry_air_gas_constant = R / Md
dry_air_spec_heat_ratio = units.Quantity(1.4, 'dimensionless')
Cp_d = dry_air_spec_heat_press = (
dry_air_spec_heat_ratio * Rd / (dry_air_spec_heat_ratio - 1)
)
Cv_d = dry_air_spec_heat_vol = Cp_d / dry_air_spec_heat_ratio
rho_d = dry_air_density_stp = (
units.Quantity(1000., 'mbar') / (Rd * units.Quantity(273.15, 'K'))
).to('kg / m^3')
# General meteorology constants
P0 = pot_temp_ref_press = units.Quantity(1000., 'mbar')
kappa = poisson_exponent = (Rd / Cp_d).to('dimensionless')
gamma_d = dry_adiabatic_lapse_rate = g / Cp_d
epsilon = molecular_weight_ratio = (Mw / Md).to('dimensionless')
del Exporter
| 44.68254 | 83 | 0.694494 |
acec8f302d4193e26c09f8434b42c9d5872bc5fe | 1,927 | py | Python | aioairctrl/coap/encryption.py | rkuralev/aioairctrl | daa0e1c4fbb051126f19764720765f708e8ba4fc | [
"MIT"
] | 4 | 2021-10-17T14:05:18.000Z | 2021-12-05T10:34:29.000Z | aioairctrl/coap/encryption.py | rkuralev/aioairctrl | daa0e1c4fbb051126f19764720765f708e8ba4fc | [
"MIT"
] | 3 | 2021-04-23T23:44:54.000Z | 2022-02-11T12:10:09.000Z | aioairctrl/coap/encryption.py | rkuralev/aioairctrl | daa0e1c4fbb051126f19764720765f708e8ba4fc | [
"MIT"
] | 13 | 2021-02-25T21:10:21.000Z | 2022-03-18T07:34:30.000Z | import hashlib
from Cryptodome.Cipher import AES
from Cryptodome.Util.Padding import pad, unpad
class DigestMismatchException(Exception):
pass
class EncryptionContext:
SECRET_KEY = "JiangPan"
def __init__(self):
self._client_key = None
def set_client_key(self, client_key):
self._client_key = client_key
def _increment_client_key(self):
client_key_next = (int(self._client_key, 16) + 1).to_bytes(4, byteorder="big").hex().upper()
self._client_key = client_key_next
def _create_cipher(self, key: str):
key_and_iv = hashlib.md5((self.SECRET_KEY + key).encode()).hexdigest().upper()
half_keylen = len(key_and_iv) // 2
secret_key = key_and_iv[0:half_keylen]
iv = key_and_iv[half_keylen:]
cipher = AES.new(
key=secret_key.encode(),
mode=AES.MODE_CBC,
iv=iv.encode(),
)
return cipher
def encrypt(self, payload: str) -> str:
self._increment_client_key()
key = self._client_key
plaintext_padded = pad(payload.encode(), 16, style="pkcs7")
cipher = self._create_cipher(key)
ciphertext = cipher.encrypt(plaintext_padded).hex().upper()
digest = hashlib.sha256((key + ciphertext).encode()).hexdigest().upper()
return key + ciphertext + digest
def decrypt(self, payload_encrypted: str) -> str:
key = payload_encrypted[0:8]
ciphertext = payload_encrypted[8:-64]
digest = payload_encrypted[-64:]
digest_calculated = hashlib.sha256((key + ciphertext).encode()).hexdigest().upper()
if digest != digest_calculated:
raise DigestMismatchException
cipher = self._create_cipher(key)
plaintext_padded = cipher.decrypt(bytes.fromhex(ciphertext))
plaintext_unpadded = unpad(plaintext_padded, 16, style="pkcs7")
return plaintext_unpadded.decode()
| 34.410714 | 100 | 0.654385 |
acec8fc7f4795ce0b42b79a7aa59ada0080d23bc | 162 | py | Python | test_scm/hello.py | xkortex/test_scm | 2252ab3b53b3cda31fdd82ebc90d3c113bd8d987 | [
"MIT"
] | null | null | null | test_scm/hello.py | xkortex/test_scm | 2252ab3b53b3cda31fdd82ebc90d3c113bd8d987 | [
"MIT"
] | null | null | null | test_scm/hello.py | xkortex/test_scm | 2252ab3b53b3cda31fdd82ebc90d3c113bd8d987 | [
"MIT"
] | null | null | null | from test_scm import __version__
def main():
print("hello from test_scm iter {} version {}".format(1, __version__))
if __name__ == "__main__":
main()
| 16.2 | 74 | 0.67284 |
acec923ae5f0442f58581209f14b50cf1afa055a | 1,536 | py | Python | cirq/sim/clifford/stabilizer_state_ch_form_test.py | lilies/Cirq | 519b8b70ba4d2d92d1c034c398161ebdbd23e2e7 | [
"Apache-2.0"
] | 3 | 2020-09-26T03:56:28.000Z | 2020-09-27T13:21:04.000Z | cirq/sim/clifford/stabilizer_state_ch_form_test.py | lilies/Cirq | 519b8b70ba4d2d92d1c034c398161ebdbd23e2e7 | [
"Apache-2.0"
] | null | null | null | cirq/sim/clifford/stabilizer_state_ch_form_test.py | lilies/Cirq | 519b8b70ba4d2d92d1c034c398161ebdbd23e2e7 | [
"Apache-2.0"
] | 1 | 2020-04-14T15:29:29.000Z | 2020-04-14T15:29:29.000Z | # Copyright 2020 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import pytest
import cirq
import cirq.testing
# TODO: This and clifford tableau need tests.
# Github issue: https://github.com/quantumlib/Cirq/issues/3021
def test_deprecated():
with cirq.testing.assert_logs('wave_function', 'state_vector',
'deprecated'):
_ = cirq.StabilizerStateChForm(initial_state=0,
num_qubits=1).wave_function()
def test_initial_state():
with pytest.raises(ValueError, match='Out of range'):
_ = cirq.StabilizerStateChForm(initial_state=-31, num_qubits=5)
with pytest.raises(ValueError, match='Out of range'):
_ = cirq.StabilizerStateChForm(initial_state=32, num_qubits=5)
state = cirq.StabilizerStateChForm(initial_state=23, num_qubits=5)
expected_state_vector = np.zeros(32)
expected_state_vector[23] = 1
np.testing.assert_allclose(state.state_vector(), expected_state_vector)
| 37.463415 | 75 | 0.720703 |
acec927890c0004adcb654abf03e4409ad8c5333 | 1,018 | py | Python | python/phonenumbers/shortdata/region_TW.py | rodgar-nvkz/python-phonenumbers | 4c7c4892211dbc9bc328bc3356b03853eaf993dc | [
"Apache-2.0"
] | 2,424 | 2015-01-05T05:34:45.000Z | 2022-03-28T22:37:53.000Z | python/phonenumbers/shortdata/region_TW.py | rodgar-nvkz/python-phonenumbers | 4c7c4892211dbc9bc328bc3356b03853eaf993dc | [
"Apache-2.0"
] | 166 | 2015-01-30T23:59:18.000Z | 2022-03-14T21:08:42.000Z | python/phonenumbers/shortdata/region_TW.py | rodgar-nvkz/python-phonenumbers | 4c7c4892211dbc9bc328bc3356b03853eaf993dc | [
"Apache-2.0"
] | 345 | 2015-01-02T00:33:27.000Z | 2022-03-26T13:06:57.000Z | """Auto-generated file, do not edit by hand. TW metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_TW = PhoneMetadata(id='TW', country_code=None, international_prefix=None,
general_desc=PhoneNumberDesc(national_number_pattern='1\\d{2,3}', possible_length=(3, 4)),
toll_free=PhoneNumberDesc(national_number_pattern='11[0289]|1(?:81|92)\\d', example_number='110', possible_length=(3, 4)),
premium_rate=PhoneNumberDesc(national_number_pattern='10[56]', example_number='105', possible_length=(3,)),
emergency=PhoneNumberDesc(national_number_pattern='11[029]', example_number='110', possible_length=(3,)),
short_code=PhoneNumberDesc(national_number_pattern='1(?:0[04-6]|1[0237-9]|3[389]|6[05-8]|7[07]|8(?:0|11)|9(?:19|22|5[057]|68|8[05]|9[15689]))', example_number='100', possible_length=(3, 4)),
standard_rate=PhoneNumberDesc(national_number_pattern='1(?:65|9(?:1\\d|50|85|98))', example_number='165', possible_length=(3, 4)),
short_data=True)
| 84.833333 | 194 | 0.740668 |
acec93d8fd26ebe2246b2ecc6e56313c5c621f71 | 2,574 | py | Python | chemistry_methods/editable_molecules.py | hasic-haris/one_step_retrosynth_ai | 1c931bf5a4ddf74bfb628329a7646e258caf4e71 | [
"MIT"
] | 10 | 2020-10-18T10:18:52.000Z | 2021-12-03T15:44:11.000Z | chemistry_methods/editable_molecules.py | hasic-haris/one_step_retrosynth_ai | 1c931bf5a4ddf74bfb628329a7646e258caf4e71 | [
"MIT"
] | 1 | 2021-03-24T19:42:17.000Z | 2021-03-25T00:07:21.000Z | chemistry_methods/editable_molecules.py | hasic-haris/one_step_retrosynth_ai | 1c931bf5a4ddf74bfb628329a7646e258caf4e71 | [
"MIT"
] | 1 | 2020-11-07T11:09:34.000Z | 2020-11-07T11:09:34.000Z | """
Author: Haris Hasic, Phd Student @ Ishida Laboratory, Department of Computer Science, Tokyo Institute of Technology
Created on: March 10th, 2020
Description: This file contains necessary functions for handling RDKit editable RWMol molecule objects.
"""
from rdkit.Chem import AllChem
def get_atoms_to_remove(editable_mol):
""" Fetches all of the bonds that were marked for removal by the wildcard symbol '*'. """
atoms_to_remove = []
for atom in editable_mol.GetAtoms():
if atom.GetSymbol() == "*":
atoms_to_remove.append(atom.GetIdx())
# Return the descending sorted list of atom indices to avoid errors during the removal of the atoms.
return sorted(list(set(atoms_to_remove)), reverse=True)
def get_bonds_to_remove(editable_mol):
""" Fetches all of the bonds that were marked for removal by the wildcard symbol '*'. """
bonds_to_remove = []
for bond in editable_mol.GetBonds():
if editable_mol.GetAtomWithIdx(bond.GetBeginAtomIdx()).GetSymbol() == "*" and \
editable_mol.GetAtomWithIdx(bond.GetEndAtomIdx()).GetSymbol() == "*":
bonds_to_remove.append((bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()))
# Return the descending sorted list of bond atom indices to avoid errors during the removal of the bond atoms.
return sorted(list(set(bonds_to_remove)), key=lambda k: k[0], reverse=True)
def remove_floating_atoms(editable_mol):
""" Removes the leftover wildcard atoms '*' that are fully disconnected from the rest of the molecule. """
leftover_floating_atoms = sorted([atom.GetIdx() for atom in editable_mol.GetAtoms()
if atom.GetSymbol() == "*" and atom.GetDegree() == 0], reverse=True)
[editable_mol.RemoveAtom(rm_atom) for rm_atom in leftover_floating_atoms]
def remove_marked_atoms(editable_mol):
""" Removes the all of the bonds that were marked for removal by the wildcard symbol '*'. """
[editable_mol.RemoveAtom(rm_atom) for rm_atom in get_atoms_to_remove(editable_mol)]
# Sanitize the modified molecule.
AllChem.SanitizeMol(editable_mol)
def remove_marked_bonds(editable_mol):
""" Removes the all of the bonds that were marked for removal by the wildcard symbol '*'. """
[editable_mol.RemoveBond(rm_bond[0], rm_bond[1]) for rm_bond in get_bonds_to_remove(editable_mol)]
# Clean the editable mol from fully disconnected wildcard atoms '*'.
remove_floating_atoms(editable_mol)
# Sanitize the modified molecule.
AllChem.SanitizeMol(editable_mol)
| 39.6 | 120 | 0.716006 |
acec95e5d80038188eed1ac407066e69d61b1740 | 3,304 | py | Python | lib/pipeline/augment_test.py | rusty1s/embedded_gcnn | 06db3799e794d6ebcd9db023ebd8b0937587df94 | [
"MIT"
] | 74 | 2017-03-07T07:06:15.000Z | 2022-01-21T07:37:33.000Z | lib/pipeline/augment_test.py | DeepaliVerma/embedded_gcnn | 06db3799e794d6ebcd9db023ebd8b0937587df94 | [
"MIT"
] | 9 | 2017-07-01T11:22:18.000Z | 2020-03-31T04:48:52.000Z | lib/pipeline/augment_test.py | DeepaliVerma/embedded_gcnn | 06db3799e794d6ebcd9db023ebd8b0937587df94 | [
"MIT"
] | 12 | 2018-01-09T08:06:27.000Z | 2022-02-25T01:49:35.000Z | from unittest import TestCase
import numpy as np
from numpy import pi as PI
from numpy.testing import assert_equal, assert_almost_equal
import scipy.sparse as sp
from .augment import (flip_left_right_adj, random_flip_left_right_adjs,
adjust_brightness, random_brightness, adjust_contrast,
random_contrast, augment_batch)
class AugmentTest(TestCase):
def test_flip_left_right_adj(self):
adj = [[0, 0.25 * PI, 0.75 * PI], [1.25 * PI, 0, 0], [1.75 * PI, 0, 0]]
adj = sp.coo_matrix(adj)
output = flip_left_right_adj(adj)
expected = [[0, 1.75 * PI, 1.25 * PI], [0.75 * PI, 0, 0],
[0.25 * PI, 0, 0]]
assert_equal(output.toarray(), expected)
# Flip left right is mutable, so we create a new adjacency matrix.
adj = [[0, 0.25 * PI, 0.75 * PI], [1.25 * PI, 0, 0], [1.75 * PI, 0, 0]]
adj = sp.coo_matrix(adj)
assert_equal(
random_flip_left_right_adjs([adj], True)[0].toarray(), expected)
assert_equal(
random_flip_left_right_adjs([adj], False)[0].toarray(),
adj.toarray())
random = random_flip_left_right_adjs([adj])[0].toarray()
adj = [[0, 0.25 * PI, 0.75 * PI], [1.25 * PI, 0, 0], [1.75 * PI, 0, 0]]
self.assertTrue(
np.array_equal(random, adj) or np.array_equal(random, expected))
def test_adjust_brightness(self):
features = np.array([[0.2, 0.4, 0.6, 1], [0.3, 0.2, 0.5, 2]])
output = adjust_brightness(features, 0, 3, delta=0.5)
assert_almost_equal(output, [[0.7, 0.9, 1, 1], [0.8, 0.7, 1, 2]])
self.assertGreaterEqual(
random_brightness(features, 0, 3, 0.5).min(), 0)
self.assertLessEqual(random_brightness(features, 0, 3, 0.5).min(), 1)
def test_adjust_contrast(self):
features = np.array([[0.2, 0.4, 0.6, 1], [0.3, 0.2, 0.5, 2]])
output = adjust_contrast(features, 0, 3, delta=-0.5)
assert_almost_equal(output, [[0.225, 0.35, 0.575, 1],
[0.275, 0.25, 0.525, 2]])
self.assertGreaterEqual(random_contrast(features, 0, 3, 0.5).min(), 0)
self.assertLessEqual(random_contrast(features, 0, 3, 0.5).min(), 1)
def test_augment_batch(self):
features = np.array([[0.2, 0.4], [0.3, 0.2], [0.8, 0.9]])
adj_dist = [[0, 1, 2], [1, 0, 0], [2, 0, 0]]
adj_dist = sp.coo_matrix(adj_dist)
adj_rad = [[0, 0.25 * PI, 0.75 * PI], [1.25 * PI, 0, 0],
[1.75 * PI, 0, 0]]
adj_rad = sp.coo_matrix(adj_rad)
label = np.array([0, 0, 1])
batch = augment_batch([(features, [adj_dist], [adj_rad], label)])
expected = [[0, 1.75 * PI, 1.25 * PI], [0.75 * PI, 0, 0],
[0.25 * PI, 0, 0]]
adj_rad = [[0, 0.25 * PI, 0.75 * PI], [1.25 * PI, 0, 0],
[1.75 * PI, 0, 0]]
self.assertGreaterEqual(batch[0][0].min(), 0)
self.assertLessEqual(batch[0][0].max(), 1)
assert_equal(batch[0][1][0].toarray(), adj_dist.toarray())
self.assertTrue(
np.array_equal(batch[0][2][0].toarray(), expected) or
np.array_equal(batch[0][2][0].toarray(), adj_rad))
assert_equal(batch[0][3], label)
| 38.870588 | 79 | 0.549939 |
acec95fed9031d91444c85258dfb0d5e84d0d618 | 494 | py | Python | vilya/views/api/repos/push.py | mubashshirjamal/code | d9c7adf7efed8e9c1ab3ff8cdeb94e7eb1a45382 | [
"BSD-3-Clause"
] | 1,582 | 2015-01-05T02:41:44.000Z | 2022-03-30T20:03:22.000Z | vilya/views/api/repos/push.py | mubashshirjamal/code | d9c7adf7efed8e9c1ab3ff8cdeb94e7eb1a45382 | [
"BSD-3-Clause"
] | 66 | 2015-01-23T07:58:04.000Z | 2021-11-12T02:23:27.000Z | vilya/views/api/repos/push.py | mubashshirjamal/code | d9c7adf7efed8e9c1ab3ff8cdeb94e7eb1a45382 | [
"BSD-3-Clause"
] | 347 | 2015-01-05T07:47:07.000Z | 2021-09-20T21:22:32.000Z | # -*- coding: utf-8 -*-
from vilya.views.api.utils import RestAPIUI
class PushUI(RestAPIUI):
_q_exports = []
_q_methods = ['get', 'post', 'delete']
def __init__(self, repo):
self.repo = repo
def get(self, request):
return {'content': self.repo.can_push}
def post(self, request):
self.repo.update_can_push(True)
return {'content': 1}
def delete(self, request):
self.repo.update_can_push(False)
return {'content': 0}
| 21.478261 | 46 | 0.603239 |
acec97544b2d2744d0760179a996fcb0924678bc | 2,658 | py | Python | moocng/contact/forms.py | OpenMOOC/moocng | 1e3dafb84aa1838c881df0c9bcca069e47c7f52d | [
"Apache-2.0"
] | 36 | 2015-01-10T06:00:36.000Z | 2020-03-19T10:06:59.000Z | moocng/contact/forms.py | OpenMOOC/moocng | 1e3dafb84aa1838c881df0c9bcca069e47c7f52d | [
"Apache-2.0"
] | 3 | 2015-10-01T17:59:32.000Z | 2018-09-04T03:32:17.000Z | moocng/contact/forms.py | OpenMOOC/moocng | 1e3dafb84aa1838c881df0c9bcca069e47c7f52d | [
"Apache-2.0"
] | 17 | 2015-01-13T03:46:58.000Z | 2020-07-05T06:29:51.000Z | # Copyright 2013 UNED
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django import forms
from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ugettext
from moocng.courses.models import Course
from moocng.contact.models import CommunicationType
from moocng.forms import BootstrapMixin
def get_terms_of_use_link():
from django.core.urlresolvers import reverse
link = reverse('tos')
text = ugettext('See Terms of Use')
return mark_safe('<a href="%s">%s</a>' % (link, force_unicode(text)))
class ContactForm(forms.Form, BootstrapMixin):
course = forms.ChoiceField(
label=_(u'Course'),
required=True,
)
username = forms.CharField(label=_(u'Username'))
sender = forms.EmailField(label=_(u'Email'))
communication_type = forms.ModelChoiceField(
label=_(u'Communication type'),
required=True,
queryset=CommunicationType.objects.all(),
empty_label=' ',
)
message = forms.CharField(
label=_(u'Message'),
widget=forms.Textarea(attrs={'class': 'input-xxlarge'}),
)
tos = forms.BooleanField(
label=_('I have read and agree with the terms of use'),
help_text=_('See Terms of Use'),
required=True,
error_messages={'required': _('You must accept the Terms of Use')},
)
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
# the help_text can not be computed at import time because
# it needs to call reverse() and that would create circular
# imports
self.fields['tos'].help_text = get_terms_of_use_link()
# This is a really dirty hack to obtain all the published courses
# and insert the first empty option plus an "Other" option at the
# end.
all_courses = [(c.name,c.name) for c in Course.objects.filter(status='p')]
all_courses.insert(0, ('', ' '))
all_courses.append((_('Other'),_('Other')))
self.fields['course'].choices = all_courses
| 36.410959 | 82 | 0.687735 |
acec977dff82b4184b96d45a489f52cccce3ad72 | 743 | py | Python | other-libraries/learn-pandas/part 5/main.py | Ace5584/Machine-Learning-Notes | 8d721895165833f6ea2ac3c75326ec5ed29111eb | [
"Apache-2.0"
] | 2 | 2021-10-01T07:28:58.000Z | 2022-01-23T00:20:34.000Z | other-libraries/learn-pandas/part 5/main.py | Ace5584/Machine-Learning-Notes | 8d721895165833f6ea2ac3c75326ec5ed29111eb | [
"Apache-2.0"
] | null | null | null | other-libraries/learn-pandas/part 5/main.py | Ace5584/Machine-Learning-Notes | 8d721895165833f6ea2ac3c75326ec5ed29111eb | [
"Apache-2.0"
] | null | null | null | #------------------------------#
# Conditional changes and #
# Aggregate Statistics(groupby)#
# And working with large #
# amounts of data. #
#------------------------------#
import pandas as pd
df = pd.read_csv('C:/src/learn-pandas/pandas code/modified.csv')
#df.loc[df['Type 1'] == 'Fire', 'Type 1'] = 'Flamer'
#df.loc[df['Type 1'] == 'Fire', 'Legendary'] = True
#df.loc[df['Total'] > 500, ['Generation', 'Legendary']] = ['Test 1', 'Test 2']
# Changing Specific word in the csv
df['count'] = 1
print(df.groupby(['Type 1']).sum())
print(df.groupby(['Type 1']).mean().sort_values('Defense', ascending=False))
print(df.groupby(['Type 1']).count()['count'])
print(df.groupby(['Type 1', 'Type 2']).count()['count'])
| 29.72 | 78 | 0.56393 |
acec9896169b8bd014cdbb4363b29d6d6c8a4781 | 8,016 | py | Python | examples/svm/plot_rbf_parameters.py | NickVeld/scikit-learn-proj | 9694a5641a7abbec96c93817aed88ce827dbacd3 | [
"BSD-3-Clause"
] | 1 | 2021-11-26T12:22:13.000Z | 2021-11-26T12:22:13.000Z | examples/svm/plot_rbf_parameters.py | NickVeld/scikit-learn-proj | 9694a5641a7abbec96c93817aed88ce827dbacd3 | [
"BSD-3-Clause"
] | null | null | null | examples/svm/plot_rbf_parameters.py | NickVeld/scikit-learn-proj | 9694a5641a7abbec96c93817aed88ce827dbacd3 | [
"BSD-3-Clause"
] | null | null | null | '''
==================
RBF SVM parameters
==================
This example illustrates the effect of the parameters ``gamma`` and ``C`` of
the Radial Basis Function (RBF) kernel SVM.
Intuitively, the ``gamma`` parameter defines how far the influence of a single
training example reaches, with low values meaning 'far' and high values meaning
'close'. The ``gamma`` parameters can be seen as the inverse of the radius of
influence of samples selected by the model as support vectors.
The ``C`` parameter trades off misclassification of training examples against
simplicity of the decision surface. A low ``C`` makes the decision surface
smooth, while a high ``C`` aims at classifying all training examples correctly
by giving the model freedom to select more samples as support vectors.
The first plot is a visualization of the decision function for a variety of
parameter values on a simplified classification problem involving only 2 input
features and 2 possible target classes (binary classification). Note that this
kind of plot is not possible to do for problems with more features or target
classes.
The second plot is a heatmap of the classifier's cross-validation accuracy as a
function of ``C`` and ``gamma``. For this example we explore a relatively large
grid for illustration purposes. In practice, a logarithmic grid from
:math:`10^{-3}` to :math:`10^3` is usually sufficient. If the best parameters
lie on the boundaries of the grid, it can be extended in that direction in a
subsequent search.
Note that the heat map plot has a special colorbar with a midpoint value close
to the score values of the best performing models so as to make it easy to tell
them appart in the blink of an eye.
The behavior of the model is very sensitive to the ``gamma`` parameter. If
``gamma`` is too large, the radius of the area of influence of the support
vectors only includes the support vector itself and no amount of
regularization with ``C`` will be able to prevent overfitting.
When ``gamma`` is very small, the model is too constrained and cannot capture
the complexity or "shape" of the data. The region of influence of any selected
support vector would include the whole training set. The resulting model will
behave similarly to a linear model with a set of hyperplanes that separate the
centers of high density of any pair of two classes.
For intermediate values, we can see on the second plot that good models can
be found on a diagonal of ``C`` and ``gamma``. Smooth models (lower ``gamma``
values) can be made more complex by selecting a larger number of support
vectors (larger ``C`` values) hence the diagonal of good performing models.
Finally one can also observe that for some intermediate values of ``gamma`` we
get equally performing models when ``C`` becomes very large: it is not
necessary to regularize by limiting the number of support vectors. The radius of
the RBF kernel alone acts as a good structural regularizer. In practice though
it might still be interesting to limit the number of support vectors with a
lower value of ``C`` so as to favor models that use less memory and that are
faster to predict.
We should also note that small differences in scores results from the random
splits of the cross-validation procedure. Those spurious variations can be
smoothed out by increasing the number of CV iterations ``n_splits`` at the
expense of compute time. Increasing the value number of ``C_range`` and
``gamma_range`` steps will increase the resolution of the hyper-parameter heat
map.
'''
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
from sklearn.svm import SVC
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_iris
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.model_selection import GridSearchCV
# Utility function to move the midpoint of a colormap to be around
# the values of interest.
class MidpointNormalize(Normalize):
def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
self.midpoint = midpoint
Normalize.__init__(self, vmin, vmax, clip)
def __call__(self, value, clip=None):
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y))
##############################################################################
# Load and prepare data set
#
# dataset for grid search
iris = load_iris()
X = iris.data
y = iris.target
# Dataset for decision function visualization: we only keep the first two
# features in X and sub-sample the dataset to keep only 2 classes and
# make it a binary classification problem.
X_2d = X[:, :2]
X_2d = X_2d[y > 0]
y_2d = y[y > 0]
y_2d -= 1
# It is usually a good idea to scale the data for SVM training.
# We are cheating a bit in this example in scaling all of the data,
# instead of fitting the transformation on the training set and
# just applying it on the test set.
scaler = StandardScaler()
X = scaler.fit_transform(X)
X_2d = scaler.fit_transform(X_2d)
##############################################################################
# Train classifiers
#
# For an initial search, a logarithmic grid with basis
# 10 is often helpful. Using a basis of 2, a finer
# tuning can be achieved but at a much higher cost.
C_range = np.logspace(-2, 10, 13)
gamma_range = np.logspace(-9, 3, 13)
param_grid = dict(gamma=gamma_range, C=C_range)
cv = StratifiedShuffleSplit(n_splits=5, test_size=0.2, random_state=42)
grid = GridSearchCV(SVC(), param_grid=param_grid, cv=cv)
grid.fit(X, y)
print("The best parameters are %s with a score of %0.2f"
% (grid.best_params_, grid.best_score_))
# Now we need to fit a classifier for all parameters in the 2d version
# (we use a smaller set of parameters here because it takes a while to train)
C_2d_range = [1e-2, 1, 1e2]
gamma_2d_range = [1e-1, 1, 1e1]
classifiers = []
for C in C_2d_range:
for gamma in gamma_2d_range:
clf = SVC(C=C, gamma=gamma)
clf.fit(X_2d, y_2d)
classifiers.append((C, gamma, clf))
##############################################################################
# visualization
#
# draw visualization of parameter effects
plt.figure(figsize=(8, 6))
xx, yy = np.meshgrid(np.linspace(-3, 3, 200), np.linspace(-3, 3, 200))
for (k, (C, gamma, clf)) in enumerate(classifiers):
# evaluate decision function in a grid
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
# visualize decision function for these parameters
plt.subplot(len(C_2d_range), len(gamma_2d_range), k + 1)
plt.title("gamma=10^%d, C=10^%d" % (np.log10(gamma), np.log10(C)),
size='medium')
# visualize parameter's effect on decision function
plt.pcolormesh(xx, yy, -Z, cmap=plt.cm.RdBu)
plt.scatter(X_2d[:, 0], X_2d[:, 1], c=y_2d, cmap=plt.cm.RdBu_r)
plt.xticks(())
plt.yticks(())
plt.axis('tight')
scores = grid.cv_results_['mean_test_score'].reshape(len(C_range),
len(gamma_range))
# Draw heatmap of the validation accuracy as a function of gamma and C
#
# The score are encoded as colors with the hot colormap which varies from dark
# red to bright yellow. As the most interesting scores are all located in the
# 0.92 to 0.97 range we use a custom normalizer to set the mid-point to 0.92 so
# as to make it easier to visualize the small variations of score values in the
# interesting range while not brutally collapsing all the low score values to
# the same color.
plt.figure(figsize=(8, 6))
plt.subplots_adjust(left=.2, right=0.95, bottom=0.15, top=0.95)
plt.imshow(scores, interpolation='nearest', cmap=plt.cm.hot,
norm=MidpointNormalize(vmin=0.2, midpoint=0.92))
plt.xlabel('gamma')
plt.ylabel('C')
plt.colorbar()
plt.xticks(np.arange(len(gamma_range)), gamma_range, rotation=45)
plt.yticks(np.arange(len(C_range)), C_range)
plt.title('Validation accuracy')
plt.show()
| 40.690355 | 80 | 0.71744 |
acec98b95cd8469fa94fe97d52b043046867e2f0 | 743 | py | Python | brochure/value_fetchers/section_repository_interface.py | GreenLightSoftware/brochure | 925b55650d321f10b2cb4d2dcd8e11854634382c | [
"MIT"
] | null | null | null | brochure/value_fetchers/section_repository_interface.py | GreenLightSoftware/brochure | 925b55650d321f10b2cb4d2dcd8e11854634382c | [
"MIT"
] | null | null | null | brochure/value_fetchers/section_repository_interface.py | GreenLightSoftware/brochure | 925b55650d321f10b2cb4d2dcd8e11854634382c | [
"MIT"
] | null | null | null | from abc import ABCMeta, abstractmethod
from brochure.values.section import Section
class SectionRepositoryInterface(metaclass=ABCMeta):
@abstractmethod
def create_cover_section(self,
title: str,
body: str) -> int: # pragma: no cover
pass
@abstractmethod
def create_section(self,
title: str,
body: str,
parent_section_identifier: int) -> int: # pragma: no cover
pass
@abstractmethod
def fetch_cover_section(self) -> Section: # pragma: no cover
pass
@abstractmethod
def fetch_section(self, identifier: int) -> Section: # pragma: no cover
pass
| 27.518519 | 82 | 0.576043 |
acec98bd327f5fdf755ae951b71c65f517fb7846 | 961 | py | Python | agents/RLAgent.py | Mog333/DeepRL | 398914e4c475108e7fdebfb0d376595130dbb2b5 | [
"MIT"
] | null | null | null | agents/RLAgent.py | Mog333/DeepRL | 398914e4c475108e7fdebfb0d376595130dbb2b5 | [
"MIT"
] | null | null | null | agents/RLAgent.py | Mog333/DeepRL | 398914e4c475108e7fdebfb0d376595130dbb2b5 | [
"MIT"
] | null | null | null | ###
# Author: Robert Post
###
'''
This is a simple base class for a Reinforcement Learning Agent
It acts randomly
'''
import numpy as np
class RLAgent(object):
def __init__(self, actionList):
self.actionList = actionList
self.numActions = len(actionList)
def agentCleanup(self):
pass
def startEpisode(self, observation):
pass
def endEpisode(self, reward):
pass
'''
This function receives the reward and next state and returns the action to take
'''
def stepEpisode(self, reward, observation):
actionIndex = np.random.randint(self.numActions)
self.lastActionIndexTaken = actionIndex
return self.actionList[actionIndex]
def startLearningEpoch(self, epochNumber):
pass
def endLearningEpoch(self, epochNumber):
pass
def startEvaluationEpoch(self, epochNumber):
pass
def endEvaluationEpoch(self, epochNumber):
pass
| 23.439024 | 83 | 0.668054 |
acec98d011b3b52aa848f9ca4a6b4352eb14c2c7 | 1,762 | py | Python | src/uploader.py | ESPuPy/RAWImageConverter | 653b61c708b83ad69c41983eda809a837b93c703 | [
"MIT"
] | null | null | null | src/uploader.py | ESPuPy/RAWImageConverter | 653b61c708b83ad69c41983eda809a837b93c703 | [
"MIT"
] | null | null | null | src/uploader.py | ESPuPy/RAWImageConverter | 653b61c708b83ad69c41983eda809a837b93c703 | [
"MIT"
] | null | null | null | #----------------------------------
# function: uploader
# receive the RAW image data and save to S3
#
#----------------------------------
import json
import boto3
import base64
import datetime
ENABLE_AUTH = True
BUCKET_NAME = '__buketName__' # set your S3 Bucket Name e.g wificambucket
API_KEY = 'setYourAPIKey' # set your API key
def lambda_handler(event, context):
#for Debug
#print(event)
#print(event['body'])
#check API KEY
if ENABLE_AUTH:
if (not 'API-Key' in event['headers'])\
or (event['headers']['API-Key'] != API_KEY):
return {
'statusCode': 401,
'body': json.dumps('Unauthorized')
}
#check media type
if (not 'Content-type' in event['headers'])\
or (event['headers']['Content-type'] != 'application/octet-stream')\
or (not 'isBase64Encoded' in event)\
or (event['isBase64Encoded'] != True):
return {
'statusCode': 415,
'body': json.dumps('unsupported media type')
}
imgData = base64.b64decode(event['body'])
# for Debug, write to logfile data type and length
print(type(imgData))
print(len(imgData))
bucketName = BUCKET_NAME
tz_jst = datetime.timezone(datetime.timedelta(hours=+9))
dt = datetime.datetime.now(tz_jst)
folderName = 'rawdata' + '/' + dt.strftime('%Y%m')
fileName = dt.strftime('%y%m%d_%H%M%S') + ".raw"
key = folderName + '/' + fileName
s3 = boto3.resource('s3')
obj = s3.Object(bucketName,key)
obj.put(Body = imgData)
return {
'statusCode': 200,
'body': json.dumps('upload complete')
}
| 28.885246 | 77 | 0.541998 |
acec99fd42f07f91961aeb05b84f562f03194e07 | 1,514 | py | Python | migrations/versions/2502578e99fb_initial_migration.py | Gichimu/cupidr-dating-app | 5244bf7ca340606c3edf75c724c610afdc263de1 | [
"MIT"
] | 2 | 2021-03-26T21:18:15.000Z | 2022-03-23T11:58:00.000Z | migrations/versions/2502578e99fb_initial_migration.py | Gichimu/cupidr-dating-app | 5244bf7ca340606c3edf75c724c610afdc263de1 | [
"MIT"
] | 10 | 2019-12-07T02:13:38.000Z | 2019-12-07T02:25:58.000Z | migrations/versions/2502578e99fb_initial_migration.py | Gichimu/cupidr-dating-app | 5244bf7ca340606c3edf75c724c610afdc263de1 | [
"MIT"
] | 5 | 2019-12-02T20:13:28.000Z | 2021-01-15T12:03:12.000Z | """initial migration
Revision ID: 2502578e99fb
Revises:
Create Date: 2019-12-04 17:01:34.114701
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2502578e99fb'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('users',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('username', sa.String(length=80), nullable=True),
sa.Column('email', sa.String(length=80), nullable=True),
sa.Column('password_secure', sa.String(length=255), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True)
op.create_table('qualities',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('age', sa.Integer(), nullable=True),
sa.Column('gender', sa.String(length=10), nullable=True),
sa.Column('complexion', sa.String(length=10), nullable=True),
sa.Column('personality', sa.String(length=50), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('qualities')
op.drop_index(op.f('ix_users_email'), table_name='users')
op.drop_table('users')
# ### end Alembic commands ###
| 31.541667 | 76 | 0.673052 |
acec9a25fc6e68d065569bd3e5fdb40896310770 | 16,856 | py | Python | vizier/api/webservice/workflow.py | VizierDB/web-api-async | e99f43df3df80ad5647f57d805c339257336ac73 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2019-10-21T03:01:39.000Z | 2020-06-05T01:43:00.000Z | vizier/api/webservice/workflow.py | VizierDB/web-api-async | e99f43df3df80ad5647f57d805c339257336ac73 | [
"ECL-2.0",
"Apache-2.0"
] | 56 | 2019-07-12T21:16:03.000Z | 2020-11-06T23:29:22.000Z | vizier/api/webservice/workflow.py | VizierDB/web-api-async | e99f43df3df80ad5647f57d805c339257336ac73 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2020-02-07T19:56:55.000Z | 2020-08-07T11:17:51.000Z | # Copyright (C) 2017-2019 New York University,
# University at Buffalo,
# Illinois Institute of Technology.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Vizier Workflow API - Implements all methods of the API to interact with
workflows in vizier projects.
"""
from typing import TYPE_CHECKING, List, Optional, Dict, Any
if TYPE_CHECKING:
from vizier.view.chart import ChartViewHandle
from vizier.viztrail.workflow import WorkflowHandle
from vizier.viztrail.command import ModuleCommand
import vizier.api.serialize.module as serialmd
import vizier.api.serialize.workflow as serialwf
from vizier.engine.base import VizierEngine
from vizier.api.routes.base import UrlFactory
class VizierWorkflowApi(object):
"""The Vizier workflow API implements the methods that correspond to
requests that access and manipulate workflows in vizier projects.
"""
def __init__(self,
engine: VizierEngine,
urls: UrlFactory
):
"""Initialize the API components.
Parameters
----------
engine: vizier.engine.base.VizierEngine
Instance of the API engine
urls: vizier.api.routes.base.UrlFactory
Factory for resource urls
"""
self.engine = engine
self.urls = urls
def append_workflow_module(self,
project_id: str,
branch_id: str,
package_id: str,
command_id: str,
arguments: List[Dict[str, Any]]
) -> Optional[Dict[str, Any]]:
"""Append a new module to the head of the identified project branch.
The module command is identified by the package and command identifier.
Arguments is a list of command arguments.
Raises ValueError if the command is unknown or the command arguments
cannot be validated.
Parameters
----------
project_id : string
Unique project identifier
branch_id: string
Unique workflow branch identifier
package_id: string
Unique package identifier
command_id: string
Unique command identifier
arguments: list
List of dictionaries representing the user-provided command
arguments
Returns
-------
dict()
"""
# Retrieve the project and branch from the repository to ensure that
# they exist. Run this part first to ensure that all requested resources
# exist before validating the command.
project = self.engine.projects.get_project(project_id)
if project is None:
return None
branch = project.viztrail.get_branch(branch_id)
if branch is None:
return None
# Create module command (will ensure that it is a valid command) and
# append it to the workflow at the branch head. The result is the handle
# for the modified workflow.
self.engine.append_workflow_module(
project_id=project_id,
branch_id=branch_id,
command=ModuleCommand(
package_id=package_id,
command_id=command_id,
arguments=arguments,
packages=self.engine.packages
)
)
return serialwf.WORKFLOW_HANDLE(
project=project,
branch=branch,
workflow=branch.get_head(),
urls=self.urls
)
def cancel_workflow(self, project_id, branch_id):
"""Cancel execution for all running and pending modules in the head
workflow of a given project branch.
Returns a handle for the resulting workflow.
Parameters
----------
project_id : string
Unique project identifier
branch_id: string
Unique workflow branch identifier
Returns
-------
dict()
"""
# Retrieve the project and branch from the repository to ensure that
# they exist.
project = self.engine.projects.get_project(project_id)
if project is None:
return None
branch = project.viztrail.get_branch(branch_id)
if branch is None:
return None
# Cancel excecution and return the workflow handle
self.engine.cancel_exec(
project_id=project_id,
branch_id=branch_id
)
return serialwf.WORKFLOW_HANDLE(
project=project,
branch=branch,
workflow=branch.head,
urls=self.urls
)
def delete_workflow_module(self, project_id, branch_id, module_id):
"""Delete a module in the head workflow of the identified project
branch.
Returns the handle for the modified head of the workflow branch. The
result is None if either of the identified resources is unknown.
Parameters
----------
project_id : string
Unique project identifier
branch_id: string
Unique workflow branch identifier
module_id: string, optional
Unique identifier for module
Returns
-------
dict
"""
# Retrieve the project and branch from the repository to ensure that
# they exist.
project = self.engine.projects.get_project(project_id)
if project is None:
return None
branch = project.viztrail.get_branch(branch_id)
if branch is None:
return None
# Delete the module
modules = self.engine.delete_workflow_module(
project_id=project_id,
branch_id=branch_id,
module_id=module_id
)
if not modules is None:
return serialwf.WORKFLOW_HANDLE(
project=project,
branch=branch,
workflow=branch.head,
urls=self.urls
)
return None
def get_workflow(self, project_id, branch_id, workflow_id=None):
"""Retrieve a workflow from a given project branch. If the workflow
identifier is omitted, the handle for the head of the branch is
returned.
Returns None if the project, branch, or workflow do not exist.
Parameters
----------
project_id : string
Unique project identifier
branch_id: string
Unique workflow branch identifier
workflow_id: string, optional
Unique identifier for workflow
Returns
-------
dict
"""
# Retrieve the project and branch from the repository to ensure that
# they exist.
project = self.engine.projects.get_project(project_id)
if project is None:
return None
branch = project.viztrail.get_branch(branch_id)
if branch is None:
return None
# If the branch is empty we return a special empty workflow handle
if branch.head is None:
return serialwf.EMPTY_WORKFLOW_HANDLE(
project=project,
branch=branch,
urls=self.urls
)
else:
if workflow_id is None:
workflow = branch.head
else:
workflow = branch.get_workflow(workflow_id)
if workflow is not None:
return serialwf.WORKFLOW_HANDLE(
project=project,
branch=branch,
workflow=workflow,
urls=self.urls
)
return None
def get_workflow_module(self, project_id, branch_id, module_id):
"""Get handle for a module in the head workflow of a given project
branch. The result is a pair of module handle and list of dataset
descriptors for the datasets in the module state (if the module is
not active and not in an error state).
Returns None if the project, branch, or module do not exist.
Parameters
----------
project_id : string
Unique project identifier
branch_id: string
Unique workflow branch identifier
module_id: string, optional
Unique identifier for module
Returns
-------
dict
"""
# Retrieve the project from the repository to ensure that it exists
project = self.engine.projects.get_project(project_id)
if project is None:
return None
# Get the specified branch to ensure that it exists
branch = project.viztrail.get_branch(branch_id)
if branch is None:
return None
# If the branch is empty we return a special empty workflow handle
if not branch.head is None:
workflow = branch.head
for module in workflow.modules:
if module.identifier == module_id:
charts = list()
if module.is_success:
# Compute available charts only if the module is in
# a success state.
charts = get_module_charts(workflow, module_id)
return serialmd.MODULE_HANDLE(
project=project,
branch=branch,
module=module,
urls=self.urls,
workflow=workflow,
charts=charts,
include_self=True
)
return None
def insert_workflow_module(self, project_id, branch_id, before_module_id, package_id, command_id, arguments):
"""Append a new module to the head of the identified project branch.
The module command is identified by the package and command identifier.
Arguments is a list of command arguments.
Raises ValueError if the command is unknown or the command arguments
cannot be validated.
Parameters
----------
project_id : string
Unique project identifier
branch_id: string
Unique workflow branch identifier
package_id: string
Unique package identifier
command_id: string
Unique command identifier
arguments: list
List of dictionaries representing the user-provided command
arguments
Returns
-------
dict()
"""
# Retrieve the project and branch from the repository to ensure that
# they exist. Run this part first to ensure that all requested resources
# exist before validating the command.
project = self.engine.projects.get_project(project_id)
if project is None:
return None
branch = project.viztrail.get_branch(branch_id)
if branch is None:
return None
# Create module command (will ensure that it is a valid command) and
# insert it into the workflow at the branch head. The result is the list
# of affected modules.
modules = self.engine.insert_workflow_module(
project_id=project_id,
branch_id=branch_id,
before_module_id=before_module_id,
command=ModuleCommand(
package_id=package_id,
command_id=command_id,
arguments=arguments,
packages=self.engine.packages
),
)
if not modules is None:
return serialwf.WORKFLOW_HANDLE(
project=project,
branch=branch,
workflow=branch.head,
urls=self.urls
)
return None
def replace_workflow_module(self, project_id, branch_id, module_id, package_id, command_id, arguments):
"""Append a new module to the head of the identified project branch.
The module command is identified by the package and command identifier.
Arguments is a list of command arguments.
Raises ValueError if the command is unknown or the command arguments
cannot be validated.
Parameters
----------
project_id : string
Unique project identifier
branch_id: string
Unique workflow branch identifier
package_id: string
Unique package identifier
command_id: string
Unique command identifier
arguments: list
List of dictionaries representing the user-provided command
arguments
Returns
-------
dict()
"""
# Retrieve the project and branch from the repository to ensure that
# they exist. Run this part first to ensure that all requested resources
# exist before validating the command.
project = self.engine.projects.get_project(project_id)
if project is None:
return None
branch = project.viztrail.get_branch(branch_id)
if branch is None:
return None
# Create module command (will ensure that it is a valid command) and
# replace it in the workflow at the branch head. The result is the list
# of affected modules.
modules = self.engine.replace_workflow_module(
project_id=project_id,
branch_id=branch_id,
module_id=module_id,
command=ModuleCommand(
package_id=package_id,
command_id=command_id,
arguments=arguments,
packages=self.engine.packages
)
)
if not modules is None:
return serialwf.WORKFLOW_HANDLE(
project=project,
branch=branch,
workflow=branch.head,
urls=self.urls
)
return None
def query_workflow(self,
query: str,
project_id: str,
branch_id: str,
workflow_id: Optional[str] = None
) -> Dict[str, Any]:
"""Run a SQL query against the state of the workflow at its
tail. Analous to creating a SQL cell, but just a read-only
interrogation of the state rather than a mutation
returns a Mimir Data Container
"""
project = self.engine.projects.get_project(project_id)
if project is None:
raise Exception("Unknown project id: {}".format(project_id))
branch = project.viztrail.get_branch(branch_id)
if branch is None:
raise Exception("Unknown branch id: {}".format(branch_id))
if workflow_id is None:
workflow = branch.get_head()
else:
workflow = branch.get_workflow(workflow_id)
if workflow is None:
raise Exception("Unknown workflow id {}".format(workflow_id))
return project.datastore.query(query, workflow.tail_datasets)
# ------------------------------------------------------------------------------
# Helper Methods
# ------------------------------------------------------------------------------
def get_module_charts(
workflow: "WorkflowHandle",
module_id: str
) -> List["ChartViewHandle"]:
"""Get the list of charts that are available for a given module.
Parameters
----------
workflow: vizier.viztrail.workflow.WorkflowHandle
Handle for workflow containing the module
module_id: string
Unique module identifier
Returns
-------
list(vizier.view.chart.ChartViewHandle)
"""
result = list()
charts = dict()
datasets = list()
for m in workflow.modules:
if not m.provenance.charts is None:
for chart_name, chart in m.provenance.charts:
charts[chart_name] = chart
for artifact in m.artifacts:
if artifact.is_dataset:
datasets.append(artifact.name)
# Only include charts for modules that have any datasets. Otherwise the
# result is empty by definition.
if m.identifier == module_id:
for c_handle in list(charts.values()):
if c_handle.dataset_name in datasets:
result.append(c_handle)
break
return result
| 35.337526 | 113 | 0.590591 |
acec9a412bcde5dc5ee4f7cd53baaf49c4b1074d | 4,543 | py | Python | utils/kitti_segnet.py | mengli/MachineLearning | 107a5be76aabbfd57a6395a6b7e1b9c55e06bbad | [
"Apache-2.0"
] | 28 | 2017-02-19T13:06:25.000Z | 2021-09-02T09:02:48.000Z | utils/kitti_segnet.py | mengli/MachineLearning | 107a5be76aabbfd57a6395a6b7e1b9c55e06bbad | [
"Apache-2.0"
] | null | null | null | utils/kitti_segnet.py | mengli/MachineLearning | 107a5be76aabbfd57a6395a6b7e1b9c55e06bbad | [
"Apache-2.0"
] | 17 | 2017-02-19T10:44:11.000Z | 2019-11-09T16:39:50.000Z | import tensorflow as tf
from tensorflow.python.framework import ops
from tensorflow.python.framework import dtypes
IMAGE_HEIGHT = 375
IMAGE_WIDTH = 1242
IMAGE_DEPTH = 3
NUM_CLASSES = 3
NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = 100
NUM_EXAMPLES_PER_EPOCH_FOR_TEST = 100
NUM_EXAMPLES_PER_EPOCH_FOR_EVAL = 100
def _generate_image_and_label_batch(image, label, min_queue_examples,
batch_size, shuffle):
"""Construct a queued batch of images and labels.
Args:
image: 3-D Tensor of [height, width, 3] of type.float32.
label: 3-D Tensor of [height, width, 1] type.int32
min_queue_examples: int32, minimum number of samples to retain
in the queue that provides of batches of examples.
batch_size: Number of images per batch.
shuffle: boolean indicating whether to use a shuffling queue.
Returns:
images: Images. 4D tensor of [batch_size, height, width, 3] size.
labels: Labels. 3D tensor of [batch_size, height, width ,1] size.
"""
# Create a queue that shuffles the examples, and then
# read 'batch_size' images + labels from the example queue.
num_preprocess_threads = 1
if shuffle:
images, label_batch = tf.train.shuffle_batch(
[image, label],
batch_size=batch_size,
num_threads=num_preprocess_threads,
capacity=min_queue_examples + 3 * batch_size,
min_after_dequeue=min_queue_examples)
else:
images, label_batch = tf.train.batch(
[image, label],
batch_size=batch_size,
num_threads=num_preprocess_threads,
capacity=min_queue_examples + 3 * batch_size)
return images, label_batch
def CamVid_reader_seq(filename_queue, seq_length):
image_seq_filenames = tf.split(axis=0,
num_or_size_splits=seq_length,
value=filename_queue[0])
label_seq_filenames = tf.split(axis=0,
num_or_size_splits=seq_length,
value=filename_queue[1])
image_seq = []
label_seq = []
for im ,la in zip(image_seq_filenames, label_seq_filenames):
imageValue = tf.read_file(tf.squeeze(im))
labelValue = tf.read_file(tf.squeeze(la))
image_bytes = tf.image.decode_png(imageValue)
label_bytes = tf.image.decode_png(labelValue)
image = tf.cast(tf.reshape(image_bytes,
(IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_DEPTH)), tf.float32)
label = tf.cast(tf.reshape(label_bytes,
(IMAGE_HEIGHT, IMAGE_WIDTH, 1)), tf.int64)
image_seq.append(image)
label_seq.append(label)
return image_seq, label_seq
def CamVid_reader(filename_queue):
image_filename = filename_queue[0]
label_filename = filename_queue[1]
imageValue = tf.read_file(image_filename)
labelValue = tf.read_file(label_filename)
image_bytes = tf.image.decode_png(imageValue)
label_bytes = tf.image.decode_png(labelValue)
image = tf.reshape(image_bytes, (IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_DEPTH))
label = tf.reshape(label_bytes, (IMAGE_HEIGHT, IMAGE_WIDTH, 1))
return image, label
def get_filename_list(path):
fd = open(path)
image_filenames = []
label_filenames = []
for i in fd:
i = i.strip().split(" ")
image_filenames.append(i[0])
label_filenames.append(i[1])
return image_filenames, label_filenames
def CamVidInputs(image_filenames, label_filenames, batch_size, shuffle=True):
images = ops.convert_to_tensor(image_filenames, dtype=dtypes.string)
labels = ops.convert_to_tensor(label_filenames, dtype=dtypes.string)
filename_queue = tf.train.slice_input_producer([images, labels], shuffle=shuffle)
image, label = CamVid_reader(filename_queue)
reshaped_image = tf.cast(image, tf.float32)
min_fraction_of_examples_in_queue = 0.05
min_queue_examples = int(NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN *
min_fraction_of_examples_in_queue)
print ('Filling queue with %d CamVid images before starting to train. '
'This will take a few minutes.' % min_queue_examples)
# Generate a batch of images and labels by building up a queue of examples.
return _generate_image_and_label_batch(reshaped_image, label,
min_queue_examples, batch_size,
shuffle=shuffle)
| 38.176471 | 89 | 0.662338 |
acec9b5b560698f54f32df4b1dfb6848ec0a7765 | 25,782 | py | Python | scripts/sct_compute_hausdorff_distance.py | YangHee-Min/spinalcordtoolbox | 38ca15aa99b03ca99b7885ddc98adf2755adc43d | [
"MIT"
] | null | null | null | scripts/sct_compute_hausdorff_distance.py | YangHee-Min/spinalcordtoolbox | 38ca15aa99b03ca99b7885ddc98adf2755adc43d | [
"MIT"
] | null | null | null | scripts/sct_compute_hausdorff_distance.py | YangHee-Min/spinalcordtoolbox | 38ca15aa99b03ca99b7885ddc98adf2755adc43d | [
"MIT"
] | null | null | null | #!/usr/bin/env python
#
# Thinning with the Zhang-Suen algorithm (1984) --> code taken from https://github.com/linbojin/Skeletonization-by-Zhang-Suen-Thinning-Algorithm
# Computation of the distances between two skeleton
# ---------------------------------------------------------------------------------------
# Copyright (c) 2013 Polytechnique Montreal <www.neuro.polymtl.ca>
# Authors: Sara Dupont
# CREATED: 2015-07-15
#
# About the license: see the file LICENSE.TXT
#########################################################################################
from __future__ import absolute_import, division
import sys, io, os, time, shutil
import numpy as np
import sct_utils as sct
import spinalcordtoolbox.image as msct_image
from spinalcordtoolbox.image import Image
from msct_parser import Parser
# TODO: display results ==> not only max : with a violin plot of h1 and h2 distribution ? see dev/straightening --> seaborn.violinplot
# TODO: add the option Hyberbolic Hausdorff's distance : see choi and seidel paper
# ----------------------------------------------------------------------------------------------------------------------
# PARAM ----------------------------------------------------------------------------------------------------------------
class Param:
def __init__(self):
self.debug = 0
self.thinning = True
self.verbose = 1
# ----------------------------------------------------------------------------------------------------------------------
# THINNING -------------------------------------------------------------------------------------------------------------
class Thinning:
def __init__(self, im, v=1):
sct.printv('Thinning ... ', v, 'normal')
self.image = im
self.image.data = bin_data(self.image.data)
self.dim_im = len(self.image.data.shape)
if self.dim_im == 2:
self.thinned_image = msct_image.empty_like(self.image)
self.thinned_image.data = self.zhang_suen(self.image.data)
self.thinned_image.absolutepath = sct.add_suffix(self.image.absolutepath, "_thinned")
elif self.dim_im == 3:
if not self.image.orientation == 'IRP':
sct.printv('-- changing orientation ...')
self.image.change_orientation('IRP')
thinned_data = np.asarray([self.zhang_suen(im_slice) for im_slice in self.image.data])
self.thinned_image = msct_image.empty_like(self.image)
self.thinned_image.data = thinned_data
self.thinned_image.absolutepath = sct.add_suffix(self.image.absolutepath, "_thinned")
# ------------------------------------------------------------------------------------------------------------------
def get_neighbours(self, x, y, image):
"""
Return 8-neighbours of image point P1(x,y), in a clockwise order
code from https://github.com/linbojin/Skeletonization-by-Zhang-Suen-Thinning-Algorithm
:param x:
:param y:
:param image:
:return:
"""
# now = time.time()
x_1, y_1, x1, y1 = x - 1, y - 1, x + 1, y + 1
neighbours = [image[x_1][y], image[x_1][y1], image[x][y1], image[x1][y1], # P2,P3,P4,P5
image[x1][y], image[x1][y_1], image[x][y_1], image[x_1][y_1]] # P6,P7,P8,P9
# t = time.time() - now
# sct.printv('t neighbours: ', t)
return neighbours
# ------------------------------------------------------------------------------------------------------------------
def transitions(self, neighbours):
"""
No. of 0,1 patterns (transitions from 0 to 1) in the ordered sequence
code from https://github.com/linbojin/Skeletonization-by-Zhang-Suen-Thinning-Algorithm
:param neighbours:
:return:
"""
# now = time.time()
n = neighbours + neighbours[0:1] # P2, P3, ... , P8, P9, P2
s = np.sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:])) # (P2,P3), (P3,P4), ... , (P8,P9), (P9,P2)
# t = time.time() - now
# sct.printv('t transitions sum: ', t)
return s
# ------------------------------------------------------------------------------------------------------------------
def zhang_suen(self, image):
"""
the Zhang-Suen Thinning Algorithm
code from https://github.com/linbojin/Skeletonization-by-Zhang-Suen-Thinning-Algorithm
:param image:
:return:
"""
# now = time.time()
image_thinned = image.copy() # deepcopy to protect the original image
changing1 = changing2 = 1 # the points to be removed (set as 0)
while changing1 or changing2: # iterates until no further changes occur in the image
# Step 1
changing1 = []
max = len(image_thinned) - 1
pass_list = [1, max]
# rows, columns = image_thinned.shape # x for rows, y for columns
# for x in range(1, rows - 1): # No. of rows
# for y in range(1, columns - 1): # No. of columns
for x, y in non_zero_coord(image_thinned):
if x not in pass_list and y not in pass_list:
# if image_thinned[x][y] == 1: # Condition 0: Point P1 in the object regions
P2, P3, P4, P5, P6, P7, P8, P9 = n = self.get_neighbours(x, y, image_thinned)
if (2 <= sum(n) <= 6 and # Condition 1: 2<= N(P1) <= 6
P2 * P4 * P6 == 0 and # Condition 3
P4 * P6 * P8 == 0 and # Condition 4
self.transitions(n) == 1): # Condition 2: S(P1)=1
changing1.append((x, y))
for x, y in changing1:
image_thinned[x][y] = 0
# Step 2
changing2 = []
# for x in range(1, rows - 1):
# for y in range(1, columns - 1):
for x, y in non_zero_coord(image_thinned):
if x not in pass_list and y not in pass_list:
# if image_thinned[x][y] == 1: # Condition 0
P2, P3, P4, P5, P6, P7, P8, P9 = n = self.get_neighbours(x, y, image_thinned)
if (2 <= sum(n) <= 6 and # Condition 1
P2 * P4 * P8 == 0 and # Condition 3
P2 * P6 * P8 == 0 and # Condition 4
self.transitions(n) == 1): # Condition 2
changing2.append((x, y))
for x, y in changing2:
image_thinned[x][y] = 0
# t = time.time() - now
# sct.printv('t thinning: ', t)
return image_thinned
# ----------------------------------------------------------------------------------------------------------------------
# HAUSDORFF'S DISTANCE -------------------------------------------------------------------------------------------------
class HausdorffDistance:
def __init__(self, data1, data2, v=1):
"""
the hausdorff distance between two sets is the maximum of the distances from a point in any of the sets to the nearest point in the other set
:return:
"""
# now = time.time()
sct.printv('Computing 2D Hausdorff\'s distance ... ', v, 'normal')
self.data1 = bin_data(data1)
self.data2 = bin_data(data2)
self.min_distances_1 = self.relative_hausdorff_dist(self.data1, self.data2, v)
self.min_distances_2 = self.relative_hausdorff_dist(self.data2, self.data1, v)
# relatives hausdorff's distances in pixel
self.h1 = np.max(self.min_distances_1)
self.h2 = np.max(self.min_distances_2)
# Hausdorff's distance in pixel
self.H = max(self.h1, self.h2)
# t = time.time() - now
# sct.printv('Hausdorff dist time :', t)
# ------------------------------------------------------------------------------------------------------------------
def relative_hausdorff_dist(self, dat1, dat2, v=1):
h = np.zeros(dat1.shape)
nz_coord_1 = non_zero_coord(dat1)
nz_coord_2 = non_zero_coord(dat2)
if len(nz_coord_1) != 0 and len(nz_coord_2) != 0 :
for x1, y1 in nz_coord_1:
# for x1 in range(dat1.shape[0]):
# for y1 in range(dat1.shape[1]):
# if dat1[x1, y1] == 1:
d_p1_dat2 = []
p1 = np.asarray([x1, y1])
for x2, y2 in nz_coord_2:
# for x2 in range(dat2.shape[0]):
# for y2 in range(dat2.shape[1]):
# if dat2[x2, y2] == 1:
p2 = np.asarray([x2, y2])
d_p1_dat2.append(np.linalg.norm(p1 - p2)) # Euclidean distance between p1 and p2
h[x1, y1] = min(d_p1_dat2)
else:
sct.printv('Warning: an image is empty', v, 'warning')
return h
# ----------------------------------------------------------------------------------------------------------------------
# COMPUTE DISTANCES ----------------------------------------------------------------------------------------------------
class ComputeDistances:
def __init__(self, im1, im2=None, param=None):
self.im1 = im1
self.im2 = im2
self.dim_im = len(self.im1.data.shape)
self.dim_pix = 0
self.distances = None
self.res = ''
self.param = param
self.dist1_distribution = None
self.dist2_distribution = None
if self.dim_im == 3:
self.orientation1 = self.im1.orientation
if self.orientation1 != 'IRP':
self.im1.change_orientation('IRP', generate_path=True)
if self.im2 is not None:
self.orientation2 = self.im2.orientation
if self.orientation2 != 'IRP':
self.im2.change_orientation('IRP', generate_path=True)
if self.param.thinning:
self.thinning1 = Thinning(self.im1, self.param.verbose)
self.thinning1.thinned_image.save()
if self.im2 is not None:
self.thinning2 = Thinning(self.im2, self.param.verbose)
self.thinning2.thinned_image.save()
if self.dim_im == 2 and self.im2 is not None:
self.compute_dist_2im_2d()
if self.dim_im == 3:
if self.im2 is None:
self.compute_dist_1im_3d()
else:
self.compute_dist_2im_3d()
if self.dim_im == 2 and self.distances is not None:
self.dist1_distribution = self.distances.min_distances_1[np.nonzero(self.distances.min_distances_1)]
self.dist2_distribution = self.distances.min_distances_2[np.nonzero(self.distances.min_distances_2)]
if self.dim_im == 3:
self.dist1_distribution = []
self.dist2_distribution = []
for d in self.distances:
if np.nonzero(d.min_distances_1)[0].size: # Exist non zero values
self.dist1_distribution.append(d.min_distances_1[np.nonzero(d.min_distances_1)])
else: # all values are zero
self.dist1_distribution.append(0)
if np.nonzero(d.min_distances_2)[0].size: # Exist non zero values
self.dist2_distribution.append(d.min_distances_2[np.nonzero(d.min_distances_2)])
else: # all values are zero
self.dist2_distribution.append(0)
self.res = 'Hausdorff\'s distance - First relative Hausdorff\'s distance median - Second relative Hausdorff\'s distance median(all in mm)\n'
for i, d in enumerate(self.distances):
med1 = np.median(self.dist1_distribution[i])
med2 = np.median(self.dist2_distribution[i])
if self.im2 is None:
self.res += 'Slice ' + str(i) + ' - slice ' + str(i + 1) + ': ' + str(d.H * self.dim_pix) + ' - ' + str(med1 * self.dim_pix) + ' - ' + str(med2 * self.dim_pix) + ' \n'
else:
self.res += 'Slice ' + str(i) + ': ' + str(d.H * self.dim_pix) + ' - ' + str(med1 * self.dim_pix) + ' - ' + str(med2 * self.dim_pix) + ' \n'
sct.printv('-----------------------------------------------------------------------------\n' +
self.res, self.param.verbose, 'normal')
if self.param.verbose == 2:
self.show_results()
# ------------------------------------------------------------------------------------------------------------------
def compute_dist_2im_2d(self):
nx1, ny1, nz1, nt1, px1, py1, pz1, pt1 = self.im1.dim
nx2, ny2, nz2, nt2, px2, py2, pz2, pt2 = self.im2.dim
assert np.isclose(px1, px2) and np.isclose(py1, py2) and np.isclose(px1, py1)
self.dim_pix = py1
if self.param.thinning:
dat1 = self.thinning1.thinned_image.data
dat2 = self.thinning2.thinned_image.data
else:
dat1 = bin_data(self.im1.data)
dat2 = bin_data(self.im2.data)
self.distances = HausdorffDistance(dat1, dat2, self.param.verbose)
self.res = 'Hausdorff\'s distance : ' + str(self.distances.H * self.dim_pix) + ' mm\n\n' \
'First relative Hausdorff\'s distance : ' + str(self.distances.h1 * self.dim_pix) + ' mm\n' \
'Second relative Hausdorff\'s distance : ' + str(self.distances.h2 * self.dim_pix) + ' mm'
# ------------------------------------------------------------------------------------------------------------------
def compute_dist_1im_3d(self):
nx1, ny1, nz1, nt1, px1, py1, pz1, pt1 = self.im1.dim
self.dim_pix = py1
if self.param.thinning:
dat1 = self.thinning1.thinned_image.data
else:
dat1 = bin_data(self.im1.data)
self.distances = []
for i, dat_slice in enumerate(dat1[:-1]):
self.distances.append(HausdorffDistance(bin_data(dat_slice), bin_data(dat1[i + 1]), self.param.verbose))
# ------------------------------------------------------------------------------------------------------------------
def compute_dist_2im_3d(self):
nx1, ny1, nz1, nt1, px1, py1, pz1, pt1 = self.im1.dim
nx2, ny2, nz2, nt2, px2, py2, pz2, pt2 = self.im2.dim
# assert np.round(pz1, 5) == np.round(pz2, 5) and np.round(py1, 5) == np.round(py2, 5)
assert nx1 == nx2
self.dim_pix = py1
if self.param.thinning:
dat1 = self.thinning1.thinned_image.data
dat2 = self.thinning2.thinned_image.data
else:
dat1 = bin_data(self.im1.data)
dat2 = bin_data(self.im2.data)
self.distances = []
for slice1, slice2 in zip(dat1, dat2):
self.distances.append(HausdorffDistance(slice1, slice2, self.param.verbose))
# ------------------------------------------------------------------------------------------------------------------
def show_results(self):
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
plt.hold(True)
sns.set(style="whitegrid", palette="pastel", color_codes=True)
plt.figure(figsize=(35, 20))
data_dist = {"distances": [], "image": [], "slice": []}
if self.dim_im == 2:
data_dist["distances"].append([dist * self.dim_pix for dist in self.dist1_distribution])
data_dist["image"].append(len(self.dist1_distribution) * [1])
data_dist["slice"].append(len(self.dist1_distribution) * [0])
data_dist["distances"].append([dist * self.dim_pix for dist in self.dist2_distribution])
data_dist["image"].append(len(self.dist2_distribution) * [2])
data_dist["slice"].append(len(self.dist2_distribution) * [0])
if self.dim_im == 3:
for i in range(len(self.distances)):
data_dist["distances"].append([dist * self.dim_pix for dist in self.dist1_distribution[i]])
data_dist["image"].append(len(self.dist1_distribution[i]) * [1])
data_dist["slice"].append(len(self.dist1_distribution[i]) * [i])
data_dist["distances"].append([dist * self.dim_pix for dist in self.dist2_distribution[i]])
data_dist["image"].append(len(self.dist2_distribution[i]) * [2])
data_dist["slice"].append(len(self.dist2_distribution[i]) * [i])
for k in data_dist.keys(): # flatten the lists in data_dist
data_dist[k] = [item for sublist in data_dist[k] for item in sublist]
data_dist = pd.DataFrame(data_dist)
sns.violinplot(x="slice", y="distances", hue="image", data=data_dist, split=True, inner="point", cut=0)
plt.savefig('violin_plot.png')
# plt.show()
# ----------------------------------------------------------------------------------------------------------------------
def bin_data(data):
return np.asarray((data > 0).astype(int))
# ----------------------------------------------------------------------------------------------------------------------
def resample_image(fname, suffix='_resampled.nii.gz', binary=False, npx=0.3, npy=0.3, thr=0.0, interpolation='spline'):
"""
Resampling function: add a padding, resample, crop the padding
:param fname: name of the image file to be resampled
:param suffix: suffix added to the original fname after resampling
:param binary: boolean, image is binary or not
:param npx: new pixel size in the x direction
:param npy: new pixel size in the y direction
:param thr: if the image is binary, it will be thresholded at thr (default=0) after the resampling
:param interpolation: type of interpolation used for the resampling
:return: file name after resampling (or original fname if it was already in the correct resolution)
"""
im_in = Image(fname)
orientation = im_in.orientation
if orientation != 'RPI':
fname = im_in.change_orientation(im_in, 'RPI', generate_path=True).save().absolutepath
nx, ny, nz, nt, px, py, pz, pt = im_in.dim
if np.round(px, 2) != np.round(npx, 2) or np.round(py, 2) != np.round(npy, 2):
name_resample = sct.extract_fname(fname)[1] + suffix
if binary:
interpolation = 'nn'
if nz == 1: # when data is 2d: we convert it to a 3d image in order to avoid nipy problem of conversion nifti-->nipy with 2d data
sct.run(['sct_image', '-i', ','.join([fname, fname]), '-concat', 'z', '-o', fname])
sct.run(['sct_resample', '-i', fname, '-mm', str(npx) + 'x' + str(npy) + 'x' + str(pz), '-o', name_resample, '-x', interpolation])
if nz == 1: # when input data was 2d: re-convert data 3d-->2d
sct.run(['sct_image', '-i', name_resample, '-split', 'z'])
im_split = Image(name_resample.split('.nii.gz')[0] + '_Z0000.nii.gz')
im_split.save(name_resample)
if binary:
sct.run(['sct_maths', '-i', name_resample, '-bin', str(thr), '-o', name_resample])
if orientation != 'RPI':
name_resample = Image(name_resample) \
.change_orientation(orientation, generate_path=True) \
.save() \
.absolutepath
return name_resample
else:
if orientation != 'RPI':
fname = sct.add_suffix(fname, "_RPI")
im_in = msct_image.change_orientation(im_in, orientation).save(fname)
sct.printv('Image resolution already ' + str(npx) + 'x' + str(npy) + 'xpz')
return fname
# ----------------------------------------------------------------------------------------------------------------------
def non_zero_coord(data):
dim = len(data.shape)
if dim == 3:
X, Y, Z = (data > 0).nonzero()
list_coordinates = [(X[i], Y[i], Z[i]) for i in range(0, len(X))]
elif dim == 2:
X, Y = (data > 0).nonzero()
list_coordinates = [(X[i], Y[i]) for i in range(0, len(X))]
return list_coordinates
def get_parser():
# Initialize the parser
parser = Parser(__file__)
parser.usage.set_description('Compute the Hausdorff\'s distance between two binary images which can be thinned (ie skeletonized)'
'If only one image is inputted, it will be only thinned')
parser.add_option(name="-i",
type_value="file",
description="First Image on which you want to find the skeleton",
mandatory=True,
example='t2star_manual_gmseg.nii.gz')
parser.add_option(name="-d",
type_value="file",
description="Second Image on which you want to find the skeleton",
mandatory=False,
default_value=None,
example='t2star_manual_gmseg.nii.gz')
parser.add_option(name="-r",
type_value=None,
description="Second Image on which you want to find the skeleton",
mandatory=False,
deprecated_by='-d')
parser.add_option(name="-thinning",
type_value="multiple_choice",
description="Thinning : find the skeleton of the binary images using the Zhang-Suen algorithm (1984) and use it to compute the hausdorff's distance",
mandatory=False,
default_value=1,
example=['0', '1'])
parser.add_option(name="-t",
type_value=None,
description="Thinning : find the skeleton of the binary images using the Zhang-Suen algorithm (1984) and use it to compute the hausdorff's distance",
deprecated_by="-thinning",
mandatory=False)
parser.add_option(name="-resampling",
type_value="float",
description="pixel size in mm to resample to",
mandatory=False,
default_value=0.1,
example=0.5)
parser.add_option(name="-o",
type_value="file_output",
description="Name of the output file",
mandatory=False,
default_value='hausdorff_distance.txt',
example='my_hausdorff_dist.txt')
parser.add_option(name="-v",
type_value="multiple_choice",
description="Verbose. 0: nothing, 1: basic, 2: extended.",
mandatory=False,
example=['0', '1', '2'],
default_value='1')
return parser
########################################################################################################################
# ------------------------------------------------------ MAIN ------------------------------------------------------- #
########################################################################################################################
if __name__ == "__main__":
sct.init_sct()
param = Param()
input_fname = None
if param.debug:
sct.printv('\n*** WARNING: DEBUG MODE ON ***\n')
else:
param_default = Param()
parser = get_parser()
arguments = parser.parse(sys.argv[1:])
input_fname = arguments["-i"]
input_second_fname = ''
output_fname = 'hausdorff_distance.txt'
resample_to = 0.1
if "-d" in arguments:
input_second_fname = arguments["-d"]
if "-thinning" in arguments:
param.thinning = bool(int(arguments["-thinning"]))
if "-resampling" in arguments:
resample_to = arguments["-resampling"]
if "-o" in arguments:
output_fname = arguments["-o"]
param.verbose = int(arguments.get('-v'))
sct.init_sct(log_level=param.verbose, update=True) # Update log level
tmp_dir = sct.tmp_create()
im1_name = "im1.nii.gz"
sct.copy(input_fname, os.path.join(tmp_dir, im1_name))
if input_second_fname != '':
im2_name = 'im2.nii.gz'
sct.copy(input_second_fname, os.path.join(tmp_dir, im2_name))
else:
im2_name = None
curdir = os.getcwd()
os.chdir(tmp_dir)
# now = time.time()
input_im1 = Image(resample_image(im1_name, binary=True, thr=0.5, npx=resample_to, npy=resample_to))
input_im1.absolutepath = os.path.basename(input_fname)
if im2_name is not None:
input_im2 = Image(resample_image(im2_name, binary=True, thr=0.5, npx=resample_to, npy=resample_to))
input_im2.absolutepath = os.path.basename(input_second_fname)
else:
input_im2 = None
computation = ComputeDistances(input_im1, im2=input_im2, param=param)
# TODO change back the orientatin of the thinned image
if param.thinning:
computation.thinning1.thinned_image.save(os.path.join(curdir, sct.add_suffix(os.path.basename(input_fname), '_thinned')))
if im2_name is not None:
computation.thinning2.thinned_image.save(os.path.join(curdir, sct.add_suffix(os.path.basename(input_second_fname), '_thinned')))
os.chdir(curdir)
res_fic = open(output_fname, 'w')
res_fic.write(computation.res)
res_fic.write('\n\nInput 1: ' + input_fname)
res_fic.write('\nInput 2: ' + input_second_fname)
res_fic.close()
# sct.printv('Total time: ', time.time() - now)
| 46.622061 | 191 | 0.510201 |
acec9bfe2d1097eb606afae454c15c7ed07582cf | 107 | py | Python | code_new_start_2021/April/base/tree.py | dylanlee101/leetcode | b059afdadb83d504e62afd1227107de0b59557af | [
"Apache-2.0"
] | null | null | null | code_new_start_2021/April/base/tree.py | dylanlee101/leetcode | b059afdadb83d504e62afd1227107de0b59557af | [
"Apache-2.0"
] | null | null | null | code_new_start_2021/April/base/tree.py | dylanlee101/leetcode | b059afdadb83d504e62afd1227107de0b59557af | [
"Apache-2.0"
] | null | null | null | class TreeNode:
def __init__(self,val):
self.val = val
self.left,self.right = None,None | 26.75 | 40 | 0.616822 |
acec9c5fb3fde40ca38117d58a64fb86ba7075c4 | 3,560 | py | Python | pommerman/agents/state_agent_exploit.py | PBarde/ASAF-playground | 6567e5c56b6e077e0686376240bd3ccaa8a0da0c | [
"Apache-2.0"
] | 1 | 2020-12-22T06:45:18.000Z | 2020-12-22T06:45:18.000Z | pommerman/agents/state_agent_exploit.py | PBarde/ASAF-playground | 6567e5c56b6e077e0686376240bd3ccaa8a0da0c | [
"Apache-2.0"
] | null | null | null | pommerman/agents/state_agent_exploit.py | PBarde/ASAF-playground | 6567e5c56b6e077e0686376240bd3ccaa8a0da0c | [
"Apache-2.0"
] | null | null | null | """State Machine Agent
TODO:
1. rewrite score function (flow map)
"""
from functools import partial
from pommerman import constants
from pommerman.agents.score_func import score_func_with_target
from pommerman.agents.state_agent import StateAgent, State, win_cond_with_target
from . import helper_func
from . import mcts_inter_exploit
class StateAgentExploit(StateAgent):
"""This is a baseline agent. After you can beat it, submit your agent to compete."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._mcts = mcts_inter_exploit.MCTSAgentExploit(kwargs['board_shape'])
def AttackerAction(self):
#============
#PLACE BOMB IF NEAR ENEMY
#============
# Lay pomme if we are adjacent to an enemy.
# if self._is_adjacent_enemy(self.items, self.dist, self.enemies) and self._maybe_bomb(self.ammo, self.blast_strength, self.items, self.dist, self.my_position, self.board, self.prev, self.enemies):
# helper_func.agent_output(["No. 300"])
# return constants.Action.Bomb.value
#===========
#MCTS TREE SEARCH IF NEAR ENEMY
#===========
# actions_space = range(6)
directions = [constants.Action.Stop, constants.Action.Left, constants.Action.Right, constants.Action.Up, constants.Action.Down]
directions = self._filter_unsafe_directions(self.board, self.my_position, directions, self.bombs, self.items, self.dist, self.prev, self.enemies)
actions_space = [dir.value for dir in directions] + [constants.Action.Bomb.value]
if self._target is not None:
position = self.items.get(self._target,[])
if not position or self.dist[position[0]] > 4:
self._target = None
else:
#print("MCTS")
#print(self.obs['board'], self.bombing_agents)
return self._mcts.find_next_move(self.obs, actions_space, \
partial(win_cond_with_target, self._target), partial(score_func_with_target, self._target), self.bombing_agents);
else:
new_target = self._is_adjacent_enemy_target(self.items, self.dist, self.enemies)
if new_target is not None:
self._target = new_target
#print("MCTS")
#print(self.obs['board'],self.bombing_agents)
return self._mcts.find_next_move(self.obs, actions_space, \
partial(win_cond_with_target, self._target), partial(score_func_with_target, self._target), self.bombing_agents);
#============
#MOVE TOWARDS ENEMY
#============
enemy_detection_range = 6
# Move towards an enemy if there is one in exactly ten reachable spaces
direction = helper_func._near_enemy(self.my_position, self.items, self.dist, self.prev, self.enemies, enemy_detection_range)
if direction is not None:
directions = self._filter_unsafe_directions(self.board, self.my_position, [direction], self.bombs, self.items, self.dist, self.prev, self.enemies)
if directions:
self._prev_direction = direction
helper_func.agent_output(["No. 400: {}".format(direction.value)])
return direction.value
#===========
#STOP CAUSE NOT SAFE
#===========
return self.ExplorerAction()
| 48.767123 | 206 | 0.611236 |
acec9cb332bc39b638e775e9c68ba99ecaa8e9f6 | 225 | py | Python | app/config/redis.py | usename-Poezd/signly-api | 555bfebeafa30cebe5c7db1e8e724e6448feba50 | [
"MIT"
] | null | null | null | app/config/redis.py | usename-Poezd/signly-api | 555bfebeafa30cebe5c7db1e8e724e6448feba50 | [
"MIT"
] | null | null | null | app/config/redis.py | usename-Poezd/signly-api | 555bfebeafa30cebe5c7db1e8e724e6448feba50 | [
"MIT"
] | null | null | null | from typing import AsyncIterator
from aioredis import from_url, Redis
async def init_redis_pool(url: str) -> AsyncIterator[Redis]:
pool = await from_url(url)
yield pool
pool.close()
await pool.wait_closed() | 22.5 | 60 | 0.733333 |
acec9ce2d27d329a5538520eaf786eaaa689b2b8 | 1,285 | py | Python | Python_Exercicios/Mundo3/Funções em Python/python_079.py | jbauermanncode/Curso_Em_Video_Python | 330c207d7bed4e663fe1b9ab433ab57a9828b7f1 | [
"MIT"
] | null | null | null | Python_Exercicios/Mundo3/Funções em Python/python_079.py | jbauermanncode/Curso_Em_Video_Python | 330c207d7bed4e663fe1b9ab433ab57a9828b7f1 | [
"MIT"
] | null | null | null | Python_Exercicios/Mundo3/Funções em Python/python_079.py | jbauermanncode/Curso_Em_Video_Python | 330c207d7bed4e663fe1b9ab433ab57a9828b7f1 | [
"MIT"
] | null | null | null | '''
Faça um programa que tenha uma função chamada contador(), que receba três parâmetros: início, fim e passo. Seu programa tem que realizar três contagens através da função criada: a) de 1 até 10, de 1 em 1 b) de 10 até 0, de 2 em 2 c) uma contagem personalizada
'''
from time import sleep
def contador(i, f, p):
if p < 0:
p *= -1
elif p == 0:
p = 1
print('-=' * 20)
print(f'Contagem de {i} até {f} de {p} em {p}.')
sleep(2.5)
if i < f:
cont = i
while cont <= f:
print(f'{cont} ', end='', flush=True)
sleep(1)
cont += p
print('FIM!')
elif i > f:
cont = i
while cont >= f:
print(f'{cont} ', end='', flush=True)
sleep(1)
cont -= p
print('FIM!')
# Programa Principal
contador(1, 10, 1)
contador(10, 0, 2)
print('-=' * 20)
print('Agora é a sua vez de personalizar a contagem!')
ini = int(input('Inicio: '))
fim = int(input('Fim: '))
pas = int(input('Passo: '))
contador(ini, fim, pas)
| 30.595238 | 485 | 0.436576 |
acec9d99bb7b64f771a30f57173fcbe72bc56aa5 | 1,087 | py | Python | jorldy/config/rainbow/super_mario_bros.py | taechanha/JORLDY | 7356f7481dbc569bf745353105088d65665a4a51 | [
"Apache-2.0"
] | null | null | null | jorldy/config/rainbow/super_mario_bros.py | taechanha/JORLDY | 7356f7481dbc569bf745353105088d65665a4a51 | [
"Apache-2.0"
] | null | null | null | jorldy/config/rainbow/super_mario_bros.py | taechanha/JORLDY | 7356f7481dbc569bf745353105088d65665a4a51 | [
"Apache-2.0"
] | null | null | null | ### Rainbow DQN Atari Config ###
env = {
"name": "super_mario_bros",
"render": False,
"gray_img": True,
"img_width": 84,
"img_height": 84,
"stack_frame": 4,
"no_op": True,
"reward_clip": True,
}
agent = {
"name": "rainbow",
"network": "rainbow",
"head": "cnn",
"gamma": 0.99,
"explore_ratio": 0.1,
"buffer_size": 1000000,
"batch_size": 32,
"start_train_step": 100000,
"target_update_period": 10000,
# MultiStep
"n_step": 3,
# PER
"alpha": 0.6,
"beta": 0.4,
"learn_period": 4,
"uniform_sample_prob": 1e-3,
# Noisy
"noise_type": "factorized", # [independent, factorized]
# C51
"v_min": -10,
"v_max": 10,
"num_support": 51,
}
optim = {
"name": "adam",
"lr": 2.5e-4 / 4,
}
train = {
"training": True,
"load_path": None,
"run_step": 30000000,
"print_period": 10000,
"save_period": 100000,
"eval_iteration": 5,
"record": True,
"record_period": 300000,
# distributed setting
"update_period": 32,
"num_workers": 16,
}
| 19.070175 | 60 | 0.548298 |
acec9d9a066157a4d196753a41e7b9fdd55d0271 | 2,542 | py | Python | ref_convert.py | xiangzixuebit/PINNpapers | 807be8053bd333015e347b89cad35ab8ef0bb2c1 | [
"MIT"
] | 138 | 2021-08-16T06:14:54.000Z | 2022-03-28T08:08:13.000Z | ref_convert.py | Zhangxuej/PINNpapers | 842da20608ca7860faf625b62f91e4d17f2492f8 | [
"MIT"
] | 2 | 2021-11-01T15:29:07.000Z | 2021-12-26T10:25:31.000Z | ref_convert.py | Zhangxuej/PINNpapers | 842da20608ca7860faf625b62f91e4d17f2492f8 | [
"MIT"
] | 30 | 2021-08-24T15:29:12.000Z | 2022-03-26T14:10:05.000Z | #!/usr/bin/env python3
"""The script provides a GUI interface for converting bibtex to the markdown style which is used in this repo.
The user may need to install these external packages:
Usage:
pip install bibtexparser PyQt5
./ref_convert.py
Author:
weipeng0098@126.com - 2021/8/10 17:16
Version:
0.0.1
"""
import sys
from PyQt5.QtWidgets import QWidget, QPushButton, QPlainTextEdit, QFormLayout, QApplication
from bibtexparser.bparser import BibTexParser
import bibtexparser
import re
def handle_title(_title: str):
_title = re.compile('[{}]').sub('', _title.strip())
return _title
def handle_author(author: str):
author = ', '.join(list(map(lambda x: ' '.join(x.strip().split(', ')[::-1]), author.split('and'))))
return author
def handle_url(url: str):
try:
arxiv_identifier = re.compile('http://arxiv.org/abs/([\d\.]+)').findall(url)[0]
url = f'http://arxiv.org/pdf/{arxiv_identifier}.pdf'
except:
pass
return url
def bib_parser(bibref: str):
parser = BibTexParser(common_strings=True)
parser.ignore_nonstandard_types = False
parser.homogenise_fields = False
bib = bibtexparser.loads(bibref, parser)
lines = []
for entry in bib.entries:
title = handle_title(entry['title'])
author = handle_author(entry['author'])
try:
journal = entry['journal']
except:
journal = '**UNKNOWN_JOURNAL**'
try:
year = entry['year']
except:
year = '**UNKNOWN_YEAR**'
try:
url = entry['url']
url = handle_url(url)
except:
url = ''
lines.append(f"1. **{title}**, *{author}*, {journal}, {year}. [[paper]({url})][[code]()]")
target = '\n'.join(lines)
return target
def bib_convert():
bibtex_str = bib_parser(bibtexEdit.toPlainText())
targetEdit.setPlainText(bibtex_str)
app = QApplication(sys.argv)
window = QWidget()
window.setWindowTitle('Bibtex-Markdown converter')
layout = QFormLayout()
bibtexEdit = QPlainTextEdit()
layout.addRow('bibtex:', bibtexEdit)
bibtexEdit.setFixedWidth(1000)
targetEdit = QPlainTextEdit()
layout.addRow('markdown:', targetEdit)
targetEdit.setFixedWidth(1000)
btn = QPushButton('Convert')
btn.clicked.connect(bib_convert)
layout.addRow('Convert', btn)
btn = QPushButton('Clear')
btn.clicked.connect(bibtexEdit.clear)
btn.clicked.connect(targetEdit.clear)
layout.addRow('Clear', btn)
window.setLayout(layout)
window.show()
sys.exit(app.exec_())
| 24.679612 | 110 | 0.66011 |
acec9fc58141ae63a22aac600543fa8706b83f5d | 935 | py | Python | academic_observatory_workflows/dags/grid_telescope.py | The-Academic-Observatory/academic-observatory-workflows | d05cd93187934d06cbce66afff93dea1679c2fc1 | [
"Apache-2.0"
] | 6 | 2022-01-17T08:29:19.000Z | 2022-03-25T11:39:24.000Z | academic_observatory_workflows/dags/grid_telescope.py | The-Academic-Observatory/academic-observatory-workflows | d05cd93187934d06cbce66afff93dea1679c2fc1 | [
"Apache-2.0"
] | 84 | 2021-08-30T23:00:18.000Z | 2022-03-30T17:15:46.000Z | academic_observatory_workflows/dags/grid_telescope.py | The-Academic-Observatory/academic-observatory-workflows | d05cd93187934d06cbce66afff93dea1679c2fc1 | [
"Apache-2.0"
] | null | null | null | # Copyright 2020 Curtin University
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Author: James Diprose
# The keywords airflow and DAG are required to load the DAGs from this file, see bullet 2 in the Apache Airflow FAQ:
# https://airflow.apache.org/docs/stable/faq.html
from academic_observatory_workflows.workflows.grid_telescope import GridTelescope
telescope = GridTelescope()
globals()[telescope.dag_id] = telescope.make_dag()
| 38.958333 | 116 | 0.779679 |
aceca1f63f7d0281f74b04aa01a18344b538f074 | 3,389 | py | Python | rbac/common/role/reject_task.py | kthblmfld/sawtooth-next-directory | 57291f1a7e6ce1dfc11a9c5e2930e8c5ebd31707 | [
"Apache-2.0"
] | null | null | null | rbac/common/role/reject_task.py | kthblmfld/sawtooth-next-directory | 57291f1a7e6ce1dfc11a9c5e2930e8c5ebd31707 | [
"Apache-2.0"
] | null | null | null | rbac/common/role/reject_task.py | kthblmfld/sawtooth-next-directory | 57291f1a7e6ce1dfc11a9c5e2930e8c5ebd31707 | [
"Apache-2.0"
] | null | null | null | # Copyright 2018 Contributors to Hyperledger Sawtooth
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# -----------------------------------------------------------------------------
"""Implements the REJECT_ADD_ROLE_TASK message
usage: rbac.role.task.reject.create()"""
import logging
from rbac.common import addresser
from rbac.common.proposal.proposal_reject import ProposalReject
LOGGER = logging.getLogger(__name__)
class RejectAddRoleTask(ProposalReject):
"""Implements the REJECT_ADD_ROLE_TASK message
usage: rbac.role.task.reject.create()"""
def __init__(self):
super().__init__()
self._register()
@property
def message_action_type(self):
"""The action type performed by this message"""
return addresser.MessageActionType.REJECT
@property
def message_subaction_type(self):
"""The subsequent action performed or proposed by this message"""
return addresser.MessageActionType.ADD
@property
def message_object_type(self):
"""The object type this message acts upon"""
return addresser.ObjectType.ROLE
@property
def message_related_type(self):
"""the object type of the related object this message acts upon"""
return addresser.ObjectType.TASK
@property
def message_relationship_type(self):
"""The relationship type this message acts upon"""
return addresser.RelationshipType.MEMBER
def make_addresses(self, message, signer_user_id):
"""Makes the appropriate inputs & output addresses for the message"""
inputs, outputs = super().make_addresses(message, signer_user_id)
signer_task_owner_address = addresser.task.owner.address(
message.related_id, signer_user_id
)
inputs.add(signer_task_owner_address)
proposal_address = self.address(
object_id=message.object_id, related_id=message.related_id
)
inputs.add(proposal_address)
outputs.add(proposal_address)
return inputs, outputs
def validate_state(self, context, message, payload, input_state, store):
"""Validates that:
1. the signer is an owner of the task"""
super().validate_state(
context=context,
message=message,
payload=payload,
input_state=input_state,
store=store,
)
# TODO: change to verify proposal assignment and hierarchy
# if not addresser.task.owner.exists_in_state_inputs(
# inputs=inputs,
# input_state=input_state,
# object_id=message.related_id,
# related_id=payload.signer.user_id,
# ):
# raise ValueError(
# "Signer {} must be an owner of the task {}".format(
# payload.signer.user_id, message.object_id
# )
# )
| 34.581633 | 79 | 0.658601 |
aceca21b5eb6445c12a425b2f15bf881bf222c01 | 397 | py | Python | app/main/mail.py | COdingaorg/Rudimental_blog | 463c2da646a8d7a7b073714a7e72589c4d8fc865 | [
"MIT"
] | null | null | null | app/main/mail.py | COdingaorg/Rudimental_blog | 463c2da646a8d7a7b073714a7e72589c4d8fc865 | [
"MIT"
] | null | null | null | app/main/mail.py | COdingaorg/Rudimental_blog | 463c2da646a8d7a7b073714a7e72589c4d8fc865 | [
"MIT"
] | null | null | null | import os
from flask_mail import Message
from .. import mail
from flask import render_template
def mail_message(subject, template, to, **kwargs):
sender_email = os.environ.get('MAIL_USERNAME')
email = Message(subject, sender=sender_email, recipients=[to])
email.body = render_template(template + '.txt',**kwargs)
email.html = render_template(template+'.html', **kwargs)
mail.send(email) | 36.090909 | 64 | 0.753149 |
aceca39b5e857529c057a03b9c3921968a968995 | 15,100 | py | Python | Python Simulator/Frontier Exploration/backup/1 (initial backup)/Burgard.py | yiorgosk/Path-Planning-Simulator | 84847d0068a3fd6fa30098b99a75dff237768a73 | [
"MIT"
] | 50 | 2018-11-15T08:42:49.000Z | 2022-03-20T10:51:58.000Z | Python Simulator/Frontier Exploration/backup/1 (initial backup)/Burgard.py | yiorgosk/Path-Planning-Simulator | 84847d0068a3fd6fa30098b99a75dff237768a73 | [
"MIT"
] | null | null | null | Python Simulator/Frontier Exploration/backup/1 (initial backup)/Burgard.py | yiorgosk/Path-Planning-Simulator | 84847d0068a3fd6fa30098b99a75dff237768a73 | [
"MIT"
] | 24 | 2019-02-03T06:11:58.000Z | 2022-03-15T06:18:39.000Z | # The MIT License (MIT)
# Copyright (c) 2015 INSPIRE Lab, BITS Pilani
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
Provides an implementation of the Communicative Exploration algorithm for a fixed base station.
"""
import math
import random
import sys
import time
import AStar
import Cluster
import GridWorld
import Hungarian
import kmeans
import Robot
from collections import defaultdict
# The Burgard class
class Burgard:
"""
height and width specify the dimensions of the environment
obstacles is a list of locations which are to be initialized as obstacles
R specifies the range of communication
numRobots specifies the number of robot objects to be initialized
initLocs specifies the initial locations for each of the robots
k specifies the size of the population of configuration changes
T specifies the number of time steps to run the simulation for
base specifies the coordinates of the base station
"""
def __init__(self, height, width, obstacles, numRobots, initLocs, T = 10):
# Initialize the grid world
self.gridworld = GridWorld.GridWorld(height, width, obstacles)
self.centroid = []
self.cluster = kmeans.kmeans()
# Initialize a list of robots
self.robots = [Robot.Robot(j+1, -1, -1) for j in range(numRobots)]
# Initialize the starting location of each robot
i = 0
#self.allotted=Cell.Cell(0,0)
for initLoc in initLocs:
# If any robot is placed out of bounds or on an obstacle, print an error message and exit
currentPoint = (initLoc[0], initLoc[1])
if not self.gridworld.inBounds(currentPoint) or not self.gridworld.passable(currentPoint):
print 'Initial location', currentPoint, 'is not possible'
sys.exit(-1)
# Otherwise, modify the current location of the robot to currentPoint
self.robots[i].setLocation(initLoc[0], initLoc[1])
# Update that particular grid cell's occupied status
self.gridworld.cells[initLoc[0]][initLoc[1]].occupied = True
self.gridworld.cells[initLoc[0]][initLoc[1]].visited = True
i += 1
# Initialize other parameters of the algorithm
# Height of the Grid
self.height = height
# Width of the Grid
self.width = width
# List of Clusters (obtained using K-Means clustering)
self.frontierClusters=[]
# Number of Robots
self.numRobots = numRobots
# Parameter for adaptive K-Means
self.K = self.numRobots
# Time steps for which the algorithm is run
self.T = T
# Variable to indicate whether reclustering should be performed
self.reclusterFlag = True
# Centroids of clusters
self.centroids = []
# Number of time steps elapsed
self.t = 0
# Time taken to exhaust the frontier
self.completionTime = 0
# Set to True on completion
self.completedFlag = False
# List of Frontier Cells
self.frontier = []
# New Positions of each of the Robots
self.newPos = []
# Population of Configuration Changes
self.cfgc = []
# Number of Stalls (Used only for simulating Rooker's work)
self.stalls = 0
# Keeps track of whether the Final Stats were displayed
self.printedFinalStats = False
# Keeps track of Possible Configurations
self.possible = []
# Keeps track of Number of Cells Visited
# (Initialize this to self.numRobots, since the starting locations of the robots are considered visited)
self.visited = self.numRobots
self.sumNewVisited = numRobots
# Flag to switch between A* and Manhattan distance
self.aStarFlag = False
# Define value for infinity
self.infinity = 10000000
# Flag to switch between Hungarian and Greedy assignment
self.hungarianFlag = True
# Flag to switch between Greedy and Random Motion Planner
self.randomMotionPlan = False
# Variable to store the number of robots that do not make a move in the current iteration
self.currentEights = 0
# Variable to store the total number of moves made by the robots
self.totalMoves = 0
# We also initialize an instance of AStar, which helps us in computing Manhattan distance
self.astar = AStar.AStar()
# Method to print the current gridworld to the output descriptor
def printGrid(self):
## Comment this later
frontier = self.computeFrontier()
##
print 'occupied cells:'
for i in range(self.height):
for j in range(self.width):
if self.gridworld.cells[i][j].occupied == True:
print i, j
print 'robot locations:'
for robot in self.robots:
print robot.curX, robot.curY
for i in range(self.height):
for j in range(self.width):
# If the current cell is an obstacle, print #
if self.gridworld.cells[i][j].obstacle == True:
sys.stdout.write(' # ')
# If the current cell is occupied by a robot, print its id
elif self.gridworld.cells[i][j].occupied == True:
robotId = 0
for robot in self.robots:
if robot.curX == i and robot.curY == j:
robotId = robot.id
temp = ' ' + str(robotId) + ' '
sys.stdout.write(temp)
# If the current cell is a frontier, print a |
elif (i, j) in frontier:
sys.stdout.write(' | ')
# Otherwise, print -
else:
if self.gridworld.cells[i][j].visited == True:
sys.stdout.write(' . ')
else:
sys.stdout.write(' - ')
sys.stdout.write('\n')
# Method to print the status of each cell to the output descriptor
def printVisitedStatus(self):
visited = 0
visitable = self.height * self.width
for i in range(self.height):
for j in range(self.width):
# If the current cell is an obstacle, print #
if self.gridworld.cells[i][j].visited == True:
sys.stdout.write(' 1 ')
visited += 1
# If the current cell is a frontier, print a |
else:
sys.stdout.write(' 0 ')
if self.gridworld.cells[i][j].obstacle == True:
visitable -= 1
sys.stdout.write('\n')
print 'visited:', visited, ' of ', visitable
print 'stalls:', self.stalls
return self.completionTime
# Method to print the final statistics to the output descriptor
# The final stats should be printed only once
# i.e., either when T steps have elapsed or when the frontier is empty
def printFinalStats(self, force = 0):
# if self.t != self.T:
# if self.completedFlag == False or self.printedFinalStats == True:
# return
# print 'Time taken:', self.t
visitednow=0
visitable = self.height * self.width
for i in range(self.height):
for j in range(self.width):
# If the current cell is an obstacle, print #
if self.gridworld.cells[i][j].visited == True:
visitednow += 1
# If the current cell is a frontier, print a |
else:
if self.gridworld.cells[i][j].obstacle == True:
visitable -= 1
metric = self.visited / visitable
# print (visitednow - self.visited)
print 'visitednow', visitednow
redundancy = (self.numRobots - self.currentEights) - (visitednow - self.visited)
print 'redundancy:', redundancy
# print self.currentEights
self.visited = visitednow
numMoves = self.numRobots - self.currentEights
self.totalMoves += numMoves
print 'totalMoves:', self.totalMoves
self.printedFinalStats = True
return
# Method to compute the frontier
def computeFrontier(self):
frontier = []
# Iterate over all cells in the grid
for i in range(self.height):
for j in range(self.width):
# We compute 8-neighbors for only those cells that haven't been visited or are obstacles
# Only such cells are possible candidates for the frontier
if self.gridworld.cells[i][j].visited == False and self.gridworld.cells[i][j].obstacle == False:
point = (i, j)
neighbors = self.gridworld.get8Neighbors(point)
# Now we see if there is at least one neighbor of the current cell which has been visited
# In such a case, the current cell would become a frontier cell
frontierFlag = False
for nbhr in neighbors:
if self.gridworld.cells[nbhr[0]][nbhr[1]].visited == True:
frontierFlag = True
if frontierFlag == True:
frontier.append((i, j))
return frontier
# Method to compute the new locations of each robot, given a command vector
def getNewPositions(self, cmd):
newPos = []
for i in range(self.numRobots):
nextX, nextY = self.gridworld.getNextPos(self.robots[i].curX, self.robots[i].curY, cmd[i])
newPos.append((nextX, nextY))
return newPos
# Method to check if a given configuration is possible
# We return an integer that describes the nature of the impossibility of a configuration
# 0 denotes that all robots move into non-obstacle cells
# 1 denotes that two robots occupy the same cell
# 2 denotes that one robot encounters an obstacle
def isCfgPossible(self, cfg):
# We first compute the new positions and see if two next positions coincide
# newPos = self.getNewPositions(cfg)
if any(self.newPos.count(element) > 1 for element in self.newPos) == True:
return 1
# Now we check if some robot encounters an obstacle
retval = 0
for i in range(self.numRobots):
if self.gridworld.checkCommand(self.robots[i].curX, self.robots[i].curY, cfg[i]) == False:
retval = 2
# Otherwise, the configuration is possible
return retval
def allocateFrontiers(self):
cmd = []
isJobless = False
allotted_frontier = ()
# Assign to each robot the frontier cell that yields the maximum benefit
for i in range(self.numRobots):
nearestDist = self.infinity
curX = self.robots[i].curX
curY = self.robots[i].curY
bestBenefit = -1 * self.infinity
# Compute the frontier cell with the best benefit (utility minus distance)
for cell in self.frontier:
if self.aStarFlag == True:
path, dist = self.astar.aStarSearch(self.gridworld, (curX, curY), (cell[0], cell[1]))
dist = dist[(cell[0], cell[1])]
else:
dist = abs(curX - cell[0]) + abs(curY - cell[1])
benefit = self.gridworld.cells[cell[0]][cell[1]].utility - dist
if benefit > bestBenefit:
bestBenefit = benefit
allotted_frontier = cell
# print 'allotted_frontier', i, 'gets', allotted_frontier
if allotted_frontier == ():
self.robots[i].isJobless = True
else:
self.robots[i].isJobless = False
# Reduce the utility of the allotted frontier and its neighbors
if self.robots[i].isJobless == False:
self.gridworld.cells[allotted_frontier[0]][allotted_frontier[1]].utility -= 1
# print 'newUtil:', self.gridworld.cells[allotted_frontier[0]][allotted_frontier[1]].utility
neighbors = self.gridworld.get8Neighbors(allotted_frontier)
for neighbor in neighbors:
self.gridworld.cells[neighbor[0]][neighbor[1]].utility -= 1
"""
Move the ith robot closer to its allotted frontier
"""
# If all cells in the robot's assigned cluster have been explored, the robot waits in the same cell
if isJobless == True:
# genmax stores the command that is given to a robot
# Kindly do not worry about the variable naming style
# It was all Arjun's creativity and it shall be fixed soon
shouldRecluster = True
genmax = 8
# Otherwise, it visits the cell
else:
# possCells stores the current 8-neighbors of the ith robot
possCells=[]
possCells = self.gridworld.get8Neighbors((self.robots[i].curX, self.robots[i].curY))
# If using A*
if self.aStarFlag == True:
path, tmp = self.astar.aStarSearch(self.gridworld, possCells[0], allotted_frontier)
tmp = tmp[allotted_frontier]
# If A* is not being used, Manhattan distance is used
else:
tmp = abs(possCells[0][0]-allotted_frontier[0]) + abs(possCells[0][1]-allotted_frontier[1])
# Here's yet another name from our creative genius (Arjun)
# This variable is initialized with the first of its 8-neighbors
thechosenone=possCells[0]
# For each neighbor of the ith robot
for nextcell in possCells:
# If using A*
if self.aStarFlag == True:
path, tmp1 = self.astar.aStarSearch(self.gridworld, nextcell, allotted_frontier)
tmp1 = tmp1[allotted_frontier]
# If A* is not being used, Manhattan distance is used
else:
tmp1=abs(nextcell[0]-allotted_frontier[0]) + abs(nextcell[1]-allotted_frontier[1])
# if tmp>=tmp1: ## Error ?
if tmp1 < tmp:
# path, tmp = self.astar.aStarSearch(self.gridworld, nextcell, allotted_frontier)
tmp=tmp1;
thechosenone = nextcell
genmax=self.gridworld.getcmd(thechosenone[0], thechosenone[1], self.robots[i].curX, self.robots[i].curY)
cmd.append(genmax)
# print 'cmd:', cmd
return cmd
def executeBestCfgc(self, bestCfgc):
i = 0
for cmd in bestCfgc:
tempX = self.robots[i].curX
tempY = self.robots[i].curY
if self.gridworld.checkCommand(tempX, tempY, cmd) == True:
nextX, nextY = self.gridworld.getNextPos(tempX, tempY, cmd)
self.gridworld.cells[tempX][tempY].occupied = False
self.robots[i].curX = nextX
self.robots[i].curY = nextY
self.gridworld.cells[nextX][nextY].occupied = True
self.gridworld.cells[nextX][nextY].visited = True
i += 1
# Run the algorithm for 1 iteration
def runOneIter(self):
# If t time steps have already expired, return
self.t += 1
if self.t >= self.T:
if self.printedFinalStats == False:
self.printFinalStats()
return
# Else, run the algorithm for one time step
self.frontier = self.computeFrontier()
if self.frontier == []:
if self.completedFlag == False:
self.completedFlag = True
self.completionTime = self.t
# print 'Completed in time', self.completionTime
self.printFinalStats()
return
print 'volume:', len(self.frontier)
# Perform frontier allocation
bestCfgc = self.allocateFrontiers()
self.executeBestCfgc(bestCfgc)
# time.sleep(1)
# Print the final statistics
self.printFinalStats()
| 33.932584 | 109 | 0.683775 |
aceca43bf415d1d1eae8181b7e94d265852ce1f2 | 15,867 | py | Python | salmon/uploader/spectrals.py | ligh7s/smoked-salmon | f995ebc760321638e207f52ad0154ac29eb74946 | [
"Apache-2.0"
] | 42 | 2020-03-02T11:42:17.000Z | 2022-03-02T13:51:05.000Z | salmon/uploader/spectrals.py | 151henry151/smoked-salmon | c4694d5f2383cdf7a862d2a346cb821f0fd876f5 | [
"Apache-2.0"
] | 20 | 2020-03-02T11:46:43.000Z | 2022-01-26T23:33:37.000Z | salmon/uploader/spectrals.py | 151henry151/smoked-salmon | c4694d5f2383cdf7a862d2a346cb821f0fd876f5 | [
"Apache-2.0"
] | 16 | 2020-03-01T11:29:55.000Z | 2022-01-24T18:10:35.000Z | import asyncio
import os
import platform
import shutil
import subprocess
import time
from os.path import dirname, join
import click
from salmon import config
from salmon.common import flush_stdin, get_audio_files, prompt_async
from salmon.errors import (
AbortAndDeleteFolder,
ImageUploadFailed,
UploadError,
WebServerIsAlreadyRunning,
)
from salmon.images import upload_spectrals as upload_spectral_imgs
from salmon.web import create_app_async, spectrals
# used by post upload stuff might move.
import re
from bs4 import BeautifulSoup
loop = asyncio.get_event_loop()
THREADS = [None] * config.SIMULTANEOUS_SPECTRALS
def check_spectrals(
path, audio_info, lossy_master=None, spectral_ids=None, check_lma=True
):
"""
Run the spectral checker functions. Generate the spectrals and ask whether or
not the files are lossy. If the IDs were not all provided, prompt for spectrals
to upload.
"""
click.secho(f"\nChecking lossy master / spectrals...", fg="cyan", bold=True)
spectrals_path = create_specs_folder(path)
if not spectral_ids:
all_spectral_ids = generate_spectrals_all(path, spectrals_path, audio_info)
while True:
view_spectrals(spectrals_path, all_spectral_ids)
if lossy_master is None and check_lma:
lossy_master = prompt_lossy_master()
if lossy_master is not None:
break
else:
break
else:
if lossy_master is None:
lossy_master = prompt_lossy_master()
if not spectral_ids:
spectral_ids = prompt_spectrals(all_spectral_ids, lossy_master, check_lma)
else:
spectral_ids = generate_spectrals_ids(
path, spectral_ids, spectrals_path, audio_info
)
return lossy_master, spectral_ids
def handle_spectrals_upload_and_deletion(
spectrals_path, spectral_ids, delete_spectrals=True
):
spectral_urls = upload_spectrals(spectrals_path, spectral_ids)
if delete_spectrals and os.path.isdir(spectrals_path):
shutil.rmtree(spectrals_path)
return spectral_urls
def generate_spectrals_all(path, spectrals_path, audio_info):
"""Wrapper function to generate all spectrals."""
files_li = get_audio_files(path)
return _generate_spectrals(path, files_li, spectrals_path, audio_info)
def generate_spectrals_ids(path, track_ids, spectrals_path, audio_info):
"""Wrapper function to generate a specific set of spectrals."""
if track_ids == (0,):
click.secho("Uploading no spectrals...", fg="yellow")
return {}
wanted_filenames = get_wanted_filenames(list(audio_info), track_ids)
files_li = [fn for fn in get_audio_files(path) if fn in wanted_filenames]
return _generate_spectrals(path, files_li, spectrals_path, audio_info)
def get_wanted_filenames(filenames, track_ids):
"""Get the filenames from the spectrals specified as cli options."""
try:
return {filenames[i - 1] for i in track_ids}
except IndexError:
raise UploadError("Spectral IDs out of range.")
def _generate_spectrals(path, files_li, spectrals_path, audio_info):
"""
Iterate over the filenames and generate the spectrals. Abuse async nature of
subprocess.Popen to spawn multiple processes and generate multiple spectrals
at the same time.
"""
cur_track = 1
spectral_ids = {}
files = iter(files_li)
broken = False
while True:
for i in range(len(THREADS)):
if THREADS[i] is None or THREADS[i].poll() is not None:
try:
filename = next(files)
except StopIteration:
broken = True
break
zoom_startpoint = calculate_zoom_startpoint(audio_info[filename])
click.secho(
f"Generating spectrals for track {cur_track:02d}/"
f"{len(files_li):02d}\r",
nl=False,
)
cur_track += 1
THREADS[i] = subprocess.Popen(
[
"sox",
"--multi-threaded",
os.path.join(path, filename),
"--buffer",
"128000",
"-n",
"remix",
"1",
"spectrogram",
"-x",
"2000",
"-y",
"513",
"-z",
"120",
"-w",
"Kaiser",
"-o",
os.path.join(spectrals_path, f"{cur_track - 1:02d} Full.png"),
"remix",
"1",
"spectrogram",
"-x",
"500",
"-y",
"1025",
"-z",
"120",
"-w",
"Kaiser",
"-S",
str(zoom_startpoint),
"-d",
"0:02",
"-o",
os.path.join(spectrals_path, f"{cur_track - 1:02d} Zoom.png"),
]
)
spectral_ids[cur_track - 1] = filename
if broken and all(
THREADS[i] is None or THREADS[i].poll() is not None
for i in range(len(THREADS))
):
break
time.sleep(0.05)
click.secho("Finished generating spectrals. ", fg="green")
if config.COMPRESS_SPECTRALS:
_compress_spectrals(spectrals_path)
return spectral_ids
def _compress_spectrals(spectrals_path):
"""
Iterate over the spectrals directory and compress them. Abuse async nature of
subprocess.Popen to spawn multiple processes and compress multiple simultaneously.
"""
files = [f for f in os.listdir(spectrals_path) if f.endswith(".png")]
files_iter = iter(files)
cur_file = 1
broken = False
while True:
with open(os.devnull, "rb") as devnull:
for i in range(len(THREADS)):
if THREADS[i] is None or THREADS[i].poll() is not None:
try:
filename = next(files_iter)
except StopIteration:
broken = True
break
click.secho(
f"Compressing spectral image {cur_file:02d}/{len(files):02d}\r",
nl=False,
)
cur_file += 1
THREADS[i] = subprocess.Popen(
[
"optipng",
"-o2",
"-strip",
"all",
os.path.join(spectrals_path, filename),
],
stdout=devnull,
stderr=devnull,
)
if broken and all(
THREADS[i] is None or THREADS[i].poll() is not None
for i in range(len(THREADS))
):
break
time.sleep(0.05)
click.secho("Finished compressing spectrals. ", fg="green")
def create_specs_folder(path):
"""Create the spectrals folder."""
spectrals_path = os.path.join(path, "Spectrals")
if os.path.isdir(spectrals_path):
shutil.rmtree(spectrals_path)
os.mkdir(spectrals_path)
return spectrals_path
def calculate_zoom_startpoint(track_data):
"""
Calculate the point in the track to generate the zoom. Do 5 seconds before
the end of the track if it's over 5 seconds long. Otherwise start at 2.
"""
if "duration" in track_data and track_data["duration"] > 5:
return track_data["duration"] // 2
return 0
def view_spectrals(spectrals_path, all_spectral_ids):
"""Open the generated spectrals in an image viewer."""
if not config.NATIVE_SPECTRALS_VIEWER:
loop.run_until_complete(
_open_specs_in_web_server(spectrals_path, all_spectral_ids)
)
elif platform.system() == "Darwin":
_open_specs_in_preview(spectrals_path)
else:
_open_specs_in_feh(spectrals_path)
def _open_specs_in_preview(spectrals_path):
args = [
"qlmanage",
"-p",
f"{spectrals_path}/*",
]
with open(os.devnull, "w") as devnull:
subprocess.Popen(args, stdout=devnull, stderr=devnull)
def _open_specs_in_feh(spectrals_path):
args = [
"feh",
"--cycle-once",
"--sort",
"filename",
"-d",
"--auto-zoom",
"-geometry",
"-.",
spectrals_path,
]
if config.FEH_FULLSCREEN:
args.insert(4, "--fullscreen")
with open(os.devnull, "w") as devnull:
subprocess.Popen(args, stdout=devnull, stderr=devnull)
async def _open_specs_in_web_server(specs_path, all_spectral_ids):
spectrals.set_active_spectrals(all_spectral_ids)
symlink_path = join(dirname(dirname(__file__)), "web", "static", "specs")
shutdown = True
try:
try:
os.symlink(specs_path, symlink_path)
except FileExistsError:
os.unlink(symlink_path)
os.symlink(specs_path, symlink_path)
try:
runner = await create_app_async()
except WebServerIsAlreadyRunning:
shutdown = False
url = f"{config.WEB_HOST}/spectrals"
await prompt_async(
click.style(
f"Spectrals are available at {url} . Press enter once you are finished "
"viewing to continue the uploading process:",
fg="magenta",
bold=True,
),
end=" ",
flush=True,
)
if shutdown:
await runner.cleanup()
finally:
os.unlink(symlink_path)
def upload_spectrals(spectrals_path, spectral_ids):
"""
Create the tuples of spectral ids and filenames, then send them to the
spectral uploader.
"""
if not spectral_ids:
return None
spectrals = []
for sid, filename in spectral_ids.items():
spectrals.append(
(
sid - 1,
filename,
(
os.path.join(spectrals_path, f"{sid:02d} Full.png"),
os.path.join(spectrals_path, f"{sid:02d} Zoom.png"),
),
)
)
try:
return upload_spectral_imgs(spectrals)
except ImageUploadFailed as e:
return click.secho(f"Failed to upload spectral: {e}", fg="red")
def prompt_spectrals(spectral_ids, lossy_master, check_lma):
"""Ask which spectral IDs the user wants to upload."""
while True:
ids = click.prompt(
click.style(
f"What spectral IDs would you like to upload to "
f"{config.SPECS_UPLOADER}? (\" * \" for all)",
fg="magenta",
bold=True,
),
default="",
)
if ids.strip() == "*":
return spectral_ids
ids = [i.strip() for i in ids.split()]
if not ids and lossy_master and check_lma:
click.secho(
"This release has been flagged as lossy master, please select at least "
"one spectral.",
fg="red",
)
continue
if all(i.isdigit() and int(i) in spectral_ids for i in ids):
return {int(id_): spectral_ids[int(id_)] for id_ in ids}
click.secho(
f"Invalid IDs. Valid IDs are: {', '.join(str(s) for s in spectral_ids)}.",
fg="red",
)
def prompt_lossy_master():
while True:
flush_stdin()
r = click.prompt(
click.style(
"\nIs this release lossy mastered? [y]es, [N]o, [r]eopen spectrals, "
"[a]bort, [d]elete folder",
fg="magenta",
bold=True,
),
type=click.STRING,
default="N",
)[0].lower()
if r == "y":
return True
elif r == "n":
return False
elif r == "r":
return None
elif r == "a":
raise click.Abort
elif r == "d":
raise AbortAndDeleteFolder
def report_lossy_master(
gazelle_site,
torrent_id,
spectral_urls,
track_data,
source,
comment,
source_url=None,
):
"""
Generate the report description and call the function to report the torrent
for lossy WEB/master approval.
"""
filenames = list(track_data.keys())
comment = _add_spectral_links_to_lossy_comment(
comment, source_url, spectral_urls, filenames
)
loop.run_until_complete(
gazelle_site.report_lossy_master(torrent_id, comment, source)
)
click.secho("\nReported upload for Lossy Master/WEB Approval Request.", fg="cyan")
def generate_lossy_approval_comment(source_url, filenames):
comment = click.prompt(
click.style(
"Do you have a comment for the lossy approval report? It is appropriate to "
"make a note about the source here. Source information from go, gos, and the "
"queue will be included automatically.",
fg="cyan",
bold=True,
),
default="",
)
if not (comment or source_url):
click.secho(
f"This release was not uploaded with go, gos, or the queue, "
"so you must add a comment about the source.",
fg="red",
)
return generate_lossy_approval_comment(source_url, filenames)
return comment
def _add_spectral_links_to_lossy_comment(comment, source_url, spectral_urls, filenames):
if comment:
comment += "\n\n"
if source_url:
comment += f"Sourced from: {source_url}\n\n"
comment+=make_spectral_bbcode(filenames,spectral_urls)
return comment
def make_spectral_bbcode(filenames, spectral_urls):
"Generates the bbcode for spectrals in descriptions and reports."
bbcode = "[hide=Spectrals]"
for spec_id, urls in spectral_urls.items():
filename = re.sub(r"[\[\]]", "_", filenames[spec_id])
bbcode += f'[b]{filename} Full[/b]\n[img={urls[0]}]\n[hide=Zoomed][img={urls[1]}][/hide]\n\n'
bbcode += '[/hide]\n'
return bbcode
def post_upload_spectral_check(
gazelle_site, path, torrent_id, spectral_ids, track_data, source, source_url
):
"Offers generation and adition of spectrals after upload"
lossy_master, spectral_ids = check_spectrals(path, track_data, None, spectral_ids)
lossy_comment = None
if lossy_master:
lossy_comment = generate_lossy_approval_comment(
source_url, list(track_data.keys())
)
click.echo()
spectrals_path = os.path.join(path, "Spectrals")
spectral_urls = handle_spectrals_upload_and_deletion(spectrals_path, spectral_ids)
# need to refactor bbcode to not be repeated.
if spectral_urls:
spectrals_bbcode = make_spectral_bbcode(list(track_data.keys()), spectral_urls)
a = loop.run_until_complete(
gazelle_site.append_to_torrent_description(torrent_id, spectrals_bbcode)
)
if lossy_master:
report_lossy_master(
gazelle_site,
torrent_id,
spectral_urls,
track_data,
source,
lossy_comment,
source_url,
)
return lossy_master, lossy_comment, spectral_urls
| 31.861446 | 101 | 0.563749 |
aceca4823bca03e9f565d76813808711750befc1 | 1,314 | py | Python | pyvisdk/do/virtual_e1000_option.py | Infinidat/pyvisdk | f2f4e5f50da16f659ccc1d84b6a00f397fa997f8 | [
"MIT"
] | null | null | null | pyvisdk/do/virtual_e1000_option.py | Infinidat/pyvisdk | f2f4e5f50da16f659ccc1d84b6a00f397fa997f8 | [
"MIT"
] | null | null | null | pyvisdk/do/virtual_e1000_option.py | Infinidat/pyvisdk | f2f4e5f50da16f659ccc1d84b6a00f397fa997f8 | [
"MIT"
] | null | null | null |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def VirtualE1000Option(vim, *args, **kwargs):
'''The VirtualE1000 option data object type contains the options for the
VirtualE1000 data object type.'''
obj = vim.client.factory.create('{urn:vim25}VirtualE1000Option')
# do some validation checking...
if (len(args) + len(kwargs)) < 8:
raise IndexError('Expected at least 9 arguments got: %d' % len(args))
required = [ 'macType', 'supportedOUI', 'vmDirectPathGen2Supported', 'wakeOnLanEnabled',
'deprecated', 'hotRemoveSupported', 'plugAndPlay', 'type' ]
optional = [ 'autoAssignController', 'backingOption', 'connectOption', 'controllerType',
'defaultBackingOptionIndex', 'licensingLimit', 'dynamicProperty', 'dynamicType' ]
for name, arg in zip(required+optional, args):
setattr(obj, name, arg)
for name, value in kwargs.items():
if name in required + optional:
setattr(obj, name, value)
else:
raise InvalidArgumentError("Invalid argument: %s. Expected one of %s" % (name, ", ".join(required + optional)))
return obj
| 36.5 | 124 | 0.637747 |
aceca639e396399c3dec7f7ffa4b72b618586026 | 544 | py | Python | merkki.py | UrsaOK/supertassu | c9158f50281000f57fe14aba4115aa867a72e0ca | [
"BSD-2-Clause"
] | null | null | null | merkki.py | UrsaOK/supertassu | c9158f50281000f57fe14aba4115aa867a72e0ca | [
"BSD-2-Clause"
] | 2 | 2015-01-18T14:51:32.000Z | 2016-02-24T20:15:12.000Z | merkki.py | UrsaOK/supertassu | c9158f50281000f57fe14aba4115aa867a72e0ca | [
"BSD-2-Clause"
] | null | null | null | import libtcodpy as libtcod
class Merkki(object):
def __init__(self, merkki):
print("merkki init")
self.merkki = merkki
def draw(self, puskuri, x, y):
libtcod.console_put_char(puskuri, x, y, self.merkki, libtcod.BKGND_NONE)
class Sprite(Merkki):
def __init__(self, x, y, merkki):
print("Sprite init")
super(Sprite, self).__init__(merkki)
self.x = x
self.y = y
def draw(self, puskuri):
print("Sprite draw")
super(Sprite, self).draw(puskuri, self.x, self.y)
| 27.2 | 80 | 0.619485 |
aceca63e0bf8a67c50939b2ccecfbf2a993962d7 | 2,830 | py | Python | src/pipeline.py | n0tus/sdcnd-2-advaned-lane-detection | 44dd627b8e9b5be44373007c1494d7a446050c1c | [
"MIT"
] | null | null | null | src/pipeline.py | n0tus/sdcnd-2-advaned-lane-detection | 44dd627b8e9b5be44373007c1494d7a446050c1c | [
"MIT"
] | null | null | null | src/pipeline.py | n0tus/sdcnd-2-advaned-lane-detection | 44dd627b8e9b5be44373007c1494d7a446050c1c | [
"MIT"
] | null | null | null | import numpy as np
import cv2
from edgedetection import EdgeDetection
from schannel import s_channel_threshold
from lanes import Lane
from plot import plot_images
def detect_edges(img, gradx_params, grady_params, mag_params, dir_params, plot_steps=False):
hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)
l_channel = hls[:,:,1]
s_channel = hls[:,:,2]
edge_d = EdgeDetection()
grad_x_binary = edge_d.gradient(img, 'x', gradx_params[0], gradx_params[1], l_channel)
grad_x_binary_s = s_channel_threshold(s_channel, gradx_params[2], grad_x_binary)
grad_y_binary = edge_d.gradient(img, 'y', grady_params[0], grady_params[1], l_channel)
grad_y_binary_s = s_channel_threshold(s_channel, grady_params[2], grad_y_binary)
mag_binary = edge_d.magnitude(img, mag_params[0], mag_params[1], l_channel)
mag_binary_s = s_channel_threshold(s_channel, mag_params[2], mag_binary)
dir_binary = edge_d.direction(img, dir_params[0], dir_params[1], l_channel)
dir_binary_s = s_channel_threshold(s_channel, dir_params[2], dir_binary)
combined = edge_d.combine(grad_x_binary_s, grad_y_binary_s, mag_binary_s, dir_binary_s)
if plot_steps == True:
threshold_images = []
threshold_images.append(grad_x_binary)
threshold_images.append(grad_y_binary)
threshold_images.append(mag_binary)
threshold_images.append(dir_binary)
threshold_images.append(grad_x_binary_s)
threshold_images.append(grad_y_binary_s)
threshold_images.append(mag_binary_s)
threshold_images.append(dir_binary_s)
plot_images(threshold_images, 2)
return combined
def transform_perspective(image, camera):
try:
height, width = image.shape
except:
height, width, _ = image.shape
offset = 150
upper_left_src = [width/2 - 50, height/2 + 100]
upper_right_src = [width/2 + 50, height/2 + 100]
bottom_left_src = [0+offset, height - 20]
bottom_right_src = [width-offset, height - 20]
src = np.float32([upper_left_src, upper_right_src, bottom_right_src, bottom_left_src])
lines = np.array(src, np.int32)
upper_left_dst = [0+offset*2+10, 0]
upper_right_dst = [width-offset*2, 0]
bottom_left_dst = [0+offset+20, height]
bottom_right_dst = [width-offset-20, height]
dst = np.float32([upper_left_dst, upper_right_dst, bottom_right_dst, bottom_left_dst])
return camera.transform_perspective(image, src, dst)
def find_lane_lines(lane, img, nwindows, margin, minpix):
if lane == None:
lane = Lane(img)
lane.find_pixels(nwindows, margin, minpix)
else:
left_fit = lane.left_fit
right_fit = lane.right_fit
lane.img = img
lane.search_around_poly(left_fit, right_fit)
lane.fit_polynomial()
return lane
| 34.096386 | 92 | 0.709894 |
aceca6d6d7d0459350150ff70d7711f2b4dd65d5 | 3,610 | py | Python | src/direct_trainer/train_direct_matching.py | renyi-ai/drfrankenstein | b9064cdea67698f70af07849bc5decaafccac9f3 | [
"MIT"
] | 4 | 2021-12-08T14:27:19.000Z | 2022-01-05T20:19:03.000Z | src/direct_trainer/train_direct_matching.py | renyi-ai/drfrankenstein | b9064cdea67698f70af07849bc5decaafccac9f3 | [
"MIT"
] | null | null | null | src/direct_trainer/train_direct_matching.py | renyi-ai/drfrankenstein | b9064cdea67698f70af07849bc5decaafccac9f3 | [
"MIT"
] | null | null | null | """
This file is the entry point of direct matching methods trained by optimization.
"""
import argparse
import os
import pickle
from os import path
from losses import get_loss
from src.models import load_from_path
from src.models.frank.frankenstein import FrankeinsteinNet
from src.direct_trainer.direct_trainer import DirectTrainer
def _parse_args(args):
parser = argparse.ArgumentParser(description='Simple settings.')
parser.add_argument('pickle', nargs="+", help='Path to pickle')
parser.add_argument('--init_model', type=str,
default='ps_inv_model',
choices=["frank_model", "ps_inv_model", "front_model", "end_model"],
help="Which model's transformation matrix to use as init")
parser.add_argument('--train_on', type=str,
default='val',
choices=["train", "val"],
help="Which split to use for training, val or train")
parser.add_argument('--loss', type=str, help="Choose loss from direct_trainer.losses")
parser.add_argument('--epoch', type=int,
default=100,
help='Number of epochs to train')
parser.add_argument('--batch', type=int,
default=64,
help='Batch size')
parser.add_argument('--lr', type=float,
default=0.0001,
help='Learning rate')
parser.add_argument('--dev', type=int,
default=0,
help='If true save results to temp folder')
parser.add_argument('--out_dir', type=str,
default=None,
help='Output folder for result pickle')
args = parser.parse_args(args)
return args
def main(args=None):
args = _parse_args(args)
for pkl in args.pickle:
print(f"Processing: {pkl}")
data_dict = pickle.load(open(pkl, "br"))
front_model = load_from_path(data_dict['params']['front_model'])
end_model = load_from_path(data_dict['params']['end_model'])
frank_model = FrankeinsteinNet.from_data_dict(data_dict, "after")
ps_inv_model = FrankeinsteinNet.from_data_dict(data_dict, 'ps_inv')
device = "cuda"
frank_model.to(device)
ps_inv_model.to(device)
front_model.to(device)
end_model.to(device)
data_name = data_dict['params']['dataset']
pickle_dir, pickle_filename = path.split(pkl)
pickle_filename = pickle_filename.replace(" ", "_").replace(":", "")
out_file_name = "direct_matching_" + pickle_filename
if args.out_dir is not None:
os.makedirs(args.out_dir, exist_ok=True)
out_file = path.join(args.out_dir, out_file_name)
else:
out_file = None
comparator = DirectTrainer(frank_model=frank_model,
ps_inv_model=ps_inv_model,
front_model=front_model,
end_model=end_model,
init_model=args.init_model,
loss=get_loss(args.loss),
batch_size=args.batch,
epoch=args.epoch,
lr=args.lr,
out_file=out_file,
original_data_dict=data_dict)
comparator(dataset_str=data_name, train_on=args.train_on)
if __name__ == '__main__':
main()
| 39.23913 | 92 | 0.563158 |
aceca7fa096e8571025b629bf621d00cb5929628 | 1,742 | py | Python | beagle/datasources/procmon_csv.py | limkokhian/beagle | 791e83db94e5a8ab1965b155bb79d32bb259d2b3 | [
"MIT"
] | 1,139 | 2019-03-24T09:09:05.000Z | 2022-03-27T14:54:38.000Z | beagle/datasources/procmon_csv.py | limkokhian/beagle | 791e83db94e5a8ab1965b155bb79d32bb259d2b3 | [
"MIT"
] | 78 | 2019-03-24T16:56:06.000Z | 2022-02-27T21:31:38.000Z | beagle/datasources/procmon_csv.py | limkokhian/beagle | 791e83db94e5a8ab1965b155bb79d32bb259d2b3 | [
"MIT"
] | 149 | 2019-03-24T16:44:45.000Z | 2022-03-11T12:20:51.000Z | import datetime
import os
from typing import Generator
import pandas as pd
from beagle.common.logging import logger
from beagle.datasources.base_datasource import DataSource
from beagle.transformers.procmon_transformer import ProcmonTransformer
class ProcmonCSV(DataSource):
"""Reads events in one by one from a ProcMon CSV, and parses them into the GenericTransformer"""
name = "Procmon CSV" # The name as it'll appear in the web GUI
category = "Procmon" # The category this will output to.
transformers = [ProcmonTransformer] # The transformer this will send events to
def __init__(self, procmon_csv: str) -> None:
self._df = pd.read_csv(procmon_csv)
# Procmon doesn't have dates time.
self.now = datetime.datetime.now()
logger.info("Set up ProcmonCSVs")
def metadata(self) -> dict:
return {}
def events(self) -> Generator[dict, None, None]:
for _, row in self._df.iterrows():
# Get times
hr_min_sec = row["Time of Day"].split(".")[0]
# Check if AM
in_am = "AM" in row["Time of Day"]
# set the hours/min/sec
date = self.now.replace(
second=int(hr_min_sec.split(":")[-1]),
hour=int(hr_min_sec.split(":")[0]) + (0 if in_am else 12),
minute=int(hr_min_sec.split(":")[1]),
)
epoch = int(date.strftime("%s"))
yield {
"event_time": epoch,
"event_type": row["Operation"],
"process_name": row["Process Name"],
"path": row["Path"],
"process_id": int(row["PID"]),
"params": row["Detail"],
}
| 30.561404 | 100 | 0.578645 |
aceca8d9abc53153d395ee641376d08ff17bb116 | 11,621 | py | Python | hknweb/candidate/views.py | briana-jin-zhang/hknweb | 45b319f77774d11802763710feb997c6b627237b | [
"MIT"
] | null | null | null | hknweb/candidate/views.py | briana-jin-zhang/hknweb | 45b319f77774d11802763710feb997c6b627237b | [
"MIT"
] | null | null | null | hknweb/candidate/views.py | briana-jin-zhang/hknweb | 45b319f77774d11802763710feb997c6b627237b | [
"MIT"
] | null | null | null | from django.views import generic
from django.views.generic.edit import FormView
from django.shortcuts import render, redirect, reverse
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.utils import timezone
from django.conf import settings
from django.contrib.staticfiles.finders import find
from django.db.models import Q
from random import randint
from .models import OffChallenge, Announcement
from ..events.models import Event, Rsvp
from .forms import ChallengeRequestForm, ChallengeConfirmationForm
# decorators
# used for things only officers and candidates can access
# TODO: use permissions instead of just the groups
def check_account_access(func):
def check_then_call(request, *args, **kwargs):
if not is_cand_or_officer(request.user):
return render(request, "errors/401.html", status=401)
return func(request, *args, **kwargs)
return check_then_call
# views
# Candidate portal home
@method_decorator(login_required(login_url='/accounts/login/'), name='dispatch')
@method_decorator(check_account_access, name='dispatch')
# @method_decorator(is_cand_or_officer)
class IndexView(generic.TemplateView):
template_name = 'candidate/index.html'
context_object_name = 'my_favorite_publishers'
def get_context_data(self):
challenges = OffChallenge.objects \
.filter(requester__exact=self.request.user)
# if either one is waiting, challenge is still being reviewed
num_pending = challenges \
.filter(Q(officer_confirmed__isnull=True) | Q(csec_confirmed__isnull=True)) \
.count()
num_rejected = challenges \
.filter(Q(officer_confirmed=False) | Q(csec_confirmed=False)) \
.count()
announcements = Announcement.objects \
.filter(visible=True) \
.order_by('-release_date')
today = timezone.now()
rsvps = Rsvp.objects.filter(user__exact=self.request.user)
# Both confirmed and unconfirmed rsvps have been sorted into event types
confirmed_events = sort_rsvps_into_events(rsvps.filter(confirmed=True))
unconfirmed_events = sort_rsvps_into_events(rsvps.filter(confirmed=False))
req_statuses = check_requirements(confirmed_events)
upcoming_events = Event.objects \
.filter(start_time__range=(today, today + timezone.timedelta(days=7))) \
.order_by('start_time')
context = {
'num_pending' : num_pending,
'num_rejected' : num_rejected,
# anything not pending or rejected is confirmed
'num_confirmed' : challenges.count() - num_pending - num_rejected,
'announcements' : announcements,
'confirmed_events': confirmed_events,
'unconfirmed_events': unconfirmed_events,
'req_statuses' : req_statuses,
'upcoming_events': upcoming_events,
}
return context
# Form for submitting officer challenge requests
# And list of past requests for candidate
@method_decorator(login_required(login_url='/accounts/login/'), name='dispatch')
@method_decorator(check_account_access, name='dispatch')
class CandRequestView(FormView, generic.ListView):
template_name = 'candidate/candreq.html'
form_class = ChallengeRequestForm
success_url = "/cand/candreq"
context_object_name = 'challenge_list'
# resolve conflicting inheritance
def get(self, request, *args, **kwargs):
return generic.ListView.get(self, request, *args, **kwargs)
def form_valid(self, form):
form.instance.requester = self.request.user
form.save()
self.send_request_email(form)
messages.success(self.request, 'Your request was submitted to the officer!')
return super().form_valid(form)
def send_request_email(self, form):
subject = '[HKN] Confirm Officer Challenge'
officer_email = form.instance.officer.email
confirm_link = self.request.build_absolute_uri(
reverse("candidate:challengeconfirm", kwargs={ 'pk' : form.instance.id }))
html_content = render_to_string(
'candidate/request_email.html',
{
'candidate_name' : form.instance.requester.get_full_name(),
# TODO: for some usernames such as catherine.hu, this becomes a link. Why??
'candidate_username' : form.instance.requester.username,
'confirm_link' : confirm_link,
'img_link' : get_rand_photo(),
}
)
msg = EmailMultiAlternatives(subject, subject,
'no-reply@hkn.eecs.berkeley.edu', [officer_email])
msg.attach_alternative(html_content, "text/html")
msg.send()
def get_queryset(self):
result = OffChallenge.objects \
.filter(requester__exact=self.request.user) \
.order_by('-request_date')
return result
# List of past challenge requests for officer
# Non-officers can still visit this page but it will not have any entries
@method_decorator(login_required(login_url='/accounts/login/'), name='dispatch')
@method_decorator(check_account_access, name='dispatch')
class OffRequestView(generic.ListView):
template_name = 'candidate/offreq.html'
context_object_name = 'challenge_list'
def get_queryset(self):
result = OffChallenge.objects \
.filter(officer__exact=self.request.user) \
.order_by('-request_date')
return result
# Officer views and confirms a challenge request after clicking email link
# Only the officer who game the challenge can review it
@login_required(login_url='/accounts/login/')
@check_account_access
def officer_confirm_view(request, pk):
# TODO: gracefully handle when a challenge does not exist
challenge = OffChallenge.objects.get(id=pk)
if request.user.id != challenge.officer.id:
return render(request, "errors/401.html", status=401)
requester_name = challenge.requester.get_full_name()
form = ChallengeConfirmationForm(request.POST or None, instance=challenge)
context = {
'challenge': challenge,
'requester_name': requester_name,
'form': form,
}
if form.is_valid():
form.instance.reviewed = True
form.save()
# csec has already confirmed, and now officer confirms
if challenge.officer_confirmed is True and challenge.csec_confirmed is True:
send_cand_confirm_email(request, form.instance, True)
# csec has not already rejected, and now officer rejects
elif challenge.officer_confirmed is False and challenge.csec_confirmed is not False:
send_cand_confirm_email(request, form.instance, False)
# if neither is true, either need to wait for csec to review,
# or csec has already rejected
return redirect('/cand/reviewconfirm/{}'.format(pk))
return render(request, "candidate/challenge_confirm.html", context=context)
# The page displayed after officer reviews challenge and clicks "submit"
@login_required(login_url='/accounts/login/')
@check_account_access
def officer_review_confirmation(request, pk):
challenge = OffChallenge.objects.get(id=pk)
requester_name = challenge.requester.get_full_name()
context = {
'challenge' : challenge,
'requester_name' : requester_name,
}
return render(request, "candidate/review_confirm.html", context=context)
# Detail view of an officer challenge
@login_required(login_url='/accounts/login/')
@check_account_access
def challenge_detail_view(request, pk):
challenge = OffChallenge.objects.get(id=pk)
officer_name = challenge.officer.get_full_name()
requester_name = challenge.requester.get_full_name()
# check whether the viewer of page is the officer who gave the challenge
viewer_is_the_officer = challenge.officer == request.user
# check whether the viewer of page is an officer
if viewer_is_the_officer:
review_link = request.build_absolute_uri(
reverse("candidate:challengeconfirm", kwargs={ 'pk' : pk }))
else:
review_link = None
context = {
"challenge" : challenge,
"officer_name" : officer_name,
"requester_name" : requester_name,
"viewer_is_the_officer" : viewer_is_the_officer,
# viewer_is_an_officer is already added as a context variable with a context processor
"review_link" : review_link,
}
return render(request, "candidate/challenge_detail.html", context=context)
# HELPERS
def is_cand_or_officer(user):
return user.groups.filter(name=settings.CAND_GROUP).exists() or \
user.groups.filter(name=settings.OFFICER_GROUP).exists()
# This function is not used; it can be used to view all photos available
def get_all_photos():
with open(find("candidate/animal_photo_urls.txt")) as f:
urls = f.readlines()
return [url.strip() + "?w=400" for url in urls]
# images from pexels.com
def get_rand_photo(width=400):
with open(find("candidate/animal_photo_urls.txt")) as f:
urls = f.readlines()
return urls[randint(0, len(urls) - 1)].strip() + "?w=" + str(width)
def send_cand_confirm_email(request, challenge, confirmed):
subject = '[HKN] Your officer challenge was reviewed'
candidate_email = challenge.requester.email
challenge_link = request.build_absolute_uri(
reverse("candidate:detail", kwargs={ 'pk': challenge.id }))
html_content = render_to_string(
'candidate/cand_confirm_email.html',
{
'confirmed': confirmed,
'officer_name': challenge.officer.get_full_name(),
'officer_username': challenge.officer.username,
'challenge_link': challenge_link,
'img_link': get_rand_photo(),
}
)
msg = EmailMultiAlternatives(subject, subject,
'no-reply@hkn.eecs.berkeley.edu', [candidate_email])
msg.attach_alternative(html_content, "text/html")
msg.send()
# Takes in all confirmed rsvps and sorts them into types, current hard coded
# TODO: support more flexible typing and string-to-var parsing/conversion
def sort_rsvps_into_events(rsvps):
# Events in admin are currently in a readable format, must convert them to callable keys for Django template
map_event_vars = {
'mandatory_meetings': 'Mandatory',
'big_fun': 'Big Fun',
'fun': 'Fun',
'serv': 'Serv',
'prodev': 'Prodev',
}
sorted_events = dict.fromkeys(map_event_vars.keys())
for event_key, event_type in map_event_vars.items():
temp = []
for rsvp in rsvps.filter(event__event_type__type=event_type):
temp.append(rsvp.event)
sorted_events[event_key] = temp
return sorted_events
# Checks which requirements have been fulfilled by a candidate
def check_requirements(sorted_rsvps):
# TODO: increase flexibility by fetching event requirement count from database
req_list = {
'mandatory_meetings': 3,
'big_fun': 1,
'fun': 3,
'serv': 1,
'prodev': 1,
}
req_statuses = dict.fromkeys(req_list.keys(), False)
for req_type, minimum in req_list.items():
if len(sorted_rsvps[req_type])>= minimum:
req_statuses[req_type] = True
return req_statuses
| 39.662116 | 112 | 0.689269 |
acecaa8fe4627c3f69ec0a7dee63fb097b097a25 | 395 | py | Python | ExcelBack/wsgi.py | teddydotpy/Excel_Api | 3cb14769eb8e7a53dc102b707b698efb536f7cb7 | [
"MIT"
] | null | null | null | ExcelBack/wsgi.py | teddydotpy/Excel_Api | 3cb14769eb8e7a53dc102b707b698efb536f7cb7 | [
"MIT"
] | null | null | null | ExcelBack/wsgi.py | teddydotpy/Excel_Api | 3cb14769eb8e7a53dc102b707b698efb536f7cb7 | [
"MIT"
] | null | null | null | """
WSGI config for ExcelBack project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ExcelBack.settings')
application = get_wsgi_application()
| 23.235294 | 78 | 0.787342 |
acecabaea3985b445039500e89198fca0cb91e8b | 785 | py | Python | post/urls.py | silvareal/personal-blog | 9ed8ac48864510cd5b3227b7b0f7d335beb648de | [
"MIT"
] | 2 | 2018-03-15T16:53:11.000Z | 2020-01-17T15:56:33.000Z | post/urls.py | silvareal/personal-blog | 9ed8ac48864510cd5b3227b7b0f7d335beb648de | [
"MIT"
] | null | null | null | post/urls.py | silvareal/personal-blog | 9ed8ac48864510cd5b3227b7b0f7d335beb648de | [
"MIT"
] | null | null | null | from django.conf.urls import url
from . import views
app_name = 'post'
urlpatterns = [
url(r'^list', views.PostList.as_view(), name='lists'),
url(r'^(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/'\
r'(?P<post>[-\w]+)/$', views.detail, name='post_detail'),
url(r'^(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/'\
r'(?P<post>[-\w]+)/delete/$', views.delete, name='post_delete'),
url(r'^create/$', views.post_create, name="post_create"),
url(r'^(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/'\
r'(?P<post>[-\w]+)/update/$', views.post_update, name='post_update'),
url(r'^(?P<post_id>\d+)/share/$', views.post_share, name='post_share'),
url(r'^tag/(?P<tag_slug>[-\w]+)/$', views.post_list, name='post_list_by_tag'),
]
| 32.708333 | 82 | 0.557962 |
acecac7b118c8c0ff205263cae75798d714616c0 | 1,879 | py | Python | ProdTracker/product/management/commands/create_admin_role.py | rishthas/ProdTracker | c62927b95cabb6b81752239eaee0f2f722fb1523 | [
"MIT"
] | null | null | null | ProdTracker/product/management/commands/create_admin_role.py | rishthas/ProdTracker | c62927b95cabb6b81752239eaee0f2f722fb1523 | [
"MIT"
] | null | null | null | ProdTracker/product/management/commands/create_admin_role.py | rishthas/ProdTracker | c62927b95cabb6b81752239eaee0f2f722fb1523 | [
"MIT"
] | null | null | null | from django.core.management.base import BaseCommand, CommandError
from django.utils.translation import ugettext_lazy as _
from accounts.models import Role,RoleAccess,Profile
from django.contrib.auth.models import User
from django.conf import settings
class Command(BaseCommand):
def menu_access_for_admin(self,role,menu_array):
for menu in menu_array:
if "submenu" in menu:
role_access, created = RoleAccess.objects.get_or_create(role=role,access_point=menu['ref'],access_string='child')
role_access.save()
self.menu_access_for_admin(role,menu["submenu"])
else:
for access_type in menu["access_type"]:
role_access, created = RoleAccess.objects.get_or_create(role=role,access_point=menu['ref'],access_string=access_type['type'])
role_access.save()
def handle(self, *args, **options):
self.stdout.write(self.style.NOTICE(_('Starting Admin Role and Assign to the admin user') ))
if hasattr(settings,'ADMIN_MENU'):
if User.objects.filter(id=1):
self.stdout.write(self.style.NOTICE(_('Admin User available') ))
admin_role ,created = Role.objects.get_or_create(role_id='Admin',description='Admin')
admin_role.save()
menuArray = settings.ADMIN_MENU
self.stdout.write("Generating Menu for Admin")
self.menu_access_for_admin(admin_role,menuArray)
admin_profile = Profile.objects.get(user__id=1)
admin_profile.role_id = admin_role
admin_profile.save()
else:
self.stdout.write(self.style.WARNING(_('Admin User Not available') ))
else:
self.stdout.write(self.style.WARNING(_('Menu JSON is present in the setting.py') ))
| 45.829268 | 145 | 0.643427 |
acecacccb5641e92f4fcef936e212fee0ec6d0ca | 3,611 | py | Python | Lib/distutils/errors.py | deadsnakes/python3.1 | 88d77610a7873c5161bfc15cd69557fc7697b1a3 | [
"PSF-2.0"
] | null | null | null | Lib/distutils/errors.py | deadsnakes/python3.1 | 88d77610a7873c5161bfc15cd69557fc7697b1a3 | [
"PSF-2.0"
] | null | null | null | Lib/distutils/errors.py | deadsnakes/python3.1 | 88d77610a7873c5161bfc15cd69557fc7697b1a3 | [
"PSF-2.0"
] | null | null | null | """distutils.errors
Provides exceptions used by the Distutils modules. Note that Distutils
modules may raise standard exceptions; in particular, SystemExit is
usually raised for errors that are obviously the end-user's fault
(eg. bad command-line arguments).
This module is safe to use in "from ... import *" mode; it only exports
symbols whose names start with "Distutils" and end with "Error"."""
__revision__ = "$Id$"
class DistutilsError (Exception):
"""The root of all Distutils evil."""
pass
class DistutilsModuleError (DistutilsError):
"""Unable to load an expected module, or to find an expected class
within some module (in particular, command modules and classes)."""
pass
class DistutilsClassError (DistutilsError):
"""Some command class (or possibly distribution class, if anyone
feels a need to subclass Distribution) is found not to be holding
up its end of the bargain, ie. implementing some part of the
"command "interface."""
pass
class DistutilsGetoptError (DistutilsError):
"""The option table provided to 'fancy_getopt()' is bogus."""
pass
class DistutilsArgError (DistutilsError):
"""Raised by fancy_getopt in response to getopt.error -- ie. an
error in the command line usage."""
pass
class DistutilsFileError (DistutilsError):
"""Any problems in the filesystem: expected file not found, etc.
Typically this is for problems that we detect before IOError or
OSError could be raised."""
pass
class DistutilsOptionError (DistutilsError):
"""Syntactic/semantic errors in command options, such as use of
mutually conflicting options, or inconsistent options,
badly-spelled values, etc. No distinction is made between option
values originating in the setup script, the command line, config
files, or what-have-you -- but if we *know* something originated in
the setup script, we'll raise DistutilsSetupError instead."""
pass
class DistutilsSetupError (DistutilsError):
"""For errors that can be definitely blamed on the setup script,
such as invalid keyword arguments to 'setup()'."""
pass
class DistutilsPlatformError (DistutilsError):
"""We don't know how to do something on the current platform (but
we do know how to do it on some platform) -- eg. trying to compile
C files on a platform not supported by a CCompiler subclass."""
pass
class DistutilsExecError (DistutilsError):
"""Any problems executing an external program (such as the C
compiler, when compiling C files)."""
pass
class DistutilsInternalError (DistutilsError):
"""Internal inconsistencies or impossibilities (obviously, this
should never be seen if the code is working!)."""
pass
class DistutilsTemplateError (DistutilsError):
"""Syntax error in a file list template."""
class DistutilsByteCompileError(DistutilsError):
"""Byte compile error."""
# Exception classes used by the CCompiler implementation classes
class CCompilerError (Exception):
"""Some compile/link operation failed."""
class PreprocessError (CCompilerError):
"""Failure to preprocess one or more C/C++ files."""
class CompileError (CCompilerError):
"""Failure to compile one or more C/C++ source files."""
class LibError (CCompilerError):
"""Failure to create a static library from one or more C/C++ object
files."""
class LinkError (CCompilerError):
"""Failure to link one or more C/C++ object files into an executable
or shared library file."""
class UnknownFileError (CCompilerError):
"""Attempt to process an unknown file type."""
| 36.11 | 72 | 0.731376 |
acecacdb553cbb4b28e52ab94c02a5c7f4b26b22 | 140 | py | Python | fireworks/scripts/tests/__init__.py | jmmshn/fireworks | 5c2f0586e76ab08cadf8b9f4f85638d838f15448 | [
"BSD-3-Clause-LBNL"
] | null | null | null | fireworks/scripts/tests/__init__.py | jmmshn/fireworks | 5c2f0586e76ab08cadf8b9f4f85638d838f15448 | [
"BSD-3-Clause-LBNL"
] | null | null | null | fireworks/scripts/tests/__init__.py | jmmshn/fireworks | 5c2f0586e76ab08cadf8b9f4f85638d838f15448 | [
"BSD-3-Clause-LBNL"
] | null | null | null | __author__ = "Janosh Riebesell <janosh.riebesell@gmail.com>"
from os.path import abspath, dirname
module_dir = dirname(abspath(__file__))
| 23.333333 | 60 | 0.785714 |
acecaed8b0b7d9d57139a5ed121d8ecf01a4b6a7 | 5,246 | py | Python | sockets.py | c25vdw/CMPUT404-assignment-websockets | 5675679dc1db732995cbc91c4c29f4ec64d82f64 | [
"Apache-2.0"
] | null | null | null | sockets.py | c25vdw/CMPUT404-assignment-websockets | 5675679dc1db732995cbc91c4c29f4ec64d82f64 | [
"Apache-2.0"
] | null | null | null | sockets.py | c25vdw/CMPUT404-assignment-websockets | 5675679dc1db732995cbc91c4c29f4ec64d82f64 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# coding: utf-8
# Copyright (c) 2013-2014 Abram Hindle
# Copyright 2021 Lucas Zeng
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import flask
from flask import Flask, request
from flask_sockets import Sockets
import gevent
from gevent import queue
import time
import json
import os
app = Flask(__name__)
sockets = Sockets(app)
app.debug = True
# this class is grabbed from https://github.com/abramhindle/WebSocketsExamples/blob/master/chat.py
class Client:
def __init__(self):
self.queue = queue.Queue()
def put(self, v):
self.queue.put_nowait(v)
def get(self):
return self.queue.get()
class World:
def __init__(self):
self.clear()
# we've got listeners now!
self.listeners = list()
def add_set_listener(self, listener):
self.listeners.append( listener )
def update(self, entity, key, value):
entry = self.space.get(entity,dict())
entry[key] = value
self.space[entity] = entry
self.update_listeners( entity )
def set(self, entity, data):
self.space[entity] = data
self.update_listeners( entity )
def update_listeners(self, entity):
'''update the set listeners'''
for listener in self.listeners:
listener(entity, self.get(entity))
def clear(self):
self.space = dict()
def get(self, entity):
return self.space.get(entity,dict())
def world(self):
return self.space
myWorld = World()
def set_listener( entity, data ):
''' do something with the update ! '''
myWorld.add_set_listener( set_listener )
clients = []
def send_all(msg):
for c in clients:
c.put(msg)
@app.route('/')
def hello():
'''Return something coherent here.. perhaps redirect to /static/index.html '''
return flask.redirect("/static/index.html")
# reference: https://github.com/abramhindle/WebSocketsExamples/blob/547b31b1a6873dd67dc5a4a44cbed0a2003d7811/chat.py#L65
def read_ws(socket, client):
'''A greenlet function that reads from the websocket and updates the world'''
try:
while True:
msg = socket.receive()
print("ws receive: ", msg)
if (msg is not None):
packet = json.loads(msg)
for (entity, attributes) in packet.items():
myWorld.set(entity, attributes)
send_all(json.dumps(packet))
else:
break
except:
'''Done'''
# reference: https://github.com/abramhindle/WebSocketsExamples/blob/547b31b1a6873dd67dc5a4a44cbed0a2003d7811/chat.py#L80
@sockets.route('/subscribe')
def subscribe_socket(socket):
'''Fufill the websocket URL of /subscribe, every update notify the
websocket and read updates from the websocket '''
client = Client()
clients.append(client)
g = gevent.spawn(read_ws, socket, client)
try:
# send the whole world just to sync
print("sending world: ", myWorld.world())
socket.send(json.dumps(myWorld.world()))
while True:
# read update
msg = client.get()
socket.send(msg)
finally:
clients.remove(client)
gevent.kill(g)
# I give this to you, this is how you get the raw body/data portion of a post in flask
# this should come with flask but whatever, it's not my project.
def flask_post_json():
'''Ah the joys of frameworks! They do so much work for you
that they get in the way of sane operation!'''
if (request.json != None):
return request.json
elif (request.data != None and request.data.decode("utf8") != u''):
return json.loads(request.data.decode("utf8"))
else:
return json.loads(request.form.keys()[0])
@app.route("/entity/<entity>", methods=['POST','PUT'])
def update(entity):
'''update the entities via this interface'''
entity_val = flask_post_json()
myWorld.set(entity, entity_val)
return flask.jsonify(myWorld.get(entity))
@app.route("/world", methods=['POST','GET'])
def world():
'''you should probably return the world here'''
return flask.jsonify(myWorld.world())
@app.route("/entity/<entity>")
def get_entity(entity):
'''This is the GET version of the entity interface, return a representation of the entity'''
return flask.jsonify(myWorld.get(entity))
@app.route("/clear", methods=['POST','GET'])
def clear():
'''Clear the world out!'''
myWorld.clear()
return flask.jsonify(myWorld.world())
if __name__ == "__main__":
''' This doesn't work well anymore:
pip install gunicorn
and run
gunicorn -k flask_sockets.worker sockets:app
'''
app.run()
| 29.806818 | 120 | 0.650591 |
acecaf5b621bc832abe2338f9222f175a7cdbcab | 1,325 | py | Python | django_plotly_dash/__init__.py | weber-s/django-plotly-dash | feabacb601d2eca7bca740f73e3b87ce251dd3dd | [
"MIT"
] | null | null | null | django_plotly_dash/__init__.py | weber-s/django-plotly-dash | feabacb601d2eca7bca740f73e3b87ce251dd3dd | [
"MIT"
] | null | null | null | django_plotly_dash/__init__.py | weber-s/django-plotly-dash | feabacb601d2eca7bca740f73e3b87ce251dd3dd | [
"MIT"
] | null | null | null | '''
Django-plotly-dash
==================
This module provides a wrapper around a Plotly Dash instance
and enables it to be served as part of a Django application.
Copyright (c) 2018 Gibbs Consulting and others - see CONTRIBUTIONS.md
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'''
__version__ = "0.9.0"
from .dash_wrapper import DjangoDash
| 41.40625 | 78 | 0.78717 |
acecaf5e22d716416d0762a964c7d3f25523d680 | 2,740 | py | Python | db/py_mysql.py | claw0ed/HelloScrap | 0f11fe7c887780430cd86f77f60e31613a95a66c | [
"BSD-2-Clause"
] | null | null | null | db/py_mysql.py | claw0ed/HelloScrap | 0f11fe7c887780430cd86f77f60e31613a95a66c | [
"BSD-2-Clause"
] | null | null | null | db/py_mysql.py | claw0ed/HelloScrap | 0f11fe7c887780430cd86f77f60e31613a95a66c | [
"BSD-2-Clause"
] | null | null | null | #-*- coding: utf-8 -*-
# 파이썬에서 mysql을 사용하려면 Python 표준 DB API를 지원하는
# MySQL DB 모듈을 다운로드 한 후 설치해야 함 - PyMySQL
import pymysql
# mysql connection 생성
conn = pymysql.connect(host='192.168.220.128', port=3306,\
user='claw0ed', password='Abcdef_12',\
db='claw0ed', charset='utf8')
# connection 에서 cursor 생성
curs = conn.cursor()
# sql 문 작성 후 실행
sql = 'select * from employees'
rows = curs.execute(sql)
# 필요하다면, 실행한 sql 로 부터 데이터 처리
rows = curs.fetchall()
for row in rows:
print(row[0], row[1], row[2])
# print(row['lastName'], row['email'], row['jobTitle']) # 인됨!
# cursor, connection 닫기
curs.close()
conn.close()
# 사전식 커서 사용
conn = pymysql.connect(host='192.168.220.128', port=3306,\
user='claw0ed', password='Abcdef_12',\
db='claw0ed', charset='utf8')
curs = conn.cursor(pymysql.cursors.DictCursor)
sql = 'select * from customers where state=%s and city=%s'
curs.execute(sql, ('NY', 'NYC'))
rows = curs.fetchall()
for row in rows:
print(row['phone'], row['city'], row['state'])
# cursor, connection 닫기
curs.close()
conn.close()
# 간단한 CRUD 테스트
# delete from index_test
# insert into index_test values ('zzyzzy', '987654')
# select * from index_test
# update index_test set uid = 'zzyzigy' where uid = 'zzyzzy'
# select * from index_test
# delete from index_test
conn = pymysql.connect(host='192.168.220.128', port=3306,\
user='claw0ed', password='Abcdef_12',\
db='claw0ed', charset='utf8')
curs = conn.cursor()
sql = 'delete from index_test'
curs.execute(sql)
curs.close()
conn.commit() # insert, update, delete 시 필요!
# insert into index_test values ('zzyzzy', '987654')
curs = conn.cursor()
# sql = "insert into index_test values ('zzyzzy', '987654')"
sql = 'insert into index_test values (%s, %s)'
curs.execute(sql, ('zzyzzy', '987654'))
curs.close()
conn.commit()
conn.close()
# update index_test set uid = 'zzyzigy' where uid = 'zzyzzy'
conn = pymysql.connect(host='192.168.220.128', port=3306,\
user='claw0ed', password='Abcdef_12',\
db='claw0ed', charset='utf8')
curs = conn.cursor()
sql = 'update index_test set uid =%s where uid =%s'
curs.execute(sql, ('zzyzigy', 'zzyzzy'))
curs.close()
conn.commit()
conn.close()
# select * from index_test
conn = pymysql.connect(host='192.168.220.128', port=3306,\
user='claw0ed', password='Abcdef_12',\
db='claw0ed', charset='utf8')
curs = conn.cursor(pymysql.cursors.DictCursor)
sql = 'select * from index_test'
curs.execute(sql)
rows = curs.fetchall()
for row in rows:
print(row['uid'], row['pwd'])
curs.close()
conn.close()
| 24.684685 | 65 | 0.625547 |
acecafedb0f2d9b0a45c5e34c25681c9f985f591 | 11,830 | py | Python | easycaching/proxy.py | codemation/easycaching | 0b613885fcc8814889c1aec1ddc15b48d982cbda | [
"MIT"
] | 1 | 2021-12-18T00:52:36.000Z | 2021-12-18T00:52:36.000Z | easycaching/proxy.py | codemation/easycaching | 0b613885fcc8814889c1aec1ddc15b48d982cbda | [
"MIT"
] | 1 | 2021-06-23T13:36:13.000Z | 2021-06-25T19:14:34.000Z | easycaching/proxy.py | codemation/easycaching | 0b613885fcc8814889c1aec1ddc15b48d982cbda | [
"MIT"
] | null | null | null | import asyncio
import os, time
from asyncio import Queue
from easyrpc.server import EasyRpcServer
from aiopyql.data import Database
def db_proxy_setup(server):
@server.on_event('startup')
async def db_setup():
db_config = {}
# get database type
db_type = os.environ.get('DB_TYPE')
db_type = 'sqlite' if not db_type else db_type
db_name = os.environ.get('DB_NAME')
if not db_name:
raise Exception(f"missing required DB_NAME environment variable")
db_config['db_type'] = db_type
db_config['database'] = db_name
if db_type in {'mysql', 'postgres'}:
for cfg in {'HOST','PORT', 'USER', 'PASSWORD'}:
db_config[cfg.lower()] = os.environ.get(f"DB_{cfg}")
if not db_config[cfg.lower()]:
raise Exception(f"missing required DB_{cfg} environment variable")
else:
sqlite_db_path = os.environ.get('DB_LOCAL_PATH')
if sqlite_db_path:
db_config['database'] = f"{sqlite_db_path}/{db_name}"
db_config['cache_enabled'] = True
rpc_config = {}
rpc_secret = os.environ.get('RPC_SECRET')
if not rpc_secret:
raise Exception(f"missing required RPC_SECRET environment variable")
rpc_path = os.environ.get('RPC_PATH')
rpc_config['origin_path'] = rpc_path if rpc_path else f'/ws/{db_name}'
rpc_config['server_secret'] = rpc_secret
rcp_enryption = os.environ.get('RPC_ENCRYPTION')
if rcp_enryption:
rpc_config['encryption_enabled'] = True if rcp_enryption == 1 else False
rpc_debug = os.environ.get('RPC_DEBUG')
if rpc_debug:
rpc_config['debug'] = True if rpc_debug == 'True' else False
# Rpc Server
db_server = await EasyRpcServer.create(
server,
**rpc_config
)
# insert logger
db_config['log'] = db_server.log
# Database Conection
db = await Database.create(
**db_config
)
# register each func table namespace
def register_table(table):
async def insert(**kwargs):
return await db.tables[table].insert(**kwargs)
insert.__name__ = f"{table}_insert"
async def select(*args, **kwargs):
return await db.tables[table].select(*args, **kwargs)
select.__name__ = f"{table}_select"
async def update(**kwargs):
return await db.tables[table].update(**kwargs)
update.__name__ = f"{table}_update"
async def delete(**kwargs):
return await db.tables[table].delete(**kwargs)
delete.__name__ = f"{table}_delete"
async def set_item(key, values):
return await db.tables[table].set_item(key, values)
set_item.__name__ = f"{table}_set_item"
async def get_item(key_val):
return await db.tables[table][key_val]
get_item.__name__ = f"{table}_get_item"
async def get_schema():
return {
table: {
"primary_key": db.tables[table].prim_key,
"foreign_keys": db.tables[table].foreign_keys,
"columns": [
{
"name": col.name, "type": str(col.type.__name__), "mods": col.mods
} for k, col in db.tables[table].columns.items()
],
"cache_enabled": db.tables[table].cache_enabled,
"max_cache_len": db.tables[table].max_cache_len
}
}
get_schema.__name__ = f"{table}_get_schema"
for func in {insert, update, select, delete, select, get_schema, set_item, get_item}:
db_server.origin(func, namespace=db_name)
for table in db.tables:
register_table(table)
@db_server.origin(namespace=db_name)
async def show_tables():
table_list = []
for table in db.tables:
for func in {'insert', 'select', 'update', 'delete', 'set_item', 'get_item', 'get_schema'}:
if not f"{table}_{func}" in db_server.namespaces[db_name]:
register_table(table)
break
table_list.append(table)
return table_list
@db_server.origin(namespace=db_name)
async def drop_table(table: str):
result = await db.remove_table(table)
print(f"drop table result: {result}")
return f"drop table {table} completed"
@db_server.origin(namespace=db_name)
async def create_table(
name: str,
columns: list,
prim_key: str,
**kw
):
result = await db.create_table(
name=name,
columns=columns,
prim_key=prim_key,
**kw
)
await show_tables()
return result
server.queues = {}
cache_ns = db_name
@db_server.origin(namespace=cache_ns)
async def ec_cache_setup():
await db.create_table(
'queues',
[
['queue', 'str', 'UNIQUE NOT NULL'],
['created', 'float']
],
'queue',
cache_enabled=True
)
# create cache table
await db.create_table(
'cache',
[
['cache', 'str', 'UNIQUE NOT NULL'],
['created', 'float']
],
'cache',
cache_enabled=True
)
@db_server.origin(namespace=cache_ns)
async def ec_create_cache(cache, cache_size):
if cache in db.tables:
raise Exception(f"cache name {cache} already exists")
await db.create_table(
cache,
[
['cache_key', 'str', 'UNIQUE NOT NULL'],
['value', 'str'],
],
'cache_key',
cache_enabled=True,
max_cache_len=cache_size
)
await db.tables['cache'].insert(
cache=cache,
created=time.time()
)
@db_server.origin(namespace=cache_ns)
async def ec_create_queue(queue):
if queue in server.queues:
raise Exception(f"queue name {queue} already exists")
server.queues[queue] = Queue()
await db.create_table(
name=queue,
columns=[
['timestamp', 'float', 'UNIQUE NOT NULL'],
['data', str]
],
prim_key='timestamp',
cache_enabled=True,
)
await db.tables['queues'].insert(
queue=queue
)
return f"queue {queue} created"
@db_server.origin(namespace=cache_ns)
async def ec_clear_queue(queue) -> None:
if not queue in db.tables:
raise Exception(f"queue name {queue} does not exist")
items = await db.tables[queue].select('timestamp')
for item in items:
await db.tables[queue].delete(
where={'timestamp': item['timestamp']}
)
server.queues[queue] = Queue()
@db_server.origin(namespace=cache_ns)
async def ec_load_cache() -> None:
caches = await db.tables['cache'].select(
'*'
)
for cache in caches:
keys = await db.tables[cache['cache']].select('cache_key')
for key in keys:
await db.tables[cache['cache']][key]
@db_server.origin(namespace=cache_ns)
async def ec_load_queues():
queues = await db.tables['queues'].select(
'*'
)
for queue in queues:
queue_name = queue['queue']
# create queue
if not queue_name in server.queues:
server.queues[queue_name] = Queue()
# load queue
queued_items = await db.tables[queue_name].select('*')
print(queued_items)
for item in queued_items:
timestamp = item['timestamp']
await server.queues[queue_name].put({'time': timestamp, 'data': item['data']})
print(server.queues[queue_name])
return [queue['queue'] for queue in queues]
@db_server.origin(namespace=cache_ns)
async def ec_queue_put(queue, data):
# add data to db
time_now = time.time()
await db.tables[queue].insert(
timestamp=time_now,
data=data
)
await server.queues[queue].put({'time': time_now, 'data': data})
return {'message': 'added to queue'}
@db_server.origin(namespace=cache_ns)
async def ec_queue_get(queue):
try:
item = server.queues[queue].get_nowait()
asyncio.create_task(
db.tables[queue].delete(
where={'timestamp': item['time']}
)
)
return item['data']
except asyncio.queues.QueueEmpty:
return {'warning': 'queue empty'}
@db_server.origin(namespace=cache_ns)
async def ec_cache_set(cache_name: str, key: str, value) -> str:
cache = db.tables[cache_name]
existing = await cache[key]
if existing is None:
result = await cache.insert(
cache_key=key,
value=value
)
return f"value for {key} added to {cache_name}"
else:
result = await cache.update(
value=value,
where={
'cache_key': key
}
)
return f"value for {key} updated in {cache_name}"
@db_server.origin(namespace=cache_ns)
async def ec_cache_get(cache: str, key):
return await db.tables[cache][key]
@db_server.origin(namespace=cache_ns)
async def ec_cache_get_all(cache):
for item in await db.tables[cache].select('*'):
yield {item['cache_key']: item['value']}
@db_server.origin(namespace=cache_ns)
async def ec_cache_delete(cache, key) -> str:
result = await db.tables[cache].delete(
where={'cache_key': key}
)
return f"{key} deleted from {cache}"
@db_server.origin(namespace=cache_ns)
async def ec_cache_clear(cache) -> str:
keys = await db.tables[cache].select('cache_key')
for key in keys:
await db.tables[cache].delete(
where={'cache_key': key['cache_key']}
)
return f"cache {cache} cleared"
db_server.origin(db.run, namespace=db_name)
server.db_server = db_server
server.db = db
@server.on_event('shutdown')
async def shutdown():
await server.db.close() | 35 | 107 | 0.499155 |
acecb07f6dc217126e0cc740700cfc903b55a9db | 253,211 | py | Python | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_aaa_locald_oper.py | Maikor/ydk-py | b86c4a7c570ae3b2c5557d098420446df5de4929 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_aaa_locald_oper.py | Maikor/ydk-py | b86c4a7c570ae3b2c5557d098420446df5de4929 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_aaa_locald_oper.py | Maikor/ydk-py | b86c4a7c570ae3b2c5557d098420446df5de4929 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | """ Cisco_IOS_XR_aaa_locald_oper
This module contains a collection of YANG definitions
for Cisco IOS\-XR aaa\-locald package operational data.
This module contains definitions
for the following management objects\:
aaa\: AAA operational data
Copyright (c) 2013\-2018 by Cisco Systems, Inc.
All rights reserved.
"""
from collections import OrderedDict
from ydk.types import Entity, EntityPath, Identity, Enum, YType, YLeaf, YLeafList, YList, LeafDataList, Bits, Empty, Decimal64
from ydk.filters import YFilter
from ydk.errors import YError, YModelError
from ydk.errors.error_handler import handle_type_error as _handle_type_error
class Aaa(Entity):
"""
AAA operational data
.. attribute:: all_tasks
All tasks supported by system
**type**\: :py:class:`AllTasks <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.AllTasks>`
.. attribute:: currentuser_detail
Current user specific details
**type**\: :py:class:`CurrentuserDetail <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.CurrentuserDetail>`
.. attribute:: task_map
Task map of current user
**type**\: :py:class:`TaskMap <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.TaskMap>`
.. attribute:: taskgroups
Individual taskgroups container
**type**\: :py:class:`Taskgroups <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Taskgroups>`
.. attribute:: users
Container for individual local user information
**type**\: :py:class:`Users <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Users>`
.. attribute:: password_policies
Container for individual password policy Information
**type**\: :py:class:`PasswordPolicies <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.PasswordPolicies>`
.. attribute:: usergroups
Container for individual usergroup Information
**type**\: :py:class:`Usergroups <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Usergroups>`
.. attribute:: authen_method
Current users authentication method
**type**\: :py:class:`AuthenMethod <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.AuthenMethod>`
.. attribute:: current_usergroup
Specific Usergroup Information
**type**\: :py:class:`CurrentUsergroup <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.CurrentUsergroup>`
.. attribute:: radius
RADIUS operational data
**type**\: :py:class:`Radius <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Radius>`
.. attribute:: tacacs
TACACS operational data
**type**\: :py:class:`Tacacs <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Tacacs>`
.. attribute:: diameter
Diameter operational data
**type**\: :py:class:`Diameter <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Diameter>`
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa, self).__init__()
self._top_entity = None
self.yang_name = "aaa"
self.yang_parent_name = "Cisco-IOS-XR-aaa-locald-oper"
self.is_top_level_class = True
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([("all-tasks", ("all_tasks", Aaa.AllTasks)), ("currentuser-detail", ("currentuser_detail", Aaa.CurrentuserDetail)), ("task-map", ("task_map", Aaa.TaskMap)), ("taskgroups", ("taskgroups", Aaa.Taskgroups)), ("users", ("users", Aaa.Users)), ("password-policies", ("password_policies", Aaa.PasswordPolicies)), ("usergroups", ("usergroups", Aaa.Usergroups)), ("authen-method", ("authen_method", Aaa.AuthenMethod)), ("current-usergroup", ("current_usergroup", Aaa.CurrentUsergroup)), ("Cisco-IOS-XR-aaa-protocol-radius-oper:radius", ("radius", Aaa.Radius)), ("Cisco-IOS-XR-aaa-tacacs-oper:tacacs", ("tacacs", Aaa.Tacacs)), ("Cisco-IOS-XR-aaa-diameter-oper:diameter", ("diameter", Aaa.Diameter))])
self._leafs = OrderedDict()
self.all_tasks = Aaa.AllTasks()
self.all_tasks.parent = self
self._children_name_map["all_tasks"] = "all-tasks"
self.currentuser_detail = Aaa.CurrentuserDetail()
self.currentuser_detail.parent = self
self._children_name_map["currentuser_detail"] = "currentuser-detail"
self.task_map = Aaa.TaskMap()
self.task_map.parent = self
self._children_name_map["task_map"] = "task-map"
self.taskgroups = Aaa.Taskgroups()
self.taskgroups.parent = self
self._children_name_map["taskgroups"] = "taskgroups"
self.users = Aaa.Users()
self.users.parent = self
self._children_name_map["users"] = "users"
self.password_policies = Aaa.PasswordPolicies()
self.password_policies.parent = self
self._children_name_map["password_policies"] = "password-policies"
self.usergroups = Aaa.Usergroups()
self.usergroups.parent = self
self._children_name_map["usergroups"] = "usergroups"
self.authen_method = Aaa.AuthenMethod()
self.authen_method.parent = self
self._children_name_map["authen_method"] = "authen-method"
self.current_usergroup = Aaa.CurrentUsergroup()
self.current_usergroup.parent = self
self._children_name_map["current_usergroup"] = "current-usergroup"
self.radius = Aaa.Radius()
self.radius.parent = self
self._children_name_map["radius"] = "Cisco-IOS-XR-aaa-protocol-radius-oper:radius"
self.tacacs = Aaa.Tacacs()
self.tacacs.parent = self
self._children_name_map["tacacs"] = "Cisco-IOS-XR-aaa-tacacs-oper:tacacs"
self.diameter = Aaa.Diameter()
self.diameter.parent = self
self._children_name_map["diameter"] = "Cisco-IOS-XR-aaa-diameter-oper:diameter"
self._segment_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa"
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa, [], name, value)
class AllTasks(Entity):
"""
All tasks supported by system
.. attribute:: task_id
Names of available task\-ids
**type**\: list of str
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.AllTasks, self).__init__()
self.yang_name = "all-tasks"
self.yang_parent_name = "aaa"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('task_id', (YLeafList(YType.str, 'task-id'), ['str'])),
])
self.task_id = []
self._segment_path = lambda: "all-tasks"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.AllTasks, [u'task_id'], name, value)
class CurrentuserDetail(Entity):
"""
Current user specific details
.. attribute:: name
Name of the usergroup
**type**\: str
.. attribute:: authenmethod
Authentication method
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: usergroup
Component usergroups
**type**\: list of str
.. attribute:: taskmap
Task map details
**type**\: list of str
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.CurrentuserDetail, self).__init__()
self.yang_name = "currentuser-detail"
self.yang_parent_name = "aaa"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('name', (YLeaf(YType.str, 'name'), ['str'])),
('authenmethod', (YLeaf(YType.int32, 'authenmethod'), ['int'])),
('usergroup', (YLeafList(YType.str, 'usergroup'), ['str'])),
('taskmap', (YLeafList(YType.str, 'taskmap'), ['str'])),
])
self.name = None
self.authenmethod = None
self.usergroup = []
self.taskmap = []
self._segment_path = lambda: "currentuser-detail"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.CurrentuserDetail, [u'name', u'authenmethod', u'usergroup', u'taskmap'], name, value)
class TaskMap(Entity):
"""
Task map of current user
.. attribute:: name
Name of the usergroup
**type**\: str
.. attribute:: authenmethod
Authentication method
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: usergroup
Component usergroups
**type**\: list of str
.. attribute:: taskmap
Task map details
**type**\: list of str
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.TaskMap, self).__init__()
self.yang_name = "task-map"
self.yang_parent_name = "aaa"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('name', (YLeaf(YType.str, 'name'), ['str'])),
('authenmethod', (YLeaf(YType.int32, 'authenmethod'), ['int'])),
('usergroup', (YLeafList(YType.str, 'usergroup'), ['str'])),
('taskmap', (YLeafList(YType.str, 'taskmap'), ['str'])),
])
self.name = None
self.authenmethod = None
self.usergroup = []
self.taskmap = []
self._segment_path = lambda: "task-map"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.TaskMap, [u'name', u'authenmethod', u'usergroup', u'taskmap'], name, value)
class Taskgroups(Entity):
"""
Individual taskgroups container
.. attribute:: taskgroup
Specific Taskgroup Information
**type**\: list of :py:class:`Taskgroup <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Taskgroups.Taskgroup>`
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Taskgroups, self).__init__()
self.yang_name = "taskgroups"
self.yang_parent_name = "aaa"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([("taskgroup", ("taskgroup", Aaa.Taskgroups.Taskgroup))])
self._leafs = OrderedDict()
self.taskgroup = YList(self)
self._segment_path = lambda: "taskgroups"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Taskgroups, [], name, value)
class Taskgroup(Entity):
"""
Specific Taskgroup Information
.. attribute:: name (key)
Taskgroup name
**type**\: str
.. attribute:: included_task_ids
Task\-ids included
**type**\: :py:class:`IncludedTaskIds <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Taskgroups.Taskgroup.IncludedTaskIds>`
.. attribute:: task_map
Computed task map
**type**\: :py:class:`TaskMap <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Taskgroups.Taskgroup.TaskMap>`
.. attribute:: name_xr
Name of the taskgroup
**type**\: str
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Taskgroups.Taskgroup, self).__init__()
self.yang_name = "taskgroup"
self.yang_parent_name = "taskgroups"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = ['name']
self._child_classes = OrderedDict([("included-task-ids", ("included_task_ids", Aaa.Taskgroups.Taskgroup.IncludedTaskIds)), ("task-map", ("task_map", Aaa.Taskgroups.Taskgroup.TaskMap))])
self._leafs = OrderedDict([
('name', (YLeaf(YType.str, 'name'), ['str'])),
('name_xr', (YLeaf(YType.str, 'name-xr'), ['str'])),
])
self.name = None
self.name_xr = None
self.included_task_ids = Aaa.Taskgroups.Taskgroup.IncludedTaskIds()
self.included_task_ids.parent = self
self._children_name_map["included_task_ids"] = "included-task-ids"
self.task_map = Aaa.Taskgroups.Taskgroup.TaskMap()
self.task_map.parent = self
self._children_name_map["task_map"] = "task-map"
self._segment_path = lambda: "taskgroup" + "[name='" + str(self.name) + "']"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/taskgroups/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Taskgroups.Taskgroup, [u'name', u'name_xr'], name, value)
class IncludedTaskIds(Entity):
"""
Task\-ids included
.. attribute:: tasks
List of permitted tasks
**type**\: list of :py:class:`Tasks <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Taskgroups.Taskgroup.IncludedTaskIds.Tasks>`
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Taskgroups.Taskgroup.IncludedTaskIds, self).__init__()
self.yang_name = "included-task-ids"
self.yang_parent_name = "taskgroup"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_classes = OrderedDict([("tasks", ("tasks", Aaa.Taskgroups.Taskgroup.IncludedTaskIds.Tasks))])
self._leafs = OrderedDict()
self.tasks = YList(self)
self._segment_path = lambda: "included-task-ids"
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Taskgroups.Taskgroup.IncludedTaskIds, [], name, value)
class Tasks(Entity):
"""
List of permitted tasks
.. attribute:: task_id
Name of the task\-id
**type**\: str
.. attribute:: read
Is read permitted?
**type**\: bool
.. attribute:: write
Is write permitted?
**type**\: bool
.. attribute:: execute
Is execute permitted?
**type**\: bool
.. attribute:: debug
Is debug permitted?
**type**\: bool
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Taskgroups.Taskgroup.IncludedTaskIds.Tasks, self).__init__()
self.yang_name = "tasks"
self.yang_parent_name = "included-task-ids"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('task_id', (YLeaf(YType.str, 'task-id'), ['str'])),
('read', (YLeaf(YType.boolean, 'read'), ['bool'])),
('write', (YLeaf(YType.boolean, 'write'), ['bool'])),
('execute', (YLeaf(YType.boolean, 'execute'), ['bool'])),
('debug', (YLeaf(YType.boolean, 'debug'), ['bool'])),
])
self.task_id = None
self.read = None
self.write = None
self.execute = None
self.debug = None
self._segment_path = lambda: "tasks"
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Taskgroups.Taskgroup.IncludedTaskIds.Tasks, [u'task_id', u'read', u'write', u'execute', u'debug'], name, value)
class TaskMap(Entity):
"""
Computed task map
.. attribute:: tasks
List of permitted tasks
**type**\: list of :py:class:`Tasks <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Taskgroups.Taskgroup.TaskMap.Tasks>`
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Taskgroups.Taskgroup.TaskMap, self).__init__()
self.yang_name = "task-map"
self.yang_parent_name = "taskgroup"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_classes = OrderedDict([("tasks", ("tasks", Aaa.Taskgroups.Taskgroup.TaskMap.Tasks))])
self._leafs = OrderedDict()
self.tasks = YList(self)
self._segment_path = lambda: "task-map"
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Taskgroups.Taskgroup.TaskMap, [], name, value)
class Tasks(Entity):
"""
List of permitted tasks
.. attribute:: task_id
Name of the task\-id
**type**\: str
.. attribute:: read
Is read permitted?
**type**\: bool
.. attribute:: write
Is write permitted?
**type**\: bool
.. attribute:: execute
Is execute permitted?
**type**\: bool
.. attribute:: debug
Is debug permitted?
**type**\: bool
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Taskgroups.Taskgroup.TaskMap.Tasks, self).__init__()
self.yang_name = "tasks"
self.yang_parent_name = "task-map"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('task_id', (YLeaf(YType.str, 'task-id'), ['str'])),
('read', (YLeaf(YType.boolean, 'read'), ['bool'])),
('write', (YLeaf(YType.boolean, 'write'), ['bool'])),
('execute', (YLeaf(YType.boolean, 'execute'), ['bool'])),
('debug', (YLeaf(YType.boolean, 'debug'), ['bool'])),
])
self.task_id = None
self.read = None
self.write = None
self.execute = None
self.debug = None
self._segment_path = lambda: "tasks"
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Taskgroups.Taskgroup.TaskMap.Tasks, [u'task_id', u'read', u'write', u'execute', u'debug'], name, value)
class Users(Entity):
"""
Container for individual local user information
.. attribute:: user
Specific local user information
**type**\: list of :py:class:`User <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Users.User>`
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Users, self).__init__()
self.yang_name = "users"
self.yang_parent_name = "aaa"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([("user", ("user", Aaa.Users.User))])
self._leafs = OrderedDict()
self.user = YList(self)
self._segment_path = lambda: "users"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Users, [], name, value)
class User(Entity):
"""
Specific local user information
.. attribute:: name (key)
Username
**type**\: str
.. attribute:: task_map
Computed taskmap
**type**\: :py:class:`TaskMap <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Users.User.TaskMap>`
.. attribute:: name_xr
Username
**type**\: str
.. attribute:: admin_user
Is admin plane user ?
**type**\: bool
.. attribute:: first_user
Is first user ?
**type**\: bool
.. attribute:: usergroup
Member usergroups
**type**\: list of str
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Users.User, self).__init__()
self.yang_name = "user"
self.yang_parent_name = "users"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = ['name']
self._child_classes = OrderedDict([("task-map", ("task_map", Aaa.Users.User.TaskMap))])
self._leafs = OrderedDict([
('name', (YLeaf(YType.str, 'name'), ['str'])),
('name_xr', (YLeaf(YType.str, 'name-xr'), ['str'])),
('admin_user', (YLeaf(YType.boolean, 'admin-user'), ['bool'])),
('first_user', (YLeaf(YType.boolean, 'first-user'), ['bool'])),
('usergroup', (YLeafList(YType.str, 'usergroup'), ['str'])),
])
self.name = None
self.name_xr = None
self.admin_user = None
self.first_user = None
self.usergroup = []
self.task_map = Aaa.Users.User.TaskMap()
self.task_map.parent = self
self._children_name_map["task_map"] = "task-map"
self._segment_path = lambda: "user" + "[name='" + str(self.name) + "']"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/users/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Users.User, [u'name', u'name_xr', u'admin_user', u'first_user', u'usergroup'], name, value)
class TaskMap(Entity):
"""
Computed taskmap
.. attribute:: tasks
List of permitted tasks
**type**\: list of :py:class:`Tasks <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Users.User.TaskMap.Tasks>`
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Users.User.TaskMap, self).__init__()
self.yang_name = "task-map"
self.yang_parent_name = "user"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_classes = OrderedDict([("tasks", ("tasks", Aaa.Users.User.TaskMap.Tasks))])
self._leafs = OrderedDict()
self.tasks = YList(self)
self._segment_path = lambda: "task-map"
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Users.User.TaskMap, [], name, value)
class Tasks(Entity):
"""
List of permitted tasks
.. attribute:: task_id
Name of the task\-id
**type**\: str
.. attribute:: read
Is read permitted?
**type**\: bool
.. attribute:: write
Is write permitted?
**type**\: bool
.. attribute:: execute
Is execute permitted?
**type**\: bool
.. attribute:: debug
Is debug permitted?
**type**\: bool
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Users.User.TaskMap.Tasks, self).__init__()
self.yang_name = "tasks"
self.yang_parent_name = "task-map"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('task_id', (YLeaf(YType.str, 'task-id'), ['str'])),
('read', (YLeaf(YType.boolean, 'read'), ['bool'])),
('write', (YLeaf(YType.boolean, 'write'), ['bool'])),
('execute', (YLeaf(YType.boolean, 'execute'), ['bool'])),
('debug', (YLeaf(YType.boolean, 'debug'), ['bool'])),
])
self.task_id = None
self.read = None
self.write = None
self.execute = None
self.debug = None
self._segment_path = lambda: "tasks"
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Users.User.TaskMap.Tasks, [u'task_id', u'read', u'write', u'execute', u'debug'], name, value)
class PasswordPolicies(Entity):
"""
Container for individual password policy
Information
.. attribute:: password_policy
Password policy details
**type**\: list of :py:class:`PasswordPolicy <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.PasswordPolicies.PasswordPolicy>`
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.PasswordPolicies, self).__init__()
self.yang_name = "password-policies"
self.yang_parent_name = "aaa"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([("password-policy", ("password_policy", Aaa.PasswordPolicies.PasswordPolicy))])
self._leafs = OrderedDict()
self.password_policy = YList(self)
self._segment_path = lambda: "password-policies"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.PasswordPolicies, [], name, value)
class PasswordPolicy(Entity):
"""
Password policy details
.. attribute:: name (key)
Password policy name
**type**\: str
.. attribute:: life_time
Lifetime of the policy
**type**\: :py:class:`LifeTime <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.PasswordPolicies.PasswordPolicy.LifeTime>`
.. attribute:: lock_out_time
Lockout time of the policy
**type**\: :py:class:`LockOutTime <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.PasswordPolicies.PasswordPolicy.LockOutTime>`
.. attribute:: name_xr
Password Policy Name
**type**\: str
.. attribute:: min_len
Min Length
**type**\: int
**range:** 0..255
.. attribute:: max_len
Max Length
**type**\: int
**range:** 0..255
.. attribute:: spl_char
Special Character length
**type**\: int
**range:** 0..255
.. attribute:: upper_case
UpperCase Character length
**type**\: int
**range:** 0..255
.. attribute:: lower_case
LowerCase Character length
**type**\: int
**range:** 0..255
.. attribute:: numeric
Numeric Character length
**type**\: int
**range:** 0..255
.. attribute:: min_char_change
Number of different characters
**type**\: int
**range:** 0..255
.. attribute:: num_of_users
Number of users with this policy
**type**\: int
**range:** 0..255
.. attribute:: max_fail_attempts
Maximum Failure Attempts allowed
**type**\: int
**range:** 0..4294967295
.. attribute:: usr_count
Count of users
**type**\: int
**range:** 0..255
.. attribute:: err_count
Error Count
**type**\: int
**range:** 0..255
.. attribute:: lock_out_count
Lock Out Count
**type**\: int
**range:** 0..255
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.PasswordPolicies.PasswordPolicy, self).__init__()
self.yang_name = "password-policy"
self.yang_parent_name = "password-policies"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = ['name']
self._child_classes = OrderedDict([("life-time", ("life_time", Aaa.PasswordPolicies.PasswordPolicy.LifeTime)), ("lock-out-time", ("lock_out_time", Aaa.PasswordPolicies.PasswordPolicy.LockOutTime))])
self._leafs = OrderedDict([
('name', (YLeaf(YType.str, 'name'), ['str'])),
('name_xr', (YLeaf(YType.str, 'name-xr'), ['str'])),
('min_len', (YLeaf(YType.uint8, 'min-len'), ['int'])),
('max_len', (YLeaf(YType.uint8, 'max-len'), ['int'])),
('spl_char', (YLeaf(YType.uint8, 'spl-char'), ['int'])),
('upper_case', (YLeaf(YType.uint8, 'upper-case'), ['int'])),
('lower_case', (YLeaf(YType.uint8, 'lower-case'), ['int'])),
('numeric', (YLeaf(YType.uint8, 'numeric'), ['int'])),
('min_char_change', (YLeaf(YType.uint8, 'min-char-change'), ['int'])),
('num_of_users', (YLeaf(YType.uint8, 'num-of-users'), ['int'])),
('max_fail_attempts', (YLeaf(YType.uint32, 'max-fail-attempts'), ['int'])),
('usr_count', (YLeaf(YType.uint8, 'usr-count'), ['int'])),
('err_count', (YLeaf(YType.uint8, 'err-count'), ['int'])),
('lock_out_count', (YLeaf(YType.uint8, 'lock-out-count'), ['int'])),
])
self.name = None
self.name_xr = None
self.min_len = None
self.max_len = None
self.spl_char = None
self.upper_case = None
self.lower_case = None
self.numeric = None
self.min_char_change = None
self.num_of_users = None
self.max_fail_attempts = None
self.usr_count = None
self.err_count = None
self.lock_out_count = None
self.life_time = Aaa.PasswordPolicies.PasswordPolicy.LifeTime()
self.life_time.parent = self
self._children_name_map["life_time"] = "life-time"
self.lock_out_time = Aaa.PasswordPolicies.PasswordPolicy.LockOutTime()
self.lock_out_time.parent = self
self._children_name_map["lock_out_time"] = "lock-out-time"
self._segment_path = lambda: "password-policy" + "[name='" + str(self.name) + "']"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/password-policies/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.PasswordPolicies.PasswordPolicy, [u'name', u'name_xr', u'min_len', u'max_len', u'spl_char', u'upper_case', u'lower_case', u'numeric', u'min_char_change', u'num_of_users', u'max_fail_attempts', u'usr_count', u'err_count', u'lock_out_count'], name, value)
class LifeTime(Entity):
"""
Lifetime of the policy
.. attribute:: years
years
**type**\: int
**range:** 0..255
.. attribute:: months
months
**type**\: int
**range:** 0..255
.. attribute:: days
days
**type**\: int
**range:** 0..255
.. attribute:: hours
hours
**type**\: int
**range:** 0..255
.. attribute:: mins
mins
**type**\: int
**range:** 0..255
.. attribute:: secs
secs
**type**\: int
**range:** 0..255
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.PasswordPolicies.PasswordPolicy.LifeTime, self).__init__()
self.yang_name = "life-time"
self.yang_parent_name = "password-policy"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('years', (YLeaf(YType.uint8, 'years'), ['int'])),
('months', (YLeaf(YType.uint8, 'months'), ['int'])),
('days', (YLeaf(YType.uint8, 'days'), ['int'])),
('hours', (YLeaf(YType.uint8, 'hours'), ['int'])),
('mins', (YLeaf(YType.uint8, 'mins'), ['int'])),
('secs', (YLeaf(YType.uint8, 'secs'), ['int'])),
])
self.years = None
self.months = None
self.days = None
self.hours = None
self.mins = None
self.secs = None
self._segment_path = lambda: "life-time"
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.PasswordPolicies.PasswordPolicy.LifeTime, [u'years', u'months', u'days', u'hours', u'mins', u'secs'], name, value)
class LockOutTime(Entity):
"""
Lockout time of the policy
.. attribute:: years
years
**type**\: int
**range:** 0..255
.. attribute:: months
months
**type**\: int
**range:** 0..255
.. attribute:: days
days
**type**\: int
**range:** 0..255
.. attribute:: hours
hours
**type**\: int
**range:** 0..255
.. attribute:: mins
mins
**type**\: int
**range:** 0..255
.. attribute:: secs
secs
**type**\: int
**range:** 0..255
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.PasswordPolicies.PasswordPolicy.LockOutTime, self).__init__()
self.yang_name = "lock-out-time"
self.yang_parent_name = "password-policy"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('years', (YLeaf(YType.uint8, 'years'), ['int'])),
('months', (YLeaf(YType.uint8, 'months'), ['int'])),
('days', (YLeaf(YType.uint8, 'days'), ['int'])),
('hours', (YLeaf(YType.uint8, 'hours'), ['int'])),
('mins', (YLeaf(YType.uint8, 'mins'), ['int'])),
('secs', (YLeaf(YType.uint8, 'secs'), ['int'])),
])
self.years = None
self.months = None
self.days = None
self.hours = None
self.mins = None
self.secs = None
self._segment_path = lambda: "lock-out-time"
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.PasswordPolicies.PasswordPolicy.LockOutTime, [u'years', u'months', u'days', u'hours', u'mins', u'secs'], name, value)
class Usergroups(Entity):
"""
Container for individual usergroup Information
.. attribute:: usergroup
Specific Usergroup Information
**type**\: list of :py:class:`Usergroup <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Usergroups.Usergroup>`
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Usergroups, self).__init__()
self.yang_name = "usergroups"
self.yang_parent_name = "aaa"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([("usergroup", ("usergroup", Aaa.Usergroups.Usergroup))])
self._leafs = OrderedDict()
self.usergroup = YList(self)
self._segment_path = lambda: "usergroups"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Usergroups, [], name, value)
class Usergroup(Entity):
"""
Specific Usergroup Information
.. attribute:: name (key)
Usergroup name
**type**\: str
.. attribute:: task_map
Computed task map
**type**\: :py:class:`TaskMap <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Usergroups.Usergroup.TaskMap>`
.. attribute:: name_xr
Name of the usergroup
**type**\: str
.. attribute:: taskgroup
Component taskgroups
**type**\: list of :py:class:`Taskgroup <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Usergroups.Usergroup.Taskgroup>`
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Usergroups.Usergroup, self).__init__()
self.yang_name = "usergroup"
self.yang_parent_name = "usergroups"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = ['name']
self._child_classes = OrderedDict([("task-map", ("task_map", Aaa.Usergroups.Usergroup.TaskMap)), ("taskgroup", ("taskgroup", Aaa.Usergroups.Usergroup.Taskgroup))])
self._leafs = OrderedDict([
('name', (YLeaf(YType.str, 'name'), ['str'])),
('name_xr', (YLeaf(YType.str, 'name-xr'), ['str'])),
])
self.name = None
self.name_xr = None
self.task_map = Aaa.Usergroups.Usergroup.TaskMap()
self.task_map.parent = self
self._children_name_map["task_map"] = "task-map"
self.taskgroup = YList(self)
self._segment_path = lambda: "usergroup" + "[name='" + str(self.name) + "']"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/usergroups/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Usergroups.Usergroup, [u'name', u'name_xr'], name, value)
class TaskMap(Entity):
"""
Computed task map
.. attribute:: tasks
List of permitted tasks
**type**\: list of :py:class:`Tasks <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Usergroups.Usergroup.TaskMap.Tasks>`
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Usergroups.Usergroup.TaskMap, self).__init__()
self.yang_name = "task-map"
self.yang_parent_name = "usergroup"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_classes = OrderedDict([("tasks", ("tasks", Aaa.Usergroups.Usergroup.TaskMap.Tasks))])
self._leafs = OrderedDict()
self.tasks = YList(self)
self._segment_path = lambda: "task-map"
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Usergroups.Usergroup.TaskMap, [], name, value)
class Tasks(Entity):
"""
List of permitted tasks
.. attribute:: task_id
Name of the task\-id
**type**\: str
.. attribute:: read
Is read permitted?
**type**\: bool
.. attribute:: write
Is write permitted?
**type**\: bool
.. attribute:: execute
Is execute permitted?
**type**\: bool
.. attribute:: debug
Is debug permitted?
**type**\: bool
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Usergroups.Usergroup.TaskMap.Tasks, self).__init__()
self.yang_name = "tasks"
self.yang_parent_name = "task-map"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('task_id', (YLeaf(YType.str, 'task-id'), ['str'])),
('read', (YLeaf(YType.boolean, 'read'), ['bool'])),
('write', (YLeaf(YType.boolean, 'write'), ['bool'])),
('execute', (YLeaf(YType.boolean, 'execute'), ['bool'])),
('debug', (YLeaf(YType.boolean, 'debug'), ['bool'])),
])
self.task_id = None
self.read = None
self.write = None
self.execute = None
self.debug = None
self._segment_path = lambda: "tasks"
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Usergroups.Usergroup.TaskMap.Tasks, [u'task_id', u'read', u'write', u'execute', u'debug'], name, value)
class Taskgroup(Entity):
"""
Component taskgroups
.. attribute:: included_task_ids
Task\-ids included
**type**\: :py:class:`IncludedTaskIds <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Usergroups.Usergroup.Taskgroup.IncludedTaskIds>`
.. attribute:: task_map
Computed task map
**type**\: :py:class:`TaskMap <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Usergroups.Usergroup.Taskgroup.TaskMap>`
.. attribute:: name_xr
Name of the taskgroup
**type**\: str
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Usergroups.Usergroup.Taskgroup, self).__init__()
self.yang_name = "taskgroup"
self.yang_parent_name = "usergroup"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_classes = OrderedDict([("included-task-ids", ("included_task_ids", Aaa.Usergroups.Usergroup.Taskgroup.IncludedTaskIds)), ("task-map", ("task_map", Aaa.Usergroups.Usergroup.Taskgroup.TaskMap))])
self._leafs = OrderedDict([
('name_xr', (YLeaf(YType.str, 'name-xr'), ['str'])),
])
self.name_xr = None
self.included_task_ids = Aaa.Usergroups.Usergroup.Taskgroup.IncludedTaskIds()
self.included_task_ids.parent = self
self._children_name_map["included_task_ids"] = "included-task-ids"
self.task_map = Aaa.Usergroups.Usergroup.Taskgroup.TaskMap()
self.task_map.parent = self
self._children_name_map["task_map"] = "task-map"
self._segment_path = lambda: "taskgroup"
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Usergroups.Usergroup.Taskgroup, [u'name_xr'], name, value)
class IncludedTaskIds(Entity):
"""
Task\-ids included
.. attribute:: tasks
List of permitted tasks
**type**\: list of :py:class:`Tasks <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Usergroups.Usergroup.Taskgroup.IncludedTaskIds.Tasks>`
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Usergroups.Usergroup.Taskgroup.IncludedTaskIds, self).__init__()
self.yang_name = "included-task-ids"
self.yang_parent_name = "taskgroup"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_classes = OrderedDict([("tasks", ("tasks", Aaa.Usergroups.Usergroup.Taskgroup.IncludedTaskIds.Tasks))])
self._leafs = OrderedDict()
self.tasks = YList(self)
self._segment_path = lambda: "included-task-ids"
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Usergroups.Usergroup.Taskgroup.IncludedTaskIds, [], name, value)
class Tasks(Entity):
"""
List of permitted tasks
.. attribute:: task_id
Name of the task\-id
**type**\: str
.. attribute:: read
Is read permitted?
**type**\: bool
.. attribute:: write
Is write permitted?
**type**\: bool
.. attribute:: execute
Is execute permitted?
**type**\: bool
.. attribute:: debug
Is debug permitted?
**type**\: bool
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Usergroups.Usergroup.Taskgroup.IncludedTaskIds.Tasks, self).__init__()
self.yang_name = "tasks"
self.yang_parent_name = "included-task-ids"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('task_id', (YLeaf(YType.str, 'task-id'), ['str'])),
('read', (YLeaf(YType.boolean, 'read'), ['bool'])),
('write', (YLeaf(YType.boolean, 'write'), ['bool'])),
('execute', (YLeaf(YType.boolean, 'execute'), ['bool'])),
('debug', (YLeaf(YType.boolean, 'debug'), ['bool'])),
])
self.task_id = None
self.read = None
self.write = None
self.execute = None
self.debug = None
self._segment_path = lambda: "tasks"
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Usergroups.Usergroup.Taskgroup.IncludedTaskIds.Tasks, [u'task_id', u'read', u'write', u'execute', u'debug'], name, value)
class TaskMap(Entity):
"""
Computed task map
.. attribute:: tasks
List of permitted tasks
**type**\: list of :py:class:`Tasks <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Usergroups.Usergroup.Taskgroup.TaskMap.Tasks>`
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Usergroups.Usergroup.Taskgroup.TaskMap, self).__init__()
self.yang_name = "task-map"
self.yang_parent_name = "taskgroup"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_classes = OrderedDict([("tasks", ("tasks", Aaa.Usergroups.Usergroup.Taskgroup.TaskMap.Tasks))])
self._leafs = OrderedDict()
self.tasks = YList(self)
self._segment_path = lambda: "task-map"
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Usergroups.Usergroup.Taskgroup.TaskMap, [], name, value)
class Tasks(Entity):
"""
List of permitted tasks
.. attribute:: task_id
Name of the task\-id
**type**\: str
.. attribute:: read
Is read permitted?
**type**\: bool
.. attribute:: write
Is write permitted?
**type**\: bool
.. attribute:: execute
Is execute permitted?
**type**\: bool
.. attribute:: debug
Is debug permitted?
**type**\: bool
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Usergroups.Usergroup.Taskgroup.TaskMap.Tasks, self).__init__()
self.yang_name = "tasks"
self.yang_parent_name = "task-map"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('task_id', (YLeaf(YType.str, 'task-id'), ['str'])),
('read', (YLeaf(YType.boolean, 'read'), ['bool'])),
('write', (YLeaf(YType.boolean, 'write'), ['bool'])),
('execute', (YLeaf(YType.boolean, 'execute'), ['bool'])),
('debug', (YLeaf(YType.boolean, 'debug'), ['bool'])),
])
self.task_id = None
self.read = None
self.write = None
self.execute = None
self.debug = None
self._segment_path = lambda: "tasks"
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Usergroups.Usergroup.Taskgroup.TaskMap.Tasks, [u'task_id', u'read', u'write', u'execute', u'debug'], name, value)
class AuthenMethod(Entity):
"""
Current users authentication method
.. attribute:: name
Name of the usergroup
**type**\: str
.. attribute:: authenmethod
Authentication method
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: usergroup
Component usergroups
**type**\: list of str
.. attribute:: taskmap
Task map details
**type**\: list of str
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.AuthenMethod, self).__init__()
self.yang_name = "authen-method"
self.yang_parent_name = "aaa"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('name', (YLeaf(YType.str, 'name'), ['str'])),
('authenmethod', (YLeaf(YType.int32, 'authenmethod'), ['int'])),
('usergroup', (YLeafList(YType.str, 'usergroup'), ['str'])),
('taskmap', (YLeafList(YType.str, 'taskmap'), ['str'])),
])
self.name = None
self.authenmethod = None
self.usergroup = []
self.taskmap = []
self._segment_path = lambda: "authen-method"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.AuthenMethod, [u'name', u'authenmethod', u'usergroup', u'taskmap'], name, value)
class CurrentUsergroup(Entity):
"""
Specific Usergroup Information
.. attribute:: name
Name of the usergroup
**type**\: str
.. attribute:: authenmethod
Authentication method
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: usergroup
Component usergroups
**type**\: list of str
.. attribute:: taskmap
Task map details
**type**\: list of str
"""
_prefix = 'aaa-locald-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.CurrentUsergroup, self).__init__()
self.yang_name = "current-usergroup"
self.yang_parent_name = "aaa"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('name', (YLeaf(YType.str, 'name'), ['str'])),
('authenmethod', (YLeaf(YType.int32, 'authenmethod'), ['int'])),
('usergroup', (YLeafList(YType.str, 'usergroup'), ['str'])),
('taskmap', (YLeafList(YType.str, 'taskmap'), ['str'])),
])
self.name = None
self.authenmethod = None
self.usergroup = []
self.taskmap = []
self._segment_path = lambda: "current-usergroup"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.CurrentUsergroup, [u'name', u'authenmethod', u'usergroup', u'taskmap'], name, value)
class Radius(Entity):
"""
RADIUS operational data
.. attribute:: servers
List of RADIUS servers configured
**type**\: :py:class:`Servers <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Radius.Servers>`
.. attribute:: radius_source_interface
RADIUS source interfaces
**type**\: :py:class:`RadiusSourceInterface <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Radius.RadiusSourceInterface>`
.. attribute:: global_
RADIUS Client Information
**type**\: :py:class:`Global <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Radius.Global>`
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2017-11-13'
def __init__(self):
super(Aaa.Radius, self).__init__()
self.yang_name = "radius"
self.yang_parent_name = "aaa"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([("servers", ("servers", Aaa.Radius.Servers)), ("radius-source-interface", ("radius_source_interface", Aaa.Radius.RadiusSourceInterface)), ("global", ("global_", Aaa.Radius.Global))])
self._leafs = OrderedDict()
self.servers = Aaa.Radius.Servers()
self.servers.parent = self
self._children_name_map["servers"] = "servers"
self.radius_source_interface = Aaa.Radius.RadiusSourceInterface()
self.radius_source_interface.parent = self
self._children_name_map["radius_source_interface"] = "radius-source-interface"
self.global_ = Aaa.Radius.Global()
self.global_.parent = self
self._children_name_map["global_"] = "global"
self._segment_path = lambda: "Cisco-IOS-XR-aaa-protocol-radius-oper:radius"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Radius, [], name, value)
class Servers(Entity):
"""
List of RADIUS servers configured
.. attribute:: server
RADIUS Server
**type**\: list of :py:class:`Server <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Radius.Servers.Server>`
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2017-11-13'
def __init__(self):
super(Aaa.Radius.Servers, self).__init__()
self.yang_name = "servers"
self.yang_parent_name = "radius"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([("server", ("server", Aaa.Radius.Servers.Server))])
self._leafs = OrderedDict()
self.server = YList(self)
self._segment_path = lambda: "servers"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-protocol-radius-oper:radius/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Radius.Servers, [], name, value)
class Server(Entity):
"""
RADIUS Server
.. attribute:: ip_address
IP address of RADIUS server
**type**\: union of the below types:
**type**\: str
**pattern:** (([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])(%[\\p{N}\\p{L}]+)?
**type**\: str
**pattern:** ((\:\|[0\-9a\-fA\-F]{0,4})\:)([0\-9a\-fA\-F]{0,4}\:){0,5}((([0\-9a\-fA\-F]{0,4}\:)?(\:\|[0\-9a\-fA\-F]{0,4}))\|(((25[0\-5]\|2[0\-4][0\-9]\|[01]?[0\-9]?[0\-9])\\.){3}(25[0\-5]\|2[0\-4][0\-9]\|[01]?[0\-9]?[0\-9])))(%[\\p{N}\\p{L}]+)?
.. attribute:: auth_port_number
Authentication Port number (standard port 1645)
**type**\: int
**range:** 1..65535
.. attribute:: acct_port_number
Accounting Port number (standard port 1646)
**type**\: int
**range:** 1..65535
.. attribute:: ipv4_address
IP address of RADIUS server
**type**\: str
**pattern:** (([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])(%[\\p{N}\\p{L}]+)?
.. attribute:: priority
A number that indicates the priority of the server
**type**\: int
**range:** 0..4294967295
.. attribute:: timeout_xr
Per\-server timeout in seconds
**type**\: int
**range:** 0..4294967295
**units**\: second
.. attribute:: retransmit
Per\-server retransmit
**type**\: int
**range:** 0..4294967295
.. attribute:: dead_time
Per\-server deadtime in minutes
**type**\: int
**range:** 0..4294967295
**units**\: minute
.. attribute:: dead_detect_time
Per\-server dead\-detect time in seconds
**type**\: int
**range:** 0..4294967295
**units**\: second
.. attribute:: dead_detect_tries
Per\-server dead\-detect tries
**type**\: int
**range:** 0..4294967295
.. attribute:: authentication_port
Authentication port
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_port
Accounting port
**type**\: int
**range:** 0..4294967295
.. attribute:: state
State of the server UP/DOWN
**type**\: str
.. attribute:: current_state_duration
Elapsed time the server has been in current state
**type**\: int
**range:** 0..4294967295
.. attribute:: previous_state_duration
Elapsed time the server was been in previous state
**type**\: int
**range:** 0..4294967295
.. attribute:: packets_in
Total number of incoming packets read
**type**\: int
**range:** 0..4294967295
.. attribute:: packets_out
Total number of outgoing packets sent
**type**\: int
**range:** 0..4294967295
.. attribute:: timeouts
Total number of packets timed\-out
**type**\: int
**range:** 0..4294967295
.. attribute:: aborts
Total number of requests aborted
**type**\: int
**range:** 0..4294967295
.. attribute:: replies_expected
Number of replies expected to arrive
**type**\: int
**range:** 0..4294967295
.. attribute:: redirected_requests
Number of requests redirected
**type**\: int
**range:** 0..4294967295
.. attribute:: authentication_rtt
Round\-trip time for authentication in milliseconds
**type**\: int
**range:** 0..4294967295
**units**\: millisecond
.. attribute:: access_requests
Number of access requests
**type**\: int
**range:** 0..4294967295
.. attribute:: access_request_retransmits
Number of retransmitted access requests
**type**\: int
**range:** 0..4294967295
.. attribute:: access_accepts
Number of access accepts
**type**\: int
**range:** 0..4294967295
.. attribute:: access_rejects
Number of access rejects
**type**\: int
**range:** 0..4294967295
.. attribute:: access_challenges
Number of access challenges
**type**\: int
**range:** 0..4294967295
.. attribute:: bad_access_responses
Number of bad access responses
**type**\: int
**range:** 0..4294967295
.. attribute:: bad_access_authenticators
Number of bad access authenticators
**type**\: int
**range:** 0..4294967295
.. attribute:: pending_access_requests
Number of pending access requests
**type**\: int
**range:** 0..4294967295
.. attribute:: access_timeouts
Number of access packets timed\-out
**type**\: int
**range:** 0..4294967295
.. attribute:: unknown_access_types
Number of packets received with unknown type from authentication server
**type**\: int
**range:** 0..4294967295
.. attribute:: dropped_access_responses
Number of access responses dropped
**type**\: int
**range:** 0..4294967295
.. attribute:: throttled_access_reqs
No of throttled access reqs stats
**type**\: int
**range:** 0..4294967295
.. attribute:: throttled_timed_out_reqs
No of access reqs that is throttled is timedout
**type**\: int
**range:** 0..4294967295
.. attribute:: throttled_dropped_reqs
No of discarded access reqs
**type**\: int
**range:** 0..4294967295
.. attribute:: max_throttled_access_reqs
Max throttled access reqs
**type**\: int
**range:** 0..4294967295
.. attribute:: currently_throttled_access_reqs
No of currently throttled access reqs
**type**\: int
**range:** 0..4294967295
.. attribute:: authen_response_time
Average response time for authentication requests
**type**\: int
**range:** 0..4294967295
.. attribute:: authen_transaction_successess
Number of succeeded authentication transactions
**type**\: int
**range:** 0..4294967295
.. attribute:: authen_transaction_failure
Number of failed authentication transactions
**type**\: int
**range:** 0..4294967295
.. attribute:: authen_unexpected_responses
Number of unexpected authentication responses
**type**\: int
**range:** 0..4294967295
.. attribute:: authen_server_error_responses
Number of server error authentication responses
**type**\: int
**range:** 0..4294967295
.. attribute:: authen_incorrect_responses
Number of incorrect authentication responses
**type**\: int
**range:** 0..4294967295
.. attribute:: author_requests
Number of access requests
**type**\: int
**range:** 0..4294967295
.. attribute:: author_request_timeouts
Number of access packets timed out
**type**\: int
**range:** 0..4294967295
.. attribute:: author_response_time
Average response time for authorization requests
**type**\: int
**range:** 0..4294967295
.. attribute:: author_transaction_successess
Number of succeeded authorization transactions
**type**\: int
**range:** 0..4294967295
.. attribute:: author_transaction_failure
Number of failed authorization transactions
**type**\: int
**range:** 0..4294967295
.. attribute:: author_unexpected_responses
Number of unexpected authorization responses
**type**\: int
**range:** 0..4294967295
.. attribute:: author_server_error_responses
Number of server error authorization responses
**type**\: int
**range:** 0..4294967295
.. attribute:: author_incorrect_responses
Number of incorrect authorization responses
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_rtt
Round\-trip time for accounting in milliseconds
**type**\: int
**range:** 0..4294967295
**units**\: millisecond
.. attribute:: accounting_requests
Number of accounting requests
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_retransmits
Number of retransmitted accounting requests
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_responses
Number of accounting responses
**type**\: int
**range:** 0..4294967295
.. attribute:: bad_accounting_responses
Number of bad accounting responses
**type**\: int
**range:** 0..4294967295
.. attribute:: bad_accounting_authenticators
Number of bad accounting authenticators
**type**\: int
**range:** 0..4294967295
.. attribute:: pending_accounting_requets
Number of pending accounting requests
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_timeouts
Number of accounting packets timed\-out
**type**\: int
**range:** 0..4294967295
.. attribute:: unknown_accounting_types
Number of packets received with unknown type from accounting server
**type**\: int
**range:** 0..4294967295
.. attribute:: dropped_accounting_responses
Number of accounting responses dropped
**type**\: int
**range:** 0..4294967295
.. attribute:: is_a_private_server
Is a private server
**type**\: bool
.. attribute:: total_test_auth_reqs
Total auth test request
**type**\: int
**range:** 0..4294967295
.. attribute:: total_test_auth_timeouts
Total auth test timeouts
**type**\: int
**range:** 0..4294967295
.. attribute:: total_test_auth_response
Total auth test response
**type**\: int
**range:** 0..4294967295
.. attribute:: total_test_auth_pending
Total auth test pending
**type**\: int
**range:** 0..4294967295
.. attribute:: total_test_acct_reqs
Total acct test req
**type**\: int
**range:** 0..4294967295
.. attribute:: total_test_acct_timeouts
Total acct test timeouts
**type**\: int
**range:** 0..4294967295
.. attribute:: total_test_acct_response
Total acct test response
**type**\: int
**range:** 0..4294967295
.. attribute:: total_test_acct_pending
Total acct test pending
**type**\: int
**range:** 0..4294967295
.. attribute:: throttled_acct_transactions
No of throttled acct transactions stats
**type**\: int
**range:** 0..4294967295
.. attribute:: throttled_acct_timed_out_stats
No of acct transaction that is throttled is timedout
**type**\: int
**range:** 0..4294967295
.. attribute:: throttled_acct_failures_stats
No of acct discarded transaction
**type**\: int
**range:** 0..4294967295
.. attribute:: max_acct_throttled
Max throttled acct transactions
**type**\: int
**range:** 0..4294967295
.. attribute:: throttleda_acct_transactions
No of currently throttled acct transactions
**type**\: int
**range:** 0..4294967295
.. attribute:: acct_unexpected_responses
Number of unexpected accounting responses
**type**\: int
**range:** 0..4294967295
.. attribute:: acct_server_error_responses
Number of server error accounting responses
**type**\: int
**range:** 0..4294967295
.. attribute:: acct_incorrect_responses
Number of incorrect accounting responses
**type**\: int
**range:** 0..4294967295
.. attribute:: acct_response_time
Average response time for authentication requests
**type**\: int
**range:** 0..4294967295
.. attribute:: acct_transaction_successess
Number of succeeded authentication transactions
**type**\: int
**range:** 0..4294967295
.. attribute:: acct_transaction_failure
Number of failed authentication transactions
**type**\: int
**range:** 0..4294967295
.. attribute:: total_deadtime
Total time of Server being in DEAD state
**type**\: int
**range:** 0..4294967295
.. attribute:: last_deadtime
Time of Server being in DEAD state, after last UP
**type**\: int
**range:** 0..4294967295
.. attribute:: is_quarantined
flag to indicate Server is quarantined or not (Automated TEST in progress)
**type**\: bool
.. attribute:: group_name
Server group name for private server
**type**\: str
.. attribute:: ip_address_xr
IP address buffer
**type**\: str
.. attribute:: family
IP address Family
**type**\: str
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2017-11-13'
def __init__(self):
super(Aaa.Radius.Servers.Server, self).__init__()
self.yang_name = "server"
self.yang_parent_name = "servers"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('ip_address', (YLeaf(YType.str, 'ip-address'), ['str','str'])),
('auth_port_number', (YLeaf(YType.uint32, 'auth-port-number'), ['int'])),
('acct_port_number', (YLeaf(YType.uint32, 'acct-port-number'), ['int'])),
('ipv4_address', (YLeaf(YType.str, 'ipv4-address'), ['str'])),
('priority', (YLeaf(YType.uint32, 'priority'), ['int'])),
('timeout_xr', (YLeaf(YType.uint32, 'timeout-xr'), ['int'])),
('retransmit', (YLeaf(YType.uint32, 'retransmit'), ['int'])),
('dead_time', (YLeaf(YType.uint32, 'dead-time'), ['int'])),
('dead_detect_time', (YLeaf(YType.uint32, 'dead-detect-time'), ['int'])),
('dead_detect_tries', (YLeaf(YType.uint32, 'dead-detect-tries'), ['int'])),
('authentication_port', (YLeaf(YType.uint32, 'authentication-port'), ['int'])),
('accounting_port', (YLeaf(YType.uint32, 'accounting-port'), ['int'])),
('state', (YLeaf(YType.str, 'state'), ['str'])),
('current_state_duration', (YLeaf(YType.uint32, 'current-state-duration'), ['int'])),
('previous_state_duration', (YLeaf(YType.uint32, 'previous-state-duration'), ['int'])),
('packets_in', (YLeaf(YType.uint32, 'packets-in'), ['int'])),
('packets_out', (YLeaf(YType.uint32, 'packets-out'), ['int'])),
('timeouts', (YLeaf(YType.uint32, 'timeouts'), ['int'])),
('aborts', (YLeaf(YType.uint32, 'aborts'), ['int'])),
('replies_expected', (YLeaf(YType.uint32, 'replies-expected'), ['int'])),
('redirected_requests', (YLeaf(YType.uint32, 'redirected-requests'), ['int'])),
('authentication_rtt', (YLeaf(YType.uint32, 'authentication-rtt'), ['int'])),
('access_requests', (YLeaf(YType.uint32, 'access-requests'), ['int'])),
('access_request_retransmits', (YLeaf(YType.uint32, 'access-request-retransmits'), ['int'])),
('access_accepts', (YLeaf(YType.uint32, 'access-accepts'), ['int'])),
('access_rejects', (YLeaf(YType.uint32, 'access-rejects'), ['int'])),
('access_challenges', (YLeaf(YType.uint32, 'access-challenges'), ['int'])),
('bad_access_responses', (YLeaf(YType.uint32, 'bad-access-responses'), ['int'])),
('bad_access_authenticators', (YLeaf(YType.uint32, 'bad-access-authenticators'), ['int'])),
('pending_access_requests', (YLeaf(YType.uint32, 'pending-access-requests'), ['int'])),
('access_timeouts', (YLeaf(YType.uint32, 'access-timeouts'), ['int'])),
('unknown_access_types', (YLeaf(YType.uint32, 'unknown-access-types'), ['int'])),
('dropped_access_responses', (YLeaf(YType.uint32, 'dropped-access-responses'), ['int'])),
('throttled_access_reqs', (YLeaf(YType.uint32, 'throttled-access-reqs'), ['int'])),
('throttled_timed_out_reqs', (YLeaf(YType.uint32, 'throttled-timed-out-reqs'), ['int'])),
('throttled_dropped_reqs', (YLeaf(YType.uint32, 'throttled-dropped-reqs'), ['int'])),
('max_throttled_access_reqs', (YLeaf(YType.uint32, 'max-throttled-access-reqs'), ['int'])),
('currently_throttled_access_reqs', (YLeaf(YType.uint32, 'currently-throttled-access-reqs'), ['int'])),
('authen_response_time', (YLeaf(YType.uint32, 'authen-response-time'), ['int'])),
('authen_transaction_successess', (YLeaf(YType.uint32, 'authen-transaction-successess'), ['int'])),
('authen_transaction_failure', (YLeaf(YType.uint32, 'authen-transaction-failure'), ['int'])),
('authen_unexpected_responses', (YLeaf(YType.uint32, 'authen-unexpected-responses'), ['int'])),
('authen_server_error_responses', (YLeaf(YType.uint32, 'authen-server-error-responses'), ['int'])),
('authen_incorrect_responses', (YLeaf(YType.uint32, 'authen-incorrect-responses'), ['int'])),
('author_requests', (YLeaf(YType.uint32, 'author-requests'), ['int'])),
('author_request_timeouts', (YLeaf(YType.uint32, 'author-request-timeouts'), ['int'])),
('author_response_time', (YLeaf(YType.uint32, 'author-response-time'), ['int'])),
('author_transaction_successess', (YLeaf(YType.uint32, 'author-transaction-successess'), ['int'])),
('author_transaction_failure', (YLeaf(YType.uint32, 'author-transaction-failure'), ['int'])),
('author_unexpected_responses', (YLeaf(YType.uint32, 'author-unexpected-responses'), ['int'])),
('author_server_error_responses', (YLeaf(YType.uint32, 'author-server-error-responses'), ['int'])),
('author_incorrect_responses', (YLeaf(YType.uint32, 'author-incorrect-responses'), ['int'])),
('accounting_rtt', (YLeaf(YType.uint32, 'accounting-rtt'), ['int'])),
('accounting_requests', (YLeaf(YType.uint32, 'accounting-requests'), ['int'])),
('accounting_retransmits', (YLeaf(YType.uint32, 'accounting-retransmits'), ['int'])),
('accounting_responses', (YLeaf(YType.uint32, 'accounting-responses'), ['int'])),
('bad_accounting_responses', (YLeaf(YType.uint32, 'bad-accounting-responses'), ['int'])),
('bad_accounting_authenticators', (YLeaf(YType.uint32, 'bad-accounting-authenticators'), ['int'])),
('pending_accounting_requets', (YLeaf(YType.uint32, 'pending-accounting-requets'), ['int'])),
('accounting_timeouts', (YLeaf(YType.uint32, 'accounting-timeouts'), ['int'])),
('unknown_accounting_types', (YLeaf(YType.uint32, 'unknown-accounting-types'), ['int'])),
('dropped_accounting_responses', (YLeaf(YType.uint32, 'dropped-accounting-responses'), ['int'])),
('is_a_private_server', (YLeaf(YType.boolean, 'is-a-private-server'), ['bool'])),
('total_test_auth_reqs', (YLeaf(YType.uint32, 'total-test-auth-reqs'), ['int'])),
('total_test_auth_timeouts', (YLeaf(YType.uint32, 'total-test-auth-timeouts'), ['int'])),
('total_test_auth_response', (YLeaf(YType.uint32, 'total-test-auth-response'), ['int'])),
('total_test_auth_pending', (YLeaf(YType.uint32, 'total-test-auth-pending'), ['int'])),
('total_test_acct_reqs', (YLeaf(YType.uint32, 'total-test-acct-reqs'), ['int'])),
('total_test_acct_timeouts', (YLeaf(YType.uint32, 'total-test-acct-timeouts'), ['int'])),
('total_test_acct_response', (YLeaf(YType.uint32, 'total-test-acct-response'), ['int'])),
('total_test_acct_pending', (YLeaf(YType.uint32, 'total-test-acct-pending'), ['int'])),
('throttled_acct_transactions', (YLeaf(YType.uint32, 'throttled-acct-transactions'), ['int'])),
('throttled_acct_timed_out_stats', (YLeaf(YType.uint32, 'throttled-acct-timed-out-stats'), ['int'])),
('throttled_acct_failures_stats', (YLeaf(YType.uint32, 'throttled-acct-failures-stats'), ['int'])),
('max_acct_throttled', (YLeaf(YType.uint32, 'max-acct-throttled'), ['int'])),
('throttleda_acct_transactions', (YLeaf(YType.uint32, 'throttleda-acct-transactions'), ['int'])),
('acct_unexpected_responses', (YLeaf(YType.uint32, 'acct-unexpected-responses'), ['int'])),
('acct_server_error_responses', (YLeaf(YType.uint32, 'acct-server-error-responses'), ['int'])),
('acct_incorrect_responses', (YLeaf(YType.uint32, 'acct-incorrect-responses'), ['int'])),
('acct_response_time', (YLeaf(YType.uint32, 'acct-response-time'), ['int'])),
('acct_transaction_successess', (YLeaf(YType.uint32, 'acct-transaction-successess'), ['int'])),
('acct_transaction_failure', (YLeaf(YType.uint32, 'acct-transaction-failure'), ['int'])),
('total_deadtime', (YLeaf(YType.uint32, 'total-deadtime'), ['int'])),
('last_deadtime', (YLeaf(YType.uint32, 'last-deadtime'), ['int'])),
('is_quarantined', (YLeaf(YType.boolean, 'is-quarantined'), ['bool'])),
('group_name', (YLeaf(YType.str, 'group-name'), ['str'])),
('ip_address_xr', (YLeaf(YType.str, 'ip-address-xr'), ['str'])),
('family', (YLeaf(YType.str, 'family'), ['str'])),
])
self.ip_address = None
self.auth_port_number = None
self.acct_port_number = None
self.ipv4_address = None
self.priority = None
self.timeout_xr = None
self.retransmit = None
self.dead_time = None
self.dead_detect_time = None
self.dead_detect_tries = None
self.authentication_port = None
self.accounting_port = None
self.state = None
self.current_state_duration = None
self.previous_state_duration = None
self.packets_in = None
self.packets_out = None
self.timeouts = None
self.aborts = None
self.replies_expected = None
self.redirected_requests = None
self.authentication_rtt = None
self.access_requests = None
self.access_request_retransmits = None
self.access_accepts = None
self.access_rejects = None
self.access_challenges = None
self.bad_access_responses = None
self.bad_access_authenticators = None
self.pending_access_requests = None
self.access_timeouts = None
self.unknown_access_types = None
self.dropped_access_responses = None
self.throttled_access_reqs = None
self.throttled_timed_out_reqs = None
self.throttled_dropped_reqs = None
self.max_throttled_access_reqs = None
self.currently_throttled_access_reqs = None
self.authen_response_time = None
self.authen_transaction_successess = None
self.authen_transaction_failure = None
self.authen_unexpected_responses = None
self.authen_server_error_responses = None
self.authen_incorrect_responses = None
self.author_requests = None
self.author_request_timeouts = None
self.author_response_time = None
self.author_transaction_successess = None
self.author_transaction_failure = None
self.author_unexpected_responses = None
self.author_server_error_responses = None
self.author_incorrect_responses = None
self.accounting_rtt = None
self.accounting_requests = None
self.accounting_retransmits = None
self.accounting_responses = None
self.bad_accounting_responses = None
self.bad_accounting_authenticators = None
self.pending_accounting_requets = None
self.accounting_timeouts = None
self.unknown_accounting_types = None
self.dropped_accounting_responses = None
self.is_a_private_server = None
self.total_test_auth_reqs = None
self.total_test_auth_timeouts = None
self.total_test_auth_response = None
self.total_test_auth_pending = None
self.total_test_acct_reqs = None
self.total_test_acct_timeouts = None
self.total_test_acct_response = None
self.total_test_acct_pending = None
self.throttled_acct_transactions = None
self.throttled_acct_timed_out_stats = None
self.throttled_acct_failures_stats = None
self.max_acct_throttled = None
self.throttleda_acct_transactions = None
self.acct_unexpected_responses = None
self.acct_server_error_responses = None
self.acct_incorrect_responses = None
self.acct_response_time = None
self.acct_transaction_successess = None
self.acct_transaction_failure = None
self.total_deadtime = None
self.last_deadtime = None
self.is_quarantined = None
self.group_name = None
self.ip_address_xr = None
self.family = None
self._segment_path = lambda: "server"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-protocol-radius-oper:radius/servers/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Radius.Servers.Server, ['ip_address', 'auth_port_number', 'acct_port_number', u'ipv4_address', u'priority', u'timeout_xr', u'retransmit', u'dead_time', u'dead_detect_time', u'dead_detect_tries', u'authentication_port', u'accounting_port', u'state', u'current_state_duration', u'previous_state_duration', u'packets_in', u'packets_out', u'timeouts', u'aborts', u'replies_expected', u'redirected_requests', u'authentication_rtt', u'access_requests', u'access_request_retransmits', u'access_accepts', u'access_rejects', u'access_challenges', u'bad_access_responses', u'bad_access_authenticators', u'pending_access_requests', u'access_timeouts', u'unknown_access_types', u'dropped_access_responses', u'throttled_access_reqs', u'throttled_timed_out_reqs', u'throttled_dropped_reqs', u'max_throttled_access_reqs', u'currently_throttled_access_reqs', u'authen_response_time', u'authen_transaction_successess', u'authen_transaction_failure', u'authen_unexpected_responses', u'authen_server_error_responses', u'authen_incorrect_responses', u'author_requests', u'author_request_timeouts', u'author_response_time', u'author_transaction_successess', u'author_transaction_failure', u'author_unexpected_responses', u'author_server_error_responses', u'author_incorrect_responses', u'accounting_rtt', u'accounting_requests', u'accounting_retransmits', u'accounting_responses', u'bad_accounting_responses', u'bad_accounting_authenticators', u'pending_accounting_requets', u'accounting_timeouts', u'unknown_accounting_types', u'dropped_accounting_responses', u'is_a_private_server', u'total_test_auth_reqs', u'total_test_auth_timeouts', u'total_test_auth_response', u'total_test_auth_pending', u'total_test_acct_reqs', u'total_test_acct_timeouts', u'total_test_acct_response', u'total_test_acct_pending', u'throttled_acct_transactions', u'throttled_acct_timed_out_stats', u'throttled_acct_failures_stats', u'max_acct_throttled', u'throttleda_acct_transactions', u'acct_unexpected_responses', u'acct_server_error_responses', u'acct_incorrect_responses', u'acct_response_time', u'acct_transaction_successess', u'acct_transaction_failure', u'total_deadtime', u'last_deadtime', u'is_quarantined', u'group_name', u'ip_address_xr', u'family'], name, value)
class RadiusSourceInterface(Entity):
"""
RADIUS source interfaces
.. attribute:: list_of_source_interface
List of source interfaces
**type**\: list of :py:class:`ListOfSourceInterface <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Radius.RadiusSourceInterface.ListOfSourceInterface>`
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2017-11-13'
def __init__(self):
super(Aaa.Radius.RadiusSourceInterface, self).__init__()
self.yang_name = "radius-source-interface"
self.yang_parent_name = "radius"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([("list-of-source-interface", ("list_of_source_interface", Aaa.Radius.RadiusSourceInterface.ListOfSourceInterface))])
self._leafs = OrderedDict()
self.list_of_source_interface = YList(self)
self._segment_path = lambda: "radius-source-interface"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-protocol-radius-oper:radius/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Radius.RadiusSourceInterface, [], name, value)
class ListOfSourceInterface(Entity):
"""
List of source interfaces
.. attribute:: interface_name
Name of the source interface
**type**\: str
.. attribute:: ipaddrv4
IP address buffer
**type**\: str
.. attribute:: ipaddrv6
IP address buffer
**type**\: str
.. attribute:: vrfid
VRF Id
**type**\: int
**range:** 0..4294967295
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2017-11-13'
def __init__(self):
super(Aaa.Radius.RadiusSourceInterface.ListOfSourceInterface, self).__init__()
self.yang_name = "list-of-source-interface"
self.yang_parent_name = "radius-source-interface"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('interface_name', (YLeaf(YType.str, 'interface-name'), ['str'])),
('ipaddrv4', (YLeaf(YType.str, 'ipaddrv4'), ['str'])),
('ipaddrv6', (YLeaf(YType.str, 'ipaddrv6'), ['str'])),
('vrfid', (YLeaf(YType.uint32, 'vrfid'), ['int'])),
])
self.interface_name = None
self.ipaddrv4 = None
self.ipaddrv6 = None
self.vrfid = None
self._segment_path = lambda: "list-of-source-interface"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-protocol-radius-oper:radius/radius-source-interface/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Radius.RadiusSourceInterface.ListOfSourceInterface, [u'interface_name', u'ipaddrv4', u'ipaddrv6', u'vrfid'], name, value)
class Global(Entity):
"""
RADIUS Client Information
.. attribute:: unknown_authentication_response
Number of RADIUS Access\-Responsepackets received from unknownaddresses
**type**\: int
**range:** 0..4294967295
.. attribute:: authentication_nas_id
NAS\-Identifier of the RADIUSauthentication client
**type**\: str
.. attribute:: unknown_accounting_response
Number of RADIUS Accounting\-Responsepackets received from unknownaddresses
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_nas_id
NAS\-Identifier of the RADIUSaccounting client
**type**\: str
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2017-11-13'
def __init__(self):
super(Aaa.Radius.Global, self).__init__()
self.yang_name = "global"
self.yang_parent_name = "radius"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('unknown_authentication_response', (YLeaf(YType.uint32, 'unknown-authentication-response'), ['int'])),
('authentication_nas_id', (YLeaf(YType.str, 'authentication-nas-id'), ['str'])),
('unknown_accounting_response', (YLeaf(YType.uint32, 'unknown-accounting-response'), ['int'])),
('accounting_nas_id', (YLeaf(YType.str, 'accounting-nas-id'), ['str'])),
])
self.unknown_authentication_response = None
self.authentication_nas_id = None
self.unknown_accounting_response = None
self.accounting_nas_id = None
self._segment_path = lambda: "global"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-protocol-radius-oper:radius/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Radius.Global, [u'unknown_authentication_response', u'authentication_nas_id', u'unknown_accounting_response', u'accounting_nas_id'], name, value)
class Tacacs(Entity):
"""
TACACS operational data
.. attribute:: requests
TACACS Active Request List
**type**\: :py:class:`Requests <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Tacacs.Requests>`
.. attribute:: servers
TACACS server Information
**type**\: :py:class:`Servers <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Tacacs.Servers>`
.. attribute:: server_groups
TACACS sg Information
**type**\: :py:class:`ServerGroups <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Tacacs.ServerGroups>`
"""
_prefix = 'aaa-tacacs-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Tacacs, self).__init__()
self.yang_name = "tacacs"
self.yang_parent_name = "aaa"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([("requests", ("requests", Aaa.Tacacs.Requests)), ("servers", ("servers", Aaa.Tacacs.Servers)), ("server-groups", ("server_groups", Aaa.Tacacs.ServerGroups))])
self._leafs = OrderedDict()
self.requests = Aaa.Tacacs.Requests()
self.requests.parent = self
self._children_name_map["requests"] = "requests"
self.servers = Aaa.Tacacs.Servers()
self.servers.parent = self
self._children_name_map["servers"] = "servers"
self.server_groups = Aaa.Tacacs.ServerGroups()
self.server_groups.parent = self
self._children_name_map["server_groups"] = "server-groups"
self._segment_path = lambda: "Cisco-IOS-XR-aaa-tacacs-oper:tacacs"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Tacacs, [], name, value)
class Requests(Entity):
"""
TACACS Active Request List
.. attribute:: request
request
**type**\: list of :py:class:`Request <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Tacacs.Requests.Request>`
"""
_prefix = 'aaa-tacacs-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Tacacs.Requests, self).__init__()
self.yang_name = "requests"
self.yang_parent_name = "tacacs"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([("request", ("request", Aaa.Tacacs.Requests.Request))])
self._leafs = OrderedDict()
self.request = YList(self)
self._segment_path = lambda: "requests"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-tacacs-oper:tacacs/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Tacacs.Requests, [], name, value)
class Request(Entity):
"""
request
.. attribute:: tacacs_requestbag
tacacs requestbag
**type**\: list of :py:class:`TacacsRequestbag <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Tacacs.Requests.Request.TacacsRequestbag>`
"""
_prefix = 'aaa-tacacs-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Tacacs.Requests.Request, self).__init__()
self.yang_name = "request"
self.yang_parent_name = "requests"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([("tacacs-requestbag", ("tacacs_requestbag", Aaa.Tacacs.Requests.Request.TacacsRequestbag))])
self._leafs = OrderedDict()
self.tacacs_requestbag = YList(self)
self._segment_path = lambda: "request"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-tacacs-oper:tacacs/requests/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Tacacs.Requests.Request, [], name, value)
class TacacsRequestbag(Entity):
"""
tacacs requestbag
.. attribute:: time_remaining
time remaining for this request
**type**\: int
**range:** 0..4294967295
.. attribute:: bytes_out
bytes written
**type**\: int
**range:** 0..4294967295
**units**\: byte
.. attribute:: out_pak_size
size of the packet to be sent
**type**\: int
**range:** 0..4294967295
.. attribute:: bytes_in
bytes read from socket
**type**\: int
**range:** 0..4294967295
**units**\: byte
.. attribute:: in_pak_size
size of the packet to be received
**type**\: int
**range:** 0..4294967295
.. attribute:: pak_type
the type of packet
**type**\: str
.. attribute:: session_id
same as in pkt hdr
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: sock
socket number
**type**\: int
**range:** \-2147483648..2147483647
"""
_prefix = 'aaa-tacacs-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Tacacs.Requests.Request.TacacsRequestbag, self).__init__()
self.yang_name = "tacacs-requestbag"
self.yang_parent_name = "request"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('time_remaining', (YLeaf(YType.uint32, 'time-remaining'), ['int'])),
('bytes_out', (YLeaf(YType.uint32, 'bytes-out'), ['int'])),
('out_pak_size', (YLeaf(YType.uint32, 'out-pak-size'), ['int'])),
('bytes_in', (YLeaf(YType.uint32, 'bytes-in'), ['int'])),
('in_pak_size', (YLeaf(YType.uint32, 'in-pak-size'), ['int'])),
('pak_type', (YLeaf(YType.str, 'pak-type'), ['str'])),
('session_id', (YLeaf(YType.int32, 'session-id'), ['int'])),
('sock', (YLeaf(YType.int32, 'sock'), ['int'])),
])
self.time_remaining = None
self.bytes_out = None
self.out_pak_size = None
self.bytes_in = None
self.in_pak_size = None
self.pak_type = None
self.session_id = None
self.sock = None
self._segment_path = lambda: "tacacs-requestbag"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-tacacs-oper:tacacs/requests/request/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Tacacs.Requests.Request.TacacsRequestbag, ['time_remaining', 'bytes_out', 'out_pak_size', 'bytes_in', 'in_pak_size', 'pak_type', 'session_id', 'sock'], name, value)
class Servers(Entity):
"""
TACACS server Information
.. attribute:: server
server
**type**\: list of :py:class:`Server <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Tacacs.Servers.Server>`
"""
_prefix = 'aaa-tacacs-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Tacacs.Servers, self).__init__()
self.yang_name = "servers"
self.yang_parent_name = "tacacs"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([("server", ("server", Aaa.Tacacs.Servers.Server))])
self._leafs = OrderedDict()
self.server = YList(self)
self._segment_path = lambda: "servers"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-tacacs-oper:tacacs/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Tacacs.Servers, [], name, value)
class Server(Entity):
"""
server
.. attribute:: addr
internet address of T+ server
**type**\: str
**pattern:** (([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])(%[\\p{N}\\p{L}]+)?
.. attribute:: timeout
per\-server timeout
**type**\: int
**range:** 0..4294967295
.. attribute:: port
per server port to use
**type**\: int
**range:** 0..4294967295
.. attribute:: bytes_in
# of bytes read
**type**\: int
**range:** 0..4294967295
**units**\: byte
.. attribute:: bytes_out
# of bytes out
**type**\: int
**range:** 0..4294967295
**units**\: byte
.. attribute:: closes
socket closes
**type**\: int
**range:** 0..4294967295
.. attribute:: opens
socket opens
**type**\: int
**range:** 0..4294967295
.. attribute:: errors
error count
**type**\: int
**range:** 0..4294967295
.. attribute:: aborts
abort count
**type**\: int
**range:** 0..4294967295
.. attribute:: paks_in
# of incoming packets read
**type**\: int
**range:** 0..4294967295
.. attribute:: paks_out
# of outgoing packets sent
**type**\: int
**range:** 0..4294967295
.. attribute:: replies_expected
# of replies expected to arrive
**type**\: int
**range:** 0..4294967295
.. attribute:: up
is the server UP or down ?
**type**\: bool
.. attribute:: conn_up
is the server connected ?
**type**\: bool
.. attribute:: single_connect
is this a single connect server ?
**type**\: bool
.. attribute:: is_private
is this a private server ?
**type**\: bool
.. attribute:: vrf_name
VRF in which server is reachable
**type**\: str
**length:** 0..33
.. attribute:: addr_buf
IP address buffer
**type**\: str
**length:** 0..46
.. attribute:: family
IP address Family
**type**\: str
**length:** 0..5
"""
_prefix = 'aaa-tacacs-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Tacacs.Servers.Server, self).__init__()
self.yang_name = "server"
self.yang_parent_name = "servers"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('addr', (YLeaf(YType.str, 'addr'), ['str'])),
('timeout', (YLeaf(YType.uint32, 'timeout'), ['int'])),
('port', (YLeaf(YType.uint32, 'port'), ['int'])),
('bytes_in', (YLeaf(YType.uint32, 'bytes-in'), ['int'])),
('bytes_out', (YLeaf(YType.uint32, 'bytes-out'), ['int'])),
('closes', (YLeaf(YType.uint32, 'closes'), ['int'])),
('opens', (YLeaf(YType.uint32, 'opens'), ['int'])),
('errors', (YLeaf(YType.uint32, 'errors'), ['int'])),
('aborts', (YLeaf(YType.uint32, 'aborts'), ['int'])),
('paks_in', (YLeaf(YType.uint32, 'paks-in'), ['int'])),
('paks_out', (YLeaf(YType.uint32, 'paks-out'), ['int'])),
('replies_expected', (YLeaf(YType.uint32, 'replies-expected'), ['int'])),
('up', (YLeaf(YType.boolean, 'up'), ['bool'])),
('conn_up', (YLeaf(YType.boolean, 'conn-up'), ['bool'])),
('single_connect', (YLeaf(YType.boolean, 'single-connect'), ['bool'])),
('is_private', (YLeaf(YType.boolean, 'is-private'), ['bool'])),
('vrf_name', (YLeaf(YType.str, 'vrf-name'), ['str'])),
('addr_buf', (YLeaf(YType.str, 'addr-buf'), ['str'])),
('family', (YLeaf(YType.str, 'family'), ['str'])),
])
self.addr = None
self.timeout = None
self.port = None
self.bytes_in = None
self.bytes_out = None
self.closes = None
self.opens = None
self.errors = None
self.aborts = None
self.paks_in = None
self.paks_out = None
self.replies_expected = None
self.up = None
self.conn_up = None
self.single_connect = None
self.is_private = None
self.vrf_name = None
self.addr_buf = None
self.family = None
self._segment_path = lambda: "server"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-tacacs-oper:tacacs/servers/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Tacacs.Servers.Server, ['addr', 'timeout', 'port', 'bytes_in', 'bytes_out', 'closes', 'opens', 'errors', 'aborts', 'paks_in', 'paks_out', 'replies_expected', 'up', 'conn_up', 'single_connect', 'is_private', 'vrf_name', 'addr_buf', 'family'], name, value)
class ServerGroups(Entity):
"""
TACACS sg Information
.. attribute:: server_group
server group
**type**\: list of :py:class:`ServerGroup <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Tacacs.ServerGroups.ServerGroup>`
"""
_prefix = 'aaa-tacacs-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Tacacs.ServerGroups, self).__init__()
self.yang_name = "server-groups"
self.yang_parent_name = "tacacs"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([("server-group", ("server_group", Aaa.Tacacs.ServerGroups.ServerGroup))])
self._leafs = OrderedDict()
self.server_group = YList(self)
self._segment_path = lambda: "server-groups"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-tacacs-oper:tacacs/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Tacacs.ServerGroups, [], name, value)
class ServerGroup(Entity):
"""
server group
.. attribute:: group_name
name of the server group
**type**\: str
.. attribute:: sg_map_num
server group mapped number
**type**\: int
**range:** 0..4294967295
.. attribute:: vrf_name
vrf of the group
**type**\: str
**length:** 0..33
.. attribute:: server
list of servers in this group
**type**\: list of :py:class:`Server <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Tacacs.ServerGroups.ServerGroup.Server>`
"""
_prefix = 'aaa-tacacs-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Tacacs.ServerGroups.ServerGroup, self).__init__()
self.yang_name = "server-group"
self.yang_parent_name = "server-groups"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([("server", ("server", Aaa.Tacacs.ServerGroups.ServerGroup.Server))])
self._leafs = OrderedDict([
('group_name', (YLeaf(YType.str, 'group-name'), ['str'])),
('sg_map_num', (YLeaf(YType.uint32, 'sg-map-num'), ['int'])),
('vrf_name', (YLeaf(YType.str, 'vrf-name'), ['str'])),
])
self.group_name = None
self.sg_map_num = None
self.vrf_name = None
self.server = YList(self)
self._segment_path = lambda: "server-group"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-tacacs-oper:tacacs/server-groups/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Tacacs.ServerGroups.ServerGroup, ['group_name', 'sg_map_num', 'vrf_name'], name, value)
class Server(Entity):
"""
list of servers in this group
.. attribute:: addr
internet address of T+ server
**type**\: str
**pattern:** (([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])(%[\\p{N}\\p{L}]+)?
.. attribute:: timeout
per\-server timeout
**type**\: int
**range:** 0..4294967295
.. attribute:: port
per server port to use
**type**\: int
**range:** 0..4294967295
.. attribute:: bytes_in
# of bytes read
**type**\: int
**range:** 0..4294967295
**units**\: byte
.. attribute:: bytes_out
# of bytes out
**type**\: int
**range:** 0..4294967295
**units**\: byte
.. attribute:: closes
socket closes
**type**\: int
**range:** 0..4294967295
.. attribute:: opens
socket opens
**type**\: int
**range:** 0..4294967295
.. attribute:: errors
error count
**type**\: int
**range:** 0..4294967295
.. attribute:: aborts
abort count
**type**\: int
**range:** 0..4294967295
.. attribute:: paks_in
# of incoming packets read
**type**\: int
**range:** 0..4294967295
.. attribute:: paks_out
# of outgoing packets sent
**type**\: int
**range:** 0..4294967295
.. attribute:: replies_expected
# of replies expected to arrive
**type**\: int
**range:** 0..4294967295
.. attribute:: up
is the server UP or down ?
**type**\: bool
.. attribute:: conn_up
is the server connected ?
**type**\: bool
.. attribute:: single_connect
is this a single connect server ?
**type**\: bool
.. attribute:: is_private
is this a private server ?
**type**\: bool
.. attribute:: vrf_name
VRF in which server is reachable
**type**\: str
**length:** 0..33
.. attribute:: addr_buf
IP address buffer
**type**\: str
**length:** 0..46
.. attribute:: family
IP address Family
**type**\: str
**length:** 0..5
"""
_prefix = 'aaa-tacacs-oper'
_revision = '2015-11-09'
def __init__(self):
super(Aaa.Tacacs.ServerGroups.ServerGroup.Server, self).__init__()
self.yang_name = "server"
self.yang_parent_name = "server-group"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('addr', (YLeaf(YType.str, 'addr'), ['str'])),
('timeout', (YLeaf(YType.uint32, 'timeout'), ['int'])),
('port', (YLeaf(YType.uint32, 'port'), ['int'])),
('bytes_in', (YLeaf(YType.uint32, 'bytes-in'), ['int'])),
('bytes_out', (YLeaf(YType.uint32, 'bytes-out'), ['int'])),
('closes', (YLeaf(YType.uint32, 'closes'), ['int'])),
('opens', (YLeaf(YType.uint32, 'opens'), ['int'])),
('errors', (YLeaf(YType.uint32, 'errors'), ['int'])),
('aborts', (YLeaf(YType.uint32, 'aborts'), ['int'])),
('paks_in', (YLeaf(YType.uint32, 'paks-in'), ['int'])),
('paks_out', (YLeaf(YType.uint32, 'paks-out'), ['int'])),
('replies_expected', (YLeaf(YType.uint32, 'replies-expected'), ['int'])),
('up', (YLeaf(YType.boolean, 'up'), ['bool'])),
('conn_up', (YLeaf(YType.boolean, 'conn-up'), ['bool'])),
('single_connect', (YLeaf(YType.boolean, 'single-connect'), ['bool'])),
('is_private', (YLeaf(YType.boolean, 'is-private'), ['bool'])),
('vrf_name', (YLeaf(YType.str, 'vrf-name'), ['str'])),
('addr_buf', (YLeaf(YType.str, 'addr-buf'), ['str'])),
('family', (YLeaf(YType.str, 'family'), ['str'])),
])
self.addr = None
self.timeout = None
self.port = None
self.bytes_in = None
self.bytes_out = None
self.closes = None
self.opens = None
self.errors = None
self.aborts = None
self.paks_in = None
self.paks_out = None
self.replies_expected = None
self.up = None
self.conn_up = None
self.single_connect = None
self.is_private = None
self.vrf_name = None
self.addr_buf = None
self.family = None
self._segment_path = lambda: "server"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-tacacs-oper:tacacs/server-groups/server-group/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Tacacs.ServerGroups.ServerGroup.Server, ['addr', 'timeout', 'port', 'bytes_in', 'bytes_out', 'closes', 'opens', 'errors', 'aborts', 'paks_in', 'paks_out', 'replies_expected', 'up', 'conn_up', 'single_connect', 'is_private', 'vrf_name', 'addr_buf', 'family'], name, value)
class Diameter(Entity):
"""
Diameter operational data
.. attribute:: gy
Diameter global gy data
**type**\: :py:class:`Gy <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Diameter.Gy>`
.. attribute:: gx_statistics
Diameter Gx Statistics data
**type**\: :py:class:`GxStatistics <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Diameter.GxStatistics>`
.. attribute:: gx
Diameter global gx data
**type**\: :py:class:`Gx <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Diameter.Gx>`
.. attribute:: peers
Diameter peer global data
**type**\: :py:class:`Peers <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Diameter.Peers>`
.. attribute:: nas
Diameter NAS data
**type**\: :py:class:`Nas <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Diameter.Nas>`
.. attribute:: nas_summary
Diameter NAS summary
**type**\: :py:class:`NasSummary <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Diameter.NasSummary>`
.. attribute:: gy_session_ids
Diameter Gy Session data list
**type**\: :py:class:`GySessionIds <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Diameter.GySessionIds>`
.. attribute:: gy_statistics
Diameter Gy Statistics data
**type**\: :py:class:`GyStatistics <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Diameter.GyStatistics>`
.. attribute:: gx_session_ids
Diameter Gx Session data list
**type**\: :py:class:`GxSessionIds <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Diameter.GxSessionIds>`
.. attribute:: nas_session
Diameter Nas Session data
**type**\: :py:class:`NasSession <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Diameter.NasSession>`
"""
_prefix = 'aaa-diameter-oper'
_revision = '2017-09-07'
def __init__(self):
super(Aaa.Diameter, self).__init__()
self.yang_name = "diameter"
self.yang_parent_name = "aaa"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([("gy", ("gy", Aaa.Diameter.Gy)), ("gx-statistics", ("gx_statistics", Aaa.Diameter.GxStatistics)), ("gx", ("gx", Aaa.Diameter.Gx)), ("peers", ("peers", Aaa.Diameter.Peers)), ("nas", ("nas", Aaa.Diameter.Nas)), ("nas-summary", ("nas_summary", Aaa.Diameter.NasSummary)), ("gy-session-ids", ("gy_session_ids", Aaa.Diameter.GySessionIds)), ("gy-statistics", ("gy_statistics", Aaa.Diameter.GyStatistics)), ("gx-session-ids", ("gx_session_ids", Aaa.Diameter.GxSessionIds)), ("nas-session", ("nas_session", Aaa.Diameter.NasSession))])
self._leafs = OrderedDict()
self.gy = Aaa.Diameter.Gy()
self.gy.parent = self
self._children_name_map["gy"] = "gy"
self.gx_statistics = Aaa.Diameter.GxStatistics()
self.gx_statistics.parent = self
self._children_name_map["gx_statistics"] = "gx-statistics"
self.gx = Aaa.Diameter.Gx()
self.gx.parent = self
self._children_name_map["gx"] = "gx"
self.peers = Aaa.Diameter.Peers()
self.peers.parent = self
self._children_name_map["peers"] = "peers"
self.nas = Aaa.Diameter.Nas()
self.nas.parent = self
self._children_name_map["nas"] = "nas"
self.nas_summary = Aaa.Diameter.NasSummary()
self.nas_summary.parent = self
self._children_name_map["nas_summary"] = "nas-summary"
self.gy_session_ids = Aaa.Diameter.GySessionIds()
self.gy_session_ids.parent = self
self._children_name_map["gy_session_ids"] = "gy-session-ids"
self.gy_statistics = Aaa.Diameter.GyStatistics()
self.gy_statistics.parent = self
self._children_name_map["gy_statistics"] = "gy-statistics"
self.gx_session_ids = Aaa.Diameter.GxSessionIds()
self.gx_session_ids.parent = self
self._children_name_map["gx_session_ids"] = "gx-session-ids"
self.nas_session = Aaa.Diameter.NasSession()
self.nas_session.parent = self
self._children_name_map["nas_session"] = "nas-session"
self._segment_path = lambda: "Cisco-IOS-XR-aaa-diameter-oper:diameter"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Diameter, [], name, value)
class Gy(Entity):
"""
Diameter global gy data
.. attribute:: is_enabled
Gy state
**type**\: bool
.. attribute:: tx_timer
Gy transaction timer in seconds
**type**\: int
**range:** 0..4294967295
**units**\: second
.. attribute:: retransmits
Gy retransmit count
**type**\: int
**range:** 0..4294967295
"""
_prefix = 'aaa-diameter-oper'
_revision = '2017-09-07'
def __init__(self):
super(Aaa.Diameter.Gy, self).__init__()
self.yang_name = "gy"
self.yang_parent_name = "diameter"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('is_enabled', (YLeaf(YType.boolean, 'is-enabled'), ['bool'])),
('tx_timer', (YLeaf(YType.uint32, 'tx-timer'), ['int'])),
('retransmits', (YLeaf(YType.uint32, 'retransmits'), ['int'])),
])
self.is_enabled = None
self.tx_timer = None
self.retransmits = None
self._segment_path = lambda: "gy"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-diameter-oper:diameter/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Diameter.Gy, ['is_enabled', 'tx_timer', 'retransmits'], name, value)
class GxStatistics(Entity):
"""
Diameter Gx Statistics data
.. attribute:: ccr_init_messages
CCR Initial Messages
**type**\: int
**range:** 0..4294967295
.. attribute:: ccr_init_failed_messages
CCR Initial Messages Failed
**type**\: int
**range:** 0..4294967295
.. attribute:: ccr_init_timed_out_messages
CCR Initial Messages Timed Out
**type**\: int
**range:** 0..4294967295
.. attribute:: ccr_init_retry_messages
CCR Initial Messages retry
**type**\: int
**range:** 0..4294967295
.. attribute:: ccr_update_messages
CCR Update Messages
**type**\: int
**range:** 0..4294967295
.. attribute:: ccr_update_failed_messages
CCR Update Messages Failed
**type**\: int
**range:** 0..4294967295
.. attribute:: ccr_update_timed_out_messages
CCR Update Messages Timed Out
**type**\: int
**range:** 0..4294967295
.. attribute:: ccr_update_retry_messages
CCR Update Messages retry
**type**\: int
**range:** 0..4294967295
.. attribute:: ccr_final_messages
CCR Final Messages
**type**\: int
**range:** 0..4294967295
.. attribute:: ccr_final_failed_messages
CCR Final Messages Failed
**type**\: int
**range:** 0..4294967295
.. attribute:: ccr_final_timed_out_messages
CCR Final Messages Timed Out
**type**\: int
**range:** 0..4294967295
.. attribute:: ccr_final_retry_messages
CCR Final Messages retry
**type**\: int
**range:** 0..4294967295
.. attribute:: cca_init_messages
CCA Initial Messages
**type**\: int
**range:** 0..4294967295
.. attribute:: cca_init_error_messages
CCA Initial Messages Error
**type**\: int
**range:** 0..4294967295
.. attribute:: cca_update_messages
CCA Update Messages
**type**\: int
**range:** 0..4294967295
.. attribute:: cca_update_error_messages
CCA Update Messages Error
**type**\: int
**range:** 0..4294967295
.. attribute:: cca_final_messages
CCA Final Messages
**type**\: int
**range:** 0..4294967295
.. attribute:: cca_final_error_messages
CCA Final Messages Error
**type**\: int
**range:** 0..4294967295
.. attribute:: rar_received_messages
RAR Received Messages
**type**\: int
**range:** 0..4294967295
.. attribute:: rar_received_error_messages
RAR Received Messages Error
**type**\: int
**range:** 0..4294967295
.. attribute:: raa_sent_messages
RAA Sent Messages
**type**\: int
**range:** 0..4294967295
.. attribute:: raa_sent_error_messages
RAA Sent Messages Error
**type**\: int
**range:** 0..4294967295
.. attribute:: asr_received_messages
ASR Received Messages
**type**\: int
**range:** 0..4294967295
.. attribute:: asr_received_error_messages
ASR Received Messages Error
**type**\: int
**range:** 0..4294967295
.. attribute:: asa_sent_messsages
ASA Sent Messages
**type**\: int
**range:** 0..4294967295
.. attribute:: asa_sent_error_messages
ASA Sent Messages Error
**type**\: int
**range:** 0..4294967295
.. attribute:: session_termination_messages
Session Termination from server
**type**\: int
**range:** 0..4294967295
.. attribute:: unknown_request_messages
Unknown Request Messages
**type**\: int
**range:** 0..4294967295
.. attribute:: restore_sessions
Restore Sessions
**type**\: int
**range:** 0..4294967295
.. attribute:: open_sessions
Total Opened Sessions
**type**\: int
**range:** 0..4294967295
.. attribute:: close_sessions
Total Closed Sessions
**type**\: int
**range:** 0..4294967295
.. attribute:: active_sessions
Total Active Sessions
**type**\: int
**range:** 0..4294967295
"""
_prefix = 'aaa-diameter-oper'
_revision = '2017-09-07'
def __init__(self):
super(Aaa.Diameter.GxStatistics, self).__init__()
self.yang_name = "gx-statistics"
self.yang_parent_name = "diameter"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('ccr_init_messages', (YLeaf(YType.uint32, 'ccr-init-messages'), ['int'])),
('ccr_init_failed_messages', (YLeaf(YType.uint32, 'ccr-init-failed-messages'), ['int'])),
('ccr_init_timed_out_messages', (YLeaf(YType.uint32, 'ccr-init-timed-out-messages'), ['int'])),
('ccr_init_retry_messages', (YLeaf(YType.uint32, 'ccr-init-retry-messages'), ['int'])),
('ccr_update_messages', (YLeaf(YType.uint32, 'ccr-update-messages'), ['int'])),
('ccr_update_failed_messages', (YLeaf(YType.uint32, 'ccr-update-failed-messages'), ['int'])),
('ccr_update_timed_out_messages', (YLeaf(YType.uint32, 'ccr-update-timed-out-messages'), ['int'])),
('ccr_update_retry_messages', (YLeaf(YType.uint32, 'ccr-update-retry-messages'), ['int'])),
('ccr_final_messages', (YLeaf(YType.uint32, 'ccr-final-messages'), ['int'])),
('ccr_final_failed_messages', (YLeaf(YType.uint32, 'ccr-final-failed-messages'), ['int'])),
('ccr_final_timed_out_messages', (YLeaf(YType.uint32, 'ccr-final-timed-out-messages'), ['int'])),
('ccr_final_retry_messages', (YLeaf(YType.uint32, 'ccr-final-retry-messages'), ['int'])),
('cca_init_messages', (YLeaf(YType.uint32, 'cca-init-messages'), ['int'])),
('cca_init_error_messages', (YLeaf(YType.uint32, 'cca-init-error-messages'), ['int'])),
('cca_update_messages', (YLeaf(YType.uint32, 'cca-update-messages'), ['int'])),
('cca_update_error_messages', (YLeaf(YType.uint32, 'cca-update-error-messages'), ['int'])),
('cca_final_messages', (YLeaf(YType.uint32, 'cca-final-messages'), ['int'])),
('cca_final_error_messages', (YLeaf(YType.uint32, 'cca-final-error-messages'), ['int'])),
('rar_received_messages', (YLeaf(YType.uint32, 'rar-received-messages'), ['int'])),
('rar_received_error_messages', (YLeaf(YType.uint32, 'rar-received-error-messages'), ['int'])),
('raa_sent_messages', (YLeaf(YType.uint32, 'raa-sent-messages'), ['int'])),
('raa_sent_error_messages', (YLeaf(YType.uint32, 'raa-sent-error-messages'), ['int'])),
('asr_received_messages', (YLeaf(YType.uint32, 'asr-received-messages'), ['int'])),
('asr_received_error_messages', (YLeaf(YType.uint32, 'asr-received-error-messages'), ['int'])),
('asa_sent_messsages', (YLeaf(YType.uint32, 'asa-sent-messsages'), ['int'])),
('asa_sent_error_messages', (YLeaf(YType.uint32, 'asa-sent-error-messages'), ['int'])),
('session_termination_messages', (YLeaf(YType.uint32, 'session-termination-messages'), ['int'])),
('unknown_request_messages', (YLeaf(YType.uint32, 'unknown-request-messages'), ['int'])),
('restore_sessions', (YLeaf(YType.uint32, 'restore-sessions'), ['int'])),
('open_sessions', (YLeaf(YType.uint32, 'open-sessions'), ['int'])),
('close_sessions', (YLeaf(YType.uint32, 'close-sessions'), ['int'])),
('active_sessions', (YLeaf(YType.uint32, 'active-sessions'), ['int'])),
])
self.ccr_init_messages = None
self.ccr_init_failed_messages = None
self.ccr_init_timed_out_messages = None
self.ccr_init_retry_messages = None
self.ccr_update_messages = None
self.ccr_update_failed_messages = None
self.ccr_update_timed_out_messages = None
self.ccr_update_retry_messages = None
self.ccr_final_messages = None
self.ccr_final_failed_messages = None
self.ccr_final_timed_out_messages = None
self.ccr_final_retry_messages = None
self.cca_init_messages = None
self.cca_init_error_messages = None
self.cca_update_messages = None
self.cca_update_error_messages = None
self.cca_final_messages = None
self.cca_final_error_messages = None
self.rar_received_messages = None
self.rar_received_error_messages = None
self.raa_sent_messages = None
self.raa_sent_error_messages = None
self.asr_received_messages = None
self.asr_received_error_messages = None
self.asa_sent_messsages = None
self.asa_sent_error_messages = None
self.session_termination_messages = None
self.unknown_request_messages = None
self.restore_sessions = None
self.open_sessions = None
self.close_sessions = None
self.active_sessions = None
self._segment_path = lambda: "gx-statistics"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-diameter-oper:diameter/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Diameter.GxStatistics, ['ccr_init_messages', 'ccr_init_failed_messages', 'ccr_init_timed_out_messages', 'ccr_init_retry_messages', 'ccr_update_messages', 'ccr_update_failed_messages', 'ccr_update_timed_out_messages', 'ccr_update_retry_messages', 'ccr_final_messages', 'ccr_final_failed_messages', 'ccr_final_timed_out_messages', 'ccr_final_retry_messages', 'cca_init_messages', 'cca_init_error_messages', 'cca_update_messages', 'cca_update_error_messages', 'cca_final_messages', 'cca_final_error_messages', 'rar_received_messages', 'rar_received_error_messages', 'raa_sent_messages', 'raa_sent_error_messages', 'asr_received_messages', 'asr_received_error_messages', 'asa_sent_messsages', 'asa_sent_error_messages', 'session_termination_messages', 'unknown_request_messages', 'restore_sessions', 'open_sessions', 'close_sessions', 'active_sessions'], name, value)
class Gx(Entity):
"""
Diameter global gx data
.. attribute:: is_enabled
Gx state
**type**\: bool
.. attribute:: tx_timer
Gx transaction timer in seconds
**type**\: int
**range:** 0..4294967295
**units**\: second
.. attribute:: retransmits
Gx retransmit count
**type**\: int
**range:** 0..4294967295
"""
_prefix = 'aaa-diameter-oper'
_revision = '2017-09-07'
def __init__(self):
super(Aaa.Diameter.Gx, self).__init__()
self.yang_name = "gx"
self.yang_parent_name = "diameter"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('is_enabled', (YLeaf(YType.boolean, 'is-enabled'), ['bool'])),
('tx_timer', (YLeaf(YType.uint32, 'tx-timer'), ['int'])),
('retransmits', (YLeaf(YType.uint32, 'retransmits'), ['int'])),
])
self.is_enabled = None
self.tx_timer = None
self.retransmits = None
self._segment_path = lambda: "gx"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-diameter-oper:diameter/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Diameter.Gx, ['is_enabled', 'tx_timer', 'retransmits'], name, value)
class Peers(Entity):
"""
Diameter peer global data
.. attribute:: origin_host
Origin Host
**type**\: str
.. attribute:: origin_realm
Origin Realm
**type**\: str
.. attribute:: source_interface
Source Interface
**type**\: str
.. attribute:: tls_trustpoint
TLS Trustpoint
**type**\: str
.. attribute:: conn_retry_timer
Connection retry timer in seconds
**type**\: int
**range:** 0..4294967295
**units**\: second
.. attribute:: watchdog_timer
Watch dog timer in seconds
**type**\: int
**range:** 0..4294967295
**units**\: second
.. attribute:: transaction_timer
Transaction timer in seconds
**type**\: int
**range:** 0..4294967295
**units**\: second
.. attribute:: trans_total
Total number of transactions
**type**\: int
**range:** 0..4294967295
.. attribute:: trans_max
Maximum number of transactions
**type**\: int
**range:** 0..4294967295
.. attribute:: peer
Peer List
**type**\: list of :py:class:`Peer <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Diameter.Peers.Peer>`
"""
_prefix = 'aaa-diameter-oper'
_revision = '2017-09-07'
def __init__(self):
super(Aaa.Diameter.Peers, self).__init__()
self.yang_name = "peers"
self.yang_parent_name = "diameter"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([("peer", ("peer", Aaa.Diameter.Peers.Peer))])
self._leafs = OrderedDict([
('origin_host', (YLeaf(YType.str, 'origin-host'), ['str'])),
('origin_realm', (YLeaf(YType.str, 'origin-realm'), ['str'])),
('source_interface', (YLeaf(YType.str, 'source-interface'), ['str'])),
('tls_trustpoint', (YLeaf(YType.str, 'tls-trustpoint'), ['str'])),
('conn_retry_timer', (YLeaf(YType.uint32, 'conn-retry-timer'), ['int'])),
('watchdog_timer', (YLeaf(YType.uint32, 'watchdog-timer'), ['int'])),
('transaction_timer', (YLeaf(YType.uint32, 'transaction-timer'), ['int'])),
('trans_total', (YLeaf(YType.uint32, 'trans-total'), ['int'])),
('trans_max', (YLeaf(YType.uint32, 'trans-max'), ['int'])),
])
self.origin_host = None
self.origin_realm = None
self.source_interface = None
self.tls_trustpoint = None
self.conn_retry_timer = None
self.watchdog_timer = None
self.transaction_timer = None
self.trans_total = None
self.trans_max = None
self.peer = YList(self)
self._segment_path = lambda: "peers"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-diameter-oper:diameter/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Diameter.Peers, ['origin_host', 'origin_realm', 'source_interface', 'tls_trustpoint', 'conn_retry_timer', 'watchdog_timer', 'transaction_timer', 'trans_total', 'trans_max'], name, value)
class Peer(Entity):
"""
Peer List
.. attribute:: peer_name
Peer Name
**type**\: str
.. attribute:: peer_index
Peer Index
**type**\: int
**range:** 0..4294967295
.. attribute:: address
IPv4 or IPv6 address of DIAMETER peer
**type**\: str
.. attribute:: port
Port number on which the peeris running
**type**\: int
**range:** 0..4294967295
.. attribute:: port_connect
Local Connection port
**type**\: int
**range:** 0..4294967295
.. attribute:: protocol_type
Protocol Type
**type**\: :py:class:`ProtocolTypeValue <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_diameter_oper.ProtocolTypeValue>`
.. attribute:: security_type
Security type used to transport
**type**\: :py:class:`SecurityTypeValue <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_diameter_oper.SecurityTypeValue>`
.. attribute:: conn_retry_timer
Connection retry timer in seconds
**type**\: int
**range:** 0..4294967295
**units**\: second
.. attribute:: watchdog_timer
Watch dog timer in seconds
**type**\: int
**range:** 0..4294967295
**units**\: second
.. attribute:: transaction_timer
Transaction timer in seconds
**type**\: int
**range:** 0..4294967295
**units**\: second
.. attribute:: vrf_name
Vrf Name
**type**\: str
.. attribute:: source_interface
Source Interface
**type**\: str
.. attribute:: destination_host
Destination host name
**type**\: str
.. attribute:: destination_realm
Destination realm
**type**\: str
.. attribute:: peer_type
Peer Type
**type**\: :py:class:`Peer <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_diameter_oper.Peer>`
.. attribute:: firmware_revision
Firmware revision
**type**\: int
**range:** 0..4294967295
.. attribute:: state_duration
State Duration in seconds
**type**\: int
**range:** 0..4294967295
**units**\: second
.. attribute:: last_disconnect_cause
Last Disconnect Reason
**type**\: :py:class:`DisconnectCause <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_diameter_oper.DisconnectCause>`
.. attribute:: who_init_disconnect
Who Initiated Disconnect
**type**\: :py:class:`WhoInitiatedDisconnect <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_diameter_oper.WhoInitiatedDisconnect>`
.. attribute:: in_as_rs
Incoming ASRs
**type**\: int
**range:** 0..4294967295
.. attribute:: out_as_rs
Outgoing ASRs
**type**\: int
**range:** 0..4294967295
.. attribute:: in_as_as
Incoming ASAs
**type**\: int
**range:** 0..4294967295
.. attribute:: out_as_as
Outgoing ASAs
**type**\: int
**range:** 0..4294967295
.. attribute:: in_ac_rs
Incoming ACRs
**type**\: int
**range:** 0..4294967295
.. attribute:: out_ac_rs
Outgoing ACRs
**type**\: int
**range:** 0..4294967295
.. attribute:: in_ac_as
Incoming ACAs
**type**\: int
**range:** 0..4294967295
.. attribute:: out_ac_as
Outgoing ACAs
**type**\: int
**range:** 0..4294967295
.. attribute:: in_ce_rs
Incoming CERs
**type**\: int
**range:** 0..4294967295
.. attribute:: out_ce_rs
Outgoing CERs
**type**\: int
**range:** 0..4294967295
.. attribute:: in_ce_as
Incoming CEAs
**type**\: int
**range:** 0..4294967295
.. attribute:: out_ce_as
Outgoing CEAs
**type**\: int
**range:** 0..4294967295
.. attribute:: in_dw_rs
Incoming DWRs
**type**\: int
**range:** 0..4294967295
.. attribute:: out_dw_rs
Outgoing DWRs
**type**\: int
**range:** 0..4294967295
.. attribute:: in_dw_as
Incoming DWAs
**type**\: int
**range:** 0..4294967295
.. attribute:: out_dw_as
Outgoing DWAs
**type**\: int
**range:** 0..4294967295
.. attribute:: in_dp_rs
Incoming DPRs
**type**\: int
**range:** 0..4294967295
.. attribute:: out_dp_rs
Outgoing DPRs
**type**\: int
**range:** 0..4294967295
.. attribute:: in_dp_as
Incoming DPAs
**type**\: int
**range:** 0..4294967295
.. attribute:: out_dp_as
Outgoing DPAs
**type**\: int
**range:** 0..4294967295
.. attribute:: in_ra_rs
Incoming RARs
**type**\: int
**range:** 0..4294967295
.. attribute:: out_ra_rs
Outgoing RARs
**type**\: int
**range:** 0..4294967295
.. attribute:: in_ra_as
Incoming RAAs
**type**\: int
**range:** 0..4294967295
.. attribute:: out_ra_as
Outgoing RAAs
**type**\: int
**range:** 0..4294967295
.. attribute:: in_st_rs
Incoming STRs
**type**\: int
**range:** 0..4294967295
.. attribute:: out_st_rs
Outgoing STRs
**type**\: int
**range:** 0..4294967295
.. attribute:: in_st_as
Incoming STAs
**type**\: int
**range:** 0..4294967295
.. attribute:: out_st_as
Outgoing STAs
**type**\: int
**range:** 0..4294967295
.. attribute:: in_cc_rs
Incoming CCRs
**type**\: int
**range:** 0..4294967295
.. attribute:: out_cc_rs
Outgoing CCRs
**type**\: int
**range:** 0..4294967295
.. attribute:: in_cc_as
Incoming CCAs
**type**\: int
**range:** 0..4294967295
.. attribute:: out_cc_as
Outgoing CCAs
**type**\: int
**range:** 0..4294967295
.. attribute:: out_aa_rs
Outgoing AARs
**type**\: int
**range:** 0..4294967295
.. attribute:: in_aa_as
Incoming AAAs
**type**\: int
**range:** 0..4294967295
.. attribute:: malformed_requests
Malformed Requests
**type**\: int
**range:** 0..4294967295
.. attribute:: received_proto_errors
Protocol Error Received
**type**\: int
**range:** 0..4294967295
.. attribute:: sent_proto_errors
Protocol Error Sent
**type**\: int
**range:** 0..4294967295
.. attribute:: received_transient_fails
Transient failures Received
**type**\: int
**range:** 0..4294967295
.. attribute:: sent_transient_fails
Transient failures Sent
**type**\: int
**range:** 0..4294967295
.. attribute:: received_permanent_fails
Permanent Failures Received
**type**\: int
**range:** 0..4294967295
.. attribute:: sent_permanent_fails
Permanent Failures Sent
**type**\: int
**range:** 0..4294967295
.. attribute:: transport_down
Transport Down
**type**\: int
**range:** 0..4294967295
.. attribute:: state
Peer Connection Status
**type**\: :py:class:`PeerStateValue <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_diameter_oper.PeerStateValue>`
"""
_prefix = 'aaa-diameter-oper'
_revision = '2017-09-07'
def __init__(self):
super(Aaa.Diameter.Peers.Peer, self).__init__()
self.yang_name = "peer"
self.yang_parent_name = "peers"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('peer_name', (YLeaf(YType.str, 'peer-name'), ['str'])),
('peer_index', (YLeaf(YType.uint32, 'peer-index'), ['int'])),
('address', (YLeaf(YType.str, 'address'), ['str'])),
('port', (YLeaf(YType.uint32, 'port'), ['int'])),
('port_connect', (YLeaf(YType.uint32, 'port-connect'), ['int'])),
('protocol_type', (YLeaf(YType.enumeration, 'protocol-type'), [('ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_diameter_oper', 'ProtocolTypeValue', '')])),
('security_type', (YLeaf(YType.enumeration, 'security-type'), [('ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_diameter_oper', 'SecurityTypeValue', '')])),
('conn_retry_timer', (YLeaf(YType.uint32, 'conn-retry-timer'), ['int'])),
('watchdog_timer', (YLeaf(YType.uint32, 'watchdog-timer'), ['int'])),
('transaction_timer', (YLeaf(YType.uint32, 'transaction-timer'), ['int'])),
('vrf_name', (YLeaf(YType.str, 'vrf-name'), ['str'])),
('source_interface', (YLeaf(YType.str, 'source-interface'), ['str'])),
('destination_host', (YLeaf(YType.str, 'destination-host'), ['str'])),
('destination_realm', (YLeaf(YType.str, 'destination-realm'), ['str'])),
('peer_type', (YLeaf(YType.enumeration, 'peer-type'), [('ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_diameter_oper', 'Peer', '')])),
('firmware_revision', (YLeaf(YType.uint32, 'firmware-revision'), ['int'])),
('state_duration', (YLeaf(YType.uint32, 'state-duration'), ['int'])),
('last_disconnect_cause', (YLeaf(YType.enumeration, 'last-disconnect-cause'), [('ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_diameter_oper', 'DisconnectCause', '')])),
('who_init_disconnect', (YLeaf(YType.enumeration, 'who-init-disconnect'), [('ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_diameter_oper', 'WhoInitiatedDisconnect', '')])),
('in_as_rs', (YLeaf(YType.uint32, 'in-as-rs'), ['int'])),
('out_as_rs', (YLeaf(YType.uint32, 'out-as-rs'), ['int'])),
('in_as_as', (YLeaf(YType.uint32, 'in-as-as'), ['int'])),
('out_as_as', (YLeaf(YType.uint32, 'out-as-as'), ['int'])),
('in_ac_rs', (YLeaf(YType.uint32, 'in-ac-rs'), ['int'])),
('out_ac_rs', (YLeaf(YType.uint32, 'out-ac-rs'), ['int'])),
('in_ac_as', (YLeaf(YType.uint32, 'in-ac-as'), ['int'])),
('out_ac_as', (YLeaf(YType.uint32, 'out-ac-as'), ['int'])),
('in_ce_rs', (YLeaf(YType.uint32, 'in-ce-rs'), ['int'])),
('out_ce_rs', (YLeaf(YType.uint32, 'out-ce-rs'), ['int'])),
('in_ce_as', (YLeaf(YType.uint32, 'in-ce-as'), ['int'])),
('out_ce_as', (YLeaf(YType.uint32, 'out-ce-as'), ['int'])),
('in_dw_rs', (YLeaf(YType.uint32, 'in-dw-rs'), ['int'])),
('out_dw_rs', (YLeaf(YType.uint32, 'out-dw-rs'), ['int'])),
('in_dw_as', (YLeaf(YType.uint32, 'in-dw-as'), ['int'])),
('out_dw_as', (YLeaf(YType.uint32, 'out-dw-as'), ['int'])),
('in_dp_rs', (YLeaf(YType.uint32, 'in-dp-rs'), ['int'])),
('out_dp_rs', (YLeaf(YType.uint32, 'out-dp-rs'), ['int'])),
('in_dp_as', (YLeaf(YType.uint32, 'in-dp-as'), ['int'])),
('out_dp_as', (YLeaf(YType.uint32, 'out-dp-as'), ['int'])),
('in_ra_rs', (YLeaf(YType.uint32, 'in-ra-rs'), ['int'])),
('out_ra_rs', (YLeaf(YType.uint32, 'out-ra-rs'), ['int'])),
('in_ra_as', (YLeaf(YType.uint32, 'in-ra-as'), ['int'])),
('out_ra_as', (YLeaf(YType.uint32, 'out-ra-as'), ['int'])),
('in_st_rs', (YLeaf(YType.uint32, 'in-st-rs'), ['int'])),
('out_st_rs', (YLeaf(YType.uint32, 'out-st-rs'), ['int'])),
('in_st_as', (YLeaf(YType.uint32, 'in-st-as'), ['int'])),
('out_st_as', (YLeaf(YType.uint32, 'out-st-as'), ['int'])),
('in_cc_rs', (YLeaf(YType.uint32, 'in-cc-rs'), ['int'])),
('out_cc_rs', (YLeaf(YType.uint32, 'out-cc-rs'), ['int'])),
('in_cc_as', (YLeaf(YType.uint32, 'in-cc-as'), ['int'])),
('out_cc_as', (YLeaf(YType.uint32, 'out-cc-as'), ['int'])),
('out_aa_rs', (YLeaf(YType.uint32, 'out-aa-rs'), ['int'])),
('in_aa_as', (YLeaf(YType.uint32, 'in-aa-as'), ['int'])),
('malformed_requests', (YLeaf(YType.uint32, 'malformed-requests'), ['int'])),
('received_proto_errors', (YLeaf(YType.uint32, 'received-proto-errors'), ['int'])),
('sent_proto_errors', (YLeaf(YType.uint32, 'sent-proto-errors'), ['int'])),
('received_transient_fails', (YLeaf(YType.uint32, 'received-transient-fails'), ['int'])),
('sent_transient_fails', (YLeaf(YType.uint32, 'sent-transient-fails'), ['int'])),
('received_permanent_fails', (YLeaf(YType.uint32, 'received-permanent-fails'), ['int'])),
('sent_permanent_fails', (YLeaf(YType.uint32, 'sent-permanent-fails'), ['int'])),
('transport_down', (YLeaf(YType.uint32, 'transport-down'), ['int'])),
('state', (YLeaf(YType.enumeration, 'state'), [('ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_diameter_oper', 'PeerStateValue', '')])),
])
self.peer_name = None
self.peer_index = None
self.address = None
self.port = None
self.port_connect = None
self.protocol_type = None
self.security_type = None
self.conn_retry_timer = None
self.watchdog_timer = None
self.transaction_timer = None
self.vrf_name = None
self.source_interface = None
self.destination_host = None
self.destination_realm = None
self.peer_type = None
self.firmware_revision = None
self.state_duration = None
self.last_disconnect_cause = None
self.who_init_disconnect = None
self.in_as_rs = None
self.out_as_rs = None
self.in_as_as = None
self.out_as_as = None
self.in_ac_rs = None
self.out_ac_rs = None
self.in_ac_as = None
self.out_ac_as = None
self.in_ce_rs = None
self.out_ce_rs = None
self.in_ce_as = None
self.out_ce_as = None
self.in_dw_rs = None
self.out_dw_rs = None
self.in_dw_as = None
self.out_dw_as = None
self.in_dp_rs = None
self.out_dp_rs = None
self.in_dp_as = None
self.out_dp_as = None
self.in_ra_rs = None
self.out_ra_rs = None
self.in_ra_as = None
self.out_ra_as = None
self.in_st_rs = None
self.out_st_rs = None
self.in_st_as = None
self.out_st_as = None
self.in_cc_rs = None
self.out_cc_rs = None
self.in_cc_as = None
self.out_cc_as = None
self.out_aa_rs = None
self.in_aa_as = None
self.malformed_requests = None
self.received_proto_errors = None
self.sent_proto_errors = None
self.received_transient_fails = None
self.sent_transient_fails = None
self.received_permanent_fails = None
self.sent_permanent_fails = None
self.transport_down = None
self.state = None
self._segment_path = lambda: "peer"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-diameter-oper:diameter/peers/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Diameter.Peers.Peer, ['peer_name', 'peer_index', 'address', 'port', 'port_connect', 'protocol_type', 'security_type', 'conn_retry_timer', 'watchdog_timer', 'transaction_timer', 'vrf_name', 'source_interface', 'destination_host', 'destination_realm', 'peer_type', 'firmware_revision', 'state_duration', 'last_disconnect_cause', 'who_init_disconnect', 'in_as_rs', 'out_as_rs', 'in_as_as', 'out_as_as', 'in_ac_rs', 'out_ac_rs', 'in_ac_as', 'out_ac_as', 'in_ce_rs', 'out_ce_rs', 'in_ce_as', 'out_ce_as', 'in_dw_rs', 'out_dw_rs', 'in_dw_as', 'out_dw_as', 'in_dp_rs', 'out_dp_rs', 'in_dp_as', 'out_dp_as', 'in_ra_rs', 'out_ra_rs', 'in_ra_as', 'out_ra_as', 'in_st_rs', 'out_st_rs', 'in_st_as', 'out_st_as', 'in_cc_rs', 'out_cc_rs', 'in_cc_as', 'out_cc_as', 'out_aa_rs', 'in_aa_as', 'malformed_requests', 'received_proto_errors', 'sent_proto_errors', 'received_transient_fails', 'sent_transient_fails', 'received_permanent_fails', 'sent_permanent_fails', 'transport_down', 'state'], name, value)
class Nas(Entity):
"""
Diameter NAS data
.. attribute:: aaanas_id
AAA NAS id
**type**\: str
.. attribute:: list_of_nas
List of NAS Entries
**type**\: list of :py:class:`ListOfNas <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Diameter.Nas.ListOfNas>`
"""
_prefix = 'aaa-diameter-oper'
_revision = '2017-09-07'
def __init__(self):
super(Aaa.Diameter.Nas, self).__init__()
self.yang_name = "nas"
self.yang_parent_name = "diameter"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([("list-of-nas", ("list_of_nas", Aaa.Diameter.Nas.ListOfNas))])
self._leafs = OrderedDict([
('aaanas_id', (YLeaf(YType.str, 'aaanas-id'), ['str'])),
])
self.aaanas_id = None
self.list_of_nas = YList(self)
self._segment_path = lambda: "nas"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-diameter-oper:diameter/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Diameter.Nas, ['aaanas_id'], name, value)
class ListOfNas(Entity):
"""
List of NAS Entries
.. attribute:: aaa_session_id
AAA session id
**type**\: str
.. attribute:: diameter_session_id
Diameter session id
**type**\: str
.. attribute:: authentication_status
Diameter AAR status
**type**\: int
**range:** 0..4294967295
.. attribute:: authorization_status
Diameter AAR status
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_status
Diameter ACR status start
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_status_stop
Diameter ACR status stop
**type**\: int
**range:** 0..4294967295
.. attribute:: disconnect_status
Diameter STR status
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_intrim_in_packets
Accounting intrim packet response in
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_intrim_out_packets
Accounting intrim requests packets out
**type**\: int
**range:** 0..4294967295
.. attribute:: method_list
Method list used for authentication
**type**\: str
.. attribute:: server_used_list
Server used for authentication
**type**\: str
"""
_prefix = 'aaa-diameter-oper'
_revision = '2017-09-07'
def __init__(self):
super(Aaa.Diameter.Nas.ListOfNas, self).__init__()
self.yang_name = "list-of-nas"
self.yang_parent_name = "nas"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('aaa_session_id', (YLeaf(YType.str, 'aaa-session-id'), ['str'])),
('diameter_session_id', (YLeaf(YType.str, 'diameter-session-id'), ['str'])),
('authentication_status', (YLeaf(YType.uint32, 'authentication-status'), ['int'])),
('authorization_status', (YLeaf(YType.uint32, 'authorization-status'), ['int'])),
('accounting_status', (YLeaf(YType.uint32, 'accounting-status'), ['int'])),
('accounting_status_stop', (YLeaf(YType.uint32, 'accounting-status-stop'), ['int'])),
('disconnect_status', (YLeaf(YType.uint32, 'disconnect-status'), ['int'])),
('accounting_intrim_in_packets', (YLeaf(YType.uint32, 'accounting-intrim-in-packets'), ['int'])),
('accounting_intrim_out_packets', (YLeaf(YType.uint32, 'accounting-intrim-out-packets'), ['int'])),
('method_list', (YLeaf(YType.str, 'method-list'), ['str'])),
('server_used_list', (YLeaf(YType.str, 'server-used-list'), ['str'])),
])
self.aaa_session_id = None
self.diameter_session_id = None
self.authentication_status = None
self.authorization_status = None
self.accounting_status = None
self.accounting_status_stop = None
self.disconnect_status = None
self.accounting_intrim_in_packets = None
self.accounting_intrim_out_packets = None
self.method_list = None
self.server_used_list = None
self._segment_path = lambda: "list-of-nas"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-diameter-oper:diameter/nas/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Diameter.Nas.ListOfNas, ['aaa_session_id', 'diameter_session_id', 'authentication_status', 'authorization_status', 'accounting_status', 'accounting_status_stop', 'disconnect_status', 'accounting_intrim_in_packets', 'accounting_intrim_out_packets', 'method_list', 'server_used_list'], name, value)
class NasSummary(Entity):
"""
Diameter NAS summary
.. attribute:: authen_response_in_packets
Authentication response pkt in
**type**\: int
**range:** 0..4294967295
.. attribute:: authen_request_out_packets
Authentication request pkt out
**type**\: int
**range:** 0..4294967295
.. attribute:: authen_request_in_packets
Authentication request from client
**type**\: int
**range:** 0..4294967295
.. attribute:: authen_response_out_packets
Authentication response frwd to client
**type**\: int
**range:** 0..4294967295
.. attribute:: authen_success_packets
Authentication response with success
**type**\: int
**range:** 0..4294967295
.. attribute:: authen_response_fail_packets
Authentication response with failure
**type**\: int
**range:** 0..4294967295
.. attribute:: authorization_in_packets
Authorization response packet in
**type**\: int
**range:** 0..4294967295
.. attribute:: authorization_out_packets
Authorization request packet out
**type**\: int
**range:** 0..4294967295
.. attribute:: authorization_request_in_packets
Authourization request from cleint
**type**\: int
**range:** 0..4294967295
.. attribute:: authorization_response_out_packets
Authourization response frwd to client
**type**\: int
**range:** 0..4294967295
.. attribute:: authorization_response_success_packets
Authentication response with success
**type**\: int
**range:** 0..4294967295
.. attribute:: authorization_response_fail_packets
Authentication response with failure
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_response_in_packets
Accounting packet response in
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_request_out_packets
Accounting requests packets out
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_start_request_packets
Accounting start request from cleint
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_start_response_packets
Accounting start response forward to client
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_start_success_packets
Accounting start response with success
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_start_failed_packets
Accounting start response with failure
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_stop_response_in_packets
Accounting stop packet response in
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_stop_request_out_packets
Accounting stop requests packets out
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_stop_request_in_packets
Acct stop request from cleint
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_stop_response_out_packets
Acct stop response forward to client
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_stop_success_response_packets
Accounting stop response with success
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_stop_failed_packets
Accounting stop response with failure
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_intrim_response_in_packets
Accounting interim packet response in
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_interim_request_out_packets
Accounting interim requests packets out
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_interim_request_in_packets
Accounting Interim request from cleint
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_interim_response_out_packets
Accounting interim response frwd to client
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_interim_success_packets
Accounting interim response with success
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_interim_failed_packets
Accounting interim response with failure
**type**\: int
**range:** 0..4294967295
.. attribute:: disconnect_response_in_packets
Disconnect response packets in
**type**\: int
**range:** 0..4294967295
.. attribute:: disconnect_request_out_packets
Disconnect request pkt out
**type**\: int
**range:** 0..4294967295
.. attribute:: disconnect_request_in_packets
Disconnect request from cleint
**type**\: int
**range:** 0..4294967295
.. attribute:: disconnect_response_out_packets
Disconnect response forward to client
**type**\: int
**range:** 0..4294967295
.. attribute:: disconnect_success_response_packets
Disconnect response with success
**type**\: int
**range:** 0..4294967295
.. attribute:: disconnect_failed_response_packets
Disconnect response with failure
**type**\: int
**range:** 0..4294967295
.. attribute:: coa_request_in_packets
COA/RAR Request packet in
**type**\: int
**range:** 0..4294967295
.. attribute:: coa_response_out_packets
COA/RAR Response packet out
**type**\: int
**range:** 0..4294967295
.. attribute:: coa_request_packets
COA request from client
**type**\: int
**range:** 0..4294967295
.. attribute:: coa_response_packets
COA response forward to client
**type**\: int
**range:** 0..4294967295
.. attribute:: coa_success_packets
COA response with success
**type**\: int
**range:** 0..4294967295
.. attribute:: coa_failed_packets
COA response with failure
**type**\: int
**range:** 0..4294967295
.. attribute:: pod_in_packets
POD/RAR Request packets in
**type**\: int
**range:** 0..4294967295
.. attribute:: pod_out_packets
PAD/RAR Response packets out
**type**\: int
**range:** 0..4294967295
.. attribute:: pod_request_in_packets
POD request from cleint
**type**\: int
**range:** 0..4294967295
.. attribute:: pod_response_out_packets
POD response forward to client
**type**\: int
**range:** 0..4294967295
.. attribute:: pod_success_packets
POD response with success
**type**\: int
**range:** 0..4294967295
.. attribute:: pod_failed_packets
POD response with failure
**type**\: int
**range:** 0..4294967295
"""
_prefix = 'aaa-diameter-oper'
_revision = '2017-09-07'
def __init__(self):
super(Aaa.Diameter.NasSummary, self).__init__()
self.yang_name = "nas-summary"
self.yang_parent_name = "diameter"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('authen_response_in_packets', (YLeaf(YType.uint32, 'authen-response-in-packets'), ['int'])),
('authen_request_out_packets', (YLeaf(YType.uint32, 'authen-request-out-packets'), ['int'])),
('authen_request_in_packets', (YLeaf(YType.uint32, 'authen-request-in-packets'), ['int'])),
('authen_response_out_packets', (YLeaf(YType.uint32, 'authen-response-out-packets'), ['int'])),
('authen_success_packets', (YLeaf(YType.uint32, 'authen-success-packets'), ['int'])),
('authen_response_fail_packets', (YLeaf(YType.uint32, 'authen-response-fail-packets'), ['int'])),
('authorization_in_packets', (YLeaf(YType.uint32, 'authorization-in-packets'), ['int'])),
('authorization_out_packets', (YLeaf(YType.uint32, 'authorization-out-packets'), ['int'])),
('authorization_request_in_packets', (YLeaf(YType.uint32, 'authorization-request-in-packets'), ['int'])),
('authorization_response_out_packets', (YLeaf(YType.uint32, 'authorization-response-out-packets'), ['int'])),
('authorization_response_success_packets', (YLeaf(YType.uint32, 'authorization-response-success-packets'), ['int'])),
('authorization_response_fail_packets', (YLeaf(YType.uint32, 'authorization-response-fail-packets'), ['int'])),
('accounting_response_in_packets', (YLeaf(YType.uint32, 'accounting-response-in-packets'), ['int'])),
('accounting_request_out_packets', (YLeaf(YType.uint32, 'accounting-request-out-packets'), ['int'])),
('accounting_start_request_packets', (YLeaf(YType.uint32, 'accounting-start-request-packets'), ['int'])),
('accounting_start_response_packets', (YLeaf(YType.uint32, 'accounting-start-response-packets'), ['int'])),
('accounting_start_success_packets', (YLeaf(YType.uint32, 'accounting-start-success-packets'), ['int'])),
('accounting_start_failed_packets', (YLeaf(YType.uint32, 'accounting-start-failed-packets'), ['int'])),
('accounting_stop_response_in_packets', (YLeaf(YType.uint32, 'accounting-stop-response-in-packets'), ['int'])),
('accounting_stop_request_out_packets', (YLeaf(YType.uint32, 'accounting-stop-request-out-packets'), ['int'])),
('accounting_stop_request_in_packets', (YLeaf(YType.uint32, 'accounting-stop-request-in-packets'), ['int'])),
('accounting_stop_response_out_packets', (YLeaf(YType.uint32, 'accounting-stop-response-out-packets'), ['int'])),
('accounting_stop_success_response_packets', (YLeaf(YType.uint32, 'accounting-stop-success-response-packets'), ['int'])),
('accounting_stop_failed_packets', (YLeaf(YType.uint32, 'accounting-stop-failed-packets'), ['int'])),
('accounting_intrim_response_in_packets', (YLeaf(YType.uint32, 'accounting-intrim-response-in-packets'), ['int'])),
('accounting_interim_request_out_packets', (YLeaf(YType.uint32, 'accounting-interim-request-out-packets'), ['int'])),
('accounting_interim_request_in_packets', (YLeaf(YType.uint32, 'accounting-interim-request-in-packets'), ['int'])),
('accounting_interim_response_out_packets', (YLeaf(YType.uint32, 'accounting-interim-response-out-packets'), ['int'])),
('accounting_interim_success_packets', (YLeaf(YType.uint32, 'accounting-interim-success-packets'), ['int'])),
('accounting_interim_failed_packets', (YLeaf(YType.uint32, 'accounting-interim-failed-packets'), ['int'])),
('disconnect_response_in_packets', (YLeaf(YType.uint32, 'disconnect-response-in-packets'), ['int'])),
('disconnect_request_out_packets', (YLeaf(YType.uint32, 'disconnect-request-out-packets'), ['int'])),
('disconnect_request_in_packets', (YLeaf(YType.uint32, 'disconnect-request-in-packets'), ['int'])),
('disconnect_response_out_packets', (YLeaf(YType.uint32, 'disconnect-response-out-packets'), ['int'])),
('disconnect_success_response_packets', (YLeaf(YType.uint32, 'disconnect-success-response-packets'), ['int'])),
('disconnect_failed_response_packets', (YLeaf(YType.uint32, 'disconnect-failed-response-packets'), ['int'])),
('coa_request_in_packets', (YLeaf(YType.uint32, 'coa-request-in-packets'), ['int'])),
('coa_response_out_packets', (YLeaf(YType.uint32, 'coa-response-out-packets'), ['int'])),
('coa_request_packets', (YLeaf(YType.uint32, 'coa-request-packets'), ['int'])),
('coa_response_packets', (YLeaf(YType.uint32, 'coa-response-packets'), ['int'])),
('coa_success_packets', (YLeaf(YType.uint32, 'coa-success-packets'), ['int'])),
('coa_failed_packets', (YLeaf(YType.uint32, 'coa-failed-packets'), ['int'])),
('pod_in_packets', (YLeaf(YType.uint32, 'pod-in-packets'), ['int'])),
('pod_out_packets', (YLeaf(YType.uint32, 'pod-out-packets'), ['int'])),
('pod_request_in_packets', (YLeaf(YType.uint32, 'pod-request-in-packets'), ['int'])),
('pod_response_out_packets', (YLeaf(YType.uint32, 'pod-response-out-packets'), ['int'])),
('pod_success_packets', (YLeaf(YType.uint32, 'pod-success-packets'), ['int'])),
('pod_failed_packets', (YLeaf(YType.uint32, 'pod-failed-packets'), ['int'])),
])
self.authen_response_in_packets = None
self.authen_request_out_packets = None
self.authen_request_in_packets = None
self.authen_response_out_packets = None
self.authen_success_packets = None
self.authen_response_fail_packets = None
self.authorization_in_packets = None
self.authorization_out_packets = None
self.authorization_request_in_packets = None
self.authorization_response_out_packets = None
self.authorization_response_success_packets = None
self.authorization_response_fail_packets = None
self.accounting_response_in_packets = None
self.accounting_request_out_packets = None
self.accounting_start_request_packets = None
self.accounting_start_response_packets = None
self.accounting_start_success_packets = None
self.accounting_start_failed_packets = None
self.accounting_stop_response_in_packets = None
self.accounting_stop_request_out_packets = None
self.accounting_stop_request_in_packets = None
self.accounting_stop_response_out_packets = None
self.accounting_stop_success_response_packets = None
self.accounting_stop_failed_packets = None
self.accounting_intrim_response_in_packets = None
self.accounting_interim_request_out_packets = None
self.accounting_interim_request_in_packets = None
self.accounting_interim_response_out_packets = None
self.accounting_interim_success_packets = None
self.accounting_interim_failed_packets = None
self.disconnect_response_in_packets = None
self.disconnect_request_out_packets = None
self.disconnect_request_in_packets = None
self.disconnect_response_out_packets = None
self.disconnect_success_response_packets = None
self.disconnect_failed_response_packets = None
self.coa_request_in_packets = None
self.coa_response_out_packets = None
self.coa_request_packets = None
self.coa_response_packets = None
self.coa_success_packets = None
self.coa_failed_packets = None
self.pod_in_packets = None
self.pod_out_packets = None
self.pod_request_in_packets = None
self.pod_response_out_packets = None
self.pod_success_packets = None
self.pod_failed_packets = None
self._segment_path = lambda: "nas-summary"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-diameter-oper:diameter/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Diameter.NasSummary, ['authen_response_in_packets', 'authen_request_out_packets', 'authen_request_in_packets', 'authen_response_out_packets', 'authen_success_packets', 'authen_response_fail_packets', 'authorization_in_packets', 'authorization_out_packets', 'authorization_request_in_packets', 'authorization_response_out_packets', 'authorization_response_success_packets', 'authorization_response_fail_packets', 'accounting_response_in_packets', 'accounting_request_out_packets', 'accounting_start_request_packets', 'accounting_start_response_packets', 'accounting_start_success_packets', 'accounting_start_failed_packets', 'accounting_stop_response_in_packets', 'accounting_stop_request_out_packets', 'accounting_stop_request_in_packets', 'accounting_stop_response_out_packets', 'accounting_stop_success_response_packets', 'accounting_stop_failed_packets', 'accounting_intrim_response_in_packets', 'accounting_interim_request_out_packets', 'accounting_interim_request_in_packets', 'accounting_interim_response_out_packets', 'accounting_interim_success_packets', 'accounting_interim_failed_packets', 'disconnect_response_in_packets', 'disconnect_request_out_packets', 'disconnect_request_in_packets', 'disconnect_response_out_packets', 'disconnect_success_response_packets', 'disconnect_failed_response_packets', 'coa_request_in_packets', 'coa_response_out_packets', 'coa_request_packets', 'coa_response_packets', 'coa_success_packets', 'coa_failed_packets', 'pod_in_packets', 'pod_out_packets', 'pod_request_in_packets', 'pod_response_out_packets', 'pod_success_packets', 'pod_failed_packets'], name, value)
class GySessionIds(Entity):
"""
Diameter Gy Session data list
.. attribute:: gy_session_id
Diameter Gy Session data
**type**\: list of :py:class:`GySessionId <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Diameter.GySessionIds.GySessionId>`
"""
_prefix = 'aaa-diameter-oper'
_revision = '2017-09-07'
def __init__(self):
super(Aaa.Diameter.GySessionIds, self).__init__()
self.yang_name = "gy-session-ids"
self.yang_parent_name = "diameter"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([("gy-session-id", ("gy_session_id", Aaa.Diameter.GySessionIds.GySessionId))])
self._leafs = OrderedDict()
self.gy_session_id = YList(self)
self._segment_path = lambda: "gy-session-ids"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-diameter-oper:diameter/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Diameter.GySessionIds, [], name, value)
class GySessionId(Entity):
"""
Diameter Gy Session data
.. attribute:: session_id (key)
Session Id
**type**\: int
**range:** 0..4294967295
.. attribute:: aaa_session_id
AAA session id
**type**\: int
**range:** 0..4294967295
.. attribute:: parent_aaa_session_id
AAA Parent session id
**type**\: int
**range:** 0..4294967295
.. attribute:: diameter_session_id
Diameter session id
**type**\: str
.. attribute:: request_number
Request Number
**type**\: int
**range:** 0..4294967295
.. attribute:: session_state
Session State
**type**\: str
.. attribute:: request_type
Request Type
**type**\: str
.. attribute:: retry_count
Gy Retry count
**type**\: int
**range:** 0..4294967295
"""
_prefix = 'aaa-diameter-oper'
_revision = '2017-09-07'
def __init__(self):
super(Aaa.Diameter.GySessionIds.GySessionId, self).__init__()
self.yang_name = "gy-session-id"
self.yang_parent_name = "gy-session-ids"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = ['session_id']
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('session_id', (YLeaf(YType.uint32, 'session-id'), ['int'])),
('aaa_session_id', (YLeaf(YType.uint32, 'aaa-session-id'), ['int'])),
('parent_aaa_session_id', (YLeaf(YType.uint32, 'parent-aaa-session-id'), ['int'])),
('diameter_session_id', (YLeaf(YType.str, 'diameter-session-id'), ['str'])),
('request_number', (YLeaf(YType.uint32, 'request-number'), ['int'])),
('session_state', (YLeaf(YType.str, 'session-state'), ['str'])),
('request_type', (YLeaf(YType.str, 'request-type'), ['str'])),
('retry_count', (YLeaf(YType.uint32, 'retry-count'), ['int'])),
])
self.session_id = None
self.aaa_session_id = None
self.parent_aaa_session_id = None
self.diameter_session_id = None
self.request_number = None
self.session_state = None
self.request_type = None
self.retry_count = None
self._segment_path = lambda: "gy-session-id" + "[session-id='" + str(self.session_id) + "']"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-diameter-oper:diameter/gy-session-ids/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Diameter.GySessionIds.GySessionId, ['session_id', 'aaa_session_id', 'parent_aaa_session_id', 'diameter_session_id', 'request_number', 'session_state', 'request_type', 'retry_count'], name, value)
class GyStatistics(Entity):
"""
Diameter Gy Statistics data
.. attribute:: ccr_init_messages
CCR Initial Messages
**type**\: int
**range:** 0..4294967295
.. attribute:: ccr_init_failed_messages
CCR Initial Messages Failed
**type**\: int
**range:** 0..4294967295
.. attribute:: ccr_init_timed_out_messages
CCR Initial Messages Timed Out
**type**\: int
**range:** 0..4294967295
.. attribute:: ccr_init_retry_messages
CCR Initial Messages retry
**type**\: int
**range:** 0..4294967295
.. attribute:: ccr_update_messages
CCR Update Messages
**type**\: int
**range:** 0..4294967295
.. attribute:: ccr_update_failed_messages
CCR Update Messages Failed
**type**\: int
**range:** 0..4294967295
.. attribute:: ccr_update_timed_out_messages
CCR Update Messages Timed Out
**type**\: int
**range:** 0..4294967295
.. attribute:: ccr_update_retry_messages
CCR Update Messages retry
**type**\: int
**range:** 0..4294967295
.. attribute:: ccr_final_messages
CCR Final Messages
**type**\: int
**range:** 0..4294967295
.. attribute:: ccr_final_failed_messages
CCR Final Messages Failed
**type**\: int
**range:** 0..4294967295
.. attribute:: ccr_final_timed_out_messages
CCR Final Messages Timed Out
**type**\: int
**range:** 0..4294967295
.. attribute:: ccr_final_retry_messages
CCR Final Messages retry
**type**\: int
**range:** 0..4294967295
.. attribute:: cca_init_messages
CCA Initial Messages
**type**\: int
**range:** 0..4294967295
.. attribute:: cca_init_error_messages
CCA Initial Messages Error
**type**\: int
**range:** 0..4294967295
.. attribute:: cca_update_messages
CCA Update Messages
**type**\: int
**range:** 0..4294967295
.. attribute:: cca_update_error_messages
CCA Update Messages Error
**type**\: int
**range:** 0..4294967295
.. attribute:: cca_final_messages
CCA Final Messages
**type**\: int
**range:** 0..4294967295
.. attribute:: cca_final_error_messages
CCA Final Messages Error
**type**\: int
**range:** 0..4294967295
.. attribute:: rar_received_messages
RAR Received Messages
**type**\: int
**range:** 0..4294967295
.. attribute:: rar_received_error_messages
RAR Received Messages Error
**type**\: int
**range:** 0..4294967295
.. attribute:: raa_sent_messages
RAA Sent Messages
**type**\: int
**range:** 0..4294967295
.. attribute:: raa_sent_error_messages
RAA Sent Messages Error
**type**\: int
**range:** 0..4294967295
.. attribute:: asr_received_messages
ASR Received Messages
**type**\: int
**range:** 0..4294967295
.. attribute:: asr_received_error_messages
ASR Received Messages Error
**type**\: int
**range:** 0..4294967295
.. attribute:: asa_sent_messages
ASA Sent Messages
**type**\: int
**range:** 0..4294967295
.. attribute:: asa_sent_error_messages
ASA Sent Messages Error
**type**\: int
**range:** 0..4294967295
.. attribute:: unknown_request_messages
Unknown Request Messages
**type**\: int
**range:** 0..4294967295
.. attribute:: restore_sessions
Restore Sessions
**type**\: int
**range:** 0..4294967295
.. attribute:: open_sessions
Total Opened Sessions
**type**\: int
**range:** 0..4294967295
.. attribute:: close_sessions
Total Closed Sessions
**type**\: int
**range:** 0..4294967295
.. attribute:: active_sessions
Total Active Sessions
**type**\: int
**range:** 0..4294967295
"""
_prefix = 'aaa-diameter-oper'
_revision = '2017-09-07'
def __init__(self):
super(Aaa.Diameter.GyStatistics, self).__init__()
self.yang_name = "gy-statistics"
self.yang_parent_name = "diameter"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('ccr_init_messages', (YLeaf(YType.uint32, 'ccr-init-messages'), ['int'])),
('ccr_init_failed_messages', (YLeaf(YType.uint32, 'ccr-init-failed-messages'), ['int'])),
('ccr_init_timed_out_messages', (YLeaf(YType.uint32, 'ccr-init-timed-out-messages'), ['int'])),
('ccr_init_retry_messages', (YLeaf(YType.uint32, 'ccr-init-retry-messages'), ['int'])),
('ccr_update_messages', (YLeaf(YType.uint32, 'ccr-update-messages'), ['int'])),
('ccr_update_failed_messages', (YLeaf(YType.uint32, 'ccr-update-failed-messages'), ['int'])),
('ccr_update_timed_out_messages', (YLeaf(YType.uint32, 'ccr-update-timed-out-messages'), ['int'])),
('ccr_update_retry_messages', (YLeaf(YType.uint32, 'ccr-update-retry-messages'), ['int'])),
('ccr_final_messages', (YLeaf(YType.uint32, 'ccr-final-messages'), ['int'])),
('ccr_final_failed_messages', (YLeaf(YType.uint32, 'ccr-final-failed-messages'), ['int'])),
('ccr_final_timed_out_messages', (YLeaf(YType.uint32, 'ccr-final-timed-out-messages'), ['int'])),
('ccr_final_retry_messages', (YLeaf(YType.uint32, 'ccr-final-retry-messages'), ['int'])),
('cca_init_messages', (YLeaf(YType.uint32, 'cca-init-messages'), ['int'])),
('cca_init_error_messages', (YLeaf(YType.uint32, 'cca-init-error-messages'), ['int'])),
('cca_update_messages', (YLeaf(YType.uint32, 'cca-update-messages'), ['int'])),
('cca_update_error_messages', (YLeaf(YType.uint32, 'cca-update-error-messages'), ['int'])),
('cca_final_messages', (YLeaf(YType.uint32, 'cca-final-messages'), ['int'])),
('cca_final_error_messages', (YLeaf(YType.uint32, 'cca-final-error-messages'), ['int'])),
('rar_received_messages', (YLeaf(YType.uint32, 'rar-received-messages'), ['int'])),
('rar_received_error_messages', (YLeaf(YType.uint32, 'rar-received-error-messages'), ['int'])),
('raa_sent_messages', (YLeaf(YType.uint32, 'raa-sent-messages'), ['int'])),
('raa_sent_error_messages', (YLeaf(YType.uint32, 'raa-sent-error-messages'), ['int'])),
('asr_received_messages', (YLeaf(YType.uint32, 'asr-received-messages'), ['int'])),
('asr_received_error_messages', (YLeaf(YType.uint32, 'asr-received-error-messages'), ['int'])),
('asa_sent_messages', (YLeaf(YType.uint32, 'asa-sent-messages'), ['int'])),
('asa_sent_error_messages', (YLeaf(YType.uint32, 'asa-sent-error-messages'), ['int'])),
('unknown_request_messages', (YLeaf(YType.uint32, 'unknown-request-messages'), ['int'])),
('restore_sessions', (YLeaf(YType.uint32, 'restore-sessions'), ['int'])),
('open_sessions', (YLeaf(YType.uint32, 'open-sessions'), ['int'])),
('close_sessions', (YLeaf(YType.uint32, 'close-sessions'), ['int'])),
('active_sessions', (YLeaf(YType.uint32, 'active-sessions'), ['int'])),
])
self.ccr_init_messages = None
self.ccr_init_failed_messages = None
self.ccr_init_timed_out_messages = None
self.ccr_init_retry_messages = None
self.ccr_update_messages = None
self.ccr_update_failed_messages = None
self.ccr_update_timed_out_messages = None
self.ccr_update_retry_messages = None
self.ccr_final_messages = None
self.ccr_final_failed_messages = None
self.ccr_final_timed_out_messages = None
self.ccr_final_retry_messages = None
self.cca_init_messages = None
self.cca_init_error_messages = None
self.cca_update_messages = None
self.cca_update_error_messages = None
self.cca_final_messages = None
self.cca_final_error_messages = None
self.rar_received_messages = None
self.rar_received_error_messages = None
self.raa_sent_messages = None
self.raa_sent_error_messages = None
self.asr_received_messages = None
self.asr_received_error_messages = None
self.asa_sent_messages = None
self.asa_sent_error_messages = None
self.unknown_request_messages = None
self.restore_sessions = None
self.open_sessions = None
self.close_sessions = None
self.active_sessions = None
self._segment_path = lambda: "gy-statistics"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-diameter-oper:diameter/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Diameter.GyStatistics, ['ccr_init_messages', 'ccr_init_failed_messages', 'ccr_init_timed_out_messages', 'ccr_init_retry_messages', 'ccr_update_messages', 'ccr_update_failed_messages', 'ccr_update_timed_out_messages', 'ccr_update_retry_messages', 'ccr_final_messages', 'ccr_final_failed_messages', 'ccr_final_timed_out_messages', 'ccr_final_retry_messages', 'cca_init_messages', 'cca_init_error_messages', 'cca_update_messages', 'cca_update_error_messages', 'cca_final_messages', 'cca_final_error_messages', 'rar_received_messages', 'rar_received_error_messages', 'raa_sent_messages', 'raa_sent_error_messages', 'asr_received_messages', 'asr_received_error_messages', 'asa_sent_messages', 'asa_sent_error_messages', 'unknown_request_messages', 'restore_sessions', 'open_sessions', 'close_sessions', 'active_sessions'], name, value)
class GxSessionIds(Entity):
"""
Diameter Gx Session data list
.. attribute:: gx_session_id
Diameter Gx Session data
**type**\: list of :py:class:`GxSessionId <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Diameter.GxSessionIds.GxSessionId>`
"""
_prefix = 'aaa-diameter-oper'
_revision = '2017-09-07'
def __init__(self):
super(Aaa.Diameter.GxSessionIds, self).__init__()
self.yang_name = "gx-session-ids"
self.yang_parent_name = "diameter"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([("gx-session-id", ("gx_session_id", Aaa.Diameter.GxSessionIds.GxSessionId))])
self._leafs = OrderedDict()
self.gx_session_id = YList(self)
self._segment_path = lambda: "gx-session-ids"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-diameter-oper:diameter/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Diameter.GxSessionIds, [], name, value)
class GxSessionId(Entity):
"""
Diameter Gx Session data
.. attribute:: session_id (key)
Session Id
**type**\: int
**range:** 0..4294967295
.. attribute:: aaa_session_id
AAA session id
**type**\: int
**range:** 0..4294967295
.. attribute:: diameter_session_id
Diameter session id
**type**\: str
.. attribute:: request_number
Request Number
**type**\: int
**range:** 0..4294967295
.. attribute:: session_state
Session State
**type**\: str
.. attribute:: request_type
Request Type
**type**\: str
.. attribute:: retry_count
Gx Retry count
**type**\: int
**range:** 0..4294967295
.. attribute:: service_count
Gx Plus Service Count
**type**\: int
**range:** 0..4294967295
.. attribute:: gx_plus_services
Gx Plus Services
**type**\: str
.. attribute:: reavalidation_time
Revalidation Time
**type**\: str
"""
_prefix = 'aaa-diameter-oper'
_revision = '2017-09-07'
def __init__(self):
super(Aaa.Diameter.GxSessionIds.GxSessionId, self).__init__()
self.yang_name = "gx-session-id"
self.yang_parent_name = "gx-session-ids"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = ['session_id']
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('session_id', (YLeaf(YType.uint32, 'session-id'), ['int'])),
('aaa_session_id', (YLeaf(YType.uint32, 'aaa-session-id'), ['int'])),
('diameter_session_id', (YLeaf(YType.str, 'diameter-session-id'), ['str'])),
('request_number', (YLeaf(YType.uint32, 'request-number'), ['int'])),
('session_state', (YLeaf(YType.str, 'session-state'), ['str'])),
('request_type', (YLeaf(YType.str, 'request-type'), ['str'])),
('retry_count', (YLeaf(YType.uint32, 'retry-count'), ['int'])),
('service_count', (YLeaf(YType.uint32, 'service-count'), ['int'])),
('gx_plus_services', (YLeaf(YType.str, 'gx-plus-services'), ['str'])),
('reavalidation_time', (YLeaf(YType.str, 'reavalidation-time'), ['str'])),
])
self.session_id = None
self.aaa_session_id = None
self.diameter_session_id = None
self.request_number = None
self.session_state = None
self.request_type = None
self.retry_count = None
self.service_count = None
self.gx_plus_services = None
self.reavalidation_time = None
self._segment_path = lambda: "gx-session-id" + "[session-id='" + str(self.session_id) + "']"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-diameter-oper:diameter/gx-session-ids/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Diameter.GxSessionIds.GxSessionId, ['session_id', 'aaa_session_id', 'diameter_session_id', 'request_number', 'session_state', 'request_type', 'retry_count', 'service_count', 'gx_plus_services', 'reavalidation_time'], name, value)
class NasSession(Entity):
"""
Diameter Nas Session data
.. attribute:: aaanas_id
AAA NAS id
**type**\: str
.. attribute:: list_of_nas
List of NAS Entries
**type**\: list of :py:class:`ListOfNas <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_locald_oper.Aaa.Diameter.NasSession.ListOfNas>`
"""
_prefix = 'aaa-diameter-oper'
_revision = '2017-09-07'
def __init__(self):
super(Aaa.Diameter.NasSession, self).__init__()
self.yang_name = "nas-session"
self.yang_parent_name = "diameter"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([("list-of-nas", ("list_of_nas", Aaa.Diameter.NasSession.ListOfNas))])
self._leafs = OrderedDict([
('aaanas_id', (YLeaf(YType.str, 'aaanas-id'), ['str'])),
])
self.aaanas_id = None
self.list_of_nas = YList(self)
self._segment_path = lambda: "nas-session"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-diameter-oper:diameter/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Diameter.NasSession, ['aaanas_id'], name, value)
class ListOfNas(Entity):
"""
List of NAS Entries
.. attribute:: aaa_session_id
AAA session id
**type**\: str
.. attribute:: diameter_session_id
Diameter session id
**type**\: str
.. attribute:: authentication_status
Diameter AAR status
**type**\: int
**range:** 0..4294967295
.. attribute:: authorization_status
Diameter AAR status
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_status
Diameter ACR status start
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_status_stop
Diameter ACR status stop
**type**\: int
**range:** 0..4294967295
.. attribute:: disconnect_status
Diameter STR status
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_intrim_in_packets
Accounting intrim packet response in
**type**\: int
**range:** 0..4294967295
.. attribute:: accounting_intrim_out_packets
Accounting intrim requests packets out
**type**\: int
**range:** 0..4294967295
.. attribute:: method_list
Method list used for authentication
**type**\: str
.. attribute:: server_used_list
Server used for authentication
**type**\: str
"""
_prefix = 'aaa-diameter-oper'
_revision = '2017-09-07'
def __init__(self):
super(Aaa.Diameter.NasSession.ListOfNas, self).__init__()
self.yang_name = "list-of-nas"
self.yang_parent_name = "nas-session"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('aaa_session_id', (YLeaf(YType.str, 'aaa-session-id'), ['str'])),
('diameter_session_id', (YLeaf(YType.str, 'diameter-session-id'), ['str'])),
('authentication_status', (YLeaf(YType.uint32, 'authentication-status'), ['int'])),
('authorization_status', (YLeaf(YType.uint32, 'authorization-status'), ['int'])),
('accounting_status', (YLeaf(YType.uint32, 'accounting-status'), ['int'])),
('accounting_status_stop', (YLeaf(YType.uint32, 'accounting-status-stop'), ['int'])),
('disconnect_status', (YLeaf(YType.uint32, 'disconnect-status'), ['int'])),
('accounting_intrim_in_packets', (YLeaf(YType.uint32, 'accounting-intrim-in-packets'), ['int'])),
('accounting_intrim_out_packets', (YLeaf(YType.uint32, 'accounting-intrim-out-packets'), ['int'])),
('method_list', (YLeaf(YType.str, 'method-list'), ['str'])),
('server_used_list', (YLeaf(YType.str, 'server-used-list'), ['str'])),
])
self.aaa_session_id = None
self.diameter_session_id = None
self.authentication_status = None
self.authorization_status = None
self.accounting_status = None
self.accounting_status_stop = None
self.disconnect_status = None
self.accounting_intrim_in_packets = None
self.accounting_intrim_out_packets = None
self.method_list = None
self.server_used_list = None
self._segment_path = lambda: "list-of-nas"
self._absolute_path = lambda: "Cisco-IOS-XR-aaa-locald-oper:aaa/Cisco-IOS-XR-aaa-diameter-oper:diameter/nas-session/%s" % self._segment_path()
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Aaa.Diameter.NasSession.ListOfNas, ['aaa_session_id', 'diameter_session_id', 'authentication_status', 'authorization_status', 'accounting_status', 'accounting_status_stop', 'disconnect_status', 'accounting_intrim_in_packets', 'accounting_intrim_out_packets', 'method_list', 'server_used_list'], name, value)
def clone_ptr(self):
self._top_entity = Aaa()
return self._top_entity
| 40.709164 | 2,277 | 0.464541 |
acecb08280800d986b097fcc24b7c0b888877077 | 4,652 | py | Python | external/llvm/apply_patches.py | ConnectionMaster/intel-graphics-compiler | 5b3369c20357c8f7f4bebc46eeb276f11c796bfb | [
"Intel",
"MIT"
] | null | null | null | external/llvm/apply_patches.py | ConnectionMaster/intel-graphics-compiler | 5b3369c20357c8f7f4bebc46eeb276f11c796bfb | [
"Intel",
"MIT"
] | 6 | 2021-03-18T00:04:51.000Z | 2021-11-09T12:04:15.000Z | external/llvm/apply_patches.py | ConnectionMaster/intel-graphics-compiler | 5b3369c20357c8f7f4bebc46eeb276f11c796bfb | [
"Intel",
"MIT"
] | null | null | null | #=========================== begin_copyright_notice ============================
#
# Copyright (C) 2021 Intel Corporation
#
# SPDX-License-Identifier: MIT
#
#============================ end_copyright_notice =============================
import argparse
import os
from functools import total_ordering
from subprocess import check_call
parser = argparse.ArgumentParser(description='Apply LLVM patches for IGC')
parser.add_argument('--llvm-version', required=True,
help='LLVM version for patching')
parser.add_argument('--llvm-project-dir', required=True,
help='LLVM project copied sources')
parser.add_argument('--patches-dir', required=True,
help='Directory with patches')
parser.add_argument('--patch-executable', required=True,
help='Path to patch program')
parser.add_argument('--patch-disable', required=True,
help='Patch to disable')
parser.add_argument('--dry-run', action='store_true',
help='Only print list of patches that will be applied')
args = parser.parse_args()
def get_dir_patches(ver_dir):
"""Return list of patches from given version directory.
Collect patches from 'patches' subdirectory and return them
as a list of DirEntry objects.
"""
patches_dir = os.path.join(args.patches_dir, ver_dir)
patches = []
ext_patches = os.path.join(patches_dir, 'patches_external')
if os.path.exists(ext_patches):
patches.extend(os.scandir(ext_patches))
return patches
def apply_patch(patch_path):
"""Apply patch to llvm project."""
rel_path = os.path.relpath(patch_path.path, args.patches_dir)
print('Applying {} file'.format(rel_path))
if args.dry_run:
return
check_call([args.patch_executable,
'-t', '-s', '-N',
'-d', args.llvm_project_dir,
'-p1', '-i', patch_path])
def split_ver_str(ver_str):
"""Split version string into numeric components.
Return list of components as numbers additionally checking
that all components are correct (i.e. can be converted to numbers).
"""
ver_list = []
for c in ver_str.split('.')[0:3]:
if not c.isdecimal():
raise RuntimeError("Malformed version string '{}'. "
"Component '{}' is not an integer."
.format(ver_str, c))
ver_list.append(int(c))
return ver_list
def get_ver_component(ver_list, idx):
"""Get version component from components list.
Return 0 for components out of range as default.
"""
if idx < len(ver_list):
return ver_list[idx]
return 0
@total_ordering
class Version:
"""Simple wrapper around three-component version.
This class provides convenient accessors to version components
represented by decimal numbers. Suitable for LLVM version in IGC.
"""
def __init__(self, ver_str):
ver_list = split_ver_str(ver_str)
ver_tuple = tuple(get_ver_component(ver_list, idx) for idx in (0, 1, 2))
self.major = ver_tuple[0]
self.minor = ver_tuple[1]
self.patch = ver_tuple[2]
def as_tuple(self):
return (self.major, self.minor, self.patch)
def __repr__(self):
return '{}.{}.{}'.format(self.major, self.minor, self.patch)
def __eq__(self, other):
return self.as_tuple() == other.as_tuple()
def __lt__(self, other):
return self.as_tuple() < other.as_tuple()
required_ver = Version(args.llvm_version)
# Create mapping of version to directory with suitable
# version range sorted in descending order.
# All directories with same major version as required are suitable.
patches_dir = os.listdir(args.patches_dir)
ver_to_dir = [(Version(v), v) for v in patches_dir]
ver_to_dir = filter(lambda tpl: tpl[0].major == required_ver.major, ver_to_dir)
ver_to_dir = filter(lambda tpl: tpl[0] <= required_ver, ver_to_dir)
ver_to_dir = sorted(ver_to_dir, key=lambda tpl: tpl[0], reverse=True)
# Merge patches from suitable directories taking only patches from
# newest versions if same patch is present in several directries.
patches = {}
for _, d in ver_to_dir:
dir_patches = get_dir_patches(d)
dir_patches = {d.name : d for d in dir_patches}
dir_patches.update(patches)
patches = dir_patches
patches = list(patches.values())
patches.sort(key=lambda p: p.name)
checkDisabledPatch = False
if args.patch_disable != "None":
checkDisabledPatch = True
for patch in patches:
if checkDisabledPatch:
if args.patch_disable in patch.name:
continue
apply_patch(patch)
| 33.956204 | 80 | 0.655632 |
acecb0d999647c96e6602c0ec4e31e7f0f786c3a | 7,178 | py | Python | scripts/dvs_file_reader.py | cisprague/smarc_perception | 149bc7873a029466d7dbfbfb09ab9d34e6c9232b | [
"BSD-3-Clause"
] | null | null | null | scripts/dvs_file_reader.py | cisprague/smarc_perception | 149bc7873a029466d7dbfbfb09ab9d34e6c9232b | [
"BSD-3-Clause"
] | null | null | null | scripts/dvs_file_reader.py | cisprague/smarc_perception | 149bc7873a029466d7dbfbfb09ab9d34e6c9232b | [
"BSD-3-Clause"
] | null | null | null | from enum import Enum
from dataclasses import dataclass
import utils
from typing import List, BinaryIO, Tuple, Dict
import struct
from pathlib import Path
from matplotlib import pyplot as plt
import numpy as np
class Side(Enum):
"""The side-scan sonar ping side (port or starboard)"""
PORT = 0
STARBOARD = 1
@dataclass
class SSSPing:
"""A side-scan sonar ping."""
lat: float #Ctype double in V1_Position in deepvision_sss_driver
lon: float #Ctype double in V1_Position deepvision_sss_driver
speed: float
heading: float
side: Side
ping: List[int]
def plot(self) -> None:
plt.figure()
plt.plot(self.ping,
linestyle='-',
marker='o',
markersize=1,
linewidth=.5)
plt.title(f'SSS Ping, side = {self.side}')
@dataclass
class DVSFileHeader:
"""DVS File header. See details in deepvision_sss_driver."""
version: int = -1
sample_res: float = -1
line_rate: float = -1
n_samples: int = -1
left: bool = False
right: bool = False
class DVSFile:
def __init__(self, filename: str):
self.filename = filename
# Placeholder attributes, filled by _parse_file()
self.header = None
self.sss_pings = {Side.PORT: [], Side.STARBOARD: []}
self._parse_file()
def _parse_file(self):
with open(self.filename, 'rb') as f:
self.header = self._parse_header(f)
while True:
try:
ping = self._parse_ping(f)
for key, value in ping.items():
self.sss_pings[key].append(value)
except struct.error as e:
pointer_pos = f.tell()
file_size = Path(self.filename).stat().st_size
print(f'Current pointer position: {pointer_pos}')
print(f'Total file size: {file_size}')
print(f'Remaining bytes: {file_size - pointer_pos}')
print(f'Parsing completed: {e}')
return
def _parse_ping(self, fileobj: BinaryIO) -> Dict[Side, SSSPing]:
"""Read one side-scan ping from the fileobj. Note that one ping
may consists of two channels (port and starboard)."""
lat = utils.unpack_struct(fileobj, struct_type='double')
lon = utils.unpack_struct(fileobj, struct_type='double')
speed = utils.unpack_struct(fileobj, struct_type='float')
heading = utils.unpack_struct(fileobj, struct_type='float')
ping = dict()
if self.header.left:
left_channel = utils.unpack_channel(
fileobj, channel_size=self.header.n_samples)
ping[Side.PORT] = SSSPing(lat=lat,
lon=lon,
speed=speed,
heading=heading,
side=Side.PORT,
ping=left_channel)
if self.header.right:
right_channel = utils.unpack_channel(
fileobj, channel_size=self.header.n_samples)
ping[Side.STARBOARD] = SSSPing(lat=lat,
lon=lon,
speed=speed,
heading=heading,
side=Side.STARBOARD,
ping=right_channel)
return ping
def _parse_header(self, fileobj: BinaryIO) -> DVSFileHeader:
"""Read version and V1_FileHeader from the file object"""
header = DVSFileHeader()
header.version = utils.unpack_struct(fileobj, struct_type='uint')
header.sample_res = utils.unpack_struct(fileobj, struct_type='float')
header.line_rate = utils.unpack_struct(fileobj, struct_type='float')
header.n_samples = utils.unpack_struct(fileobj, struct_type='int')
header.left = utils.unpack_struct(fileobj, struct_type='bool')
header.right = utils.unpack_struct(fileobj, struct_type='bool')
# DVSFileHeader object is 16 bytes, although all fields together adds up to
# 14 bytes. The 2 extra bytes are for probably for data structure alignment
fileobj.read(2)
return header
def _get_pings_from_one_side(self, side: Side, start_idx: int,
end_idx) -> np.ndarray:
pings = []
for i in range(start_idx, end_idx):
pings.append(self.sss_pings[side][i].ping)
return np.array(pings)
def _imshow(self, sss_pings: np.ndarray, start_idx: int, end_idx: int,
title: str, figsize: tuple) -> None:
"""Plot multiple SSSPings as an heatmap."""
num_pings, num_channels = sss_pings.shape
plt.figure(figsize=figsize)
plt.imshow(sss_pings,
origin='lower',
extent=(0, num_channels, start_idx, end_idx))
plt.title(title)
def plot_one_side(
self,
side: Side,
start_idx: int = 0,
end_idx: int = None,
figsize: tuple = (5, 10)) -> np.ndarray:
"""Plot sss pings between (start_idx, end_idx) from the requested side
if exists."""
if side not in self.sss_pings.keys():
raise ValueError(
f'Side {side} does not exist. Available sides: {self.sss_pings.keys()}'
)
if not end_idx:
end_idx = len(self.sss_pings[side])
side_pings = self._get_pings_from_one_side(side, start_idx, end_idx)
title = f'SSS pings from {side} of {self.filename}'
self._imshow(side_pings, start_idx, end_idx, title, figsize)
return side_pings
def plot(self,
start_idx: int = 0,
end_idx: int = None,
figsize: tuple = (10, 20)) -> np.ndarray:
"""Plot all sss pings in the DVSFile"""
if self.header.right and not self.header.left:
return self.plot_one_side(side=Side.STARBOARD,
start_idx=start_idx,
end_idx=end_idx)
if self.header.left and not self.header.right:
return self.plot_one_side(side=Side.PORT,
start_idx=start_idx,
end_idx=end_idx)
if not end_idx:
end_idx = min(len(self.sss_pings[Side.PORT]),
len(self.sss_pings[Side.STARBOARD]))
left_pings = self._get_pings_from_one_side(Side.PORT, start_idx,
end_idx)
right_pings = self._get_pings_from_one_side(Side.STARBOARD, start_idx,
end_idx)
sss_image = np.concatenate((np.flip(left_pings, axis=1), right_pings),
axis=1)
title = f'SSS pings from {self.filename}'
self._imshow(sss_image, start_idx, end_idx, title, figsize)
return sss_image
| 38.8 | 87 | 0.552104 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.