示例#1
0
class SingletonScopeCache(ScopeCache):
    def __init__(self, name: str, scoped_components: List[type]):
        """
        :param name: human-readable name
        :param scoped_components: components managed by this scope
        """
        super().__init__(name)
        self.scoped_components = Stream(scoped_components).map(
            lambda clazz: (clazz, None)).toDict()

    def handles_component(self, component: type) -> bool:
        return component in self.scoped_components.keys()

    def is_stored(self, component: type) -> bool:
        return self.scoped_components[component] is not None

    def get(self, component: type) -> object:
        stored_component = self.scoped_components.get(component)
        if stored_component is None:
            raise UninstantiatedObjectException(component)
        return stored_component

    def store(self, component: type, instance: object):
        if component not in self.scoped_components.keys():
            raise ComponentNotHandledByScopeException(component)
        self.scoped_components[component] = instance
示例#2
0
    def test_whenCountingElementsOfIterableWithoutLength_thenIndividuallyCountElements(
            self):
        self.stream = Stream(zip(self.COLLECTION, self.COLLECTION))

        count = self.stream.count()

        self.assertEqual(len(self.COLLECTION), count)
    def create_route_handlers(self,
                              request: Request) -> Iterable[RouteHandler]:
        route_registrations = Stream(self.routing_rules) \
            .map(lambda rule: rule.get_route_registrations(request.path)) \
            .flat().toList()

        routable_http_methods = Stream(route_registrations).map(
            lambda route: route.http_method).toSet()

        if len(route_registrations) == 0:
            raise UnknownPathException(request.path)

        if self.is_cors_request(
                request) and OPTIONS not in routable_http_methods:
            return Stream.of(
                self.cors_handler_factory.create_cors_preflight_handler(
                    request.path))

        if request.method_annotation not in routable_http_methods:
            raise MethodNotAllowedException()

        return Stream(self.routing_rules) \
            .map(lambda rule: rule.create_route_handlers(request, self.service_locator, self.deserializer)) \
            .flat() \
            .map(lambda route_handler: self.cors_handler_factory.apply_cors_rules(request.path, route_handler))
示例#4
0
 def __getitem__(self, item: str) -> str:
     found_header = Stream(self.content.items()).firstMatch(
         lambda key, value: key == item or _format_camel_case(
             key) == _format_camel_case(item))
     if found_header:
         return found_header.get()[1]
     return None
示例#5
0
    def serialize(self, obj: object) -> Union[dict, list]:
        res = Stream(self.strategies) \
            .firstMatch(lambda s: s.can_handle_serialization(obj)) \
            .map(lambda s: s.serialize(obj))

        if res.isPresent():
            return res.get()

        if obj is None:
            return None

        if issubclass(type(obj), BUILTIN_TYPES):
            return obj

        if isinstance(obj, list) or isinstance(obj, tuple):
            return [self.serialize(x) for x in obj]

        if isinstance(obj, dict):
            dictionary = obj
            for key, value in dictionary.items():
                dictionary[key] = self.serialize(value)
            return dictionary

        if hasattr(obj, '__dict__'):
            return self.serialize({**obj.__dict__})

        raise SerializationException(
            f"Cannot serialize type {obj.__class__}. {obj}")
示例#6
0
    def find_sheets(self, image: Image) -> List[Sheet]:
        hsv_image = colourspace.bgr_to_hsv(image)
        white_mask = hsv_image.get_in_range_mask([0, 0, 150], [180, 255, 235])

        im, contours, hier = cv2.findContours(white_mask.matrix, cv2.RETR_TREE,
                                              cv2.CHAIN_APPROX_SIMPLE)

        sheets = []

        for c in contours:
            x, y, w, h = cv2.boundingRect(c)
            if w > 100 and h > 100:
                corners = cv2.boxPoints(cv2.minAreaRect(c))

                distances = Stream.range(1, 4) \
                                .map(lambda i: (corners[i - 1], corners[i])) \
                                .map(euclidean_distance).toList() + [euclidean_distance(corners[-1], corners[0])]
                corners = Stream(corners).toList() + [corners[0]]

                length_threshold = (max(distances) + min(distances)) / 2

                opposing_corners = Stream.zip(
                    range(1, 5), distances +
                    distances).filter(lambda _, d: d > length_threshold).map(
                        lambda i, _: corners[i]).toList()
                origin = Stream(opposing_corners).reduce(
                    [0, 0], lambda acc, e: e if e[1] > acc[1] else acc)
                opposite = Stream(opposing_corners).firstMatch(
                    lambda e: e[0] != origin[0] or e[1] != origin[1])

                sheets.append(
                    Sheet(CameraCoordinate(*origin),
                          CameraCoordinate(*opposite)))

        return sheets
示例#7
0
 def __init__(self, name: str, scoped_components: List[type]):
     """
     :param name: human-readable name
     :param scoped_components: components managed by this scope
     """
     super().__init__(name)
     self.scoped_components = Stream(scoped_components).map(
         lambda clazz: (clazz, None)).toDict()
示例#8
0
    def post(self, body: dict, callback_id="vote_callback") -> dict:
        unquoted_query = urllib.parse.unquote(body['text']).replace(
            "+", " ").replace('”', '"').replace('“', '"')
        tokens = Stream(re.findall(
            '"([^"]*)"', unquoted_query)).filter(lambda x: x != '+').toList()

        # args = unquoted_query.split("+")
        question = tokens[0]
        responses = tokens[1::]
        button_actions = Stream(responses).map(
            lambda x: {
                "callback_id": callback_id,
                "name": "poll",
                "text": x,
                "type": "button",
                "value": x
            }).toList()

        text = question

        for option in responses:
            text += f"\n- {option} ->  "

        if len(button_actions) > 5:
            splitted_attachments = [
                button_actions[i:i + 5]
                for i in range(0, len(button_actions), 5)
            ]
            response = {
                "response_type":
                "in_channel",
                "attachments": [{
                    "fallback": "poll button",
                    "text": text,
                    "callback_id": callback_id,
                    "actions": splitted_attachments[0]
                }, *Stream(splitted_attachments[1::]).map(
                    lambda x: {
                        "fallback": "poll button",
                        "text": "",
                        "callback_id": callback_id,
                        "actions": x
                    })]
            }
        else:

            response = {
                "response_type":
                "in_channel",
                "attachments": [{
                    "fallback": "poll button",
                    "text": text,
                    "callback_id": callback_id,
                    "actions": button_actions
                }]
            }

        return response
示例#9
0
    def test_givenCollectionOfTuples_whenForEach_thenExpandTuplesWhenCallingFunction(
            self):
        result = []
        self.stream = Stream([(1, -1), (2, -2)])
        add_sum_to_list = lambda x, y: result.append(x + y)

        self.stream.forEach(add_sum_to_list)

        self.assertEqual([0, 0], result)
示例#10
0
 def doFilter(self, request: Request, response: Response,
              chain: FilterChain):
     try:
         chain.doFilter(request, response)
     except Exception as e:
         exception_mapper = Stream(self.exception_mappers).firstMatch(
             lambda mapper: mapper.handles(e))
         if exception_mapper.isPresent():
             response.copy(exception_mapper.get().create_response(e))
         else:
             raise e
示例#11
0
 def to_model(self, album: AlbumInfo) -> AlbumModel:
     tracks = Stream(album.tracks).map(lambda t: self.track_mapper.to_model(t)).toList()
     tracks.sort(key=lambda t: (t.disc_number, t.track_number))
     return AlbumModel(
         str(album.id),
         album.name,
         album.artist,
         album.release_year,
         tracks,
         "/media/artwork/{}".format(album.id) if self.artwork_repository.has_artwork_for(album.id) else '',
         album.genre,
         str(album.artist_id))
示例#12
0
    def create_filter_chain(self, request: Request) -> FilterChain:
        if request.method == 'OPTIONS':
            filters = Stream(JIVAGO_DEFAULT_OPTIONS_FILTERS) \
                .map(self.service_locator.get) \
                .toList()
        else:
            filters = Stream(self.filtering_rules) \
                .filter(lambda rule: rule.matches(request.path)) \
                .map(lambda rule: rule.get_filters(self.service_locator)) \
                .flat() \
                .toList()

        return FilterChain(filters, self.route_handler_factory)
示例#13
0
    def __init__(self, root_module=None, *, debug: bool = False,
                 context: Union[AbstractContext, Type[ProductionJivagoContext]] = None):
        self.registry = Registry()
        self.root_module = root_module

        if context is None:
            self.context = DebugJivagoContext(self.root_module, self.registry) if debug else ProductionJivagoContext(
                self.root_module, self.registry)
        elif isinstance(context, type):
            self.context = context(self.root_module, self.registry)
        else:
            self.context = context

        self.print_banner()
        self.__initialize_logger()

        self.LOGGER.info(f"Using {self.context.__class__.__name__} with root package {root_module}.")

        if self.root_module:
            self.LOGGER.info("Discovering annotated classes")
            self.__import_package_recursive(root_module)

        self.context.configure_service_locator()
        self.serviceLocator = self.context.service_locator()

        self.serviceLocator.bind(ApplicationProperties, self.__load_application_properties(self.context))
        self.serviceLocator.bind(SystemEnvironmentProperties, self.__load_system_environment_properties())

        self.LOGGER.info("Running PreInit hooks")
        self.call_startup_hook(PreInit)

        self.router = self.context.create_router_config().build(self.registry, self.serviceLocator)

        self.LOGGER.info("Running Init hooks")
        self.call_startup_hook(Init)

        self.LOGGER.info("Starting background workers")
        self.backgroundWorkers = Stream(self.get_annotated(BackgroundWorker)).map(
            lambda clazz: self.serviceLocator.get(clazz)).map(lambda worker: Thread(target=worker.run, daemon=True))
        Stream(self.backgroundWorkers).forEach(lambda thread: thread.start())

        task_schedule_initializer = TaskScheduleInitializer(self.registry, self.root_module_name)
        self.task_scheduler: TaskScheduler = self.serviceLocator.get(TaskScheduler)
        task_schedule_initializer.initialize_task_scheduler(self.task_scheduler)

        self.LOGGER.info("Running PostInit hooks")
        self.call_startup_hook(PostInit)

        signal.signal(signal.SIGTERM, self.cleanup)
        signal.signal(signal.SIGINT, self.cleanup)
示例#14
0
 def search_by_track_title(self, q: QueryParam[str]) -> TrackSearch:
     tracks = self.media_library.search_tracks_by_title(q)
     if len(tracks) > MAX_RESULTS:
         tracks = tracks[:MAX_RESULTS]
     return TrackSearch(
         Stream(tracks).map(
             lambda t: self.track_mapper.to_model(t)).toList())
示例#15
0
 def get_annotated_in_package(self, annotation: "Annotation",
                              package: str) -> List[Registration]:
     if annotation not in self.content:
         return []
     annotated = self.content[annotation]
     return Stream(annotated).filter(
         lambda r: r.is_in_package(package)).toList()
示例#16
0
 def to_model(self, artist: ArtistInfo) -> ArtistModel:
     return ArtistModel(
         str(artist.id),
         artist.name,
         Stream(artist.albums).map(lambda album: self.album_search_mapper.to_model(album)).toList(),
         '/media/artwork/{}'.format(artist.id) if self.artwork_repository.has_artwork_for(artist.id) else '',
     )
示例#17
0
    def __load_application_properties(self, context: AbstractContext) -> ApplicationProperties:
        composite_config_loader = GlobalConfigLoader([YamlConfigLoader(), JsonConfigLoader()])

        return Stream(context.get_config_file_locations()) \
            .firstMatch(lambda filepath: os.path.exists(filepath)) \
            .map(lambda x: composite_config_loader.read(x)) \
            .orElse(ApplicationProperties())
示例#18
0
    def deserialize(self, obj, declared_type: Optional[T]) -> Optional[T]:
        if obj is None:
            return obj

        non_nil_declared_type = Stream(declared_type.__args__).firstMatch(
            lambda x: x != type(None)).get()
        return self.deserializer.deserialize(obj, non_nil_declared_type)
示例#19
0
 def print_banner(self):
     Stream(self.context.get_banner()).forEach(lambda x: print(x))
     print(f":: Running Jivago {jivago.__version__} ::")
     import sys
     sys.stdout.flush()
     import time
     time.sleep(0.01)
示例#20
0
 def get_route_registrations(self, path: str) -> List[RouteRegistration]:
     path_elements = split_path(path)
     try:
         route_node = self.root_node.explore(path_elements)
         return Stream(route_node.invocators.values()).flat().toList()
     except UnknownPathException:
         return []
示例#21
0
    def get(self, interface: type):
        if interface in self.literals.keys():
            return self.literals[interface]
        if typing_meta_helper.is_typing_meta_collection(interface):
            return self.get_all(interface.__args__[0])

        stored_component = Stream.of(self.components, self.providers) \
            .firstMatch(lambda x: interface in x) \
            .map(lambda x: x[interface]) \
            .orElseThrow(InstantiationException("Could not instantiate {}.".format(interface)))

        scope = self.__get_scope(stored_component)
        if scope is not None and scope.is_stored(stored_component):
            return scope.get(stored_component)
        instance = None

        if interface in self.providers.keys():
            instance = self.__inject_function(self.providers[interface])
        else:
            constructor = stored_component.__init__
            instance = self.__inject_constructor(stored_component, constructor)

        if scope:
            scope.store(stored_component, instance)
        return instance
示例#22
0
    def test_givenTupleIteration_whenUnzipping_thenReturnSeparateLists(self):
        expected = ((1, 3, 5), (2, 4, 6))

        first_list, second_list = Stream([(1, 2), (3, 4), (5, 6)]).unzip()

        self.assertEqual(expected[0], first_list)
        self.assertEqual(expected[1], second_list)
示例#23
0
    def test_givenNoMatchingElements_whenCheckingNoneMatch_thenReturnTrue(
            self):
        always_false = lambda x: False

        result = Stream(self.COLLECTION).noneMatch(always_false)

        self.assertTrue(result)
示例#24
0
 def deserialize(self, obj: dict, object_clazz: Type[T]) -> T:
     try:
         return Stream(self.deserialization_strategies). \
             firstMatch(lambda s: s.can_handle_deserialization(object_clazz)) \
             .orElseThrow(lambda: NoMatchingDeserializationStrategyException(object_clazz)) \
             .deserialize(obj, object_clazz)
     except (AttributeError, TypeError):
         raise IncorrectAttributeTypeException()
示例#25
0
    def deserialize(self, obj, declared_type: Type[T]) -> T:
        if _has_defined_initializer(declared_type):
            initializer_signature = inspect.signature(declared_type)
            return declared_type(**Stream(initializer_signature.parameters.items()) \
                                 .map(lambda name, parameter:
                                      (name, self.deserializer.deserialize(obj.get(name), parameter.annotation))) \
                                 .toDict())

        else:
            instance = object.__new__(declared_type)
            attributes = declared_type.__annotations__
            Stream(attributes.items()) \
                .map(lambda name, attribute_type:
                     (name, self.deserializer.deserialize(obj.get(name), attribute_type))) \
                .forEach(lambda name, attribute: instance.__setattr__(name, attribute))

            return instance
 def _is_in(self, sheet: Sheet, sheets: List[Sheet]):
     matching_sheet = Stream(sheets).firstMatch(
         lambda sheet_to_compare: sheet.origin.isclose(
             sheet_to_compare.origin, 10) and sheet.opposite_corner.isclose(
                 sheet_to_compare.opposite_corner, 10))
     if matching_sheet is not None:
         return True
     return False
示例#27
0
    def test_givenMethodWhichRequiresTwoParameters_whenMapping_thenInvokeAndExpandParameters(
            self):
        calculator_object = AClassWithAMethod(0)

        result = Stream.zip([1, 2, 3, 4], [1, 2, 3, 4]).map(
            calculator_object.sum_of_two_values).toList()

        self.assertEqual([2, 4, 6, 8], result)
示例#28
0
    def test_givenMethodWhichRequiresAParameter_whenMapping_thenInvokeMethodWithParameter(
            self):
        calculator_object = AClassWithAMethod(0)

        result = Stream.of(1, 2, 3,
                           4).map(calculator_object.increment).toList()

        self.assertEqual([1, 2, 3, 4], result)
示例#29
0
    def search_by_album(self, q: QueryParam[str]) -> AlbumSearch:
        albums = self.media_library.search_albums(q)
        if len(albums) > MAX_RESULTS:
            albums = albums[:MAX_RESULTS]

        return AlbumSearch(
            Stream(albums).map(
                lambda a: self.album_mapper.to_model(a)).toList())
示例#30
0
    def search_by_artist(self, q: QueryParam[str]) -> ArtistSearch:
        artists = self.media_library.search_artists(q)
        if len(artists) > MAX_RESULTS:
            artists = artists[:MAX_RESULTS]

        return ArtistSearch(
            Stream(artists).map(
                lambda a: self.artist_mapper.to_model(a)).toList())