@generator_container<EOL><INDENT>def list(self, max=None, **request_parameters):<DEDENT>

check_type(max, int)<EOL>params = dict_from_items_with_values(<EOL>request_parameters,<EOL>max=max,<EOL>)<EOL>items = self._session.get_items(API_ENDPOINT, params=params)<EOL>for item in items:<EOL><INDENT>yield self._object_factory(OBJECT_TYPE, item)<EOL><DEDENT>

List all of the authenticated user's webhooks.

        This method supports Webex Teams's implementation of RFC5988 Web
        Linking to provide pagination support.  It returns a generator
        container that incrementally yields all webhooks returned by the
        query.  The generator will automatically request additional 'pages' of
        responses from Webex as needed until all responses have been returned.
        The container makes the generator safe for reuse.  A new API call will
        be made, using the same parameters that were specified when the
        generator was created, every time a new iterator is requested from the
        container.

        Args:
            max(int): Limit the maximum number of items returned from the Webex
                Teams service per request.
            **request_parameters: Additional request parameters (provides
                support for parameters that may be added in the future).

        Returns:
            GeneratorContainer: A GeneratorContainer which, when iterated,
            yields the webhooks returned by the Webex Teams query.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


def create(self, name, targetUrl, resource, event,<EOL>filter=None, secret=None, **request_parameters):

check_type(name, basestring, may_be_none=False)<EOL>check_type(targetUrl, basestring, may_be_none=False)<EOL>check_type(resource, basestring, may_be_none=False)<EOL>check_type(event, basestring, may_be_none=False)<EOL>check_type(filter, basestring)<EOL>check_type(secret, basestring)<EOL>post_data = dict_from_items_with_values(<EOL>request_parameters,<EOL>name=name,<EOL>targetUrl=targetUrl,<EOL>resource=resource,<EOL>event=event,<EOL>filter=filter,<EOL>secret=secret,<EOL>)<EOL>json_data = self._session.post(API_ENDPOINT, json=post_data)<EOL>return self._object_factory(OBJECT_TYPE, json_data)<EOL>

Create a webhook.

        Args:
            name(basestring): A user-friendly name for this webhook.
            targetUrl(basestring): The URL that receives POST requests for
                each event.
            resource(basestring): The resource type for the webhook.
            event(basestring): The event type for the webhook.
            filter(basestring): The filter that defines the webhook scope.
            secret(basestring): The secret used to generate payload signature.
            **request_parameters: Additional request parameters (provides
                support for parameters that may be added in the future).

        Returns:
            Webhook: A Webhook object with the details of the created webhook.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


check_type(webhookId, basestring, may_be_none=False)<EOL>json_data = self._session.get(API_ENDPOINT + '<STR_LIT:/>' + webhookId)<EOL>return self._object_factory(OBJECT_TYPE, json_data)<EOL>

Get the details of a webhook, by ID.

        Args:
            webhookId(basestring): The ID of the webhook to be retrieved.

        Returns:
            Webhook: A Webhook object with the details of the requested
            webhook.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


def update(self, webhookId, name=None, targetUrl=None,<EOL>**request_parameters):

check_type(webhookId, basestring, may_be_none=False)<EOL>check_type(name, basestring)<EOL>check_type(targetUrl, basestring)<EOL>put_data = dict_from_items_with_values(<EOL>request_parameters,<EOL>name=name,<EOL>targetUrl=targetUrl,<EOL>)<EOL>json_data = self._session.put(API_ENDPOINT + '<STR_LIT:/>' + webhookId,<EOL>json=put_data)<EOL>return self._object_factory(OBJECT_TYPE, json_data)<EOL>

Update a webhook, by ID.

        Args:
            webhookId(basestring): The webhook ID.
            name(basestring): A user-friendly name for this webhook.
            targetUrl(basestring): The URL that receives POST requests for
                each event.
            **request_parameters: Additional request parameters (provides
                support for parameters that may be added in the future).

        Returns:
            Webhook: A Webhook object with the updated Webex Teams webhook
                details.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


check_type(webhookId, basestring, may_be_none=False)<EOL>self._session.delete(API_ENDPOINT + '<STR_LIT:/>' + webhookId)<EOL>

Delete a webhook, by ID.

        Args:
            webhookId(basestring): The ID of the webhook to be deleted.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


check_type(access_token, basestring)<EOL>check_type(base_url, basestring)<EOL>check_type(single_request_timeout, int)<EOL>check_type(wait_on_rate_limit, bool)<EOL>check_type(client_id, basestring, may_be_none=True)<EOL>check_type(client_secret, basestring, may_be_none=True)<EOL>check_type(oauth_code, basestring, may_be_none=True)<EOL>check_type(redirect_uri, basestring, may_be_none=True)<EOL>access_token = access_token or WEBEX_TEAMS_ACCESS_TOKEN<EOL>self.access_tokens = AccessTokensAPI(<EOL>base_url, object_factory,<EOL>single_request_timeout=single_request_timeout,<EOL>)<EOL>oauth_param_list = [client_id, client_secret, oauth_code, redirect_uri]<EOL>if not access_token and all(oauth_param_list):<EOL><INDENT>access_token = self.access_tokens.get(<EOL>client_id=client_id,<EOL>client_secret=client_secret,<EOL>code=oauth_code,<EOL>redirect_uri=redirect_uri<EOL>).access_token<EOL><DEDENT>if not access_token:<EOL><INDENT>raise AccessTokenError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>self._session = RestSession(<EOL>access_token=access_token,<EOL>base_url=base_url,<EOL>single_request_timeout=single_request_timeout,<EOL>wait_on_rate_limit=wait_on_rate_limit<EOL>)<EOL>self.people = PeopleAPI(self._session, object_factory)<EOL>self.rooms = RoomsAPI(self._session, object_factory)<EOL>self.memberships = MembershipsAPI(self._session, object_factory)<EOL>self.messages = MessagesAPI(self._session, object_factory)<EOL>self.teams = TeamsAPI(self._session, object_factory)<EOL>self.team_memberships = TeamMembershipsAPI(<EOL>self._session, object_factory<EOL>)<EOL>self.webhooks = WebhooksAPI(self._session, object_factory)<EOL>self.organizations = OrganizationsAPI(self._session, object_factory)<EOL>self.licenses = LicensesAPI(self._session, object_factory)<EOL>self.roles = RolesAPI(self._session, object_factory)<EOL>self.events = EventsAPI(self._session, object_factory)<EOL>self.guest_issuer = GuestIssuerAPI(self._session, object_factory)<EOL>

Create a new WebexTeamsAPI object.

        An access token must be used when interacting with the Webex Teams API.
        This package supports three methods for you to provide that access
        token:

          1. You may manually specify the access token via the `access_token`
             argument, when creating a new WebexTeamsAPI object.

          2. If an access_token argument is not supplied, the package checks
             for a WEBEX_TEAMS_ACCESS_TOKEN environment variable.

          3. Provide the parameters (client_id, client_secret, oauth_code and
             oauth_redirect_uri) from your oauth flow.

        An AccessTokenError is raised if an access token is not provided
        via one of these two methods.

        Args:
            access_token(basestring): The access token to be used for API
                calls to the Webex Teams service.  Defaults to checking for a
                WEBEX_TEAMS_ACCESS_TOKEN environment variable.
            base_url(basestring): The base URL to be prefixed to the
                individual API endpoint suffixes.
                Defaults to webexteamssdk.DEFAULT_BASE_URL.
            single_request_timeout(int): Timeout (in seconds) for RESTful HTTP
                requests. Defaults to
                webexteamssdk.config.DEFAULT_SINGLE_REQUEST_TIMEOUT.
            wait_on_rate_limit(bool): Enables or disables automatic rate-limit
                handling. Defaults to
                webexteamssdk.config.DEFAULT_WAIT_ON_RATE_LIMIT.
            object_factory(callable): The factory function to use to create
                Python objects from the returned Webex Teams JSON data objects.
            client_id(basestring): The client id of your integration. Provided
                upon creation in the portal.
            client_secret(basestring): The client secret of your integration.
                Provided upon creation in the portal.
            oauth_code(basestring): The oauth authorization code provided by
                the user oauth process.
            oauth_redirect_uri(basestring): The redirect URI used in the user
                OAuth process.

        Returns:
            WebexTeamsAPI: A new WebexTeamsAPI object.

        Raises:
            TypeError: If the parameter types are incorrect.
            AccessTokenError: If an access token is not provided via the
                access_token argument or an environment variable.


return self._session.access_token<EOL>

The access token used for API calls to the Webex Teams service.


return self._session.base_url<EOL>

The base URL prefixed to the individual API endpoint suffixes.


return self._session.single_request_timeout<EOL>

Timeout (in seconds) for an single HTTP request.


return self._session.wait_on_rate_limit<EOL>

Automatic rate-limit handling enabled / disabled.


def __init__(self, session, object_factory):

check_type(session, RestSession, may_be_none=False)<EOL>super(TeamsAPI, self).__init__()<EOL>self._session = session<EOL>self._object_factory = object_factory<EOL>

Initialize a new TeamsAPI object with the provided RestSession.

        Args:
            session(RestSession): The RESTful session object to be used for
                API calls to the Webex Teams service.

        Raises:
            TypeError: If the parameter types are incorrect.


List teams to which the authenticated user belongs.

        This method supports Webex Teams's implementation of RFC5988 Web
        Linking to provide pagination support.  It returns a generator
        container that incrementally yields all teams returned by the
        query.  The generator will automatically request additional 'pages' of
        responses from Webex as needed until all responses have been returned.
        The container makes the generator safe for reuse.  A new API call will
        be made, using the same parameters that were specified when the
        generator was created, every time a new iterator is requested from the
        container.

        Args:
            max(int): Limit the maximum number of items returned from the Webex
                Teams service per request.
            **request_parameters: Additional request parameters (provides
                support for parameters that may be added in the future).

        Returns:
            GeneratorContainer: A GeneratorContainer which, when iterated,
            yields the teams returned by the Webex Teams query.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


def create(self, name, **request_parameters):

check_type(name, basestring, may_be_none=False)<EOL>post_data = dict_from_items_with_values(<EOL>request_parameters,<EOL>name=name,<EOL>)<EOL>json_data = self._session.post(API_ENDPOINT, json=post_data)<EOL>return self._object_factory(OBJECT_TYPE, json_data)<EOL>

Create a team.

        The authenticated user is automatically added as a member of the team.

        Args:
            name(basestring): A user-friendly name for the team.
            **request_parameters: Additional request parameters (provides
                support for parameters that may be added in the future).

        Returns:
            Team: A Team object with the details of the created team.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


check_type(teamId, basestring, may_be_none=False)<EOL>json_data = self._session.get(API_ENDPOINT + '<STR_LIT:/>' + teamId)<EOL>return self._object_factory(OBJECT_TYPE, json_data)<EOL>

Get the details of a team, by ID.

        Args:
            teamId(basestring): The ID of the team to be retrieved.

        Returns:
            Team: A Team object with the details of the requested team.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


def update(self, teamId, name=None, **request_parameters):

check_type(teamId, basestring, may_be_none=False)<EOL>check_type(name, basestring)<EOL>put_data = dict_from_items_with_values(<EOL>request_parameters,<EOL>name=name,<EOL>)<EOL>json_data = self._session.put(API_ENDPOINT + '<STR_LIT:/>' + teamId,<EOL>json=put_data)<EOL>return self._object_factory(OBJECT_TYPE, json_data)<EOL>

Update details for a team, by ID.

        Args:
            teamId(basestring): The team ID.
            name(basestring): A user-friendly name for the team.
            **request_parameters: Additional request parameters (provides
                support for parameters that may be added in the future).

        Returns:
            Team: A Team object with the updated Webex Teams team details.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


check_type(teamId, basestring, may_be_none=False)<EOL>self._session.delete(API_ENDPOINT + '<STR_LIT:/>' + teamId)<EOL>

Delete a team.

        Args:
            teamId(basestring): The ID of the team to be deleted.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


check_type(session, RestSession, may_be_none=False)<EOL>super(OrganizationsAPI, self).__init__()<EOL>self._session = session<EOL>self._object_factory = object_factory<EOL>

Init a new OrganizationsAPI object with the provided RestSession.

        Args:
            session(RestSession): The RESTful session object to be used for
                API calls to the Webex Teams service.

        Raises:
            TypeError: If the parameter types are incorrect.


<EOL>items = self._session.get_items(<EOL>API_ENDPOINT,<EOL>params=request_parameters<EOL>)<EOL>for item in items:<EOL><INDENT>yield self._object_factory(OBJECT_TYPE, item)<EOL><DEDENT>

List Organizations.

        Args:
            **request_parameters: Additional request parameters (provides
                support for parameters that may be added in the future).

        Returns:
            GeneratorContainer: A GeneratorContainer which, when iterated,
            yields the organizations returned by the Webex Teams query.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


check_type(orgId, basestring, may_be_none=False)<EOL>json_data = self._session.get(API_ENDPOINT + '<STR_LIT:/>' + orgId)<EOL>return self._object_factory(OBJECT_TYPE, json_data)<EOL>

Get the details of an Organization, by ID.

        Args:
            orgId(basestring): The ID of the Organization to be retrieved.

        Returns:
            Organization: An Organization object with the details of the
            requested organization.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


check_type(session, RestSession)<EOL>super(GuestIssuerAPI, self).__init__()<EOL>self._session = session<EOL>self._object_factory = object_factory<EOL>

Initialize a new GuestIssuerAPI object with the provided RestSession

        Args:
            session(RestSession): The RESTful session object to be used for
            API calls to the Webex Teams service

        Raises:
            TypeError: If the parameter types are incorrect


def create(self, subject, displayName, issuerToken, expiration, secret):

check_type(subject, basestring)<EOL>check_type(displayName, basestring)<EOL>check_type(issuerToken, basestring)<EOL>check_type(expiration, basestring)<EOL>check_type(secret, basestring)<EOL>payload = {<EOL>"<STR_LIT>": subject,<EOL>"<STR_LIT:name>": displayName,<EOL>"<STR_LIT>": issuerToken,<EOL>"<STR_LIT>": expiration<EOL>}<EOL>key = base64.b64decode(secret)<EOL>jwt_token = jwt.encode(payload, key, algorithm='<STR_LIT>')<EOL>url = self._session.base_url + API_ENDPOINT + "<STR_LIT:/>" + "<STR_LIT>"<EOL>headers = {<EOL>'<STR_LIT>': "<STR_LIT>" + jwt_token.decode('<STR_LIT:utf-8>')<EOL>}<EOL>response = requests.post(url, headers=headers)<EOL>check_response_code(response, EXPECTED_RESPONSE_CODE['<STR_LIT:GET>'])<EOL>return self._object_factory(OBJECT_TYPE, response.json())<EOL>

Create a new guest issuer using the provided issuer token.

        This function returns a guest issuer with an api access token.

        Args:
            subject(basestring): Unique and public identifier
            displayName(basestring): Display Name of the guest user
            issuerToken(basestring): Issuer token from developer hub
            expiration(basestring): Expiration time as a unix timestamp
            secret(basestring): The secret used to sign your guest issuers

        Returns:
            GuestIssuerToken: A Guest Issuer with a valid access token.

        Raises:
            TypeError: If the parameter types are incorrect
            ApiError: If the webex teams cloud returns an error.


check_type(session, RestSession, may_be_none=False)<EOL>super(RoomsAPI, self).__init__()<EOL>self._session = session<EOL>self._object_factory = object_factory<EOL>

Initialize a new RoomsAPI object with the provided RestSession.

        Args:
            session(RestSession): The RESTful session object to be used for
                API calls to the Webex Teams service.

        Raises:
            TypeError: If the parameter types are incorrect.


@generator_container<EOL><INDENT>def list(self, teamId=None, type=None, sortBy=None, max=None,<EOL>**request_parameters):<DEDENT>

check_type(teamId, basestring)<EOL>check_type(type, basestring)<EOL>check_type(sortBy, basestring)<EOL>check_type(max, int)<EOL>params = dict_from_items_with_values(<EOL>request_parameters,<EOL>teamId=teamId,<EOL>type=type,<EOL>sortBy=sortBy,<EOL>max=max,<EOL>)<EOL>items = self._session.get_items(API_ENDPOINT, params=params)<EOL>for item in items:<EOL><INDENT>yield self._object_factory(OBJECT_TYPE, item)<EOL><DEDENT>

List rooms.

        By default, lists rooms to which the authenticated user belongs.

        This method supports Webex Teams's implementation of RFC5988 Web
        Linking to provide pagination support.  It returns a generator
        container that incrementally yields all rooms returned by the
        query.  The generator will automatically request additional 'pages' of
        responses from Webex as needed until all responses have been returned.
        The container makes the generator safe for reuse.  A new API call will
        be made, using the same parameters that were specified when the
        generator was created, every time a new iterator is requested from the
        container.

        Args:
            teamId(basestring): Limit the rooms to those associated with a
                team, by ID.
            type(basestring): 'direct' returns all 1-to-1 rooms. `group`
                returns all group rooms. If not specified or values not
                matched, will return all room types.
            sortBy(basestring): Sort results by room ID (`id`), most recent
                activity (`lastactivity`), or most recently created
                (`created`).
            max(int): Limit the maximum number of items returned from the Webex
                Teams service per request.
            **request_parameters: Additional request parameters (provides
                support for parameters that may be added in the future).

        Returns:
            GeneratorContainer: A GeneratorContainer which, when iterated,
            yields the rooms returned by the Webex Teams query.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


def create(self, title, teamId=None, **request_parameters):

check_type(title, basestring)<EOL>check_type(teamId, basestring)<EOL>post_data = dict_from_items_with_values(<EOL>request_parameters,<EOL>title=title,<EOL>teamId=teamId,<EOL>)<EOL>json_data = self._session.post(API_ENDPOINT, json=post_data)<EOL>return self._object_factory(OBJECT_TYPE, json_data)<EOL>

Create a room.

        The authenticated user is automatically added as a member of the room.

        Args:
            title(basestring): A user-friendly name for the room.
            teamId(basestring): The team ID with which this room is
                associated.
            **request_parameters: Additional request parameters (provides
                support for parameters that may be added in the future).

        Returns:
            Room: A Room with the details of the created room.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


check_type(roomId, basestring, may_be_none=False)<EOL>json_data = self._session.get(API_ENDPOINT + '<STR_LIT:/>' + roomId)<EOL>return self._object_factory(OBJECT_TYPE, json_data)<EOL>

Get the details of a room, by ID.

        Args:
            roomId(basestring): The ID of the room to be retrieved.

        Returns:
            Room: A Room object with the details of the requested room.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


def update(self, roomId, title=None, **request_parameters):

check_type(roomId, basestring, may_be_none=False)<EOL>check_type(roomId, basestring)<EOL>put_data = dict_from_items_with_values(<EOL>request_parameters,<EOL>title=title,<EOL>)<EOL>json_data = self._session.put(API_ENDPOINT + '<STR_LIT:/>' + roomId,<EOL>json=put_data)<EOL>return self._object_factory(OBJECT_TYPE, json_data)<EOL>

Update details for a room, by ID.

        Args:
            roomId(basestring): The room ID.
            title(basestring): A user-friendly name for the room.
            **request_parameters: Additional request parameters (provides
                support for parameters that may be added in the future).

        Returns:
            Room: A Room object with the updated Webex Teams room details.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


check_type(roomId, basestring, may_be_none=False)<EOL>self._session.delete(API_ENDPOINT + '<STR_LIT:/>' + roomId)<EOL>

Delete a room.

        Args:
            roomId(basestring): The ID of the room to be deleted.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


check_type(session, RestSession, may_be_none=False)<EOL>super(EventsAPI, self).__init__()<EOL>self._session = session<EOL>self._object_factory = object_factory<EOL>

Initialize a new EventsAPI object with the provided RestSession.

        Args:
            session(RestSession): The RESTful session object to be used for
                API calls to the Webex Teams service.

        Raises:
            TypeError: If the parameter types are incorrect.


@generator_container<EOL><INDENT>def list(self, resource=None, type=None, actorId=None, _from=None, to=None,<EOL>max=None, **request_parameters):<DEDENT>

check_type(resource, basestring)<EOL>check_type(type, basestring)<EOL>check_type(actorId, basestring)<EOL>check_type(_from, basestring)<EOL>check_type(to, basestring)<EOL>check_type(max, int)<EOL>params = dict_from_items_with_values(<EOL>request_parameters,<EOL>resource=resource,<EOL>type=type,<EOL>actorId=actorId,<EOL>_from=_from,<EOL>to=to,<EOL>max=max,<EOL>)<EOL>if _from:<EOL><INDENT>params["<STR_LIT>"] = params.pop("<STR_LIT>")<EOL><DEDENT>items = self._session.get_items(API_ENDPOINT, params=params)<EOL>for item in items:<EOL><INDENT>yield self._object_factory(OBJECT_TYPE, item)<EOL><DEDENT>

List events.

        List events in your organization. Several query parameters are
        available to filter the response.

        Note: `from` is a keyword in Python and may not be used as a variable
        name, so we had to use `_from` instead.

        This method supports Webex Teams's implementation of RFC5988 Web
        Linking to provide pagination support.  It returns a generator
        container that incrementally yields all events returned by the
        query.  The generator will automatically request additional 'pages' of
        responses from Wevex as needed until all responses have been returned.
        The container makes the generator safe for reuse.  A new API call will
        be made, using the same parameters that were specified when the
        generator was created, every time a new iterator is requested from the
        container.

        Args:
            resource(basestring): Limit results to a specific resource type.
                Possible values: "messages", "memberships".
            type(basestring): Limit results to a specific event type. Possible
                values: "created", "updated", "deleted".
            actorId(basestring): Limit results to events performed by this
                person, by ID.
            _from(basestring): Limit results to events which occurred after a
                date and time, in ISO8601 format (yyyy-MM-dd'T'HH:mm:ss.SSSZ).
            to(basestring): Limit results to events which occurred before a
                date and time, in ISO8601 format (yyyy-MM-dd'T'HH:mm:ss.SSSZ).
            max(int): Limit the maximum number of items returned from the Webex
                Teams service per request.
            **request_parameters: Additional request parameters (provides
                support for parameters that may be added in the future).

        Returns:
            GeneratorContainer: A GeneratorContainer which, when iterated,
            yields the events returned by the Webex Teams query.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


check_type(eventId, basestring, may_be_none=False)<EOL>json_data = self._session.get(API_ENDPOINT + '<STR_LIT:/>' + eventId)<EOL>return self._object_factory(OBJECT_TYPE, json_data)<EOL>

Get the details for an event, by event ID.

        Args:
            eventId(basestring): The ID of the event to be retrieved.

        Returns:
            Event: A event object with the details of the requested room.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


check_type(session, RestSession)<EOL>super(MembershipsAPI, self).__init__()<EOL>self._session = session<EOL>self._object_factory = object_factory<EOL>

Init a new MembershipsAPI object with the provided RestSession.

        Args:
            session(RestSession): The RESTful session object to be used for
                API calls to the Webex Teams service.

        Raises:
            TypeError: If the parameter types are incorrect.


@generator_container<EOL><INDENT>def list(self, roomId=None, personId=None, personEmail=None, max=None,<EOL>**request_parameters):<DEDENT>

check_type(roomId, basestring)<EOL>check_type(personId, basestring)<EOL>check_type(personEmail, basestring)<EOL>check_type(max, int)<EOL>params = dict_from_items_with_values(<EOL>request_parameters,<EOL>roomId=roomId,<EOL>personId=personId,<EOL>personEmail=personEmail,<EOL>max=max,<EOL>)<EOL>items = self._session.get_items(API_ENDPOINT, params=params)<EOL>for item in items:<EOL><INDENT>yield self._object_factory(OBJECT_TYPE, item)<EOL><DEDENT>

List room memberships.

        By default, lists memberships for rooms to which the authenticated user
        belongs.

        Use query parameters to filter the response.

        Use `roomId` to list memberships for a room, by ID.

        Use either `personId` or `personEmail` to filter the results.

        This method supports Webex Teams's implementation of RFC5988 Web
        Linking to provide pagination support.  It returns a generator
        container that incrementally yields all memberships returned by the
        query.  The generator will automatically request additional 'pages' of
        responses from Webex as needed until all responses have been returned.
        The container makes the generator safe for reuse.  A new API call will
        be made, using the same parameters that were specified when the
        generator was created, every time a new iterator is requested from the
        container.

        Args:
            roomId(basestring): Limit results to a specific room, by ID.
            personId(basestring): Limit results to a specific person, by ID.
            personEmail(basestring): Limit results to a specific person, by
                email address.
            max(int): Limit the maximum number of items returned from the Webex
                Teams service per request.
            **request_parameters: Additional request parameters (provides
                support for parameters that may be added in the future).

        Returns:
            GeneratorContainer: A GeneratorContainer which, when iterated,
            yields the memberships returned by the Webex Teams query.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


def create(self, roomId, personId=None, personEmail=None,<EOL>isModerator=False, **request_parameters):

check_type(roomId, basestring, may_be_none=False)<EOL>check_type(personId, basestring)<EOL>check_type(personEmail, basestring)<EOL>check_type(isModerator, bool)<EOL>post_data = dict_from_items_with_values(<EOL>request_parameters,<EOL>roomId=roomId,<EOL>personId=personId,<EOL>personEmail=personEmail,<EOL>isModerator=isModerator,<EOL>)<EOL>json_data = self._session.post(API_ENDPOINT, json=post_data)<EOL>return self._object_factory(OBJECT_TYPE, json_data)<EOL>

Add someone to a room by Person ID or email address.

        Add someone to a room by Person ID or email address; optionally
        making them a moderator.

        Args:
            roomId(basestring): The room ID.
            personId(basestring): The ID of the person.
            personEmail(basestring): The email address of the person.
            isModerator(bool): Set to True to make the person a room moderator.
            **request_parameters: Additional request parameters (provides
                support for parameters that may be added in the future).

        Returns:
            Membership: A Membership object with the details of the created
            membership.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


check_type(membershipId, basestring, may_be_none=False)<EOL>json_data = self._session.get(API_ENDPOINT + '<STR_LIT:/>' + membershipId)<EOL>return self._object_factory(OBJECT_TYPE, json_data)<EOL>

Get details for a membership, by ID.

        Args:
            membershipId(basestring): The membership ID.

        Returns:
            Membership: A Membership object with the details of the requested
            membership.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


def update(self, membershipId, isModerator=None, **request_parameters):

check_type(membershipId, basestring, may_be_none=False)<EOL>check_type(isModerator, bool)<EOL>put_data = dict_from_items_with_values(<EOL>request_parameters,<EOL>isModerator=isModerator,<EOL>)<EOL>json_data = self._session.put(API_ENDPOINT + '<STR_LIT:/>' + membershipId,<EOL>json=put_data)<EOL>return self._object_factory(OBJECT_TYPE, json_data)<EOL>

Update properties for a membership, by ID.

        Args:
            membershipId(basestring): The membership ID.
            isModerator(bool): Set to True to make the person a room moderator.
            **request_parameters: Additional request parameters (provides
                support for parameters that may be added in the future).

        Returns:
            Membership: A Membership object with the updated Webex Teams
            membership details.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


check_type(membershipId, basestring)<EOL>self._session.delete(API_ENDPOINT + '<STR_LIT:/>' + membershipId)<EOL>

Delete a membership, by ID.

        Args:
            membershipId(basestring): The membership ID.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


next_url = str(next_url)<EOL>parsed_url = urllib.parse.urlparse(next_url)<EOL>if not parsed_url.scheme or not parsed_url.netloc or not parsed_url.path:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>if parsed_url.query:<EOL><INDENT>query_list = parsed_url.query.split('<STR_LIT:&>')<EOL>if '<STR_LIT>' in query_list:<EOL><INDENT>query_list.remove('<STR_LIT>')<EOL>warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>", RuntimeWarning)<EOL><DEDENT>new_query = '<STR_LIT:&>'.join(query_list)<EOL>parsed_url = list(parsed_url)<EOL>parsed_url[<NUM_LIT:4>] = new_query<EOL><DEDENT>return urllib.parse.urlunparse(parsed_url)<EOL>

Remove max=null parameter from URL.

    Patch for Webex Teams Defect: 'next' URL returned in the Link headers of
    the responses contain an errant 'max=null' parameter, which  causes the
    next request (to this URL) to fail if the URL is requested as-is.

    This patch parses the next_url to remove the max=null parameter.

    Args:
        next_url(basestring): The 'next' URL to be parsed and cleaned.

    Returns:
        basestring: The clean URL to be used for the 'next' request.

    Raises:
        AssertionError: If the parameter types are incorrect.
        ValueError: If 'next_url' does not contain a valid API endpoint URL
            (scheme, netloc and path).


check_type(access_token, basestring, may_be_none=False)<EOL>check_type(base_url, basestring, may_be_none=False)<EOL>check_type(single_request_timeout, int)<EOL>check_type(wait_on_rate_limit, bool, may_be_none=False)<EOL>super(RestSession, self).__init__()<EOL>self._base_url = str(validate_base_url(base_url))<EOL>self._access_token = str(access_token)<EOL>self._single_request_timeout = single_request_timeout<EOL>self._wait_on_rate_limit = wait_on_rate_limit<EOL>self._req_session = requests.session()<EOL>self.update_headers({'<STR_LIT>': '<STR_LIT>' + access_token,<EOL>'<STR_LIT>': '<STR_LIT>'})<EOL>

Initialize a new RestSession object.

        Args:
            access_token(basestring): The Webex Teams access token to be used
                for this session.
            base_url(basestring): The base URL that will be suffixed onto API
                endpoint relative URLs to produce a callable absolute URL.
            single_request_timeout(int): The timeout (seconds) for a single
                HTTP REST API request.
            wait_on_rate_limit(bool): Enable or disable automatic rate-limit
                handling.

        Raises:
            TypeError: If the parameter types are incorrect.


return self._base_url<EOL>


return self._access_token<EOL>

The Webex Teams access token used for this session.


return self._single_request_timeout<EOL>

The timeout (seconds) for a single HTTP REST API request.


check_type(value, int)<EOL>assert value is None or value > <NUM_LIT:0><EOL>self._single_request_timeout = value<EOL>


return self._wait_on_rate_limit<EOL>

Automatic rate-limit handling.

        This setting enables or disables automatic rate-limit handling.  When
        enabled, rate-limited requests will be automatically be retried after
        waiting `Retry-After` seconds (provided by Webex Teams in the
        rate-limit response header).


check_type(value, bool, may_be_none=False)<EOL>self._wait_on_rate_limit = value<EOL>

Enable or disable automatic rate-limit handling.


return self._req_session.headers.copy()<EOL>

The HTTP headers used for requests in this session.


check_type(headers, dict, may_be_none=False)<EOL>self._req_session.headers.update(headers)<EOL>

Update the HTTP headers used for requests in this session.

        Note: Updates provided by the dictionary passed as the `headers`
        parameter to this method are merged into the session headers by adding
        new key-value pairs and/or updating the values of existing keys. The
        session headers are not replaced by the provided dictionary.

        Args:
             headers(dict): Updates to the current session headers.


parsed_url = urllib.parse.urlparse(url)<EOL>if not parsed_url.scheme and not parsed_url.netloc:<EOL><INDENT>return urllib.parse.urljoin(str(self.base_url), str(url))<EOL><DEDENT>else:<EOL><INDENT>return url<EOL><DEDENT>

Given a relative or absolute URL; return an absolute URL.

        Args:
            url(basestring): A relative or absolute URL.

        Returns:
            str: An absolute URL.


def request(self, method, url, erc, **kwargs):

<EOL>abs_url = self.abs_url(url)<EOL>kwargs.setdefault('<STR_LIT>', self.single_request_timeout)<EOL>while True:<EOL><INDENT>response = self._req_session.request(method, abs_url, **kwargs)<EOL>try:<EOL><INDENT>check_response_code(response, erc)<EOL><DEDENT>except RateLimitError as e:<EOL><INDENT>if self.wait_on_rate_limit:<EOL><INDENT>warnings.warn(RateLimitWarning(response))<EOL>time.sleep(e.retry_after)<EOL>continue<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return response<EOL><DEDENT><DEDENT>

Abstract base method for making requests to the Webex Teams APIs.

        This base method:
            * Expands the API endpoint URL to an absolute URL
            * Makes the actual HTTP request to the API endpoint
            * Provides support for Webex Teams rate-limiting
            * Inspects response codes and raises exceptions as appropriate

        Args:
            method(basestring): The request-method type ('GET', 'POST', etc.).
            url(basestring): The URL of the API endpoint to be called.
            erc(int): The expected response code that should be returned by the
                Webex Teams API endpoint to indicate success.
            **kwargs: Passed on to the requests package.

        Raises:
            ApiError: If anything other than the expected response code is
                returned by the Webex Teams API endpoint.


def get(self, url, params=None, **kwargs):

check_type(url, basestring, may_be_none=False)<EOL>check_type(params, dict)<EOL>erc = kwargs.pop('<STR_LIT>', EXPECTED_RESPONSE_CODE['<STR_LIT:GET>'])<EOL>response = self.request('<STR_LIT:GET>', url, erc, params=params, **kwargs)<EOL>return extract_and_parse_json(response)<EOL>

Sends a GET request.

        Args:
            url(basestring): The URL of the API endpoint.
            params(dict): The parameters for the HTTP GET request.
            **kwargs:
                erc(int): The expected (success) response code for the request.
                others: Passed on to the requests package.

        Raises:
            ApiError: If anything other than the expected response code is
                returned by the Webex Teams API endpoint.


def get_pages(self, url, params=None, **kwargs):

check_type(url, basestring, may_be_none=False)<EOL>check_type(params, dict)<EOL>erc = kwargs.pop('<STR_LIT>', EXPECTED_RESPONSE_CODE['<STR_LIT:GET>'])<EOL>response = self.request('<STR_LIT:GET>', url, erc, params=params, **kwargs)<EOL>while True:<EOL><INDENT>yield extract_and_parse_json(response)<EOL>if response.links.get('<STR_LIT>'):<EOL><INDENT>next_url = response.links.get('<STR_LIT>').get('<STR_LIT:url>')<EOL>next_url = _fix_next_url(next_url)<EOL>response = self.request('<STR_LIT:GET>', next_url, erc, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>

Return a generator that GETs and yields pages of data.

        Provides native support for RFC5988 Web Linking.

        Args:
            url(basestring): The URL of the API endpoint.
            params(dict): The parameters for the HTTP GET request.
            **kwargs:
                erc(int): The expected (success) response code for the request.
                others: Passed on to the requests package.

        Raises:
            ApiError: If anything other than the expected response code is
                returned by the Webex Teams API endpoint.


def get_items(self, url, params=None, **kwargs):

<EOL>pages = self.get_pages(url, params=params, **kwargs)<EOL>for json_page in pages:<EOL><INDENT>assert isinstance(json_page, dict)<EOL>items = json_page.get('<STR_LIT>')<EOL>if items is None:<EOL><INDENT>error_message = "<STR_LIT>""<STR_LIT>".format(json_page)<EOL>raise MalformedResponse(error_message)<EOL><DEDENT>else:<EOL><INDENT>for item in items:<EOL><INDENT>yield item<EOL><DEDENT><DEDENT><DEDENT>

Return a generator that GETs and yields individual JSON `items`.

        Yields individual `items` from Webex Teams's top-level {'items': [...]}
        JSON objects. Provides native support for RFC5988 Web Linking.  The
        generator will request additional pages as needed until all items have
        been returned.

        Args:
            url(basestring): The URL of the API endpoint.
            params(dict): The parameters for the HTTP GET request.
            **kwargs:
                erc(int): The expected (success) response code for the request.
                others: Passed on to the requests package.

        Raises:
            ApiError: If anything other than the expected response code is
                returned by the Webex Teams API endpoint.
            MalformedResponse: If the returned response does not contain a
                top-level dictionary with an 'items' key.


def post(self, url, json=None, data=None, **kwargs):

check_type(url, basestring, may_be_none=False)<EOL>erc = kwargs.pop('<STR_LIT>', EXPECTED_RESPONSE_CODE['<STR_LIT:POST>'])<EOL>response = self.request('<STR_LIT:POST>', url, erc, json=json, data=data,<EOL>**kwargs)<EOL>return extract_and_parse_json(response)<EOL>

Sends a POST request.

        Args:
            url(basestring): The URL of the API endpoint.
            json: Data to be sent in JSON format in tbe body of the request.
            data: Data to be sent in the body of the request.
            **kwargs:
                erc(int): The expected (success) response code for the request.
                others: Passed on to the requests package.

        Raises:
            ApiError: If anything other than the expected response code is
                returned by the Webex Teams API endpoint.


def put(self, url, json=None, data=None, **kwargs):

check_type(url, basestring, may_be_none=False)<EOL>erc = kwargs.pop('<STR_LIT>', EXPECTED_RESPONSE_CODE['<STR_LIT>'])<EOL>response = self.request('<STR_LIT>', url, erc, json=json, data=data,<EOL>**kwargs)<EOL>return extract_and_parse_json(response)<EOL>

Sends a PUT request.

        Args:
            url(basestring): The URL of the API endpoint.
            json: Data to be sent in JSON format in tbe body of the request.
            data: Data to be sent in the body of the request.
            **kwargs:
                erc(int): The expected (success) response code for the request.
                others: Passed on to the requests package.

        Raises:
            ApiError: If anything other than the expected response code is
                returned by the Webex Teams API endpoint.


check_type(url, basestring, may_be_none=False)<EOL>erc = kwargs.pop('<STR_LIT>', EXPECTED_RESPONSE_CODE['<STR_LIT>'])<EOL>self.request('<STR_LIT>', url, erc, **kwargs)<EOL>

Sends a DELETE request.

        Args:
            url(basestring): The URL of the API endpoint.
            **kwargs:
                erc(int): The expected (success) response code for the request.
                others: Passed on to the requests package.

        Raises:
            ApiError: If anything other than the expected response code is
                returned by the Webex Teams API endpoint.


assert isinstance(string, basestring)<EOL>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>if isinstance(string, bytes):<EOL><INDENT>return string.decode('<STR_LIT:utf-8>')<EOL><DEDENT>else:<EOL><INDENT>return string<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if isinstance(string, str):<EOL><INDENT>return string.decode('<STR_LIT:utf-8>')<EOL><DEDENT>else:<EOL><INDENT>return string<EOL><DEDENT><DEDENT>

Convert a string (bytes, str or unicode) to unicode.


assert isinstance(string, basestring)<EOL>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>if isinstance(string, str):<EOL><INDENT>return string.encode('<STR_LIT:utf-8>')<EOL><DEDENT>else:<EOL><INDENT>return string<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if isinstance(string, unicode):<EOL><INDENT>return string.encode('<STR_LIT:utf-8>')<EOL><DEDENT>else:<EOL><INDENT>return string<EOL><DEDENT><DEDENT>

Convert a string (bytes, str or unicode) to bytes.


parsed_url = urllib.parse.urlparse(base_url)<EOL>if parsed_url.scheme and parsed_url.netloc:<EOL><INDENT>return parsed_url.geturl()<EOL><DEDENT>else:<EOL><INDENT>error_message = "<STR_LIT>""<STR_LIT>"<EOL>raise ValueError(error_message)<EOL><DEDENT>

Verify that base_url specifies a protocol and network location.


assert isinstance(string, basestring)<EOL>parsed_url = urllib.parse.urlparse(string)<EOL>return (<EOL>(<EOL>parsed_url.scheme.lower() == '<STR_LIT:http>'<EOL>or parsed_url.scheme.lower() == '<STR_LIT>'<EOL>)<EOL>and parsed_url.netloc<EOL>)<EOL>

Check to see if string is an validly-formatted web url.


assert isinstance(string, basestring)<EOL>return os.path.isfile(string)<EOL>

Check to see if string is a valid local file path.


assert isinstance(file_path, basestring)<EOL>assert is_local_file(file_path)<EOL>file_name = os.path.basename(file_path)<EOL>file_object = open(file_path, '<STR_LIT:rb>')<EOL>content_type = mimetypes.guess_type(file_name)[<NUM_LIT:0>] or '<STR_LIT>'<EOL>return EncodableFile(file_name=file_name,<EOL>file_object=file_object,<EOL>content_type=content_type)<EOL>

Open the file and return an EncodableFile tuple.


def check_type(o, acceptable_types, may_be_none=True):

if not isinstance(acceptable_types, tuple):<EOL><INDENT>acceptable_types = (acceptable_types,)<EOL><DEDENT>if may_be_none and o is None:<EOL><INDENT>pass<EOL><DEDENT>elif isinstance(o, acceptable_types):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>error_message = (<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(<EOL>types="<STR_LIT:U+002CU+0020>".join([repr(t.__name__) for t in acceptable_types]),<EOL>none="<STR_LIT>" if may_be_none else "<STR_LIT>",<EOL>o=o,<EOL>o_type=repr(type(o).__name__)<EOL>)<EOL>)<EOL>raise TypeError(error_message)<EOL><DEDENT>

Object is an instance of one of the acceptable types or None.

    Args:
        o: The object to be inspected.
        acceptable_types: A type or tuple of acceptable types.
        may_be_none(bool): Whether or not the object may be None.

    Raises:
        TypeError: If the object is None and may_be_none=False, or if the
            object is not an instance of one of the acceptable types.


dict_list = list(dictionaries)<EOL>dict_list.append(items)<EOL>result = {}<EOL>for d in dict_list:<EOL><INDENT>for key, value in d.items():<EOL><INDENT>if value is not None:<EOL><INDENT>result[key] = value<EOL><DEDENT><DEDENT><DEDENT>return result<EOL>

Creates a dict with the inputted items; pruning any that are `None`.

    Args:
        *dictionaries(dict): Dictionaries of items to be pruned and included.
        **items: Items to be pruned and included.

    Returns:
        dict: A dictionary containing all of the items with a 'non-None' value.


if kwargs:<EOL><INDENT>raise TypeError("<STR_LIT>".format(kwargs))<EOL><DEDENT>

Raise a TypeError if kwargs is not empty.


if response.status_code == expected_response_code:<EOL><INDENT>pass<EOL><DEDENT>elif response.status_code == RATE_LIMIT_RESPONSE_CODE:<EOL><INDENT>raise RateLimitError(response)<EOL><DEDENT>else:<EOL><INDENT>raise ApiError(response)<EOL><DEDENT>

Check response code against the expected code; raise ApiError.

    Checks the requests.response.status_code against the provided expected
    response code (erc), and raises a ApiError if they do not match.

    Args:
        response(requests.response): The response object returned by a request
            using the requests package.
        expected_response_code(int): The expected response code (HTTP response
            code).

    Raises:
        ApiError: If the requests.response.status_code does not match the
            provided expected response code (erc).


return json.loads(response.text, object_hook=OrderedDict)<EOL>

Extract and parse the JSON data from an requests.response object.

    Args:
        response(requests.response): The response object returned by a request
            using the requests package.

    Returns:
        The parsed JSON data as the appropriate native Python data type.


if isinstance(json_data, dict):<EOL><INDENT>return json_data<EOL><DEDENT>elif isinstance(json_data, basestring):<EOL><INDENT>return json.loads(json_data, object_hook=OrderedDict)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(json_data)<EOL>)<EOL><DEDENT>

Given a dictionary or JSON string; return a dictionary.

    Args:
        json_data(dict, str): Input JSON object.

    Returns:
        A Python dictionary with the contents of the JSON object.

    Raises:
        TypeError: If the input object is not a dictionary or string.


<EOL>return native_str("<STR_LIT>")<EOL>


return timedelta(<NUM_LIT:0>)<EOL>


@classmethod<EOL><INDENT>def strptime(cls, date_string, format=WEBEX_TEAMS_DATETIME_FORMAT):<DEDENT>

return super(WebexTeamsDateTime, cls).strptime(<EOL>date_string, format<EOL>).replace(tzinfo=ZuluTimeZone())<EOL>

strptime with the Webex Teams DateTime format as the default.


return super(WebexTeamsDateTime, self).strftime(fmt)<EOL>

strftime with the Webex Teams DateTime format as the default.


dt = self.astimezone(ZuluTimeZone())<EOL>return dt.strftime("<STR_LIT>").format(<EOL>self.microsecond // <NUM_LIT:1000><EOL>)<EOL>

Human readable string representation of this WebexTeamsDateTime.


response = requests.get(CAT_FACTS_URL, verify=False)<EOL>response.raise_for_status()<EOL>json_data = response.json()<EOL>return json_data['<STR_LIT>']<EOL>

Get a cat fact from catfact.ninja and return it as a string.

    Functions for Soundhound, Google, IBM Watson, or other APIs can be added
    to create the desired functionality into this bot.


<EOL>json_data = web.data()<EOL>print("<STR_LIT>")<EOL>print(json_data, "<STR_LIT:\n>")<EOL>webhook_obj = Webhook(json_data)<EOL>room = api.rooms.get(webhook_obj.data.roomId)<EOL>message = api.messages.get(webhook_obj.data.id)<EOL>person = api.people.get(message.personId)<EOL>print("<STR_LIT>".format(room.title))<EOL>print("<STR_LIT>".format(person.displayName))<EOL>print("<STR_LIT>".format(message.text))<EOL>me = api.people.me()<EOL>if message.personId == me.id:<EOL><INDENT>return '<STR_LIT:OK>'<EOL><DEDENT>else:<EOL><INDENT>if "<STR_LIT>" in message.text:<EOL><INDENT>print("<STR_LIT>")<EOL>cat_fact = get_catfact()<EOL>print("<STR_LIT>".format(cat_fact))<EOL>api.messages.create(room.id, text=cat_fact)<EOL><DEDENT><DEDENT>return '<STR_LIT:OK>'<EOL>

Respond to inbound webhook JSON HTTP POSTs from Webex Teams.


try:<EOL><INDENT>response = requests.get(url=NGROK_CLIENT_API_BASE_URL + "<STR_LIT>",<EOL>headers={'<STR_LIT>': '<STR_LIT:application/json>'})<EOL>response.raise_for_status()<EOL><DEDENT>except requests.exceptions.RequestException:<EOL><INDENT>print("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>return None<EOL><DEDENT>else:<EOL><INDENT>for tunnel in response.json()["<STR_LIT>"]:<EOL><INDENT>if tunnel.get("<STR_LIT>", "<STR_LIT>").startswith("<STR_LIT>"):<EOL><INDENT>print("<STR_LIT>", tunnel["<STR_LIT>"])<EOL>return tunnel["<STR_LIT>"]<EOL><DEDENT><DEDENT><DEDENT>

Get the ngrok public HTTP URL from the local client API.


for webhook in api.webhooks.list():<EOL><INDENT>if webhook.name == name:<EOL><INDENT>print("<STR_LIT>", webhook.name, webhook.targetUrl)<EOL>api.webhooks.delete(webhook.id)<EOL><DEDENT><DEDENT>


Create a Webex Teams webhook pointing to the public ngrok URL.


api = WebexTeamsAPI()<EOL>delete_webhooks_with_name(api, name=WEBHOOK_NAME)<EOL>public_url = get_ngrok_public_url()<EOL>if public_url is not None:<EOL><INDENT>create_ngrok_webhook(api, public_url)<EOL><DEDENT>

Delete previous webhooks. If local ngrok tunnel, create a webhook.


@flask_app.route('<STR_LIT>', methods=['<STR_LIT:GET>', '<STR_LIT:POST>'])<EOL>def webex_teams_webhook_events():

if request.method == '<STR_LIT:GET>':<EOL><INDENT>return ("""<STR_LIT>""".format(get_catfact()))<EOL><DEDENT>elif request.method == '<STR_LIT:POST>':<EOL><INDENT>"""<STR_LIT>"""<EOL>json_data = request.json<EOL>print("<STR_LIT:\n>")<EOL>print("<STR_LIT>")<EOL>print(json_data)<EOL>print("<STR_LIT:\n>")<EOL>webhook_obj = Webhook(json_data)<EOL>room = api.rooms.get(webhook_obj.data.roomId)<EOL>message = api.messages.get(webhook_obj.data.id)<EOL>person = api.people.get(message.personId)<EOL>print("<STR_LIT>".format(room.title))<EOL>print("<STR_LIT>".format(person.displayName))<EOL>print("<STR_LIT>".format(message.text))<EOL>me = api.people.me()<EOL>if message.personId == me.id:<EOL><INDENT>return '<STR_LIT:OK>'<EOL><DEDENT>else:<EOL><INDENT>if "<STR_LIT>" in message.text:<EOL><INDENT>print("<STR_LIT>")<EOL>cat_fact = get_catfact()<EOL>print("<STR_LIT>".format(cat_fact))<EOL>api.messages.create(room.id, text=cat_fact)<EOL><DEDENT>return '<STR_LIT:OK>'<EOL><DEDENT><DEDENT>

Processes incoming requests to the '/events' URI.


<EOL>json_data = request.json<EOL>log.info("<STR_LIT:\n>")<EOL>log.info("<STR_LIT>")<EOL>log.info(json_data)<EOL>log.info("<STR_LIT:\n>")<EOL>webhook_obj = Webhook(json_data)<EOL>room = api.rooms.get(webhook_obj.data.roomId)<EOL>message = api.messages.get(webhook_obj.data.id)<EOL>person = api.people.get(message.personId)<EOL>log.info("<STR_LIT>".format(room.title))<EOL>log.info("<STR_LIT>".format(person.displayName))<EOL>log.info("<STR_LIT>".format(message.text))<EOL>me = api.people.me()<EOL>if message.personId == me.id:<EOL><INDENT>return {'<STR_LIT>': '<STR_LIT:OK>'}<EOL><DEDENT>else:<EOL><INDENT>if "<STR_LIT>" in message.text:<EOL><INDENT>log.info("<STR_LIT>")<EOL>catfact = get_catfact()<EOL>log.info("<STR_LIT>".format(catfact))<EOL>api.messages.create(room.id, text=catfact)<EOL><DEDENT>return {'<STR_LIT>': '<STR_LIT:OK>'}<EOL><DEDENT>

Respond to inbound webhook JSON HTTP POST from Webex Teams.


root = os.path.realpath(os.path.abspath(os.getcwd()))<EOL>setup_py = os.path.join(root, "<STR_LIT>")<EOL>versioneer_py = os.path.join(root, "<STR_LIT>")<EOL>if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):<EOL><INDENT>root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[<NUM_LIT:0>])))<EOL>setup_py = os.path.join(root, "<STR_LIT>")<EOL>versioneer_py = os.path.join(root, "<STR_LIT>")<EOL><DEDENT>if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):<EOL><INDENT>err = ("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>raise VersioneerBadRootError(err)<EOL><DEDENT>try:<EOL><INDENT>me = os.path.realpath(os.path.abspath(__file__))<EOL>me_dir = os.path.normcase(os.path.splitext(me)[<NUM_LIT:0>])<EOL>vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[<NUM_LIT:0>])<EOL>if me_dir != vsr_dir:<EOL><INDENT>print("<STR_LIT>"<EOL>% (os.path.dirname(me), versioneer_py))<EOL><DEDENT><DEDENT>except NameError:<EOL><INDENT>pass<EOL><DEDENT>return root<EOL>

Get the project root directory.

    We require that all commands are run from the project root, i.e. the
    directory that contains setup.py, setup.cfg, and versioneer.py .


<EOL>setup_cfg = os.path.join(root, "<STR_LIT>")<EOL>parser = configparser.SafeConfigParser()<EOL>with open(setup_cfg, "<STR_LIT:r>") as f:<EOL><INDENT>parser.readfp(f)<EOL><DEDENT>VCS = parser.get("<STR_LIT>", "<STR_LIT>")  <EOL>def get(parser, name):<EOL><INDENT>if parser.has_option("<STR_LIT>", name):<EOL><INDENT>return parser.get("<STR_LIT>", name)<EOL><DEDENT>return None<EOL><DEDENT>cfg = VersioneerConfig()<EOL>cfg.VCS = VCS<EOL>cfg.style = get(parser, "<STR_LIT>") or "<STR_LIT>"<EOL>cfg.versionfile_source = get(parser, "<STR_LIT>")<EOL>cfg.versionfile_build = get(parser, "<STR_LIT>")<EOL>cfg.tag_prefix = get(parser, "<STR_LIT>")<EOL>if cfg.tag_prefix in ("<STR_LIT>", '<STR_LIT>'):<EOL><INDENT>cfg.tag_prefix = "<STR_LIT>"<EOL><DEDENT>cfg.parentdir_prefix = get(parser, "<STR_LIT>")<EOL>cfg.verbose = get(parser, "<STR_LIT>")<EOL>return cfg<EOL>

Read the project setup.cfg file to determine Versioneer config.


def decorate(f):<EOL><INDENT>"""<STR_LIT>"""<EOL>if vcs not in HANDLERS:<EOL><INDENT>HANDLERS[vcs] = {}<EOL><DEDENT>HANDLERS[vcs][method] = f<EOL>return f<EOL><DEDENT>return decorate<EOL>

Decorator to mark a method as the handler for a particular VCS.


def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,<EOL>env=None):

assert isinstance(commands, list)<EOL>p = None<EOL>for c in commands:<EOL><INDENT>try:<EOL><INDENT>dispcmd = str([c] + args)<EOL>p = subprocess.Popen([c] + args, cwd=cwd, env=env,<EOL>stdout=subprocess.PIPE,<EOL>stderr=(subprocess.PIPE if hide_stderr<EOL>else None))<EOL>break<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>e = sys.exc_info()[<NUM_LIT:1>]<EOL>if e.errno == errno.ENOENT:<EOL><INDENT>continue<EOL><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % dispcmd)<EOL>print(e)<EOL><DEDENT>return None, None<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % (commands,))<EOL><DEDENT>return None, None<EOL><DEDENT>stdout = p.communicate()[<NUM_LIT:0>].strip()<EOL>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>stdout = stdout.decode()<EOL><DEDENT>if p.returncode != <NUM_LIT:0>:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % dispcmd)<EOL>print("<STR_LIT>" % stdout)<EOL><DEDENT>return None, p.returncode<EOL><DEDENT>return stdout, p.returncode<EOL>


<EOL>keywords = {}<EOL>try:<EOL><INDENT>f = open(versionfile_abs, "<STR_LIT:r>")<EOL>for line in f.readlines():<EOL><INDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT:date>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT><DEDENT>f.close()<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT>return keywords<EOL>

Extract version information from the given file.


@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_versions_from_keywords(keywords, tag_prefix, verbose):

if not keywords:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>date = keywords.get("<STR_LIT:date>")<EOL>if date is not None:<EOL><INDENT>date = date.strip().replace("<STR_LIT:U+0020>", "<STR_LIT:T>", <NUM_LIT:1>).replace("<STR_LIT:U+0020>", "<STR_LIT>", <NUM_LIT:1>)<EOL><DEDENT>refnames = keywords["<STR_LIT>"].strip()<EOL>if refnames.startswith("<STR_LIT>"):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>refs = set([r.strip() for r in refnames.strip("<STR_LIT>").split("<STR_LIT:U+002C>")])<EOL>TAG = "<STR_LIT>"<EOL>tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])<EOL>if not tags:<EOL><INDENT>tags = set([r for r in refs if re.search(r'<STR_LIT>', r)])<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(refs - tags))<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(sorted(tags)))<EOL><DEDENT>for ref in sorted(tags):<EOL><INDENT>if ref.startswith(tag_prefix):<EOL><INDENT>r = ref[len(tag_prefix):]<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % r)<EOL><DEDENT>return {"<STR_LIT:version>": r,<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None,<EOL>"<STR_LIT:date>": date}<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": "<STR_LIT>", "<STR_LIT:date>": None}<EOL>

Get version information from git keywords.


@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):

GITS = ["<STR_LIT>"]<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>GITS = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root,<EOL>hide_stderr=True)<EOL>if rc != <NUM_LIT:0>:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % root)<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>describe_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>" % tag_prefix],<EOL>cwd=root)<EOL>if describe_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>describe_out = describe_out.strip()<EOL>full_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root)<EOL>if full_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>full_out = full_out.strip()<EOL>pieces = {}<EOL>pieces["<STR_LIT>"] = full_out<EOL>pieces["<STR_LIT>"] = full_out[:<NUM_LIT:7>]  <EOL>pieces["<STR_LIT:error>"] = None<EOL>git_describe = describe_out<EOL>dirty = git_describe.endswith("<STR_LIT>")<EOL>pieces["<STR_LIT>"] = dirty<EOL>if dirty:<EOL><INDENT>git_describe = git_describe[:git_describe.rindex("<STR_LIT>")]<EOL><DEDENT>if "<STR_LIT:->" in git_describe:<EOL><INDENT>mo = re.search(r'<STR_LIT>', git_describe)<EOL>if not mo:<EOL><INDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% describe_out)<EOL>return pieces<EOL><DEDENT>full_tag = mo.group(<NUM_LIT:1>)<EOL>if not full_tag.startswith(tag_prefix):<EOL><INDENT>if verbose:<EOL><INDENT>fmt = "<STR_LIT>"<EOL>print(fmt % (full_tag, tag_prefix))<EOL><DEDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% (full_tag, tag_prefix))<EOL>return pieces<EOL><DEDENT>pieces["<STR_LIT>"] = full_tag[len(tag_prefix):]<EOL>pieces["<STR_LIT>"] = int(mo.group(<NUM_LIT:2>))<EOL>pieces["<STR_LIT>"] = mo.group(<NUM_LIT:3>)<EOL><DEDENT>else:<EOL><INDENT>pieces["<STR_LIT>"] = None<EOL>count_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>cwd=root)<EOL>pieces["<STR_LIT>"] = int(count_out)  <EOL><DEDENT>date = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>cwd=root)[<NUM_LIT:0>].strip()<EOL>pieces["<STR_LIT:date>"] = date.strip().replace("<STR_LIT:U+0020>", "<STR_LIT:T>", <NUM_LIT:1>).replace("<STR_LIT:U+0020>", "<STR_LIT>", <NUM_LIT:1>)<EOL>return pieces<EOL>

Get version from 'git describe' in the root of the source tree.

    This only gets called if the git-archive 'subst' keywords were *not*
    expanded, and _version.py hasn't already been rewritten with a short
    version string, meaning we're inside a checked out source tree.


def do_vcs_install(manifest_in, versionfile_source, ipy):

GITS = ["<STR_LIT>"]<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>GITS = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>files = [manifest_in, versionfile_source]<EOL>if ipy:<EOL><INDENT>files.append(ipy)<EOL><DEDENT>try:<EOL><INDENT>me = __file__<EOL>if me.endswith("<STR_LIT>") or me.endswith("<STR_LIT>"):<EOL><INDENT>me = os.path.splitext(me)[<NUM_LIT:0>] + "<STR_LIT>"<EOL><DEDENT>versioneer_file = os.path.relpath(me)<EOL><DEDENT>except NameError:<EOL><INDENT>versioneer_file = "<STR_LIT>"<EOL><DEDENT>files.append(versioneer_file)<EOL>present = False<EOL>try:<EOL><INDENT>f = open("<STR_LIT>", "<STR_LIT:r>")<EOL>for line in f.readlines():<EOL><INDENT>if line.strip().startswith(versionfile_source):<EOL><INDENT>if "<STR_LIT>" in line.strip().split()[<NUM_LIT:1>:]:<EOL><INDENT>present = True<EOL><DEDENT><DEDENT><DEDENT>f.close()<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT>if not present:<EOL><INDENT>f = open("<STR_LIT>", "<STR_LIT>")<EOL>f.write("<STR_LIT>" % versionfile_source)<EOL>f.close()<EOL>files.append("<STR_LIT>")<EOL><DEDENT>run_command(GITS, ["<STR_LIT>", "<STR_LIT>"] + files)<EOL>

Git-specific installation logic for Versioneer.

    For Git, this means creating/changing .gitattributes to mark _version.py
    for export-subst keyword substitution.


def versions_from_parentdir(parentdir_prefix, root, verbose):

rootdirs = []<EOL>for i in range(<NUM_LIT:3>):<EOL><INDENT>dirname = os.path.basename(root)<EOL>if dirname.startswith(parentdir_prefix):<EOL><INDENT>return {"<STR_LIT:version>": dirname[len(parentdir_prefix):],<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None, "<STR_LIT:date>": None}<EOL><DEDENT>else:<EOL><INDENT>rootdirs.append(root)<EOL>root = os.path.dirname(root)  <EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" %<EOL>(str(rootdirs), parentdir_prefix))<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL>

Try to determine the version from the parent directory name.

    Source tarballs conventionally unpack into a directory that includes both
    the project name and a version string. We will also support searching up
    two directory levels for an appropriately named parent directory


try:<EOL><INDENT>with open(filename) as f:<EOL><INDENT>contents = f.read()<EOL><DEDENT><DEDENT>except EnvironmentError:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>mo = re.search(r"<STR_LIT>",<EOL>contents, re.M | re.S)<EOL>if not mo:<EOL><INDENT>mo = re.search(r"<STR_LIT>",<EOL>contents, re.M | re.S)<EOL><DEDENT>if not mo:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>return json.loads(mo.group(<NUM_LIT:1>))<EOL>

Try to determine the version from _version.py if present.


os.unlink(filename)<EOL>contents = json.dumps(versions, sort_keys=True,<EOL>indent=<NUM_LIT:1>, separators=("<STR_LIT:U+002C>", "<STR_LIT>"))<EOL>with open(filename, "<STR_LIT:w>") as f:<EOL><INDENT>f.write(SHORT_VERSION_PY % contents)<EOL><DEDENT>print("<STR_LIT>" % (filename, versions["<STR_LIT:version>"]))<EOL>

Write the given version number to the given _version.py file.


if "<STR_LIT:+>" in pieces.get("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>return "<STR_LIT:.>"<EOL><DEDENT>return "<STR_LIT:+>"<EOL>

Return a + if we don't already have one, else return a .


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % (pieces["<STR_LIT>"],<EOL>pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT>return rendered<EOL>

Build up version string, with post-release "local version identifier".

    Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
    get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty

    Exceptions:
    1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>

TAG[.post.devDISTANCE] -- No -dirty.

    Exceptions:
    1: no tags. 0.post.devDISTANCE


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>

TAG[.postDISTANCE[.dev0]+gHEX] .

    The ".dev0" means dirty. Note that .dev0 sorts backwards
    (a dirty tree will appear "older" than the corresponding clean one),
    but you shouldn't be releasing software with -dirty anyways.

    Exceptions:
    1: no tags. 0.postDISTANCE[.dev0]


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT>return rendered<EOL>

TAG[.postDISTANCE[.dev0]] .

    The ".dev0" means dirty.

    Eexceptions:
    1: no tags. 0.postDISTANCE[.dev0]


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>

TAG[-DISTANCE-gHEX][-dirty].

    Like 'git describe --tags --dirty --always'.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>

TAG-DISTANCE-gHEX[-dirty].

    Like 'git describe --tags --dirty --always -long'.
    The distance/hash is unconditional.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)


if pieces["<STR_LIT:error>"]:<EOL><INDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": pieces.get("<STR_LIT>"),<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": pieces["<STR_LIT:error>"],<EOL>"<STR_LIT:date>": None}<EOL><DEDENT>if not style or style == "<STR_LIT:default>":<EOL><INDENT>style = "<STR_LIT>"  <EOL><DEDENT>if style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_pre(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_post(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_old(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_git_describe(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_git_describe_long(pieces)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % style)<EOL><DEDENT>return {"<STR_LIT:version>": rendered, "<STR_LIT>": pieces["<STR_LIT>"],<EOL>"<STR_LIT>": pieces["<STR_LIT>"], "<STR_LIT:error>": None,<EOL>"<STR_LIT:date>": pieces.get("<STR_LIT:date>")}<EOL>

Render the given version pieces into the requested style.


if "<STR_LIT>" in sys.modules:<EOL><INDENT>del sys.modules["<STR_LIT>"]<EOL><DEDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>assert cfg.VCS is not None, "<STR_LIT>"<EOL>handlers = HANDLERS.get(cfg.VCS)<EOL>assert handlers, "<STR_LIT>" % cfg.VCS<EOL>verbose = verbose or cfg.verbose<EOL>assert cfg.versionfile_source is not None,"<STR_LIT>"<EOL>assert cfg.tag_prefix is not None, "<STR_LIT>"<EOL>versionfile_abs = os.path.join(root, cfg.versionfile_source)<EOL>get_keywords_f = handlers.get("<STR_LIT>")<EOL>from_keywords_f = handlers.get("<STR_LIT>")<EOL>if get_keywords_f and from_keywords_f:<EOL><INDENT>try:<EOL><INDENT>keywords = get_keywords_f(versionfile_abs)<EOL>ver = from_keywords_f(keywords, cfg.tag_prefix, verbose)<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % ver)<EOL><DEDENT>return ver<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>try:<EOL><INDENT>ver = versions_from_file(versionfile_abs)<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % (versionfile_abs, ver))<EOL><DEDENT>return ver<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>from_vcs_f = handlers.get("<STR_LIT>")<EOL>if from_vcs_f:<EOL><INDENT>try:<EOL><INDENT>pieces = from_vcs_f(cfg.tag_prefix, root, verbose)<EOL>ver = render(pieces, cfg.style)<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % ver)<EOL><DEDENT>return ver<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>try:<EOL><INDENT>if cfg.parentdir_prefix:<EOL><INDENT>ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose)<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % ver)<EOL><DEDENT>return ver<EOL><DEDENT><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>", "<STR_LIT>": None,<EOL>"<STR_LIT>": None, "<STR_LIT:error>": "<STR_LIT>",<EOL>"<STR_LIT:date>": None}<EOL>

Get the project version from whatever source is available.

    Returns dict with two keys: 'version' and 'full'.


return get_versions()["<STR_LIT:version>"]<EOL>

Get the short version string for this project.


if "<STR_LIT>" in sys.modules:<EOL><INDENT>del sys.modules["<STR_LIT>"]<EOL><DEDENT>cmds = {}<EOL>from distutils.core import Command<EOL>class cmd_version(Command):<EOL><INDENT>description = "<STR_LIT>"<EOL>user_options = []<EOL>boolean_options = []<EOL>def initialize_options(self):<EOL><INDENT>pass<EOL><DEDENT>def finalize_options(self):<EOL><INDENT>pass<EOL><DEDENT>def run(self):<EOL><INDENT>vers = get_versions(verbose=True)<EOL>print("<STR_LIT>" % vers["<STR_LIT:version>"])<EOL>print("<STR_LIT>" % vers.get("<STR_LIT>"))<EOL>print("<STR_LIT>" % vers.get("<STR_LIT>"))<EOL>print("<STR_LIT>" % vers.get("<STR_LIT:date>"))<EOL>if vers["<STR_LIT:error>"]:<EOL><INDENT>print("<STR_LIT>" % vers["<STR_LIT:error>"])<EOL><DEDENT><DEDENT><DEDENT>cmds["<STR_LIT:version>"] = cmd_version<EOL>if "<STR_LIT>" in sys.modules:<EOL><INDENT>from setuptools.command.build_py import build_py as _build_py<EOL><DEDENT>else:<EOL><INDENT>from distutils.command.build_py import build_py as _build_py<EOL><DEDENT>class cmd_build_py(_build_py):<EOL><INDENT>def run(self):<EOL><INDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>versions = get_versions()<EOL>_build_py.run(self)<EOL>if cfg.versionfile_build:<EOL><INDENT>target_versionfile = os.path.join(self.build_lib,<EOL>cfg.versionfile_build)<EOL>print("<STR_LIT>" % target_versionfile)<EOL>write_to_version_file(target_versionfile, versions)<EOL><DEDENT><DEDENT><DEDENT>cmds["<STR_LIT>"] = cmd_build_py<EOL>if "<STR_LIT>" in sys.modules:  <EOL><INDENT>from cx_Freeze.dist import build_exe as _build_exe<EOL>class cmd_build_exe(_build_exe):<EOL><INDENT>def run(self):<EOL><INDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>versions = get_versions()<EOL>target_versionfile = cfg.versionfile_source<EOL>print("<STR_LIT>" % target_versionfile)<EOL>write_to_version_file(target_versionfile, versions)<EOL>_build_exe.run(self)<EOL>os.unlink(target_versionfile)<EOL>with open(cfg.versionfile_source, "<STR_LIT:w>") as f:<EOL><INDENT>LONG = LONG_VERSION_PY[cfg.VCS]<EOL>f.write(LONG %<EOL>{"<STR_LIT>": "<STR_LIT:$>",<EOL>"<STR_LIT>": cfg.style,<EOL>"<STR_LIT>": cfg.tag_prefix,<EOL>"<STR_LIT>": cfg.parentdir_prefix,<EOL>"<STR_LIT>": cfg.versionfile_source,<EOL>})<EOL><DEDENT><DEDENT><DEDENT>cmds["<STR_LIT>"] = cmd_build_exe<EOL>del cmds["<STR_LIT>"]<EOL><DEDENT>if '<STR_LIT>' in sys.modules:  <EOL><INDENT>try:<EOL><INDENT>from py2exe.distutils_buildexe import py2exe as _py2exe  <EOL><DEDENT>except ImportError:<EOL><INDENT>from py2exe.build_exe import py2exe as _py2exe  <EOL><DEDENT>class cmd_py2exe(_py2exe):<EOL><INDENT>def run(self):<EOL><INDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>versions = get_versions()<EOL>target_versionfile = cfg.versionfile_source<EOL>print("<STR_LIT>" % target_versionfile)<EOL>write_to_version_file(target_versionfile, versions)<EOL>_py2exe.run(self)<EOL>os.unlink(target_versionfile)<EOL>with open(cfg.versionfile_source, "<STR_LIT:w>") as f:<EOL><INDENT>LONG = LONG_VERSION_PY[cfg.VCS]<EOL>f.write(LONG %<EOL>{"<STR_LIT>": "<STR_LIT:$>",<EOL>"<STR_LIT>": cfg.style,<EOL>"<STR_LIT>": cfg.tag_prefix,<EOL>"<STR_LIT>": cfg.parentdir_prefix,<EOL>"<STR_LIT>": cfg.versionfile_source,<EOL>})<EOL><DEDENT><DEDENT><DEDENT>cmds["<STR_LIT>"] = cmd_py2exe<EOL><DEDENT>if "<STR_LIT>" in sys.modules:<EOL><INDENT>from setuptools.command.sdist import sdist as _sdist<EOL><DEDENT>else:<EOL><INDENT>from distutils.command.sdist import sdist as _sdist<EOL><DEDENT>class cmd_sdist(_sdist):<EOL><INDENT>def run(self):<EOL><INDENT>versions = get_versions()<EOL>self._versioneer_generated_versions = versions<EOL>self.distribution.metadata.version = versions["<STR_LIT:version>"]<EOL>return _sdist.run(self)<EOL><DEDENT>def make_release_tree(self, base_dir, files):<EOL><INDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>_sdist.make_release_tree(self, base_dir, files)<EOL>target_versionfile = os.path.join(base_dir, cfg.versionfile_source)<EOL>print("<STR_LIT>" % target_versionfile)<EOL>write_to_version_file(target_versionfile,<EOL>self._versioneer_generated_versions)<EOL><DEDENT><DEDENT>cmds["<STR_LIT>"] = cmd_sdist<EOL>return cmds<EOL>

Get the custom setuptools/distutils subclasses used by Versioneer.


root = get_root()<EOL>try:<EOL><INDENT>cfg = get_config_from_root(root)<EOL><DEDENT>except (EnvironmentError, configparser.NoSectionError,<EOL>configparser.NoOptionError) as e:<EOL><INDENT>if isinstance(e, (EnvironmentError, configparser.NoSectionError)):<EOL><INDENT>print("<STR_LIT>",<EOL>file=sys.stderr)<EOL>with open(os.path.join(root, "<STR_LIT>"), "<STR_LIT:a>") as f:<EOL><INDENT>f.write(SAMPLE_CONFIG)<EOL><DEDENT><DEDENT>print(CONFIG_ERROR, file=sys.stderr)<EOL>return <NUM_LIT:1><EOL><DEDENT>print("<STR_LIT>" % cfg.versionfile_source)<EOL>with open(cfg.versionfile_source, "<STR_LIT:w>") as f:<EOL><INDENT>LONG = LONG_VERSION_PY[cfg.VCS]<EOL>f.write(LONG % {"<STR_LIT>": "<STR_LIT:$>",<EOL>"<STR_LIT>": cfg.style,<EOL>"<STR_LIT>": cfg.tag_prefix,<EOL>"<STR_LIT>": cfg.parentdir_prefix,<EOL>"<STR_LIT>": cfg.versionfile_source,<EOL>})<EOL><DEDENT>ipy = os.path.join(os.path.dirname(cfg.versionfile_source),<EOL>"<STR_LIT>")<EOL>if os.path.exists(ipy):<EOL><INDENT>try:<EOL><INDENT>with open(ipy, "<STR_LIT:r>") as f:<EOL><INDENT>old = f.read()<EOL><DEDENT><DEDENT>except EnvironmentError:<EOL><INDENT>old = "<STR_LIT>"<EOL><DEDENT>if INIT_PY_SNIPPET not in old:<EOL><INDENT>print("<STR_LIT>" % ipy)<EOL>with open(ipy, "<STR_LIT:a>") as f:<EOL><INDENT>f.write(INIT_PY_SNIPPET)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print("<STR_LIT>" % ipy)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print("<STR_LIT>" % ipy)<EOL>ipy = None<EOL><DEDENT>manifest_in = os.path.join(root, "<STR_LIT>")<EOL>simple_includes = set()<EOL>try:<EOL><INDENT>with open(manifest_in, "<STR_LIT:r>") as f:<EOL><INDENT>for line in f:<EOL><INDENT>if line.startswith("<STR_LIT>"):<EOL><INDENT>for include in line.split()[<NUM_LIT:1>:]:<EOL><INDENT>simple_includes.add(include)<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT>if "<STR_LIT>" not in simple_includes:<EOL><INDENT>print("<STR_LIT>")<EOL>with open(manifest_in, "<STR_LIT:a>") as f:<EOL><INDENT>f.write("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>if cfg.versionfile_source not in simple_includes:<EOL><INDENT>print("<STR_LIT>" %<EOL>cfg.versionfile_source)<EOL>with open(manifest_in, "<STR_LIT:a>") as f:<EOL><INDENT>f.write("<STR_LIT>" % cfg.versionfile_source)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>do_vcs_install(manifest_in, cfg.versionfile_source, ipy)<EOL>return <NUM_LIT:0><EOL>

Main VCS-independent setup function for installing Versioneer.


found = set()<EOL>setters = False<EOL>errors = <NUM_LIT:0><EOL>with open("<STR_LIT>", "<STR_LIT:r>") as f:<EOL><INDENT>for line in f.readlines():<EOL><INDENT>if "<STR_LIT>" in line:<EOL><INDENT>found.add("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in line:<EOL><INDENT>found.add("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in line:<EOL><INDENT>found.add("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in line:<EOL><INDENT>setters = True<EOL><DEDENT>if "<STR_LIT>" in line:<EOL><INDENT>setters = True<EOL><DEDENT><DEDENT><DEDENT>if len(found) != <NUM_LIT:3>:<EOL><INDENT>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>errors += <NUM_LIT:1><EOL><DEDENT>if setters:<EOL><INDENT>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>errors += <NUM_LIT:1><EOL><DEDENT>return errors<EOL>

Validate the contents of setup.py against Versioneer's expectations.


self._repo = repository<EOL>self._api = Github(token)<EOL>

Args:
    repository (str): a string in the form 'owner/repository-name'
        indicating the GitHub repository to report against.
    token (str): a GitHub token obtained following:
        https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/


def report(self, branch, commit, infourl=None):

issue_number = self._get_report_issue_number()<EOL>if issue_number:<EOL><INDENT>self._report_as_comment(issue_number, branch, commit, infourl)<EOL><DEDENT>else:<EOL><INDENT>self._report_as_issue(branch, commit, infourl)<EOL><DEDENT>

Report on GitHub that the specified branch is failing to build at
        the specified commit. The method will open an issue indicating that
        the branch is failing. If there is an issue already open, it will add a
        comment avoiding to report twice about the same failure.

        Args:
            branch (str): branch name to report about.
            commit (str): commit hash at which the build fails.
            infourl (str): URL with extra info about the failure such as the
                build logs.


time.sleep(<NUM_LIT:1>)<EOL>return x<EOL>


pass<EOL>


q = QuantumRegister(<NUM_LIT:4>)<EOL>c = ClassicalRegister(<NUM_LIT:4>)<EOL>circ1 = QuantumCircuit(q, c, name='<STR_LIT>')<EOL>circ1.h(q[<NUM_LIT:0>])<EOL>circ1.crz(<NUM_LIT:0.1>, q[<NUM_LIT:0>], q[<NUM_LIT:1>])<EOL>circ1.iden(q[<NUM_LIT:1>])<EOL>circ1.u3(<NUM_LIT:0.1>, <NUM_LIT>, -<NUM_LIT>, q[<NUM_LIT:0>])<EOL>circ1.barrier()<EOL>circ1.measure(q, c)<EOL>circ1.rz(<NUM_LIT>, q[<NUM_LIT:0>]).c_if(c, <NUM_LIT:6>)<EOL>inst = circ1.to_instruction()<EOL>circ2 = QuantumCircuit(q, c, name='<STR_LIT>')<EOL>circ2.append(inst, q[:])<EOL>self.assertEqual(circ1, circ2)<EOL>

test converting between circuit and instruction and back
        preserves the circuit


def linear(times: np.ndarray, m: float, b: float = <NUM_LIT:0.1>) -> np.ndarray:

return m*times+b<EOL>

Linear test function
    Args:
        times: Input times.
        m: Slope.
        b: Intercept
    Returns:
        np.ndarray


qasm = Qasm(file_path)<EOL>return qasm.parse().qasm(prec)<EOL>

Simple helper
- file_path: Path to the OpenQASM file
- prec: Precision for the returned string


direction = np.zeros(<NUM_LIT:3>, dtype=float)<EOL>if axis == '<STR_LIT:x>':<EOL><INDENT>direction[<NUM_LIT:0>] = <NUM_LIT:1><EOL><DEDENT>elif axis == '<STR_LIT:y>':<EOL><INDENT>direction[<NUM_LIT:1>] = <NUM_LIT:1><EOL><DEDENT>elif axis == '<STR_LIT:z>':<EOL><INDENT>direction[<NUM_LIT:2>] = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>direction = np.asarray(direction, dtype=float)<EOL>sin_angle = math.sin(angle)<EOL>cos_angle = math.cos(angle)<EOL>rot = np.diag([cos_angle, cos_angle, cos_angle])<EOL>rot += np.outer(direction, direction) * (<NUM_LIT:1.0> - cos_angle)<EOL>direction *= sin_angle<EOL>rot += np.array([<EOL>[<NUM_LIT:0>, -direction[<NUM_LIT:2>], direction[<NUM_LIT:1>]],<EOL>[direction[<NUM_LIT:2>], <NUM_LIT:0>, -direction[<NUM_LIT:0>]],<EOL>[-direction[<NUM_LIT:1>], direction[<NUM_LIT:0>], <NUM_LIT:0>]<EOL>])<EOL>return rot<EOL>

Generates a rotation matrix for a given angle and axis.

    Args:
        angle (float): Rotation angle in radians.
        axis (str): Axis for rotation: 'x', 'y', 'z'

    Returns:
        ndarray: Rotation matrix.

    Raises:
        ValueError: Invalid input axis.


z = np.asarray([<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>]).astype(np.bool)<EOL>x = np.asarray([<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>]).astype(np.bool)<EOL>self.ref_p = Pauli(z, x)<EOL>self.ref_label = '<STR_LIT>'<EOL>self.ref_matrix = np.array([[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> - <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> - <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> - <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> - <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> - <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> - <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> - <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> - <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>]])<EOL>


psi = np.random.rand(n) + <NUM_LIT> * np.random.rand(n)<EOL>rho = np.outer(psi, psi.conj())<EOL>rho /= np.trace(rho)<EOL>return rho<EOL>


@classmethod<EOL><INDENT>def rand_matrix(cls, rows, cols=None, real=False):<DEDENT>

if cols is None:<EOL><INDENT>cols = rows<EOL><DEDENT>if real:<EOL><INDENT>return np.random.rand(rows, cols)<EOL><DEDENT>return np.random.rand(rows, cols) + <NUM_LIT> * np.random.rand(rows, cols)<EOL>


qr = QuantumRegister(<NUM_LIT:2>)<EOL>circ = QuantumCircuit(qr)<EOL>circ.h(qr[<NUM_LIT:0>])<EOL>circ.x(qr[<NUM_LIT:1>])<EOL>target = Operator(np.kron(self.UX, self.UH))<EOL>return circ, target<EOL>

Return a unitary circuit and the corresponding unitary array.


qr = QuantumRegister(<NUM_LIT:2>)<EOL>cr = ClassicalRegister(<NUM_LIT:2>)<EOL>circ = QuantumCircuit(qr, cr)<EOL>circ.h(qr[<NUM_LIT:0>])<EOL>circ.x(qr[<NUM_LIT:1>])<EOL>circ.measure(qr, cr)<EOL>return circ<EOL>

Return a unitary circuit with measurement.


comparison = np.allclose(<EOL>obj1, obj2, rtol=rtol, atol=atol, equal_nan=equal_nan)<EOL>if msg is None:<EOL><INDENT>msg = '<STR_LIT>'<EOL><DEDENT>msg += '<STR_LIT>'.format(obj1, obj2)<EOL>self.assertTrue(comparison, msg=msg)<EOL>

Assert two objects are equal using Numpy.allclose.


def _compare_add_to_superop(self, rep, dim, samples, unitary=False):

for _ in range(samples):<EOL><INDENT>if unitary:<EOL><INDENT>mat1 = self.rand_matrix(dim, dim)<EOL>mat2 = self.rand_matrix(dim, dim)<EOL>sop1 = np.kron(np.conj(mat1), mat1)<EOL>sop2 = np.kron(np.conj(mat2), mat2)<EOL><DEDENT>else:<EOL><INDENT>sop1 = self.rand_matrix(dim * dim, dim * dim)<EOL>sop2 = self.rand_matrix(dim * dim, dim * dim)<EOL><DEDENT>targ = SuperOp(sop1 + sop2)<EOL>channel = SuperOp(rep(SuperOp(sop1)).add(rep(SuperOp(sop2))))<EOL>self.assertEqual(channel, targ)<EOL><DEDENT>

Test channel addition is equivalent to SuperOp


def _compare_subtract_to_superop(self, rep, dim, samples, unitary=False):

for _ in range(samples):<EOL><INDENT>if unitary:<EOL><INDENT>mat1 = self.rand_matrix(dim, dim)<EOL>mat2 = self.rand_matrix(dim, dim)<EOL>sop1 = np.kron(np.conj(mat1), mat1)<EOL>sop2 = np.kron(np.conj(mat2), mat2)<EOL><DEDENT>else:<EOL><INDENT>sop1 = self.rand_matrix(dim * dim, dim * dim)<EOL>sop2 = self.rand_matrix(dim * dim, dim * dim)<EOL><DEDENT>targ = SuperOp(sop1 - sop2)<EOL>channel = SuperOp(rep(SuperOp(sop1)).subtract(rep(SuperOp(sop2))))<EOL>self.assertEqual(channel, targ)<EOL><DEDENT>

Test channel subtraction is equivalent to SuperOp


def _compare_multiply_to_superop(self, rep, dim, samples, unitary=False):

for _ in range(samples):<EOL><INDENT>if unitary:<EOL><INDENT>mat1 = self.rand_matrix(dim, dim)<EOL>sop1 = np.kron(np.conj(mat1), mat1)<EOL><DEDENT>else:<EOL><INDENT>sop1 = self.rand_matrix(dim * dim, dim * dim)<EOL><DEDENT>val = <NUM_LIT:2> * (np.random.rand() - <NUM_LIT:0.5>)<EOL>targ = SuperOp(val * sop1)<EOL>channel = SuperOp(rep(SuperOp(sop1)).multiply(val))<EOL>self.assertEqual(channel, targ)<EOL><DEDENT>

Test channel scalar multiplication is equivalent to SuperOp


def _compare_negate_to_superop(self, rep, dim, samples, unitary=False):

for _ in range(samples):<EOL><INDENT>if unitary:<EOL><INDENT>mat1 = self.rand_matrix(dim, dim)<EOL>sop1 = np.kron(np.conj(mat1), mat1)<EOL><DEDENT>else:<EOL><INDENT>sop1 = self.rand_matrix(dim * dim, dim * dim)<EOL><DEDENT>targ = SuperOp(-<NUM_LIT:1> * sop1)<EOL>channel = SuperOp(-rep(SuperOp(sop1)))<EOL>self.assertEqual(channel, targ)<EOL><DEDENT>

Test negative channel is equivalent to SuperOp


current_rep = chan.__class__<EOL>other_reps = [Operator, Choi, SuperOp, Kraus, Stinespring, Chi, PTM]<EOL>for rep in other_reps:<EOL><INDENT>self.assertEqual(current_rep, chan.add(rep(chan)).__class__)<EOL><DEDENT>

Check addition works for other representations


current_rep = chan.__class__<EOL>other_reps = [Operator, Choi, SuperOp, Kraus, Stinespring, Chi, PTM]<EOL>for rep in other_reps:<EOL><INDENT>self.assertEqual(current_rep, chan.subtract(rep(chan)).__class__)<EOL><DEDENT>

Check subtraction works for other representations


def _compare_transpose_to_operator(self, chans, mats):

unitaries = [Operator(np.transpose(i)) for i in mats]<EOL>channels = [i.transpose() for i in chans]<EOL>for chan, uni in zip(channels, unitaries):<EOL><INDENT>self.assertEqual(chan, chan.__class__(uni))<EOL><DEDENT>


def _compare_conjugate_to_operator(self, chans, mats):

unitaries = [Operator(np.conjugate(i)) for i in mats]<EOL>channels = [i.conjugate() for i in chans]<EOL>for chan, uni in zip(channels, unitaries):<EOL><INDENT>self.assertEqual(chan, chan.__class__(uni))<EOL><DEDENT>


def _compare_adjoint_to_operator(self, chans, mats):

unitaries = [Operator(np.conjugate(np.transpose(i))) for i in mats]<EOL>channels = [i.adjoint() for i in chans]<EOL>for chan, uni in zip(channels, unitaries):<EOL><INDENT>self.assertEqual(chan, chan.__class__(uni))<EOL><DEDENT>


<EOL>circ, target = super().simple_circuit_no_measure()<EOL>return circ, SuperOp(target)<EOL>


return [<EOL>np.sqrt(<NUM_LIT:1> - p * <NUM_LIT:3> / <NUM_LIT:4>) * self.UI,<EOL>np.sqrt(p / <NUM_LIT:4>) * self.UX,<EOL>np.sqrt(p / <NUM_LIT:4>) * self.UY,<EOL>np.sqrt(p / <NUM_LIT:4>) * self.UZ<EOL>]<EOL>


return (<NUM_LIT:1> - p) * self.sopI + p * np.array(<EOL>[[<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>], [<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>], [<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>], [<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>]]) / <NUM_LIT:2><EOL>

Depolarizing channel superoperator matrix


return (<NUM_LIT:1> - p) * self.choiI + p * np.eye(<NUM_LIT:4>) / <NUM_LIT:2><EOL>


return <NUM_LIT:2> * np.diag([<NUM_LIT:1> - <NUM_LIT:3> * p / <NUM_LIT:4>, p / <NUM_LIT:4>, p / <NUM_LIT:4>, p / <NUM_LIT:4>])<EOL>


return np.diag([<NUM_LIT:1>, <NUM_LIT:1> - p, <NUM_LIT:1> - p, <NUM_LIT:1> - p])<EOL>


kraus = self.depol_kraus(p)<EOL>basis = np.eye(<NUM_LIT:4>).reshape((<NUM_LIT:4>, <NUM_LIT:4>, <NUM_LIT:1>))<EOL>return np.sum([np.kron(k, b) for k, b in zip(kraus, basis)], axis=<NUM_LIT:0>)<EOL>


def rand_kraus(self, input_dim, output_dim, n):

return [self.rand_matrix(output_dim, input_dim) for _ in range(n)]<EOL>

Return a random (non-CPTP) Kraus operator map