def prediction_schema(exact_len, *args):
    return All([{
        'threshold': float,
        'label_id': int,
        'score': float,
        'label_name': Any(*six.string_types),
    }], ExactLen(exact_len), *args)
def add_message(master_user_id=None, thread_id=None):
    data_request = request.get_json()
    schema = Schema({
        Required("message_text"): All(str, Length(min=1, max=400)),
        Required("has_attachment"): All(int, validate_is_active),
        Optional("attachment_url"): Url
    })
    try:
        schema(data_request)
    except MultipleInvalid as e:
        return multiple_invalid_response(e)
    message_text = data_request.get('message_text')
    has_attachment = data_request.get('has_attachment')
    try:
        attachment_url = data_request.get('attachment_url')
    except:
        attachment_url = ""
    message = UserMessageDelegate(master_user_id, thread_id)
    message_id = message.add(message_text, has_attachment, attachment_url)
    if message_id is not None:
        message_status = UserMessageStatusDelegate(master_user_id, thread_id)
        if message_status.add(message_id):
            thread = UserMessageThreadsDelegate(
                thread_id)  # update threads last message
            updated_last_user_message = thread.update_last_user_message(
                message_id)
            thread_participants = UserMessageThreadParticipantsDelegate(
                master_user_id,
                thread_id)  # update thread for new message info
            updated_thread_participant_new_message = thread_participants.update_thread_new_message(
            )
            if updated_last_user_message and updated_thread_participant_new_message:
                response_data = SUCCESS.copy()  # return success response
                response_data["message"] = ADDED
                response = generic_success_response(response_data)
            else:
                response = FAILURE_RESPONSE
        else:
            response = ERROR_RESPONSE
    else:
        response = ERROR_RESPONSE
    return response
예제 #3
0
def test_json_schema_validation(api: Client):
    def post(json: dict):
        return api.post("/entries", json=json)

    # a is required but not provided
    response = post({"b": "bar"})
    assert 422 == response.status_code
    assert S({"_issues": {".": str}}) <= response.get_json()

    # b does not contain c
    response = post({"a": "foo", "b": {}})
    assert 422 == response.status_code
    assert (S(
        {"_issues": {
            "b": All(str, Contains("c"), Contains("required"))
        }}) <= response.get_json())

    # c is not a number
    response = post({"a": "foo", "b": {"c": "bar"}})
    assert 422 == response.status_code
    assert (S(
        {"_issues": {
            "b.c": All(str, Contains("bar"), Contains("number"))
        }}) <= response.get_json())
예제 #4
0
    async def async_step_init(self, user_input=None):
        """Manage the options."""
        if user_input is not None:
            return self.async_create_entry(title="", data=user_input)

        return self.async_show_form(
            step_id="init",
            data_schema=vol.Schema({
                vol.Required(
                    CONFIG_UPDATE_INTERVAL,
                    default=self.config_entry.data.get(CONFIG_UPDATE_INTERVAL),
                ):
                All(int, Range(min=1, max=30))
            }),
        )
예제 #5
0
class validator:
    idSchema = Schema(All(str, Length(min=24, max=24)))
    jsStrSchema = Schema(str)
    jsIntSchema = Schema(int)

    @classmethod
    def validateId(cls, sid):
        return cls.idSchema(sid)

    @classmethod
    def validateData(cls, data):
        cls.idSchema(sid)
        cls.jsStrSchema(data["title"])
        cls.jsIntSchema(data["price"])
        cls.jsIntSchema(data["inventory_count"])
        return
def inference_schema(predicted_len, discarded_len, first_label, first_score):
    return S({
        'outputs':
        All([{
            'labels': {
                'predicted':
                prediction_schema(
                    predicted_len,
                    check_first_prediction(first_label, first_score),
                    check_score_threshold(is_predicted=True)),
                'discarded':
                prediction_schema(discarded_len,
                                  check_score_threshold(is_predicted=False))
            }
        }], ExactLen(1)),
    })
def update_is_mute(master_user_id=None, thread_id=None):
    data_request = request.get_json()
    schema = Schema({Required("is_muted"): All(int, validate_is_active)})
    try:
        schema(data_request)
    except MultipleInvalid as e:
        return multiple_invalid_response(e)
    is_muted = data_request.get('is_muted')
    thread = UserMessageThreadParticipantsDelegate(master_user_id, thread_id)
    if thread.update_is_muted(is_muted):
        response_data = SUCCESS.copy()
        response_data["message"] = UPDATED
        response = generic_success_response(response_data)
    else:
        response = ERROR_RESPONSE
    return response
예제 #8
0
class validator:
    idSchema = Schema(All(str, Length(min=24, max=24)))
    jsSchema = Schema(str)

    @classmethod
    def validateId(cls, sid):
        return cls.idSchema(sid)

    @classmethod
    def validatePut(cls, sid, data):
        cls.jsSchema(data)
        cls.idSchema(sid)
        return

    @classmethod
    def validateData(cls, data):
        cls.jsSchema(data)
        return
def add_thread_participants(master_user_id=None, thread_id=None):
    data_request = request.get_json()
    schema = Schema(
        {Required("participant_list"): All(validate_message_participant_list)})
    try:
        schema(data_request)
    except MultipleInvalid as e:
        return multiple_invalid_response(e)
    participant_list = data_request.get('participant_list')
    thread_participant = UserMessageThreadParticipantsDelegate(
        master_user_id, thread_id)
    if thread_participant.add_participants(participant_list):
        response_data = SUCCESS.copy()
        response_data["message"] = ADDED
        response = generic_success_response(response_data)
    else:
        response = INVALID_RESPONSE
    return response
예제 #10
0
async def async_setup_entry(hass, config_entry, async_add_entities):
    """Set up the Somfy cover platform."""

    domain_data = hass.data[DOMAIN]
    coordinator = domain_data[COORDINATOR]
    api = domain_data[API]

    somfy_covers = [
        SomfyCover(coordinator, device_id, api, domain_data[CONF_OPTIMISTIC])
        for device_id, device in coordinator.data.items()
        if SUPPORTED_CATEGORIES & set(device.categories)
    ]

    async_add_entities(somfy_covers)

    if any(
            somfy_cover.has_capability("position_low_speed")
            for somfy_cover in somfy_covers):

        platform = entity_platform.current_platform.get()

        platform.async_register_entity_service(
            SERVICE_CLOSE_COVER_SLOWLY,
            None,
            "close_cover_slowly",
        )

        platform.async_register_entity_service(
            SERVICE_OPEN_COVER_SLOWLY,
            None,
            "open_cover_slowly",
        )

        platform.async_register_entity_service(
            SERVICE_SET_COVER_POSITION_SLOWLY,
            {vol.Required("position"): All(int, Range(min=1, max=100))},
            "set_cover_position_slowly",
        )
예제 #11
0
_LOGGER = logging.getLogger(__name__)

DATA_SCHEMA = {
    vol.Required(CONFIG_NAME):
    str,
    vol.Required(CONFIG_KEY):
    str,
    vol.Required(CONFIG_SECRET):
    str,
    vol.Required(CONFIG_ORG_ID):
    str,
    vol.Required(CONFIG_FIAT, default="USD"):
    str,
    vol.Required(CONFIG_UPDATE_INTERVAL, default=DEFAULT_SCAN_INTERVAL_MINUTES):
    All(int, Range(min=1, max=30)),
}


async def validate_input(data: dict):
    """Validate the user input allows us to connect.
    Data has the keys from DATA_SCHEMA with values provided by the user.
    """
    private = NiceHashPrivateAPI(
        NICEHASH_API_ENDPOINT,
        data[CONFIG_ORG_ID],
        data[CONFIG_KEY],
        data[CONFIG_SECRET],
    )
    await private.get_mining_address()
    return
예제 #12
0
_LOGGER = logging.getLogger(__name__)

DATA_SCHEMA = {
    vol.Required(CONFIG_NAME):
    str,
    vol.Required(CONFIG_KEY):
    str,
    vol.Required(CONFIG_SECRET):
    str,
    vol.Required(CONFIG_ORG_ID):
    str,
    vol.Required(CONFIG_FIAT, default="USD"):
    str,
    vol.Required(CONFIG_UPDATE_INTERVAL, default=DEFAULT_SCAN_INTERVAL_SECONDS):
    All(int, Range(min=1, max=1800)),
}


async def validate_input(data: dict):
    """Validate the user input allows us to connect.
    Data has the keys from DATA_SCHEMA with values provided by the user.
    """
    private = NiceHashPrivateAPI(
        NICEHASH_API_ENDPOINT,
        data[CONFIG_ORG_ID],
        data[CONFIG_KEY],
        data[CONFIG_SECRET],
    )
    await private.get_mining_address()
    return