for botconfig in self._bot_configs:
                data['bots'][botconfig.id] = {}
                botconfig.to_yaml(data['bots'][botconfig.id], defaults)

"""

"""
from programy.utils.logging.ylogger import YLogger
from programy.config.container import BaseContainerConfigurationData
from programy.config.bot.bot import BotConfiguration
from programy.scheduling.config import SchedulerConfiguration
from programy.storage.config import StorageConfiguration
from programy.utils.substitutions.substitues import Substitutions
from programy.utils.email.config import EmailConfiguration
from programy.triggers.config import TriggerConfiguration
from programy.clients.ping.config import PingResponderConfig
from programy.config.brain.brain import BrainConfiguration

class ClientConfigurationData(BaseContainerConfigurationData):

    def __init__(self, name):
        BaseContainerConfigurationData.__init__(self, name)
        self._description = 'ProgramY AIML2.0 Client'
        self._renderer = self._get_renderer_class()
        self._scheduler = SchedulerConfiguration()
        self._storage = StorageConfiguration()
        self._email = EmailConfiguration()
        self._triggers = TriggerConfiguration()
        self._responder = PingResponderConfig()

        self._bot_selector = self._get_bot_selector_class()
        bot_config = BotConfiguration('bot')
        self._bot_configs = [bot_config]

    def _get_renderer_class(self):
        return "programy.clients.render.text.TextRenderer"

    def _get_bot_selector_class(self):
        return "programy.clients.botfactory.DefaultBotSelector"

    @property
    def description(self):
        return self._description

    @property
    def configurations(self):
        return self._bot_configs

    @property
    def bot_selector(self):
        return self._bot_selector

    @property
    def scheduler(self):
        return self._scheduler

    @property
    def storage(self):
        return self._storage

    @property
    def renderer(self):
        return self._renderer

    @property
    def email(self):
        return self._email

    @property
    def triggers(self):
        return self._triggers

    @property
    def responder(self):
        return self._responder

    def load_configuration(self, configuration_file, bot_root, subs: Substitutions = None):
        client = configuration_file.get_section(self.section_name)
        if client is None:
            YLogger.error(None, 'Client section named [%s] not found, trying "client"', self.section_name)
            client = configuration_file.get_section('client')

        if client is not None:
            self.load_configuration_section(configuration_file, client, bot_root, subs)

        else:
            YLogger.error(None, 'No client section not found!')

    def load_configuration_section(self, configuration_file, section, bot_root, subs: Substitutions = None):

        assert configuration_file is not None
        assert section is not None

        self._description = configuration_file.get_option(section, "description",
                                                          missing_value='ProgramY AIML2.0 Client', subs=subs)

        self._scheduler.load_config_section(configuration_file, section, bot_root, subs=subs)

        self._storage.load_config_section(configuration_file, section, bot_root, subs=subs)

        self._renderer = configuration_file.get_option(section, "renderer", subs=subs)

        self._email.load_config_section(configuration_file, section, bot_root, subs=subs)

        self._triggers.load_config_section(configuration_file, section, bot_root, subs=subs)

        self._responder.load_config_section(configuration_file, section, bot_root, subs=subs)

        self._load_bot_configurations(configuration_file, section, bot_root, subs)

    def _load_bot_configurations(self, configuration_file, section, bot_root, subs):
        bots = configuration_file.get_section("bots", section)
        if bots is not None:
            bot_keys = configuration_file.get_keys(bots)
            first = True
            for name in bot_keys:
                if first is True:
                    self._bot_configs.clear()
                    first = False
                bot_config = configuration_file.get_section(name, bots)
                config = BotConfiguration(name)
                config.load_configuration_section(configuration_file, bot_config, bot_root, subs=subs)
                self._bot_configs.append(config)

        if len(self._bot_configs) == 0:
            YLogger.warning(self, "No bot name defined for client [%s], defaulting to 'bot'.", self.section_name)
            self._bot_configs.append(BotConfiguration("bot"))
            self._bot_configs[0].configurations.append(BrainConfiguration("brain"))

        self._bot_selector = configuration_file.get_option(section, "bot_selector",
                       missing_value="programy.clients.botfactory.DefaultBotSelector",
                       subs=subs)

    def to_yaml(self, data, defaults=True):

        assert data is not None

        if defaults is True:
            data['description'] = 'ProgramY AIML2.0 Client'
            data['bot_selector'] = "programy.clients.botfactory.DefaultBotSelector"

            data['scheduler'] = {}
            self._scheduler.to_yaml(data['scheduler'], defaults)

            data['email'] = {}
            self._email.to_yaml(data['email'], defaults)

            data['triggers'] = {}
            self._triggers.to_yaml(data['triggers'], defaults)

            data['responder'] = {}
            self._responder.to_yaml(data['responder'], defaults)

            data['renderer'] = "programy.clients.render.text.TextRenderer"

            data['storage'] = {}
            self._storage.to_yaml(data['storage'], defaults)

            data['bots'] = {}
            data['bots']['bot'] = {}
            bot_config = BotConfiguration('bot')
            bot_config.to_yaml(data['bots']['bot'], defaults)

        else:
            data['description'] = self._description
            data['bot_selector'] = self.bot_selector

            data[self._scheduler.id] = {}
            self._scheduler.to_yaml(data[self._scheduler.id], defaults)

            data['email'] = {}
            self._email.to_yaml(data['email'], defaults)

            data['triggers'] = {}
            self._triggers.to_yaml(data['triggers'], defaults)

            data['responder'] = {}
            self._responder.to_yaml(data['responder'], defaults)

            data['renderer'] = self.renderer

            data['storage'] = {}
            self._storage.to_yaml(data['storage'], defaults)

            data['bots'] = {}


from __future__ import unicode_literals, absolute_import

import json
import unittest

import responses

from linebot import (
    LineBotApi
)
from linebot.models import (
    VideoSendMessage
)

class TestLineBotApi(unittest.TestCase):
    def setUp(self):
        self.tested = LineBotApi('channel_secret')

        self.video_message = VideoSendMessage(
            original_content_url='https://example.com/original.mp4',
            preview_image_url='https://example.com/preview.jpg',
            tracking_id='TrackId'
        )

        self.message = [{
            "type": "video",
            "originalContentUrl": "https://example.com/original.mp4",
            "previewImageUrl": "https://example.com/preview.jpg",
            "trackingId": "TrackId"
        }]

    @responses.activate

responses.add(
            responses.POST,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push',
            json={}, status=200
        )

        self.tested.push_message('to', self.video_message)

        request = responses.calls[0].request
        self.assertEqual(request.method, 'POST')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push')
        self.assertEqual(
            json.loads(request.body),
            {
                "to": "to",
                'notificationDisabled': False,
                "messages": self.message
            }
        )

    @responses.activate
    def test_reply_video_message(self):
        responses.add(
            responses.POST,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply',
            json={}, status=200
        )

        self.tested.reply_message('replyToken', self.video_message)

        request = responses.calls[0].request
        self.assertEqual(request.method, 'POST')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply')
        self.assertEqual(
            json.loads(request.body),
            {
                "replyToken": "replyToken",
                "messages": self.message,
                'notificationDisabled': False,
            }
        )

    @responses.activate
    def test_multicast_video_message(self):
        responses.add(
            responses.POST,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast',
            json={}, status=200
        )

        self.tested.multicast(['to1', 'to2'], self.video_message)

        request = responses.calls[0].request
        self.assertEqual(request.method, 'POST')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast')
        self.assertEqual(
            json.loads(request.body),
            {
                "to": ['to1', 'to2'],
                "messages": self.message,
                "notificationDisabled": False,
            }
        )

if __name__ == '__main__':
    unittest.main()


from __future__ import unicode_literals, absolute_import

import json
import unittest

import responses

from linebot import (
    LineBotApi
)
from linebot.models import (
    VideoSendMessage
)

class TestLineBotApi(unittest.TestCase):
    def setUp(self):
        self.tested = LineBotApi('channel_secret')

        self.video_message = VideoSendMessage(
            original_content_url='https://example.com/original.mp4',
            preview_image_url='https://example.com/preview.jpg',
            tracking_id='TrackId'
        )

        self.message = [{
            "type": "video",
            "originalContentUrl": "https://example.com/original.mp4",
            "previewImageUrl": "https://example.com/preview.jpg",
            "trackingId": "TrackId"
        }]

    @responses.activate
    def test_push_video_message(self):
        responses.add(
            responses.POST,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push',
            json={}, status=200
        )

        self.tested.push_message('to', self.video_message)

        request = responses.calls[0].request
        self.assertEqual(request.method, 'POST')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push')
        self.assertEqual(
            json.loads(request.body),
            {
                "to": "to",
                'notificationDisabled': False,
                "messages": self.message
            }
        )

    @responses.activate
    def test_reply_video_message(self):
        responses.add(
            responses.POST,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply',
            json={}, status=200
        )

        self.tested.reply_message('replyToken', self.video_message)

        request = responses.ca

        self.assertEqual(request.method, 'POST')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply')
        self.assertEqual(
            json.loads(request.body),
            {
                "replyToken": "replyToken",
                "messages": self.message,
                'notificationDisabled': False,
            }
        )

    @responses.activate
    def test_multicast_video_message(self):
        responses.add(
            responses.POST,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast',
            json={}, status=200
        )

        self.tested.multicast(['to1', 'to2'], self.video_message)

        request = responses.calls[0].request
        self.assertEqual(request.method, 'POST')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast')
        self.assertEqual(
            json.loads(request.body),
            {
                "to": ['to1', 'to2'],
                "messages": self.message,
                "notificationDisabled": False,
            }
        )

if __name__ == '__main__':
    unittest.main()


def prepare_hypothesis_settings(
    deadline: Optional[Union[int, NotSet]] = None,
    derandomize: Optional[bool] = None,
    max_examples: Optional[int] = None,
    phases: Optional[List[hypothesis.Phase]] = None,
    report_multiple_bugs: Optional[bool] = None,
    suppress_health_check: Optional[List[hypothesis.HealthCheck]] = None,
    verbosity: Optional[hypothesis.Verbosity] = None,
) -> hypothesis.settings:

from typing import Any, Callable, Dict, Generator, Iterable, List, Optional, Tuple, Union
from urllib.parse import urlparse

import hypothesis.errors
from starlette.applications import Starlette

from ..checks import DEFAULT_CHECKS
from ..constants import (
    DEFAULT_DATA_GENERATION_METHODS,
    DEFAULT_DEADLINE,
    DEFAULT_STATEFUL_RECURSION_LIMIT,
    DataGenerationMethod,
)
from ..models import CheckFunction
from ..schemas import BaseSchema
from ..specs.graphql import loaders as gql_loaders
from ..specs.openapi import loaders as oas_loaders
from ..stateful import Stateful
from ..targets import DEFAULT_TARGETS, Target
from ..types import Filter, NotSet, RawAuth
from ..utils import deprecated, dict_not_none_values, dict_true_values, file_exists, get_requests_auth, import_app
from . import events
from .impl import (
    BaseRunner,
    SingleThreadASGIRunner,
    SingleThreadRunner,
    SingleThreadWSGIRunner,
    ThreadPoolASGIRunner,
    ThreadPoolRunner,
    ThreadPoolWSGIRunner,
)

@deprecated(removed_in="4.0", replacement="schemathesis.runner.from_schema")
def prepare(
    schema_uri: Union[str, Dict[str, Any]],
    *,
    # Runtime behavior
    checks: Iterable[CheckFunction] = DEFAULT_CHECKS,
    data_generation_methods: Tuple[DataGenerationMethod, ...] = DEFAULT_DATA_GENERATION_METHODS,
    max_response_time: Optional[int] = None,
    targets: Iterable[Target] = DEFAULT_TARGETS,
    workers_num: int = 1,
    seed: Optional[int] = None,
    exit_first: bool = False,
    dry_run: bool = False,
    store_interactions: bool = False,
    stateful: Optional[Stateful] = None,
    stateful_recursion_limit: int = DEFAULT_STATEFUL_RECURSION_LIMIT,
    # Schema loading
    loader: Callable = oas_loaders.from_uri,
    base_url: Optional[str] = None,
    auth: Optional[Tuple[str, str]] = None,
    auth_type: Optional[str] = None,
    headers: Optional[Dict[str, str]] = None,
    request_timeout: Optional[int] = None,
    request_tls_verify: Union[bool, str] = True,
    endpoint: Optional[Filter] = None,
    method: Optional[Filter] = None,
    tag: Optional[Filter] = None,
    operation_id: Optional[Filter] = None,
    app: Optional[str] = None,
    validate_schema: bool = True,
    skip_deprecated_operations: bool = False,
    force_schema_version: Optional[str] = None,
    count_operations: bool = True,
    # Hypothesis-specific configuration
    hypothesis_deadline: Optional[Union[int, NotSet]] = None,
    hypothesis_derandomize: Optional[bool] = None,
    hypothesis_max_examples: Optional[int] = None,
    hypothesis_phases: Optional[List[hypothesis.Phase]] = None,
    hypothesis_report_multiple_bugs: Optional[bool] = None,
    hypothesis_suppress_health_check: Optional[List[hypothesis.HealthCheck]] = None,
    hypothesis_verbosity: Optional[hypothesis.Verbosity] = None,
) -> Generator[events.ExecutionEvent, None, None]:
    """Prepare a generator that will run test cases against the given API definition."""
    # pylint: disable=too-many-locals

    validate_loader(loader, schema_uri)

    if auth is None:
        # Auth type doesn't matter if auth is not passed
        auth_type = None  # type: ignore
    hypothesis_settings = prepare_hypothesis_settings(
        deadline=hypothesis_deadline,
        derandomize=hypothesis_derandomize,
        max_examples=hypothesis_max_examples,
        phases=hypothesis_phases,
        report_multiple_bugs=hypothesis_report_multiple_bugs,
        suppress_health_check=hypothesis_suppress_health_check,
        verbosity=hypothesis_verbosity,
    )
    return execute_from_schema(
        schema_uri=schema_uri,
        loader=loader,
        base_url=base_url,
        endpoint=endpoint,
        method=method,
        tag=tag,
        operation_id=operation_id,
        app=app,
        validate_schema=validate_schema,
        skip_deprecated_operations=skip_deprecated_operations,
        force_schema_version=force_schema_version,
        checks=checks,
        data_generation_methods=data_generation_methods,
        max_response_time=max_response_time,
        targets=targets,
        hypothesis_settings=hypothesis_settings,
        seed=seed,
        workers_num=workers_num,
        exit_first=exit_first,
        dry_run=dry_run,
        auth=auth,
        auth_type=auth_type,
        headers=headers,
        request_timeout=request_timeout,
        request_tls_verify=request_tls_verify,
        store_interactions=store_interactions,
        stateful=stateful,
        stateful_recursion_limit=stateful_recursion_limit,
        count_operations=count_operations,
    )

def validate_loader(loader: Callable, schema_uri: Union[str, Dict[str, Any]]) -> None:
    """Sanity checking for input schema & loader."""
    if loader not in (
        oas_loaders.from_uri,
        oas_loaders.from_aiohttp,
        oas_loaders.from_dict,
        oas_loaders.from_file,
        oas_loaders.from_path,
        oas_loaders.from_asgi,
        oas_loaders.from_wsgi,
        gql_loaders.from_dict,
        gql_loaders.from_url,
        gql_loaders.from_wsgi,
    ):
        # Custom loaders are not checked
        return
    if isinstance(schema_uri, dict):
        if loader not in (oas_loaders.from_dict, gql_loaders.from_dict):
            raise ValueError("Dictionary as a schema is allowed only with `from_dict` loader")
    elif loader in (oas_loaders.from_dict, gql_loaders.from_dict):
        raise ValueError("Schema should be a dictionary for `from_dict` loader")

def execute_from_schema(
    *,
    schema_uri: Union[str, Dict[str, Any]],
    loader: Callable = oas_loaders.from_uri,
    base_url: Optional[str] = None,
    endpoint: Optional[Filter] = None,
    method: Optional[Filter] = None,
    tag: Optional[Filter] = None,
    operation_id: Optional[Filter] = None,
    app: Optional[str] = None,
    validate_schema: bool = True,
    skip_deprecated_operations: bool = False,
    force_schema_version: Optional[str] = None,
    checks: Iterable[CheckFunction],
    data_generation_methods: Tuple[DataGenerationMethod, ...] = DEFAULT_DATA_GENERATION_METHODS,
    max_response_time: Optional[int] = None,
    targets: Iterable[Target],
    workers_num: int = 1,
    hypothesis_settings: hypothesis.settings,
    auth: Optional[RawAuth] = None,
    auth_type: Optional[str] = None,
    headers: Optional[Dict[str, Any]] = None,
    request_timeout: Optional[int] = None,
    request_tls_verify: Union[bool, str] = True,
    seed: Optional[int] = None,
    exit_first: bool = False,
    dry_run: bool = False,
    store_interactions: bool = False,
    stateful: Optional[Stateful] = None,
    stateful_recursion_limit: int = DEFAULT_STATEFUL_RECURSION_LIMIT,
    count_operations: bool = True,
) -> Generator[events.ExecutionEvent, None, None]:
    """Execute tests for the given schema.

    Provides the main testing loop and preparation step.
    """
    # pylint: disable=too-many-locals
    try:
        if app is not None:
            app = import_app(app)
        schema = load_schema(
            schema_uri,
            base_url=base_url,
            loader=loader,
            app=app,
            validate_schema=validate_schema,
            skip_deprecated_operations=skip_deprecated_operations,
            auth=auth,
            auth_type=auth_type,
            headers=headers,
            endpoint=endpoint,
            method=method,
            tag=tag,
            operation_id=operation_id,
            data_generation_methods=data_generation_methods,
            force_schema_version=force_schema_version,
            request_tls_verify=request_tls_verify,
        )
        yield from from_schema(
            schema,
            checks=checks,
            max_response_time=max_response_time,
            targets=targets,
            hypothesis_settings=hypothesis_settings,
            auth=auth,
            auth_type=auth_type,
            headers=headers,
            seed=seed,
            workers_num=workers_num,
            request_timeout=request_timeout,
            request_tls_verify=request_tls_verify,
            exit_first=exit_first,
            dry_run=dry_run,
            store_interactions=store_interactions,
            stateful=stateful,
            stateful_recursion_limit=stateful_recursion_limit,
            count_operations=count_operations,
        ).execute()
    except Exception as exc:
        yield events.InternalError.from_exc(exc)

def load_schema(
    schema_uri: Union[str, Dict[str, Any]],
    *,
    base_url: Optional[str] = None,
    loader: Callable = oas_loaders.from_uri,
    app: Any = None,
    validate_schema: bool = True,
    skip_deprecated_operations: bool = False,
    data_generation_methods: Tuple[DataGenerationMethod, ...] = DEFAULT_DATA_GENERATION_METHODS,
    force_schema_version: Optional[str] = None,
    request_tls_verify: Union[bool, str] = True,
    # Network request parameters
    auth: Optional[Tuple[str, str]] = None,
    auth_type: Optional[str] = None,
    headers: Optional[Dict[str, str]] = None,
    # Schema filters
    endpoint: Optional[Filter] = None,
    method: Optional[Filter] = None,
    tag: Optional[Filter] = None,
    operation_id: Optional[Filter] = None,
) -> BaseSchema:
    """Load schema via specified loader and parameters."""
    loader_options = dict_true_values(
        base_url=base_url,
        endpoint=endpoint,
        method=method,
        tag=tag,
        operation_id=operation_id,
        app=app,
        data_generation_methods=data_generation_methods,
    )

    if not isinstance(schema_uri, dict):
        if file_exists(schema_uri):
            loader = oas_loaders.from_path
        elif loader is not oas_loaders.from_path:
            if app is not None and not urlparse(schema_uri).netloc:
                # If `schema` is not an existing filesystem path, or a URL then it is considered as a path within
                # the given app
                loader = oas_loaders.get_loader_for_app(app)
                loader_options.update(dict_true_values(headers=headers))
            else:
                loader_options.update(dict_true_values(headers=headers, auth=auth, auth_type=auth_type))

    if loader is oas_loaders.from_uri and loader_options.get("auth"):
        loader_options["auth"] = get_requests_auth(loader_options["auth"], loader_options.pop("auth_type", None))
    if loader in (oas_loaders.from_uri, oas_loaders.from_aiohttp):
        loader_options["verify"] = request_tls_verify

    return loader(
        schema_uri,
        validate_schema=validate_schema,
        skip_deprecated_operations=skip_deprecated_operations,
        force_schema_version=force_schema_version,
        **loader_options,
    )

def from_schema(
    schema: BaseSchema,
    *,
    checks: Iterable[CheckFunction] = DEFAULT_CHECKS,
    max_response_time: Optional[int] = None,
    targets: Iterable[Target] = DEFAULT_TARGETS,
    workers_num: int = 1,
    hypothesis_settings: Optional[hypothesis.settings] = None,
    auth: Optional[RawAuth] = None,
    auth_type: Optional[str] = None,
    headers: Optional[Dict[str, Any]] = None,
    request_timeout: Optional[int] = None,
    request_tls_verify: Union[bool, str] = True,
    seed: Optional[int] = None,
    exit_first: bool = False,
    dry_run: bool = False,
    store_interactions: bool = False,
    stateful: Optional[Stateful] = None,
    stateful_recursion_limit: int = DEFAULT_STATEFUL_RECURSION_LIMIT,
    count_operations: bool = True,
) -> BaseRunner:
    hypothesis_settings = hypothesis_settings or hypothesis.settings(deadline=DEFAULT_DEADLINE)
    if workers_num > 1:
        if not schema.app:
            return ThreadPoolRunner(
                schema=schema,
                checks=checks,
                max_response_time=max_response_time,
                targets=targets,
                hypothesis_settings=hypothesis_settings,
                auth=auth,
                auth_type=auth_type,
                headers=headers,
                seed=seed,
                workers_num=workers_num,
                request_timeout=request_timeout,
                request_tls_verify=request_tls_verify,
                exit_first=exit_first,
                dry_run=dry_run,
                store_interactions=store_interactions,
                stateful=stateful,
                stateful_recursion_limit=stateful_recursion_limit,
                count_operations=count_operations,
            )
        if isinstance(schema.app, Starlette):
            return ThreadPoolASGIRunner(
                schema=schema,
                checks=checks,
                max_response_time=max_response_time,
                targets=targets,
                hypothesis_settings=hypothesis_settings,
                auth=auth,
                auth_type=auth_type,
                headers=headers,
                seed=seed,
                exit_first=exit_first,
                dry_run=dry_run,
                store_interactions=store_interactions,
                stateful=stateful,
                stateful_recursion_limit=stateful_recursion_limit,
                count_operations=count_operations,
            )
        return ThreadPoolWSGIRunner(
            schema=schema,
            checks=checks,
            max_response_time=max_response_time,
            targets=targets,
            hypothesis_settings=hypothesis_settings,
            auth=auth,
            auth_type=auth_type,
            headers=headers,
            seed=seed,
            workers_num=workers_num,
            exit_first=exit_first,
            dry_run=dry_run,
            store_interactions=store_interactions,
            stateful=stateful,
            stateful_recursion_limit=stateful_recursion_limit,
            count_operations=count_operations,
        )
    if not schema.app:
        return SingleThreadRunner(
            schema=schema,
            checks=checks,
            max_response_time=max_response_time,
            targets=targets,
            hypothesis_settings=hypothesis_settings,
            auth=auth,
            auth_type=auth_type,
            headers=headers,
            seed=seed,
            request_timeout=request_timeout,
            request_tls_verify=request_tls_verify,
            exit_first=exit_first,
            dry_run=dry_run,
            store_interactions=store_interactions,
            stateful=stateful,
            stateful_recursion_limit=stateful_recursion_limit,
            count_operations=count_operations,
        )
    if isinstance(schema.app, Starlette):
        return SingleThreadASGIRunner(
            schema=schema,
            checks=checks,
            max_response_time=max_response_time,
            targets=targets,
            hypothesis_settings=hypothesis_settings,
            auth=auth,
            auth_type=auth_type,
            headers=headers,
            seed=seed,
            exit_first=exit_first,
            dry_run=dry_run,
            store_interactions=store_interactions,
            stateful=stateful,
            stateful_recursion_limit=stateful_recursion_limit,
            count_operations=count_operations,
        )
    return SingleThreadWSGIRunner(
        schema=schema,
        checks=checks,
        max_response_time=max_response_time,
        targets=targets,
        hypothesis_settings=hypothesis_settings,
        auth=auth,
        auth_type=auth_type,
        headers=headers,
        seed=seed,
        exit_first=exit_first,
        dry_run=dry_run,
        store_interactions=store_interactions,
        stateful=stateful,
        stateful_recursion_limit=stateful_recursion_limit,
        count_operations=count_operations,
    )

kwargs = dict_not_none_values(
        derandomize=derandomize,
        max_examples=max_examples,
        phases=phases,
        report_multiple_bugs=report_multiple_bugs,
        suppress_health_check=suppress_health_check,
        verbosity=verbosity,
    )
    # `deadline` is special, since Hypothesis allows passing `None`
    if deadline is not None:
        if isinstance(deadline, NotSet):
            kwargs["deadline"] = None
        else:
            kwargs["deadline"] = deadline
    kwargs.setdefault("deadline", DEFAULT_DEADLINE)
    return hypothesis.settings(**kwargs)


from typing import Any, Callable, Dict, Generator, Iterable, List, Optional, Tuple, Union
from urllib.parse import urlparse

import hypothesis.errors
from starlette.applications import Starlette

from ..checks import DEFAULT_CHECKS
from ..constants import (
    DEFAULT_DATA_GENERATION_METHODS,
    DEFAULT_DEADLINE,
    DEFAULT_STATEFUL_RECURSION_LIMIT,
    DataGenerationMethod,
)
from ..models import CheckFunction
from ..schemas import BaseSchema
from ..specs.graphql import loaders as gql_loaders
from ..specs.openapi import loaders as oas_loaders
from ..stateful import Stateful
from ..targets import DEFAULT_TARGETS, Target
from ..types import Filter, NotSet, RawAuth
from ..utils import deprecated, dict_not_none_values, dict_true_values, file_exists, get_requests_auth, import_app
from . import events
from .impl import (
    BaseRunner,
    SingleThreadASGIRunner,
    SingleThreadRunner,
    SingleThreadWSGIRunner,
    ThreadPoolASGIRunner,
    ThreadPoolRunner,
    ThreadPoolWSGIRunner,
)

@deprecated(removed_in="4.0", replacement="schemathesis.runner.from_schema")
def prepare(
    schema_uri: Union[str, Dict[str, Any]],
    *,
    # Runtime behavior
    checks: Iterable[CheckFunction] = DEFAULT_CHECKS,
    data_generation_methods: Tuple[DataGenerationMethod, ...] = DEFAULT_DATA_GENERATION_METHODS,
    max_response_time: Optional[int] = None,
    targets: Iterable[Target] = DEFAULT_TARGETS,
    workers_num: int = 1,
    seed: Optional[int] = None,
    exit_first: bool = False,
    dry_run: bool = False,
    store_interactions: bool = False,
    stateful: Optional[Stateful] = None,
    stateful_recursion_limit: int = DEFAULT_STATEFUL_RECURSION_LIMIT,
    # Schema loading
    loader: Callable = oas_loaders.from_uri,
    base_url: Optional[str] = None,
    auth: Optional[Tuple[str, str]] = None,
    auth_type: Optional[str] = None,
    headers: Optional[Dict[str, str]] = None,
    request_timeout: Optional[int] = None,
    request_tls_verify: Union[bool, str] = True,
    endpoint: Optional[Filter] = None,
    method: Optional[Filter] = None,
    tag: Optional[Filter] = None,
    operation_id: Optional[Filter] = None,
    app: Optional[str] = None,
    validate_schema: bool = True,
    skip_deprecated_operations: bool = False,
    force_schema_version: Optional[str] = None,
    count_operations: bool = True,
    # Hypothesis-specific configuration
    hypothesis_deadline: Optional[Union[int, NotSet]] = None,
    hypothesis_derandomize: Optional[bool] = None,
    hypothesis_max_examples: Optional[int] = None,
    hypothesis_phases: Optional[List[hypothesis.Phase]] = None,
    hypothesis_report_multiple_bugs: Optional[bool] = None,
    hypothesis_suppress_health_check: Optional[List[hypothesis.HealthCheck]] = None,
    hypothesis_verbosity: Optional[hypothesis.Verbosity] = None,
) -> Generator[events.ExecutionEvent, None, None]:
    """Prepare a generator that will run test cases against the given API definition."""
    # pylint: disable=too-many-locals

    validate_loader(loader, schema_uri)

    if auth is None:
        # Auth type doesn't matter if auth is not passed
        auth_type = None  # type: ignore
    hypothesis_settings = prepare_hypothesis_settings(
        deadline=hypothesis_deadline,
        derandomize=hypothesis_derandomize,
        max_examples=hypothesis_max_examples,
        phases=hypothesis_phases,
        report_multiple_bugs=hypothesis_report_multiple_bugs,
        suppress_health_check=hypothesis_suppress_health_check,
        verbosity=hypothesis_verbosity,
    )
    return execute_from_schema(
        schema_uri=schema_uri,
        loader=loader,
        base_url=base_url,
        endpoint=endpoint,
        method=method,
        tag=tag,
        operation_id=operation_id,
        app=app,
        validate_schema=validate_schema,
        skip_deprecated_operations=skip_deprecated_operations,
        force_schema_version=force_schema_version,
        checks=checks,
        data_generation_methods=data_generation_methods,
        max_response_time=max_response_time,
        targets=targets,
        hypothesis_settings=hypothesis_settings,
        seed=seed,
        workers_num=workers_num,
        exit_first=exit_first,
        dry_run=dry_run,
        auth=auth,
        auth_type=auth_type,
        headers=headers,
        request_timeout=request_timeout,
        request_tls_verify=request_tls_verify,
        store_interactions=store_interactions,
        stateful=stateful,
        stateful_recursion_limit=stateful_recursion_limit,
        count_operations=count_operations,
    )

def validate_loader(loader: Callable, schema_uri: Union[str, Dict[str, Any]]) -> None:
    """Sanity checking for input schema & loader."""
    if loader not in (
        oas_loaders.from_uri,
        oas_loaders.from_aiohttp,
        oas_loaders.from_dict,
        oas_loaders.from_file,
        oas_loaders.from_path,
        oas_loaders.from_asgi,
        oas_loaders.from_wsgi,
        gql_loaders.from_dict,
        gql_loaders.from_url,
        gql_loaders.from_wsgi,
    ):
        # Custom loaders are not checked
        return
    if isinstance(schema_uri, dict):
        if loader not in (oas_loaders.from_dict, gql_loaders.from_dict):
            raise ValueError("Dictionary as a schema is allowed only with `from_dict` loader")
    elif loader in (oas_loaders.from_dict, gql_loaders.from_dict):
        raise ValueError("Schema should be a dictionary for `from_dict` loader")

def execute_from_schema(
    *,
    schema_uri: Union[str, Dict[str, Any]],
    loader: Callable = oas_loaders.from_uri,
    base_url: Optional[str] = None,
    endpoint: Optional[Filter] = None,
    method: Optional[Filter] = None,
    tag: Optional[Filter] = None,
    operation_id: Optional[Filter] = None,
    app: Optional[str] = None,
    validate_schema: bool = True,
    skip_deprecated_operations: bool = False,
    force_schema_version: Optional[str] = None,
    checks: Iterable[CheckFunction],
    data_generation_methods: Tuple[DataGenerationMethod, ...] = DEFAULT_DATA_GENERATION_METHODS,
    max_response_time: Optional[int] = None,
    targets: Iterable[Target],
    workers_num: int = 1,
    hypothesis_settings: hypothesis.settings,
    auth: Optional[RawAuth] = None,
    auth_type: Optional[str] = None,
    headers: Optional[Dict[str, Any]] = None,
    request_timeout: Optional[int] = None,
    request_tls_verify: Union[bool, str] = True,
    seed: Optional[int] = None,
    exit_first: bool = False,
    dry_run: bool = False,
    store_interactions: bool = False,
    stateful: Optional[Stateful] = None,
    stateful_recursion_limit: int = DEFAULT_STATEFUL_RECURSION_LIMIT,
    count_operations: bool = True,
) -> Generator[events.ExecutionEvent, None, None]:
    """Execute tests for the given schema.

    Provides the main testing loop and preparation step.
    """
    # pylint: disable=too-many-locals
    try:
        if app is not None:
            app = import_app(app)
        schema = load_schema(
            schema_uri,
            base_url=base_url,
            loader=loader,
            app=app,
            validate_schema=validate_schema,
            skip_deprecated_operations=skip_deprecated_operations,
            auth=auth,
            auth_type=auth_type,
            headers=headers,
            endpoint=endpoint,
            method=method,
            tag=tag,
            operation_id=operation_id,
            data_generation_methods=data_generation_methods,
            force_schema_version=force_schema_version,
            request_tls_verify=request_tls_verify,
        )
        yield from from_schema(
            schema,
            checks=checks,
            max_response_time=max_response_time,
            targets=targets,
            hypothesis_settings=hypothesis_settings,
            auth=auth,
            auth_type=auth_type,
            headers=headers,
            seed=seed,
            workers_num=workers_num,
            request_timeout=request_timeout,
            request_tls_verify=request_tls_verify,
            exit_first=exit_first,
            dry_run=dry_run,
            store_interactions=store_interactions,
            stateful=stateful,
            stateful_recursion_limit=stateful_recursion_limit,
            count_operations=count_operations,
        ).execute()
    except Exception as exc:
        yield events.InternalError.from_exc(exc)

def load_schema(
    schema_uri: Union[str, Dict[str, Any]],
    *,
    base_url: Optional[str] = None,
    loader: Callable = oas_loaders.from_uri,
    app: Any = None,
    validate_schema: bool = True,
    skip_deprecated_operations: bool = False,
    data_generation_methods: Tuple[DataGenerationMethod, ...] = DEFAULT_DATA_GENERATION_METHODS,
    force_schema_version: Optional[str] = None,
    request_tls_verify: Union[bool, str] = True,
    # Network request parameters
    auth: Optional[Tuple[str, str]] = None,
    auth_type: Optional[str] = None,
    headers: Optional[Dict[str, str]] = None,
    # Schema filters
    endpoint: Optional[Filter] = None,
    method: Optional[Filter] = None,
    tag: Optional[Filter] = None,
    operation_id: Optional[Filter] = None,
) -> BaseSchema:
    """Load schema via specified loader and parameters."""
    loader_options = dict_true_values(
        base_url=base_url,
        endpoint=endpoint,
        method=method,
        tag=tag,
        operation_id=operation_id,
        app=app,
        data_generation_methods=data_generation_methods,
    )

    if not isinstance(schema_uri, dict):
        if file_exists(schema_uri):
            loader = oas_loaders.from_path
        elif loader is not oas_loaders.from_path:
            if app is not None and not urlparse(schema_uri).netloc:
                # If `schema` is not an existing filesystem path, or a URL then it is considered as a path within
                # the given app
                loader = oas_loaders.get_loader_for_app(app)
                loader_options.update(dict_true_values(headers=headers))
            else:
                loader_options.update(dict_true_values(headers=headers, auth=auth, auth_type=auth_type))

    if loader is oas_loaders.from_uri and loader_options.get("auth"):
        loader_options["auth"] = get_requests_auth(loader_options["auth"], loader_options.pop("auth_type", None))
    if loader in (oas_loaders.from_uri, oas_loaders.from_aiohttp):
        loader_options["verify"] = request_tls_verify

    return loader(
        schema_uri,
        validate_schema=validate_schema,
        skip_deprecated_operations=skip_deprecated_operations,
        force_schema_version=force_schema_version,
        **loader_options,
    )

def from_schema(
    schema: BaseSchema,
    *,
    checks: Iterable[CheckFunction] = DEFAULT_CHECKS,
    max_response_time: Optional[int] = None,
    targets: Iterable[Target] = DEFAULT_TARGETS,
    workers_num: int = 1,
    hypothesis_settings: Optional[hypothesis.settings] = None,
    auth: Optional[RawAuth] = None,
    auth_type: Optional[str] = None,
    headers: Optional[Dict[str, Any]] = None,
    request_timeout: Optional[int] = None,
    request_tls_verify: Union[bool, str] = True,
    seed: Optional[int] = None,
    exit_first: bool = False,
    dry_run: bool = False,
    store_interactions: bool = False,
    stateful: Optional[Stateful] = None,
    stateful_recursion_limit: int = DEFAULT_STATEFUL_RECURSION_LIMIT,
    count_operations: bool = True,
) -> BaseRunner:
    hypothesis_settings = hypothesis_settings or hypothesis.settings(deadline=DEFAULT_DEADLINE)
    if workers_num > 1:
        if not schema.app:
            return ThreadPoolRunner(
                schema=schema,
                checks=checks,
                max_response_time=max_response_time,
                targets=targets,
                hypothesis_settings=hypothesis_settings,
                auth=auth,
                auth_type=auth_type,
                headers=headers,
                seed=seed,
                workers_num=workers_num,
                request_timeout=request_timeout,
                request_tls_verify=request_tls_verify,
                exit_first=exit_first,
                dry_run=dry_run,
                store_interactions=store_interactions,
                stateful=stateful,
                stateful_recursion_limit=stateful_recursion_limit,
                count_operations=count_operations,
            )
        if isinstance(schema.app, Starlette):
            return ThreadPoolASGIRunner(
                schema=schema,
                checks=checks,
                max_response_time=max_response_time,
                targets=targets,
                hypothesis_settings=hypothesis_settings,
                auth=auth,
                auth_type=auth_type,
                headers=headers,
                seed=seed,
                exit_first=exit_first,
                dry_run=dry_run,
                store_interactions=store_interactions,
                stateful=stateful,
                stateful_recursion_limit=stateful_recursion_limit,
                count_operations=count_operations,
            )
        return ThreadPoolWSGIRunner(
            schema=schema,
            checks=checks,
            max_response_time=max_response_time,
            targets=targets,
            hypothesis_settings=hypothesis_settings,
            auth=auth,
            auth_type=auth_type,
            headers=headers,
            seed=seed,
            workers_num=workers_num,
            exit_first=exit_first,
            dry_run=dry_run,
            store_interactions=store_interactions,
            stateful=stateful,
            stateful_recursion_limit=stateful_recursion_limit,
            count_operations=count_operations,
        )
    if not schema.app:
        return SingleThreadRunner(
            schema=schema,
            checks=checks,
            max_response_time=max_response_time,
            targets=targets,
            hypothesis_settings=hypothesis_settings,
            auth=auth,
            auth_type=auth_type,
            headers=headers,
            seed=seed,
            request_timeout=request_timeout,
            request_tls_verify=request_tls_verify,
            exit_first=exit_first,
            dry_run=dry_run,
            store_interactions=store_interactions,
            stateful=stateful,
            stateful_recursion_limit=stateful_recursion_limit,
            count_operations=count_operations,
        )
    if isinstance(schema.app, Starlette):
        return SingleThreadASGIRunner(
            schema=schema,
            checks=checks,
            max_response_time=max_response_time,
            targets=targets,
            hypothesis_settings=hypothesis_settings,
            auth=auth,
            auth_type=auth_type,
            headers=headers,
            seed=seed,
            exit_first=exit_first,
            dry_run=dry_run,
            store_interactions=store_interactions,
            stateful=stateful,
            stateful_recursion_limit=stateful_recursion_limit,
            count_operations=count_operations,
        )
    return SingleThreadWSGIRunner(
        schema=schema,
        checks=checks,
        max_response_time=max_response_time,
        targets=targets,
        hypothesis_settings=hypothesis_settings,
        auth=auth,
        auth_type=auth_type,
        headers=headers,
        seed=seed,
        exit_first=exit_first,
        dry_run=dry_run,
        store_interactions=store_interactions,
        stateful=stateful,
        stateful_recursion_limit=stateful_recursion_limit,
        count_operations=count_operations,
    )

def prepare_hypothesis_settings(
    deadline: Optional[Union[int, NotSet]] = None,
    derandomize: Optional[bool] = None,
    max_examples: Optional[int] = None,
    phases: Optional[List[hypothesis.Phase]] = None,
    report_multiple_bugs: Optional[bool] = None,
    suppress_health_check: Optional[List[hypothesis.HealthCheck]] = None,
    verbosity: Optional[hypothesis.Verbosity] = None,
) -> hypothesis.settings:
    kwargs = dict_not_none_values(
        derandomize=derandomize,
        max_examples=max_examples,
        phases=phases,
        report_multiple_bugs=report_multiple_bugs,
        suppress_health_check=suppress_health_check,
        verbosity=verbosity,
    )
    # `deadline` is special, since Hypothesis allows passing `None`
    if deadline is not None:
        if isinstance(deadline, NotSet):
            kwargs["deadline"] = None
        else:
            kwargs["deadline"] = deadline
    kwargs.setdefault("deadline", DEFAULT_DEADLINE)
    retu


# | Linux异常进程专杀
# | Author: hwliang <example@nnthink.com>

#使用示例：
#    1、将此文件重命名为btkill.py , 然后上传到服务器/root目录
#    2、执行 python /root/btkill.py

import psutil,time,os

class btkill:
    __limit = 10;   #Cpu使用率触发上限
    __vmsize = 1048576/4;  #虚拟内存触发上限(字节)

    def checkMain(self):
        pids = psutil.pids()
        num = 0;
        for pid in pids:
            try:
                p = psutil.Process(pid);
                if p.exe() == "": continue;
                name = p.name()
                if self.whiteList(name): continue;
                cputimes = p.cpu_times()
                if cputimes.user < 0.1: continue;
                percent = p.cpu_percent(interval = 0.1);
                vm = p.memory_info().vms
                if percent > self.__limit or vm > self.__vmsize:
                    log = time.strftime('%Y-%m-%d %X',time.localtime()) + "  (PID=" + str(pid) + ", NAME=" + name + ", VMS=" + str(vm) + ", PERCENT=" + str(percent) + "%)";
                    p.kill();
                    num += 1
                    print log + " >> killed\n";
            except Exception as ex:print str(ex)
        return num

    #检查白名单

wlist = ['yum','apt-get','apt','redis-cli','memcached','sshd','vm','vim','htop','top','sh','bash','zip','gzip','rsync',
                 'tar','unzip','php','composer','pkill','mongo','mongod','php-fpm','nginx','httpd','lsof','ps','redis-server',
                 'mysqld','mysqld_safe','mysql','pure-ftpd','sparse_dd','stunnel','squeezed','vncterm','awk','ruby','postgres',
                 'mpathalert','vncterm','multipathd','fe','elasticsyslog','syslogd','v6d','xapi','screen','runsvdir','svlogd',
                 'java','udevd','ntpd','irqbalance','qmgr','wpa_supplicant','mysqld_safe','sftp-server','lvmetad','gitlab-web',
                 'pure-ftpd','auditd','master','dbus-daemon','tapdisk','sshd','init','ksoftirqd','kworker','kmpathd',
                 'kmpath_handlerd','python','kdmflush','bioset','crond','kthreadd','migration','rcu_sched','kjournald',
                 'gcc','gcc++','nginx','mysqld','php-cgi','login','firewalld','iptables','systemd','network','dhclient',
                 'systemd-journald','NetworkManager','systemd-logind','systemd-udevd','polkitd','tuned','rsyslogd','AliYunDunUpdate','AliYunDun','sendmail']
        wslist = ['vif','qemu','scsi_eh','xcp','xen','docker','yunsuo','aliyun','PM2']

        for key in wlist:
            if key == name: return True

        for key in wslist:
            if name.find(key) != -1: return True

        return False

    #开始处理
    def start(self):
        num = 0;
        while True:
            num += self.checkMain();
            time.sleep(3);
        print '======================================='
        print "查杀完成, 共查杀["+str(num)+"]个异常进程!"
        print "官网: http://example.com"

if __name__ == "__main__":
    print "正在检测异常进程..."
    print '======================================='
    c = btkill();
    c.start();


num = 0;
        while True:
            num += self.checkMain();
            time.sleep(3);
        print '======================================='
        print "查杀完成, 共查杀["+str(num)+"]个异常进程!"
        print "官网: http://example.com"

# | Linux异常进程专杀
# | Author: hwliang <example@nnthink.com>

#使用示例：
#    1、将此文件重命名为btkill.py , 然后上传到服务器/root目录
#    2、执行 python /root/btkill.py

import psutil,time,os

class btkill:
    __limit = 10;   #Cpu使用率触发上限
    __vmsize = 1048576/4;  #虚拟内存触发上限(字节)

    def checkMain(self):
        pids = psutil.pids()
        num = 0;
        for pid in pids:
            try:
                p = psutil.Process(pid);
                if p.exe() == "": continue;
                name = p.name()
                if self.whiteList(name): continue;
                cputimes = p.cpu_times()
                if cputimes.user < 0.1: continue;
                percent = p.cpu_percent(interval = 0.1);
                vm = p.memory_info().vms
                if percent > self.__limit or vm > self.__vmsize:
                    log = time.strftime('%Y-%m-%d %X',time.localtime()) + "  (PID=" + str(pid) + ", NAME=" + name + ", VMS=" + str(vm) + ", PERCENT=" + str(percent) + "%)";
                    p.kill();
                    num += 1
                    print log + " >> killed\n";
            except Exception as ex:print str(ex)
        return num

    #检查白名单
    def whiteList(self,name):
        wlist = ['yum','apt-get','apt','redis-cli','memcached','sshd','vm','vim','htop','top','sh','bash','zip','gzip','rsync',
                 'tar','unzip','php','composer','pkill','mongo','mongod','php-fpm','nginx','httpd','lsof','ps','redis-server',
                 'mysqld','mysqld_safe','mysql','pure-ftpd','sparse_dd','stunnel','squeezed','vncterm','awk','ruby','postgres',
                 'mpathalert','vncterm','multipathd','fe','elasticsyslog','syslogd','v6d','xapi','screen','runsvdir','svlogd',
                 'java','udevd','ntpd','irqbalance','qmgr','wpa_supplicant','mysqld_safe','sftp-server','lvmetad','gitlab-web',
                 'pure-ftpd','auditd','master','dbus-daemon','tapdisk','sshd','init','ksoftirqd','kworker','kmpathd',
                 'kmpath_handlerd','python','kdmflush','bioset','crond','kthreadd','migration','rcu_sched','kjournald',
                 'gcc','gcc++','nginx','mysqld','php-cgi','login','firewalld','iptables','systemd','network','dhclient',
                 'systemd-journald','NetworkManager','systemd-logind','systemd-udevd','polkitd','tuned','rsyslogd','AliYunDunUpdate','AliYunDun','sendmail']
        wslist = ['vif','qemu','scsi_eh','xcp','xen','docker','yunsuo','aliyun','PM2']

        for key in wlist:
            if key == name: return True

        for key in wslist:
            if name.find(key) != -1: return True

        return False

    #开始处理
    def start(self):


# | Linux异常进程专杀
# | Author: hwliang <example@nnthink.com>

#使用示例：
#    1、将此文件重命名为btkill.py , 然后上传到服务器/root目录
#    2、执行 python /root/btkill.py

import psutil,time,os

class btkill:
    __limit = 10;   #Cpu使用率触发上限
    __vmsize = 1048576/4;  #虚拟内存触发上限(字节)

    def checkMain(self):
        pids = psutil.p

        num = 0;
        for pid in pids:
            try:
                p = psutil.Process(pid);
                if p.exe() == "": continue;
                name = p.name()
                if self.whiteList(name): continue;
                cputimes = p.cpu_times()
                if cputimes.user < 0.1: continue;
                percent = p.cpu_percent(interval = 0.1);
                vm = p.memory_info().vms
                if percent > self.__limit or vm > self.__vmsize:
                    log = time.strftime('%Y-%m-%d %X',time.localtime()) + "  (PID=" + str(pid) + ", NAME=" + name + ", VMS=" + str(vm) + ", PERCENT=" + str(percent) + "%)";
                    p.kill();
                    num += 1
                    print log + " >> killed\n";
            except Exception as ex:print str(ex)
        return num

    #检查白名单
    def whiteList(self,name):
        wlist = ['yum','apt-get','apt','redis-cli','memcached','sshd','vm','vim','htop','top','sh','bash','zip','gzip','rsync',
                 'tar','unzip','php','composer','pkill','mongo','mongod','php-fpm','nginx','httpd','lsof','ps','redis-server',
                 'mysqld','mysqld_safe','mysql','pure-ftpd','sparse_dd','stunnel','squeezed','vncterm','awk','ruby','postgres',
                 'mpathalert','vncterm','multipathd','fe','elasticsyslog','syslogd','v6d','xapi','screen','runsvdir','svlogd',
                 'java','udevd','ntpd','irqbalance','qmgr','wpa_supplicant','mysqld_safe','sftp-server','lvmetad','gitlab-web',
                 'pure-ftpd','auditd','master','dbus-daemon','tapdisk','sshd','init','ksoftirqd','kworker','kmpathd',
                 'kmpath_handlerd','python','kdmflush','bioset','crond','kthreadd','migration','rcu_sched','kjournald',
                 'gcc','gcc++','nginx','mysqld','php-cgi','login','firewalld','iptables','systemd','network','dhclient',
                 'systemd-journald','NetworkManager','systemd-logind','systemd-udevd','polkitd','tuned','rsyslogd','AliYunDunUpdate','AliYunDun','sendmail']
        wslist = ['vif','qemu','scsi_eh','xcp','xen','docker','yunsuo','aliyun','PM2']

        for key in wlist:
            if key == name: return True

        for key in wslist:
            if name.find(key) != -1: return True

        return False

    #开始处理
    def start(self):
        num = 0;
        while True:
            num += self.checkMain();
            time.sleep(3);
        print '======================================='
        print "查杀完成, 共查杀["+str(num)+"]个异常进程!"
        print "官网: http://example.com"

if __name__ == "__main__":
    print "正在检测异常进程..."
    print '======================================='
    c = btkill();
    c.start();


for key in wslist:
            if name.find(key) != -1: return True

# | Linux异常进程专杀
# | Author: hwliang <example@nnthink.com>

#使用示例：
#    1、将此文件重命名为btkill.py , 然后上传到服务器/root目录
#    2、执行 python /root/btkill.py

import psutil,time,os

class btkill:
    __limit = 10;   #Cpu使用率触发上限
    __vmsize = 1048576/4;  #虚拟内存触发上限(字节)

    def checkMain(self):
        pids = psutil.pids()
        num = 0;
        for pid in pids:
            try:
                p = psutil.Process(pid);
                if p.exe() == "": continue;
                name = p.name()
                if self.whiteList(name): continue;
                cputimes = p.cpu_times()
                if cputimes.user < 0.1: continue;
                percent = p.cpu_percent(interval = 0.1);
                vm = p.memory_info().vms
                if percent > self.__limit or vm > self.__vmsize:
                    log = time.strftime('%Y-%m-%d %X',time.localtime()) + "  (PID=" + str(pid) + ", NAME=" + name + ", VMS=" + str(vm) + ", PERCENT=" + str(percent) + "%)";
                    p.kill();
                    num += 1
                    print log + " >> killed\n";
            except Exception as ex:print str(ex)
        return num

    #检查白名单
    def whiteList(self,name):
        wlist = ['yum','apt-get','apt','redis-cli','memcached','sshd','vm','vim','htop','top','sh','bash','zip','gzip','rsync',
                 'tar','unzip','php','composer','pkill','mongo','mongod','php-fpm','nginx','httpd','lsof','ps','redis-server',
                 'mysqld','mysqld_safe','mysql','pure-ftpd','sparse_dd','stunnel','squeezed','vncterm','awk','ruby','postgres',
                 'mpathalert','vncterm','multipathd','fe','elasticsyslog','syslogd','v6d','xapi','screen','runsvdir','svlogd',
                 'java','udevd','ntpd','irqbalance','qmgr','wpa_supplicant','mysqld_safe','sftp-server','lvmetad','gitlab-web',
                 'pure-ftpd','auditd','master','dbus-daemon','tapdisk','sshd','init','ksoftirqd','kworker','kmpathd',
                 'kmpath_handlerd','python','kdmflush','bioset','crond','kthreadd','migration','rcu_sched','kjournald',
                 'gcc','gcc++','nginx','mysqld','php-cgi','login','firewalld','iptables','systemd','network','dhclient',
                 'systemd-journald','NetworkManager','systemd-logind','systemd-udevd','polkitd','tuned','rsyslogd','AliYunDunUpdate','AliYunDun','sendmail']
        wslist = ['vif','qemu','scsi_eh','xcp','xen','docker','yunsuo','aliyun','PM2']

        for key in wlist:
            if key == name: return True

        return False

    #开始处理
    def start(self):
        num = 0;
        while True:
            num += self.checkMain();
            time.sleep(3);
        print '======================================='
        print "查杀完成, 共查杀["+str(num)+"]个异常进程!"
        print "官网: http://example.com"

if __name__ == "__main__":
    print "正在检测异常进程..."
    print '======================================='
    c = btkill();
    c.start();


while True:
            num += self.checkMain();
            time.sleep(3);

# | Linux异常进程专杀
# | Author: hwliang <example@nnthink.com>

#使用示例：
#    1、将此文件重命名为btkill.py , 然后上传到服务器/root目录
#    2、执行 python /root/btkill.py

import psutil,time,os

class btkill:
    __limit = 10;   #Cpu使用率触发上限
    __vmsize = 1048576/4;  #虚拟内存触发上限(字节)

    def checkMain(self):
        pids = psutil.pids()
        num = 0;
        for pid in pids:
            try:
                p = psutil.Process(pid);
                if p.exe() == "": continue;
                name = p.name()
                if self.whiteList(name): continue;
                cputimes = p.cpu_times()
                if cputimes.user < 0.1: continue;
                percent = p.cpu_percent(interval = 0.1);
                vm = p.memory_info().vms
                if percent > self.__limit or vm > self.__vmsize:
                    log = time.strftime('%Y-%m-%d %X',time.localtime()) + "  (PID=" + str(pid) + ", NAME=" + name + ", VMS=" + str(vm) + ", PERCENT=" + str(percent) + "%)";
                    p.kill();
                    num += 1
                    print log + " >> killed\n";
            except Exception as ex:print str(ex)
        return num

    #检查白名单
    def whiteList(self,name):
        wlist = ['yum','apt-get','apt','redis-cli','memcached','sshd','vm','vim','htop','top','sh','bash','zip','gzip','rsync',
                 'tar','unzip','php','composer','pkill','mongo','mongod','php-fpm','nginx','httpd','lsof','ps','redis-server',
                 'mysqld','mysqld_safe','mysql','pure-ftpd','sparse_dd','stunnel','squeezed','vncterm','awk','ruby','postgres',
                 'mpathalert','vncterm','multipathd','fe','elasticsyslog','syslogd','v6d','xapi','screen','runsvdir','svlogd',
                 'java','udevd','ntpd','irqbalance','qmgr','wpa_supplicant','mysqld_safe','sftp-server','lvmetad','gitlab-web',
                 'pure-ftpd','auditd','master','dbus-daemon','tapdisk','sshd','init','ksoftirqd','kworker','kmpathd',
                 'kmpath_handlerd','python','kdmflush','bioset','crond','kthreadd','migration','rcu_sched','kjournald',
                 'gcc','gcc++','nginx','mysqld','php-cgi','login','firewalld','iptables','systemd','network','dhclient',
                 'systemd-journald','NetworkManager','systemd-logind','systemd-udevd','polkitd','tuned','rsyslogd','AliYunDunUpdate','AliYunDun','sendmail']
        wslist = ['vif','qemu','scsi_eh','xcp','xen','docker','yunsuo','aliyun','PM2']

        for key in wlist:
            if key == name: return True

        for key in wslist:
            if name.find(key) != -1: return True

        return False

    #开始处理
    def start(self):
        num = 0;


import argparse
import logging

from dotenv import load_dotenv

from dmake.errors import *  # noqa
from dmake import utils
from dmake import template_args
import dmake.build

LOG = logging.getLogger(__name__)

def argparser():
    parser = argparse.ArgumentParser(description="build docker images"
                                     " in a simpler way.")
    parser.add_argument('builds', type=str, nargs='*',
                        help='builds to execute.')
    parser.add_argument('-f', '--file', dest='dmakefile',
                        default='.docker-make.yml',
                        help='path to docker-make configuration file.')
    parser.add_argument('-d', '--detailed', default=False,
                        action='store_true', help='print out detailed logs')
    parser.add_argument('-rm', '--remove', default=False,
                        action='store_true',
                        help='remove intermediate containers')
    parser.add_argument('--dry-run', dest='dryrun', action='store_true',
                        default=False, help='print docker commands only')
    parser.add_argument('--no-push', dest='nopush', action='store_true',
                        default=False, help='build only, dont push images.')
    return parser

def _main():
    global LOG

    parser = argparser()
    args = parser.parse_args()

    log_format = '%(levelname)s %(name)s(%(lineno)s) %(asctime)s %(message)s'
    log_level = logging.DEBUG if args.detailed else logging.INFO
    logging.basicConfig(format=log_format, level=log_level)
    LOG = logging.getLogger("docker-make")

    load_dotenv()

    try:
        template_args.init_tag_names(args.dmakefile)
        builds_order, builds_dict = utils.get_sorted_build_dicts_from_yaml(
            args.dmakefile)
    except ConfigurationError as e:
        LOG.error("failed to parse %s: %s", args.dmakefile, e.message)
        return 1
    except ValidateError as e:
        LOG.error("wrong configuration: %s", e.message)
        return 1
    except DmakeError as e:
        LOG.eror(e.message)
        return 1

    builds = {}
    for name in builds_order:
        if (args.remove):
            builds_dict[name]['remove_intermediate'] = args.remove
        builds[name] = dmake.build.Build(name=name, **builds_dict[name])

    if args.builds:
        try:
            wants = utils.expand_wants(builds, args.builds)
        except BuildUnDefined as e:
            LOG.error("No such build:  %s", e.build)
            return 1
    else:
        wants = set(builds_order)

    if args.dryrun:
        for name in builds_order:
            if name not in wants:
                continue
            build = builds[name]
            build.dryrun()
        return

    for name in builds_order:
        if name not in wants:
            continue
        build = builds[name]
        if build.rewrite_from:
            build.rewrite_from = builds[build.rewrite_from].non_labeled_image
        try:
            build.build()
            build.tag()
        except BuildFailed as e:
            LOG.error("failed to build %s: %s", build.name, e.message)
            return 1
        except Exception:
            LOG.exception("failed to build %s", build.name)
            return 1

        if not args.nopush:
            try:
                build.push()
            except PushFailed as e:
                LOG.error("failed to push %s: %s", build.name, e.message)
                return 1
            except Exception as e:
                LOG.exception("failed to push %s", build.name)
                return 1

try:
        return _main()
    finally:
        utils.GarbageCleaner.clean_all()


try:
        return _main()
    finally:
        utils.GarbageCleaner.clean_all()

import argparse
import logging

from dotenv import load_dotenv

from dmake.errors import *  # noqa
from dmake import utils
from dmake import template_args
import dmake.build

LOG = logging.getLogger(__name__)

def argparser():
    parser = argparse.ArgumentParser(description="build docker images"
                                     " in a simpler way.")
    parser.add_argument('builds', type=str, nargs='*',
                        help='builds to execute.')
    parser.add_argument('-f', '--file', dest='dmakefile',
                        default='.docker-make.yml',
                        help='path to docker-make configuration file.')
    parser.add_argument('-d', '--detailed', default=False,
                        action='store_true', help='print out detailed logs')
    parser.add_argument('-rm', '--remove', default=False,
                        action='store_true',
                        help='remove intermediate containers')
    parser.add_argument('--dry-run', dest='dryrun', action='store_true',
                        default=False, help='print docker commands only')
    parser.add_argument('--no-push', dest='nopush', action='store_true',
                        default=False, help='build only, dont push images.')
    return parser

def _main():
    global LOG

    parser = argparser()
    args = parser.parse_args()

    log_format = '%(levelname)s %(name)s(%(lineno)s) %(asctime)s %(message)s'
    log_level = logging.DEBUG if args.detailed else logging.INFO
    logging.basicConfig(format=log_format, level=log_level)
    LOG = logging.getLogger("docker-make")

    load_dotenv()

    try:
        template_args.init_tag_names(args.dmakefile)
        builds_order, builds_dict = utils.get_sorted_build_dicts_from_yaml(
            args.dmakefile)
    except ConfigurationError as e:
        LOG.error("failed to parse %s: %s", args.dmakefile, e.message)
        return 1
    except ValidateError as e:
        LOG.error("wrong configuration: %s", e.message)
        return 1
    except DmakeError as e:
        LOG.eror(e.message)
        return 1

    builds = {}
    for name in builds_order:
        if (args.remove):
            builds_dict[name]['remove_intermediate'] = args.remove
        builds[name] = dmake.build.Build(name=name, **builds_dict[name])

    if args.builds:
        try:
            wants = utils.expand_wants(builds, args.builds)
        except BuildUnDefined as e:
            LOG.error("No such build:  %s", e.build)
            return 1
    else:
        wants = set(builds_order)

    if args.dryrun:
        for name in builds_order:
            if name not in wants:
                continue
            build = builds[name]
            build.dryrun()
        return

    for name in builds_order:
        if name not in wants:
            continue
        build = builds[name]
        if build.rewrite_from:
            build.rewrite_from = builds[build.rewrite_from].non_labeled_image
        try:
            build.build()
            build.tag()
        except BuildFailed as e:
            LOG.error("failed to build %s: %s", build.name, e.message)
            return 1
        except Exception:
            LOG.exception("failed to build %s", build.name)
            return 1

        if not args.nopush:
            try:
                build.push()
            except PushFailed as e:
                LOG.error("failed to push %s: %s", build.name, e.message)
                return 1
            except Exception as e:
                LOG.exception("failed to push %s", build.name)
                return 1

def main():


import argparse
import logging

from dotenv import load_dotenv

from dmake.errors import *  # noqa
from dmake import utils
from dmake import template_args
import dmake.build

LOG = logging.getLogger(__name__)

def argparser():
    parser = argparse.ArgumentParser(description="build docker images"
                                     " in a simpler way.")
    parser.add_argument('builds', type=str, nargs='*',
                        help='builds to execute.')
    parser.add_argument('-f', '--file', dest='dmakefile',
                        default='.docker-make.yml',
                        help='path to docker-make configuration file.')
    parser.add_argument('-d', '--detailed', default=False,
                        action='store_true', help='print out detailed logs')
    parser.add_argument('-rm', '--remove', default=False,
                        action='store_true',
                        help='remove intermediate containers')
    parser.add_argument('--dry-run', dest='dryrun', action='store_true',
                        default=False, help='print docker commands only')
    parser.add_argument('--no-push', dest='nopush', action='store_true',
                        default=False, help='build only, dont push images.')
    return parser

def _main():
    global LOG

    parser = argparser()
    args = parser.parse_args()

    log_format = '%(levelname)s %(name)s(%(lineno)s) %(asctime)s %(message)s'
    log_level = logging.DEBUG if args.detailed else logging.INFO
    logging.basicConfig(format=log_format, level=log_level)
    LOG = logging.getLogger("docker-m

    load_dotenv()

    try:
        template_args.init_tag_names(args.dmakefile)
        builds_order, builds_dict = utils.get_sorted_build_dicts_from_yaml(
            args.dmakefile)
    except ConfigurationError as e:
        LOG.error("failed to parse %s: %s", args.dmakefile, e.message)
        return 1
    except ValidateError as e:
        LOG.error("wrong configuration: %s", e.message)
        return 1
    except DmakeError as e:
        LOG.eror(e.message)
        return 1

    builds = {}
    for name in builds_order:
        if (args.remove):
            builds_dict[name]['remove_intermediate'] = args.remove
        builds[name] = dmake.build.Build(name=name, **builds_dict[name])

    if args.builds:
        try:
            wants = utils.expand_wants(builds, args.builds)
        except BuildUnDefined as e:
            LOG.error("No such build:  %s", e.build)
            return 1
    else:
        wants = set(builds_order)

    if args.dryrun:
        for name in builds_order:
            if name not in wants:
                continue
            build = builds[name]
            build.dryrun()
        return

    for name in builds_order:
        if name not in wants:
            continue
        build = builds[name]
        if build.rewrite_from:
            build.rewrite_from = builds[build.rewrite_from].non_labeled_image
        try:
            build.build()
            build.tag()
        except BuildFailed as e:
            LOG.error("failed to build %s: %s", build.name, e.message)
            return 1
        except Exception:
            LOG.exception("failed to build %s", build.name)
            return 1

        if not args.nopush:
            try:
                build.push()
            except PushFailed as e:
                LOG.error("failed to push %s: %s", build.name, e.message)
                return 1
            except Exception as e:
                LOG.exception("failed to push %s", build.name)
                return 1

def main():
    try:
        return _main()
    finally:
        utils.GarbageCleaner.clean_all()


for name in builds_order:
            if name not in wants:
                continue
            build = builds[name]
            build.dryrun()

import argparse
import logging

from dotenv import load_dotenv

from dmake.errors import *  # noqa
from dmake import utils
from dmake import template_args
import dmake.build

LOG = logging.getLogger(__name__)

def argparser():
    parser = argparse.ArgumentParser(description="build docker images"
                                     " in a simpler way.")
    parser.add_argument('builds', type=str, nargs='*',
                        help='builds to execute.')
    parser.add_argument('-f', '--file', dest='dmakefile',
                        default='.docker-make.yml',
                        help='path to docker-make configuration file.')
    parser.add_argument('-d', '--detailed', default=False,
                        action='store_true', help='print out detailed logs')
    parser.add_argument('-rm', '--remove', default=False,
                        action='store_true',
                        help='remove intermediate containers')
    parser.add_argument('--dry-run', dest='dryrun', action='store_true',
                        default=False, help='print docker commands only')
    parser.add_argument('--no-push', dest='nopush', action='store_true',
                        default=False, help='build only, dont push images.')
    return parser

def _main():
    global LOG

    parser = argparser()
    args = parser.parse_args()

    log_format = '%(levelname)s %(name)s(%(lineno)s) %(asctime)s %(message)s'
    log_level = logging.DEBUG if args.detailed else logging.INFO
    logging.basicConfig(format=log_format, level=log_level)
    LOG = logging.getLogger("docker-make")

    load_dotenv()

    try:
        template_args.init_tag_names(args.dmakefile)
        builds_order, builds_dict = utils.get_sorted_build_dicts_from_yaml(
            args.dmakefile)
    except ConfigurationError as e:
        LOG.error("failed to parse %s: %s", args.dmakefile, e.message)
        return 1
    except ValidateError as e:
        LOG.error("wrong configuration: %s", e.message)
        return 1
    except DmakeError as e:
        LOG.eror(e.message)
        return 1

    builds = {}
    for name in builds_order:
        if (args.remove):
            builds_dict[name]['remove_intermediate'] = args.remove
        builds[name] = dmake.build.Build(name=name, **builds_dict[name])

    if args.builds:
        try:
            wants = utils.expand_wants(builds, args.builds)
        except BuildUnDefined as e:
            LOG.error("No such build:  %s", e.build)
            return 1
    else:
        wants = set(builds_order)

    if args.dryrun:

        return

    for name in builds_order:
        if name not in wants:
            continue
        build = builds[name]
        if build.rewrite_from:
            build.rewrite_from = builds[build.rewrite_from].non_labeled_image
        try:
            build.build()
            build.tag()
        except BuildFailed as e:
            LOG.error("failed to build %s: %s", build.name, e.message)
            return 1
        except Exception:
            LOG.exception("failed to build %s", build.name)
            return 1

        if not args.nopush:
            try:
                build.push()
            except PushFailed as e:
                LOG.error("failed to push %s: %s", build.name, e.message)
                return 1
            except Exception as e:
                LOG.exception("failed to push %s", build.name)
                return 1

def main():
    try:
        return _main()
    finally:
        utils.GarbageCleaner.clean_all()


try:
        template_args.init_tag_names(args.dmakefile)
        builds_order, builds_dict = utils.get_sorted_build_dicts_from_yaml(
            args.dmakefile)
    except ConfigurationError as e:
        LOG.error("failed to parse %s: %s", args.dmakefile, e.message)
        return 1
    except ValidateError as e:
        LOG.error("wrong configuration: %s", e.message)
        return 1
    except DmakeError as e:
        LOG.eror(e.message)
        return 1

import argparse
import logging

from dotenv import load_dotenv

from dmake.errors import *  # noqa
from dmake import utils
from dmake import template_args
import dmake.build

LOG = logging.getLogger(__name__)

def argparser():
    parser = argparse.ArgumentParser(description="build docker images"
                                     " in a simpler way.")
    parser.add_argument('builds', type=str, nargs='*',
                        help='builds to execute.')
    parser.add_argument('-f', '--file', dest='dmakefile',
                        default='.docker-make.yml',
                        help='path to docker-make configuration file.')
    parser.add_argument('-d', '--detailed', default=False,
                        action='store_true', help='print out detailed logs')
    parser.add_argument('-rm', '--remove', default=False,
                        action='store_true',
                        help='remove intermediate containers')
    parser.add_argument('--dry-run', dest='dryrun', action='store_true',
                        default=False, help='print docker commands only')
    parser.add_argument('--no-push', dest='nopush', action='store_true',
                        default=False, help='build only, dont push images.')
    return parser

def _main():
    global LOG

    parser = argparser()
    args = parser.parse_args()

    log_format = '%(levelname)s %(name)s(%(lineno)s) %(asctime)s %(message)s'
    log_level = logging.DEBUG if args.detailed else logging.INFO
    logging.basicConfig(format=log_format, level=log_level)
    LOG = logging.getLogger("docker-make")

    load_dotenv()

    builds = {}
    for name in builds_order:
        if (args.remove):
            builds_dict[name]['remove_intermediate'] = args.remove
        builds[name] = dmake.build.Build(name=name, **builds_dict[name])

    if args.builds:
        try:
            wants = utils.expand_wants(builds, args.builds)
        except BuildUnDefined as e:
            LOG.error("No such build:  %s", e.build)
            return 1
    else:
        wants = set(builds_order)

    if args.dryrun:
        for name in builds_order:
            if name not in wants:
                continue
            build = builds[name]
            build.dryrun()
        return

    for name in builds_order:
        if name not in wants:
            continue
        build = builds[name]
        if build.rewrite_from:
            build.rewrite_from = builds[build.rewrite_from].non_labeled_image
        try:
            build.build()
            build.tag()
        except BuildFailed as e:
            LOG.error("failed to build %s: %s", build.name, e.message)
            return 1
        except Exception:
            LOG.exception("failed to build %s", build.name)
            return 1

        if not args.nopush:
            try:
                build.push()
            except PushFailed as e:
                LOG.error("failed to push %s: %s", build.name, e.message)
                return 1
            except Exception as e:
                LOG.exception("failed to push %s", build.name)
                return 1

def main():
    try:
        return _main()
    finally:
        utils.GarbageCleaner.clean_all()


sample = 0b010001111010110 ^ 0b000001111111111  # flip all error correction bits
        self.assertRaises(QrCorruptError, validate_format_info, sample)

from qreader.exceptions import QrCorruptError
from qreader.validation import validate_format_info, format_info_check
from tests.helpers import TestCase

__author__ = 'ewino'

class TestFormatInfoValidation(TestCase):
    def test_valid_format_info(self):
        samples = [
            0b010001111010110,  # L0
            0b011001000111101,  # L4
            0b000111101011001,  # M3
            0b001101110000101,  # M6
            0b110101100100011,  # Q2
            0b111010110010001,  # Q5
            0b100011110101100,  # H1
            0b101110000101001,  # H7
        ]
        for sample in samples:
            self.assertEqual(0, format_info_check(sample))

    def test_invalid_format_info(self):
        single_bit_error = [
            0b010011111010110,  # L0
            0b011001010111101,  # L4
            0b000111001011001,  # M3
            0b001100110000101,  # M6
        ]
        double_bit_error = [
            0b110101101000011,  # Q2
            0b111110110011001,  # Q5
            0b101011110001100,  # H1
            0b111110000111001,  # H7
        ]
        triple_bit_error = [
            0b110101101000010,  # Q2
            0b111110110011000,  # Q5
            0b101011110001101,  # H1
            0b111110000111000,  # H7
        ]

        for sample in single_bit_error + double_bit_error + triple_bit_error:
            self.assertNotEqual(0, format_info_check(sample))

class TestFormatInfoErrorCorrection(TestCase):
    def test_validate_format_info(self):
        samples = [
            0b010001111010110,  # L0
            0b011001000111101,  # L4
            0b000111101011001,  # M3
            0b001101110000101,  # M6
            0b110101100100011,  # Q2
            0b111010110010001,  # Q5
            0b100011110101100,  # H1
            0b101110000101001,  # H7
        ]

        for sample in samples:
            self.assertEqual(sample >> 10, validate_format_info(sample))

    def test_validate_erroneous_format_info(self):
        single_bit_error = [
            (0b010011111010110, 0b01000),  # L0
            (0b011001010111101, 0b01100),  # L4
            (0b000111001011001, 0b00011),  # M3
            (0b001100110000101, 0b00110),  # M6
        ]
        double_bit_error = [
            (0b110101101000011, 0b11010),  # Q2
            (0b111110110011001, 0b11101),  # Q5
            (0b101011110001100, 0b10001),  # H1
            (0b111110000111001, 0b10111),  # H7
        ]
        triple_bit_error = [
            (0b110101101000010, 0b11010),  # Q2
            (0b111110110011000, 0b11101),  # Q5
            (0b101011110001101, 0b10001),  # H1
            (0b111110000111000, 0b10111),  # H7
        ]

        for sample, correct in single_bit_error + double_bit_error + triple_bit_error:
            self.assertEqual(correct, validate_format_info(sample))

    def test_completely_wrong_format_info(self):
        samples = [
            0b010001111010110,  # L0
            0b011001000111101,  # L4
            0b000111101011001,  # M3
            0b001101110000101,  # M6
            0b110101100100011,  # Q2
            0b111010110010001,  # Q5
            0b100011110101100,  # H1
            0b101110000101001,  # H7
        ]
        for sample in samples:
            self.assertNotEqual(sample >> 10, validate_format_info(sample ^ 0b111111000000000))

    def test_unsalvageable_format_info(self):


from qreader.exceptions import QrCorruptError
from qreader.validation import validate_format_info, format_info_check
from tests.helpers import TestCase

__author__ = 'ewino'

class TestFormatInfoValidation(TestCase):
    def test_valid_format_info(self):
        samples = [
            0b010001111010110,  # L0
            0b011001000111101,  # L4
            0b000111101011001,  # M3
            0b001101110000101,  # M6
            0b110101100100011,  # Q2
            0b111010110010001,  # Q5
            0b100011110101100,  # H1
            0b101110000101001,  # H7
        ]
        for sample in samples:
            self.assertEqual(0, format_info_check(sample))

    def test_invalid_format_info(self):
        single_bit_error = [
            0b010011111010110,  # L0
            0b011001010111101,  # L4
            0b000111001011001,  # M3
            0b001100110000101,  # M6
        ]
        double_bit_error = [
            0b110101101000011,  # Q2
            0b111110110011001,  # Q5
            0b101011110001100,  # H1
            0b111110000111001,  # H7
        ]
        triple_bit_error = [
            0b110101101000010,  # Q2
            0b111110110011000,  # Q5
            0b101011110001101,  # H1
            0b111110000111000,  # H7
        ]

        for sample in single_bit_error + double_bit_error + triple_bit_error:
            self.assertNotEqual(0, format_info_check(sample))

class TestFormatInfoErrorCorrection(TestCase):
    def test_validate_format_info(self):
        samples = [
            0b010001111010110,  # L0
            0b011001000111101,  # L4
            0b000111101011001,  # M3
            0b001101110000101,  # M6
            0b110101100100011,  # Q2
            0b111010110010001,  # Q5
            0b100011110101100,  # H1
            0b101110000101001,  # H7
        ]

        for sample in samples:
            self.assertEqual(sample >> 10, validate_format_info(sample))

    def test_validate_erroneous_format_info(self):
        single_bit_error = [
            (0b010011111010110, 0b01000),  # L0
            (0b011001010111101, 0b01100),  # L4
            (0b000111001011001, 0b00011),  # M3
            (0b001100110000101, 0b00110),  # M6
        ]
        double_bit_error = [
            (0b110101101000011, 0b11010),  # Q2
            (0b111110110011001, 0b11101),  # Q5
            (0b101011110001100, 0b10001),  # H1
            (0b111110000111001, 0b10111),  # H7
        ]
        triple_bit_error = [
            (0b110101101000010, 0b11010),  # Q2
            (0b111110110011000, 0b11101),  # Q5
            (0b101011110001101, 0b10001),  # H1
            (0b111110000111000, 0b10111),  # H7
        ]

        for sample, correct in single_bit_error + double_bit_error + triple_bit_error:
            self.assertEqual(correct, validate_format_info(sample))

    def test_completely_wrong_format_info(self):
        samples = [
            0b010001111010110,  # L0
            0b011001000111101,  # L4
            0b000111101011001,  # M3
            0b001101110000101,  # M6
            0b110101100100011,  # Q2
            0b111010110010001,  # Q5
            0b100011110101100,  # H1
            0b101110000101001,  # H7
        ]
        for sample in samples:
            self.assertNotEqual(sample >> 10, validate_format_info(sample ^ 0b111111000000000))

    def test_unsalvageable_format_info(self):
        sample = 0b0

  # flip all error correction bits
        self.assertRaises(QrCorruptError, validate_format_info, sample)

    def test_dual_formats_one_right_one_wrong(self):
        samples = [
            0b010001111010110,  # L0
            0b011001000111101,  # L4
            0b000111101011001,  # M3
            0b001101110000101,  # M6
            0b110101100100011,  # Q2
            0b111010110010001,  # Q5
            0b100011110101100,  # H1
            0b101110000101001,  # H7
        ]
        for sample in samples:
            self.assertEqual(sample >> 10, validate_format_info(sample, sample))
            self.assertEqual(sample >> 10, validate_format_info(sample ^ 0b111100000000000, sample ^ 0b000100000011101))


for sample in samples:
            self.assertEqual(0, format_info_check(sample))

from qreader.exceptions import QrCorruptError
from qreader.validation import validate_format_info, format_info_check
from tests.helpers import TestCase

__author__ = 'ewino'

class TestFormatInfoValidation(TestCase):
    def test_valid_format_info(self):
        samples = [
            0b010001111010110,  # L0
            0b011001000111101,  # L4
            0b000111101011001,  # M3
            0b001101110000101,  # M6
            0b110101100100011,  # Q2
            0b111010110010001,  # Q5
            0b100011110101100,  # H1
            0b101110000101001,  # H7
        ]


"""
A Simple program to detect the human faces using Haarcascade Classifier

Date : 21 March 2019
Author : Shiyaz T
"""

import cv2
haar_cascade_face = cv2.CascadeClassifier('/home/shiyaztech/Documents/Applications/OpenCV/opencv/data/haarcascades/haarcascade_frontalface_default.xml')

class VideoCamera(object):
    def __init__(self):
        # Using OpenCV to capture from device 0. If you have trouble capturing
        # from a webcam, comment the line below out and use a video file
        self.video = cv2.VideoCapture(0)
        self.frameWidth = int(self.video.get(cv2.CAP_PROP_FRAME_WIDTH))
        self.frameHeight = int(self.video.get(cv2.CAP_PROP_FRAME_HEIGHT))
        # If you decide to use video.mp4, you must have this file in the folder

    def __del__(self):
        self.video.release()

success, image = self.video.read()
        image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        faces_rects = haar_cascade_face.detectMultiScale(image_gray, scaleFactor=1.2, minNeighbors=5);
        # Let us print the no. of faces found

        for (x, y, w, h) in faces_rects:
            cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)

        if len(faces_rects) > 0:

            cv2.putText(img = image, text = 'Faces found:' + str(len(faces_rects)), org=(50,50), fontFace=cv2.FONT_HERSHEY_DUPLEX, fontScale=1, color=(0, 0, 255))
        # We are using Motion JPEG, but OpenCV defaults to capture raw images,
        # so we must encode it into JPEG in order to correctly display the
        # video stream.
        ret, jpeg = cv2.imencode('.jpg', image)
        return jpeg.tobytes()


"""
A Simple program to detect the human faces using Haarcascade Classifier

Date : 21 March 2019
Author : Shiyaz T
"""

import cv2
haar_cascade_face = cv2.CascadeClassifier('/home/shiyaztech/Documents/Applications/OpenCV/opencv/data/haarcascades/haarcascade_frontalface_default.xml')

class VideoCamera(object):
    def __init__(self):
        # Using OpenCV to capture from device 0. If you have trouble capturing
        # from a webcam, comment the line below out and use a video file
        self.video = cv2.VideoCapture(0)
        self.frameWidth = int(self.video.get(cv2.CAP_PROP_FRAME_WIDTH))
        self.frameHeight = int(self.video.get(cv2.CAP_PROP_FRAME_HEIGHT))
        # If you decide to use video.mp4, you must have this file in the folder

    def __del__(self):

    def get_frame(self):
        success, image = self.video.read()
        image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        faces_rects = haar_cascade_face.detectMultiScale(image_gray, scaleFactor=1.2, minNeighbors=5);
        # Let us print the no. of faces found

        for (x, y, w, h) in faces_rects:
            cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)

        if len(faces_rects) > 0:

            cv2.putText(img = image, text = 'Faces found:' + str(len(faces_rects)), org=(50,50), fontFace=cv2.FONT_HERSHEY_DUPLEX, fontScale=1, color=(0, 0, 255))
        # We are using Motion JPEG, but OpenCV defaults to capture raw images,
        # so we must encode it into JPEG in order to correctly display the
        # video stream.
        ret, jpeg = cv2.imencode('.jpg', image)
        return jpeg.tobytes()


"""
A Simple program to detect the human faces using Haarcascade Classifier

Date : 21 March 2019
Author : Shiyaz T
"""

import cv2
haar_cascade_face = cv2.CascadeClassifier('/home/shiyaztech/Documents/Applications/OpenCV/opencv/data/haarcascades/haarcascade_frontalface_default.xml')

class VideoCamera(object):
    def __init__(self):
        # Using OpenCV to capture from device 0. If you have trouble capturing
        # from a webcam, comment the line below out and use a video file
        self.video = cv2.VideoCapture(0)
        self.frameWidth = int(self.video.get(cv2.CAP_PROP_FRAME_WIDTH))
        self.frameHeight = int(self.video.get(cv2.CAP_PROP_FRAME_HEIGHT))
        # If you decide to use video.mp4, you must have this file in the folder

    def __del__(self):
        self.video.release()

    def get_frame(self):
        success, image = self.video.read()
        image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        faces_rects = haar_cascade_face.detectMultiScale(image_gray, scaleFactor=1.2, minNeighbors=5);
        # Let us print the no. of faces found

        for (x, y, w, h) in faces_rects:
            cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)

        if len(faces_rects) > 0:

            cv2.putText(img = image, text = 'Faces found:' + str(len(faces_rects)), org=(50,50), fontFace=cv2.FONT_HERSHEY_DUPLEX, fontScale=1, color=(0, 0, 255))
        # We are using Motion JPEG, but OpenCV defaults to capture raw images,
        # so we must encode it into JPEG in order to correctly display the
        # video stream.
        ret, jpeg


for (x, y, w, h) in faces_rects:
            cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)

"""
A Simple program to detect the human faces using Haarcascade Classifier

Date : 21 March 2019
Author : Shiyaz T
"""

import cv2
haar_cascade_face = cv2.CascadeClassifier('/home/shiyaztech/Documents/Applications/OpenCV/opencv/data/haarcascades/haarcascade_frontalface_default.xml')

class VideoCamera(object):
    def __init__(self):
        # Using OpenCV to capture from device 0. If you have trouble capturing
        # from a webcam, comment the line below out and use a video file
        self.video = cv2.VideoCapture(0)
        self.frameWidth = int(self.video.get(cv2.CAP_PROP_FRAME_WIDTH))
        self.frameHeight = int(self.video.get(cv2.CAP_PROP_FRAME_HEIGHT))
        # If you decide to use video.mp4, you must have this file in the folder

    def __del__(self):
        self.video.release()

    def get_frame(self):
        success, image = self.video.read()
        image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        faces_rects = haar_cascade_face.detectMultiScale(image_gray, scaleFactor=1.2, minNeighbors=5);
        # Let us print the no. of faces found

        if len(faces_rects) > 0:

            cv2.putText(img = image, text = 'Faces found:' + str(len(faces_rects)), org=(50,50), fontFace=cv2.FONT_HERSHEY_DUPLEX, fontScale=1, color=(0, 0, 255))
        # We are using Motion JPEG, but OpenCV defaults to capture raw images,
        # so we must encode it into JPEG in order to correctly display the
        # video stream.
        ret, jpeg = cv2.imencode('.jpg', image)
        return jpeg.tobytes()


import mock
import unittest

from .helper import _ResourceMixin

class TransactionTest(_ResourceMixin, unittest.TestCase):

    def _getTargetClass(self):
        from .. import Transaction
        return Transaction

    def _getCollectionClass(self):
        from .. import Collection
        return Collection

    def _getLazyCollectionClass(self):
        from .. import LazyCollection
        return LazyCollection

    @mock.patch('requests.get')

class_ = self._getTargetClass()
        self.mockResponse(api_call, """{
            "object": "transaction",
            "id": "trxn_test",
            "type": "credit",
            "amount": 9635024,
            "currency": "thb",
            "created": "2014-10-27T06:58:56Z"
        }
        """)

        transaction = class_.retrieve('trxn_test')
        self.assertTrue(isinstance(transaction, class_))
        self.assertEqual(transaction.id, 'trxn_test')
        self.assertEqual(transaction.type, 'credit')
        self.assertEqual(transaction.amount, 9635024)
        self.assertEqual(transaction.currency, 'thb')
        self.assertRequest(
            api_call,
            'http://example.com'
        )

        transaction.amount = 9635023
        self.assertEqual(transaction.amount, 9635023)
        self.mockResponse(api_call, """{
            "object": "transaction",
            "id": "trxn_test",
            "type": "credit",
            "amount": 9635024,
            "currency": "thb",
            "created": "2014-10-27T06:58:56Z"
        }
        """)

        transaction.reload()
        self.assertEqual(transaction.amount, 9635024)
        self.assertEqual(transaction.currency, 'thb')
        self.assertRequest(
            api_call,
            'https://api.omise.co/transactions/trxn_test'
        )

    @mock.patch('requests.get')
    def test_retrieve_no_args(self, api_call):
        class_ = self._getTargetClass()
        collection_class_ = self._getCollectionClass()
        self.mockResponse(api_call, """{
            "object": "list",
            "from": "1970-01-01T07:00:00+07:00",
            "to": "2014-10-27T14:55:29+07:00",
            "offset": 0,
            "limit": 20,
            "total": 2,
            "data": [
                {
                    "object": "transaction",
                    "id": "trxn_test_1",
                    "type": "credit",
                    "amount": 9635024,
                    "currency": "thb",
                    "created": "2014-10-27T06:58:56Z"
                },
                {
                    "object": "transaction",
                    "id": "trxn_test_2",
                    "type": "debit",
                    "amount": 100025,
                    "currency": "thb",
                    "created": "2014-10-27T07:02:54Z"
                }
            ]
        }""")

        transactions = class_.retrieve()
        self.assertTrue(isinstance(transactions, collection_class_))
        self.assertTrue(isinstance(transactions[0], class_))
        self.assertTrue(transactions[0].id, 'trxn_test_1')
        self.assertTrue(transactions[0].type, 'credit')
        self.assertTrue(transactions[0].amount, 9635024)
        self.assertTrue(isinstance(transactions[1], class_))
        self.assertTrue(transactions[1].id, 'trxn_test_2')
        self.assertTrue(transactions[1].type, 'debit')
        self.assertTrue(transactions[1].amount, 100025)
        self.assertRequest(api_call, 'http://example.com')

    @mock.patch('requests.get')
    def test_list(self, api_call):
        class_ = self._getTargetClass()
        lazy_collection_class_ = self._getLazyCollectionClass()
        self.mockResponse(api_call, """{
            "object": "list",
            "from": "1970-01-01T07:00:00+07:00",
            "to": "2014-10-27T14:55:29+07:00",
            "offset": 0,
            "limit": 20,
            "total": 2,
            "data": [
                {
                    "object": "transaction",
                    "id": "trxn_test_1",
                    "type": "credit",
                    "amount": 9635024,
                    "currency": "thb",
                    "created": "2014-10-27T06:58:56Z"
                },
                {
                    "object": "transaction",
                    "id": "trxn_test_2",
                    "type": "debit",
                    "amount": 100025,
                    "currency": "thb",
                    "created": "2014-10-27T07:02:54Z"
                }
            ]
        }""")

        transactions = class_.list()
        self.assertTrue(isinstance(transactions, lazy_collection_class_))

        transactions = list(transactions)
        self.assertTrue(isinstance(transactions[0], class_))
        self.assertTrue(transactions[0].id, 'trxn_test_1')
        self.assertTrue(transactions[0].type, 'credit')
        self.assertTrue(transactions[0].amount, 9635024)
        self.assertTrue(isinstance(transactions[1], class_))
        self.assertTrue(transactions[1].id, 'trxn_test_2')
        self.assertTrue(transactions[1].type, 'debit')
        self.assertTrue(transactions[1].amount, 100025)