Get a list of tokens.

            https://www.nomadproject.io/api/acl-tokens.html

            returns: list

            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


return self.request("<STR_LIT>", id, method="<STR_LIT>").json()<EOL>

Retrieve specific token.

            https://www.nomadproject.io/api/acl-tokens.html

            returns: dict

            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


return self.request("<STR_LIT>", "<STR_LIT>", method="<STR_LIT>").json()<EOL>

Retrieve self token used for auth.

            https://www.nomadproject.io/api/acl-tokens.html

            returns: dict

            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


return self.request("<STR_LIT>", json=token, method="<STR_LIT>").json()<EOL>

Create token.

            https://www.nomadproject.io/api/acl-tokens.html

            arguments:
                token
            returns: dict

            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


return self.request("<STR_LIT>", id, method="<STR_LIT>").ok<EOL>

Delete specific token.

            https://www.nomadproject.io/api/acl-tokens.html

            returns: Boolean

            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


return self.request("<STR_LIT>", id, json=token, method="<STR_LIT>").json()<EOL>

Update token.

            https://www.nomadproject.io/api/acl-tokens.html

            arguments:
                - AccdesorID
                - token
            returns: dict

            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


return self.request("<STR_LIT>", method="<STR_LIT>").json()<EOL>

Get a list of policies.

            https://www.nomadproject.io/api/acl-policies.html

            returns: list

            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


return self.request("<STR_LIT>", id, json=policy, method="<STR_LIT>")<EOL>

Create policy.

            https://www.nomadproject.io/api/acl-policies.html

            arguments:
                - policy
            returns: request.Response

            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


Get a spacific.

            https://www.nomadproject.io/api/acl-policies.html

            returns: dict

            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


Create policy.

            https://www.nomadproject.io/api/acl-policies.html

            arguments:
                - name
                - policy
            returns: request.Response

            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


Delete specific policy.

            https://www.nomadproject.io/api/acl-policies.html

            arguments:
                - id
            returns: Boolean

            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


params = {"<STR_LIT>": prefix}<EOL>return self.request(method="<STR_LIT>", params=params).json()<EOL>

Lists all the allocations.

           https://www.nomadproject.io/docs/http/allocs.html
            arguments:
              - prefix :(str) optional, specifies a string to filter allocations on based on an prefix.
                        This is specified as a querystring parameter.
            returns: list
            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


return self.request(id, method="<STR_LIT>").json()<EOL>

Query a specific allocation.

           https://www.nomadproject.io/docs/http/alloc.html

            returns: dict
            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


Query a single namespace.

           https://www.nomadproject.io/api/namespaces.html

            arguments:
              - id
            returns: dict
            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


return self.request(json=namespace, method="<STR_LIT>")<EOL>

create namespace

           https://www.nomadproject.io/api/namespaces.html

            arguments:
              - id
              - namespace (dict)
            returns: requests.Response
            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


def update_namespace(self, id, namespace):

return self.request(id, json=namespace, method="<STR_LIT>")<EOL>

Update namespace

           https://www.nomadproject.io/api/namespaces.html

            arguments:
              - id
              - namespace (dict)
            returns: requests.Response
            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


return self.request(id, method="<STR_LIT>")<EOL>

delete namespace.

           https://www.nomadproject.io/api/namespaces.html

            arguments:
              - id
            returns: requests.Response
            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


params = {"<STR_LIT>": stale}<EOL>return self.request("<STR_LIT>", "<STR_LIT>", params=params, method="<STR_LIT>").json()<EOL>

Query the status of a client node registered with Nomad.

            https://www.nomadproject.io/docs/http/operator.html

            returns: dict
            optional arguments:
              - stale, (defaults to False), Specifies if the cluster should respond without an active leader.
                                            This is specified as a querystring parameter.
            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


def delete_peer(self, peer_address, stale=False):

params = {"<STR_LIT:address>": peer_address, "<STR_LIT>": stale}<EOL>return self.request("<STR_LIT>", "<STR_LIT>", params=params, method="<STR_LIT>").ok<EOL>

Remove the Nomad server with given address from the Raft configuration.
            The return code signifies success or failure.

            https://www.nomadproject.io/docs/http/operator.html

            arguments:
              - peer_address, The address specifies the server to remove and is given as an IP:port
            optional arguments:
              - stale, (defaults to False), Specifies if the cluster should respond without an active leader.
                                            This is specified as a querystring parameter.
            returns: Boolean
            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


Query a specific evaluation.

           https://www.nomadproject.io/docs/http/eval.html

            arguments:
              - id
            returns: dict
            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


return self.request(id, "<STR_LIT>", method="<STR_LIT>").json()<EOL>

Query the allocations created or modified by an evaluation.

           https://www.nomadproject.io/docs/http/eval.html

            arguments:
              - id
            returns: list
            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


Query the status of a client node registered with Nomad.

           https://www.nomadproject.io/docs/http/node.html

            returns: dict
            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


Query the allocations belonging to a single node.

           https://www.nomadproject.io/docs/http/node.html

            returns: list
            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


Creates a new evaluation for the given node.
            This can be used to force run the
            scheduling logic if necessary.

           https://www.nomadproject.io/docs/http/node.html

            returns: dict
            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


return self.request(id, "<STR_LIT>", params={"<STR_LIT>": enable}, method="<STR_LIT>").json()<EOL>

Toggle the drain mode of the node.
            When enabled, no further allocations will be
            assigned and existing allocations will be migrated.

           https://www.nomadproject.io/docs/http/node.html

            arguments:
              - id (str uuid): node id
              - enable (bool): enable node drain or not to enable node drain
            returns: dict
            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


def drain_node_with_spec(self, id, drain_spec, mark_eligible=None):

payload = {}<EOL>if drain_spec and mark_eligible is not None:<EOL><INDENT>payload = {<EOL>"<STR_LIT>": id,<EOL>"<STR_LIT>": drain_spec,<EOL>"<STR_LIT>": mark_eligible<EOL>}<EOL><DEDENT>elif drain_spec and mark_eligible is None:<EOL><INDENT>payload = {<EOL>"<STR_LIT>": id,<EOL>"<STR_LIT>": drain_spec<EOL>}<EOL><DEDENT>elif not drain_spec and mark_eligible is not None:<EOL><INDENT>payload = {<EOL>"<STR_LIT>": id,<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT>": mark_eligible<EOL>}<EOL><DEDENT>elif not drain_spec and mark_eligible is None:<EOL><INDENT>payload = {<EOL>"<STR_LIT>": id,<EOL>"<STR_LIT>": None,<EOL>}<EOL><DEDENT>return self.request(id, "<STR_LIT>", json=payload, method="<STR_LIT>").json()<EOL>

This endpoint toggles the drain mode of the node. When draining is enabled,
            no further allocations will be assigned to this node, and existing allocations
            will be migrated to new nodes.

            If an empty dictionary is given as drain_spec this will disable/toggle the drain.

            https://www.nomadproject.io/docs/http/node.html

            arguments:
              - id (str uuid): node id
              - drain_spec (dict): https://www.nomadproject.io/api/nodes.html#drainspec
              - mark_eligible (bool): https://www.nomadproject.io/api/nodes.html#markeligible
            returns: dict
            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


def eligible_node(self, id, eligible=None, ineligible=None):

payload = {}<EOL>if eligible is not None and ineligible is not None:<EOL><INDENT>raise nomad.api.exceptions.InvalidParameters<EOL><DEDENT>if eligible is None and ineligible is None:<EOL><INDENT>raise nomad.api.exceptions.InvalidParameters<EOL><DEDENT>if eligible is not None and eligible:<EOL><INDENT>payload = {"<STR_LIT>": "<STR_LIT>", "<STR_LIT>": id}<EOL><DEDENT>elif eligible is not None and not eligible:<EOL><INDENT>payload = {"<STR_LIT>": "<STR_LIT>", "<STR_LIT>": id}<EOL><DEDENT>elif ineligible is not None:<EOL><INDENT>payload = {"<STR_LIT>": "<STR_LIT>", "<STR_LIT>": id}<EOL><DEDENT>elif ineligible is not None and not ineligible:<EOL><INDENT>payload = {"<STR_LIT>": "<STR_LIT>", "<STR_LIT>": id}<EOL><DEDENT>return self.request(id, "<STR_LIT>", json=payload, method="<STR_LIT>").json()<EOL>

Toggle the eligibility of the node.

           https://www.nomadproject.io/docs/http/node.html

            arguments:
              - id (str uuid): node id
              - eligible (bool): Set to True to mark node eligible
              - ineligible (bool): Set to True to mark node ineligible
            returns: dict
            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


This endpoint purges a node from the system. Nodes can still join the cluster if they are alive.
        arguments:
          - id (str uuid): node id
        returns: dict
        raises:
          - nomad.api.exceptions.BaseNomadException
          - nomad.api.exceptions.URLNotFoundNomadException


return self.request(method="<STR_LIT>").json()<EOL>

Returns the address of the current leader in the region.

            https://www.nomadproject.io/docs/http/status.html

            returns: string
            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


Returns the set of raft peers in the region.

            https://www.nomadproject.io/docs/http/status.html

            returns: list
            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


Returns the known region names.

            https://www.nomadproject.io/docs/http/regions.html

            returns: list
            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException


def __init__(self, <EOL>host='<STR_LIT:127.0.0.1>', <EOL>secure=False, <EOL>port=<NUM_LIT>,<EOL>address=os.getenv('<STR_LIT>', None),<EOL>namespace=os.getenv('<STR_LIT>', None),<EOL>token=os.getenv('<STR_LIT>', None), <EOL>timeout=<NUM_LIT:5>, <EOL>region=os.getenv('<STR_LIT>', None), <EOL>version='<STR_LIT>', <EOL>verify=False, <EOL>cert=()):

self.host = host<EOL>self.secure = secure<EOL>self.port = port<EOL>self.address = address<EOL>self.region = region<EOL>self.timeout = timeout<EOL>self.version = version<EOL>self.token = token<EOL>self.verify = verify<EOL>self.cert = cert<EOL>self.__namespace = namespace<EOL>self.requester_settings = {<EOL>"<STR_LIT:address>": self.address,<EOL>"<STR_LIT>": self.get_uri(),<EOL>"<STR_LIT:port>": self.port,<EOL>"<STR_LIT>": self.__namespace,<EOL>"<STR_LIT>": self.token,<EOL>"<STR_LIT>": self.timeout,<EOL>"<STR_LIT:version>": self.version,<EOL>"<STR_LIT>": self.verify,<EOL>"<STR_LIT>": self.cert,<EOL>"<STR_LIT>": self.region<EOL>}<EOL>self._jobs = api.Jobs(**self.requester_settings)<EOL>self._job = api.Job(**self.requester_settings)<EOL>self._nodes = api.Nodes(**self.requester_settings)<EOL>self._node = api.Node(**self.requester_settings)<EOL>self._allocations = api.Allocations(**self.requester_settings)<EOL>self._allocation = api.Allocation(**self.requester_settings)<EOL>self._evaluations = api.Evaluations(**self.requester_settings)<EOL>self._evaluation = api.Evaluation(**self.requester_settings)<EOL>self._agent = api.Agent(**self.requester_settings)<EOL>self._client = api.Client(**self.requester_settings)<EOL>self._deployments = api.Deployments(**self.requester_settings)<EOL>self._deployment = api.Deployment(**self.requester_settings)<EOL>self._regions = api.Regions(**self.requester_settings)<EOL>self._status = api.Status(**self.requester_settings)<EOL>self._system = api.System(**self.requester_settings)<EOL>self._operator = api.Operator(**self.requester_settings)<EOL>self._validate = api.Validate(**self.requester_settings)<EOL>self._namespaces = api.Namespaces(**self.requester_settings)<EOL>self._namespace = api.Namespace(**self.requester_settings)<EOL>self._acl = api.Acl(**self.requester_settings)<EOL>self._sentinel = api.Sentinel(**self.requester_settings)<EOL>self._metrics = api.Metrics(**self.requester_settings)<EOL>

Nomad api client

          https://github.com/jrxFive/python-nomad/

           optional arguments:
            - host (defaults 127.0.0.1), string ip or name of the nomad api server/agent that will be used.
            - port (defaults 4646), integer port that will be used to connect.
            - secure (defaults False), define if the protocol is secured or not (https or http)
            - version (defaults v1), vesion of the api of nomad.
            - verify (defaults False), verify the certificate when tls/ssl is enabled
                                at nomad.
            - cert (defaults empty), cert, or key and cert file to validate the certificate
                                configured at nomad.
            - region (defaults None), version of the region to use. It will be used then
                                regions of the current agent of the connection.
            - namespace (defaults to None), Specifies the enterpise namespace that will
                                be use to deploy or to ask info to nomad.
            - token (defaults to None), Specifies to append ACL token to the headers to
                                make authentication on secured based nomad environemnts.
           returns: Nomad api client object

           raises:
             - nomad.api.exceptions.BaseNomadException
             - nomad.api.exceptions.URLNotFoundNomadException
             - nomad.api.exceptions.URLNotAuthorizedNomadException


if request.user.is_authenticated():<EOL><INDENT>user = request.user<EOL>content_type = ContentType.objects.get_for_model(type(object))<EOL>try:<EOL><INDENT>ObjectView.objects.get(<EOL>user=user, object_id=object.id, content_type=content_type)<EOL><DEDENT>except:<EOL><INDENT>ObjectView.objects.create(user=user, content_object=object)<EOL><DEDENT>viewed = ObjectView.objects.filter(user=user)<EOL><DEDENT>else:<EOL><INDENT>update_dict_for_guests(request, object, content_type)<EOL>return<EOL><DEDENT>if viewed:<EOL><INDENT>for obj in viewed:<EOL><INDENT>if content_type == obj.content_type:<EOL><INDENT>if not exists_in_dictionary(request, object,<EOL>content_type,<EOL>obj, True):<EOL><INDENT>if object.id != obj.object_id:<EOL><INDENT>ObjectViewDictionary.objects.create(<EOL>current_object=object,<EOL>visited_before_object=obj.content_object)<EOL>if not exists_in_dictionary(request, obj,<EOL>obj.content_type,<EOL>object, False):<EOL><INDENT>ObjectViewDictionary.objects.create(<EOL>current_object=obj.content_object,<EOL>visited_before_object=object)<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>return<EOL>

Updates the suggestions' dictionary for an object upon visiting its page


Gets a list with a certain size of suggestions for an object


Gets a list of all suggestions for an object


newstring = re.sub(re_ansi_control_codes, "<STR_LIT>", mystring)<EOL>return len(newstring)<EOL>

Takes a string, strips out the ANSI escape codes
    (used for colouring terminal output, etc.), and returns
    the length of the resulting string


def centered(mystring, linewidth=None, fill="<STR_LIT:U+0020>"):

if linewidth is None:<EOL><INDENT>linewidth = get_terminal_size().columns - <NUM_LIT:1><EOL><DEDENT>sides = (linewidth - length_no_ansi(mystring))//<NUM_LIT:2><EOL>extra = (linewidth - length_no_ansi(mystring)) % <NUM_LIT:2><EOL>fill = fill[:<NUM_LIT:1>]<EOL>sidestring = fill*sides<EOL>extrastring = fill*extra<EOL>newstring = sidestring + mystring + sidestring + extrastring<EOL>return newstring<EOL>

Takes a string, centres it, and pads it on both sides


taken = length_no_ansi(mystring)<EOL>padding = (get_terminal_size().columns - <NUM_LIT:1>) - taken - <NUM_LIT:5><EOL>clock = time.strftime("<STR_LIT>", time.localtime())<EOL>print(mystring + "<STR_LIT:U+0020>"*padding + clock)<EOL>

Takes a string, and prints it with the time right aligned


valid = {"<STR_LIT:yes>": Answers.YES, "<STR_LIT:y>": Answers.YES,  "<STR_LIT>": Answers.YES,<EOL>"<STR_LIT>": Answers.NO,   "<STR_LIT:n>": Answers.NO}<EOL>if default is None:<EOL><INDENT>prompt = "<STR_LIT>"<EOL><DEDENT>elif default == "<STR_LIT:yes>":<EOL><INDENT>prompt = "<STR_LIT>"<EOL><DEDENT>elif default == "<STR_LIT>":<EOL><INDENT>prompt = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % default)<EOL><DEDENT>while True:<EOL><INDENT>sys.stdout.write(question + prompt)<EOL>choice = input().lower()<EOL>if default is not None and choice == '<STR_LIT>':<EOL><INDENT>return valid[default]<EOL><DEDENT>elif choice in valid:<EOL><INDENT>return valid[choice]<EOL><DEDENT>else:<EOL><INDENT>sys.stdout.write("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>

Ask a yes/no question via raw_input() and return their answer.

    "question" is a string that is presented to the user.
    "default" is the presumed answer if the user just hits <Enter>.
        It must be "yes" (the default), "no" or None (meaning
        an answer is required of the user).

    The return value is one of Answers.YES or Answers.NO.

    Copied (and modified) from
    http://stackoverflow.com/questions/3041986/python-command-line-yes-no-input


valid = {"<STR_LIT:yes>": Answers.YES,  "<STR_LIT:y>": Answers.YES,  "<STR_LIT>": Answers.YES,<EOL>"<STR_LIT>": Answers.NO,   "<STR_LIT:n>": Answers.NO,<EOL>"<STR_LIT:all>": Answers.ALL,  "<STR_LIT:a>": Answers.ALL,  "<STR_LIT>": Answers.ALL}<EOL>if default is None:<EOL><INDENT>prompt = "<STR_LIT>"<EOL><DEDENT>elif default == "<STR_LIT:yes>":<EOL><INDENT>prompt = "<STR_LIT>"<EOL><DEDENT>elif default == "<STR_LIT>":<EOL><INDENT>prompt = "<STR_LIT>"<EOL><DEDENT>elif default == "<STR_LIT:all>":<EOL><INDENT>prompt = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % default)<EOL><DEDENT>while True:<EOL><INDENT>sys.stdout.write(question + prompt)<EOL>choice = input().lower()<EOL>if default is not None and choice == '<STR_LIT>':<EOL><INDENT>return valid[default]<EOL><DEDENT>elif choice in valid:<EOL><INDENT>return valid[choice]<EOL><DEDENT>else:<EOL><INDENT>sys.stdout.write("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>

Ask a yes/no/all question via raw_input() and return their answer.

    "question" is a string that is presented to the user.
    "default" is the presumed answer if the user just hits <Enter>.
        It must be "yes" (the default), "no", "all" or None (meaning
        an answer is required of the user).

    Return value is one of Answers.YES, Answers.NO, or Answers.ALL.


valid = {"<STR_LIT:yes>": Answers.YES,   "<STR_LIT:y>": Answers.YES,  "<STR_LIT>": Answers.YES,<EOL>"<STR_LIT>": Answers.NO,     "<STR_LIT:n>": Answers.NO,<EOL>"<STR_LIT:all>": Answers.ALL,   "<STR_LIT:a>": Answers.ALL,  "<STR_LIT>": Answers.ALL,<EOL>"<STR_LIT:none>": Answers.NONE, "<STR_LIT:x>": Answers.NONE, "<STR_LIT>": Answers.NONE}<EOL>if default is None:<EOL><INDENT>prompt = "<STR_LIT>"<EOL><DEDENT>elif default == "<STR_LIT:yes>":<EOL><INDENT>prompt = "<STR_LIT>"<EOL><DEDENT>elif default == "<STR_LIT>":<EOL><INDENT>prompt = "<STR_LIT>"<EOL><DEDENT>elif default == "<STR_LIT:all>":<EOL><INDENT>prompt = "<STR_LIT>"<EOL><DEDENT>elif default == "<STR_LIT:none>":<EOL><INDENT>prompt = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % default)<EOL><DEDENT>while True:<EOL><INDENT>sys.stdout.write(question + prompt)<EOL>choice = input().lower()<EOL>if default is not None and choice == '<STR_LIT>':<EOL><INDENT>return valid[default]<EOL><DEDENT>elif choice in valid:<EOL><INDENT>return valid[choice]<EOL><DEDENT>else:<EOL><INDENT>sys.stdout.write("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>

Ask a yes/no/all/none question via raw_input() and return their answer.

    "question" is a string that is presented to the user.
    "default" is the presumed answer if the user just hits <Enter>.
        It must be "yes" (the default), "no", "all", "none" (the string) or
        None (meaning an answer is required of the user).

    The return value is one of Answers.YES, Answers.NO, Answers.ALL or
        Answers.NONE.


valid = {"<STR_LIT:yes>": Answers.YES,   "<STR_LIT:y>": Answers.YES,  "<STR_LIT>": Answers.YES,<EOL>"<STR_LIT>": Answers.QUIT, "<STR_LIT:q>": Answers.QUIT}<EOL>if default is None:<EOL><INDENT>prompt = "<STR_LIT>"<EOL><DEDENT>elif default == "<STR_LIT:yes>":<EOL><INDENT>prompt = "<STR_LIT>"<EOL><DEDENT>elif default == "<STR_LIT>":<EOL><INDENT>prompt = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % default)<EOL><DEDENT>while True:<EOL><INDENT>sys.stdout.write(question + prompt)<EOL>choice = input().lower()<EOL>if default is not None and choice == '<STR_LIT>':<EOL><INDENT>return valid[default]<EOL><DEDENT>elif choice in valid:<EOL><INDENT>return valid[choice]<EOL><DEDENT>else:<EOL><INDENT>sys.stdout.write("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>

Ask a yes/quit question via raw_input() and return their answer.

    "question" is a string that is presented to the user.
    "default" is the presumed answer if the user just hits <Enter>.
        It must be "yes" (the default), "quit" or None (meaning
        an answer is required of the user).

    The "answer" return value is one of "yes" or "quit".

    Modified from
    http://stackoverflow.com/questions/3041986/python-command-line-yes-no-input


while sec > <NUM_LIT:0>:<EOL><INDENT>sys.stdout.write('<STR_LIT:\r>' + str(sec//<NUM_LIT>).zfill(<NUM_LIT:1>) + "<STR_LIT::>" +<EOL>str(sec % <NUM_LIT>).zfill(<NUM_LIT:2>) + '<STR_LIT:U+0020>')<EOL>sec -= <NUM_LIT:1><EOL>time.sleep(<NUM_LIT:1>)<EOL>sys.stdout.write('<STR_LIT:\r>' + '<STR_LIT:U+0020>' + '<STR_LIT:\r>')<EOL><DEDENT>

Prints a timer with the format 0:00 to the console,
and then clears the line when the timer is done


def version_number_str(major, minor=<NUM_LIT:0>, patch=<NUM_LIT:0>, prerelease=None, build=None):

version = str(major) + '<STR_LIT:.>' + str(minor) + '<STR_LIT:.>' + str(patch)<EOL>if prerelease:<EOL><INDENT>if prerelease.startswith('<STR_LIT:->'):<EOL><INDENT>version = version + prerelease<EOL><DEDENT>else:<EOL><INDENT>version = version + "<STR_LIT:->" + str(prerelease)<EOL><DEDENT><DEDENT>if build:<EOL><INDENT>if build.startswith('<STR_LIT:+>'):<EOL><INDENT>version = version + build<EOL><DEDENT>else:<EOL><INDENT>version = version + "<STR_LIT:+>" + str(build)<EOL><DEDENT><DEDENT>return(version)<EOL>

Takes the parts of a semantic version number, and returns a nicely
formatted string.


try:<EOL><INDENT>try:<EOL><INDENT>from shutil import get_terminal_size as _get_terminal_size  <EOL><DEDENT>except ImportError:<EOL><INDENT>from backports.shutil_get_terminal_size import get_terminal_size as _get_terminal_size  <EOL><DEDENT>sz = _get_terminal_size()<EOL><DEDENT>except ValueError:<EOL><INDENT>"""<STR_LIT>"""<EOL>terminal_size = namedtuple('<STR_LIT>', '<STR_LIT>')<EOL>sz = terminal_size(<NUM_LIT>, <NUM_LIT>)<EOL><DEDENT>return sz<EOL>

Returns terminal dimensions
    :return: Returns ``(width, height)``.  If there's no terminal
             to be found, we'll just return ``(80, 24)``.


meta_file = read(*meta_file_parts)<EOL>meta_match = re.search(r"<STR_LIT>".format(meta_key),<EOL>meta_file, re.M)<EOL>if meta_match:<EOL><INDENT>return meta_match.group(<NUM_LIT:1>)<EOL><DEDENT>raise RuntimeError("<STR_LIT>".format(meta_key))<EOL>


def fast_forward_selection(scenarios, number_of_reduced_scenarios, probability=None):

print("<STR_LIT>")<EOL>number_of_scenarios = scenarios.shape[<NUM_LIT:1>]<EOL>logger.debug("<STR_LIT>", number_of_scenarios)<EOL>if probability is None:<EOL><INDENT>probability = np.array([<NUM_LIT:1>/number_of_scenarios for i in range(<NUM_LIT:0>, number_of_scenarios)])<EOL><DEDENT>z = np.array([np.inf for i in range(<NUM_LIT:0>, number_of_scenarios)])<EOL>c = np.zeros((number_of_scenarios, number_of_scenarios))<EOL>J = range(<NUM_LIT:0>, number_of_scenarios)<EOL>if number_of_reduced_scenarios >= number_of_scenarios:<EOL><INDENT>return(scenarios, probability, J)<EOL><DEDENT>for scenario_k in range(<NUM_LIT:0>, number_of_scenarios):<EOL><INDENT>for scenario_u in range(<NUM_LIT:0>, number_of_scenarios):<EOL><INDENT>c[scenario_k, scenario_u] = distance(scenarios[:, scenario_k], scenarios[:, scenario_u])<EOL><DEDENT><DEDENT>for scenario_u in range(<NUM_LIT:0>, number_of_scenarios):<EOL><INDENT>summation = <NUM_LIT:0><EOL>for scenario_k in range(<NUM_LIT:0>, number_of_scenarios):<EOL><INDENT>if scenario_k != scenario_u:<EOL><INDENT>summation = summation + probability[scenario_k]*c[scenario_k, scenario_u]<EOL><DEDENT><DEDENT>z[scenario_u] = summation<EOL><DEDENT>U = [np.argmin(z)]<EOL>for u in U:<EOL><INDENT>J.remove(u)<EOL><DEDENT>for _ in range(<NUM_LIT:0>, number_of_scenarios - number_of_reduced_scenarios - <NUM_LIT:1>):<EOL><INDENT>print("<STR_LIT>".format(_))<EOL>for scenario_u in J:<EOL><INDENT>for scenario_k in J:<EOL><INDENT>lowest_value = np.inf<EOL>for scenario_number in U:<EOL><INDENT>lowest_value = min(c[scenario_k, scenario_u], c[scenario_k, scenario_number])<EOL><DEDENT><DEDENT>c[scenario_k, scenario_u] = lowest_value<EOL><DEDENT>for scenario_u in J:<EOL><INDENT>summation = <NUM_LIT:0><EOL>for scenario_k in J:<EOL><INDENT>if scenario_k not in U:<EOL><INDENT>summation = summation + probability[scenario_k]*c[scenario_k, scenario_u]<EOL><DEDENT><DEDENT>z[scenario_u] = summation<EOL><DEDENT>u_i = np.argmin([item if i in J else np.inf for i, item in enumerate(z)])<EOL>J.remove(u_i)<EOL>U.append(u_i)<EOL><DEDENT>reduced_scenario_set = U<EOL>reduced_probability = []<EOL>reduced_probability = copy.deepcopy(probability)<EOL>for deleted_scenario_number in J:<EOL><INDENT>lowest_value = np.inf<EOL>for scenario_j in reduced_scenario_set:<EOL><INDENT>if c[deleted_scenario_number, scenario_j] < lowest_value:<EOL><INDENT>closest_scenario_number = scenario_j<EOL>lowest_value = c[deleted_scenario_number, scenario_j]<EOL><DEDENT><DEDENT>reduced_probability[closest_scenario_number] = reduced_probability[closest_scenario_number] + reduced_probability[deleted_scenario_number]<EOL><DEDENT>reduced_scenarios = copy.deepcopy(scenarios[:, reduced_scenario_set])<EOL>reduced_probability = reduced_probability[reduced_scenario_set]<EOL>return reduced_scenarios, reduced_probability, reduced_scenario_set<EOL>

Fast forward selection algorithm

    Parameters
    ----------
    scenarios : numpy.array
        Contain the input scenarios.
        The columns representing the individual scenarios
        The rows are the vector of values in each scenario
    number_of_reduced_scenarios : int
        final number of scenarios that
        the reduced scenarios contain.
        If number of scenarios is equal to or greater than the input scenarios,
        then the original input scenario set is returned as the reduced set
    probability : numpy.array (default=None)
        probability is a numpy.array with length equal to number of scenarios.
        if probability is not defined, all scenarios get equal probabilities

    Returns
    -------
    reduced_scenarios : numpy.array
        reduced set of scenarios
    reduced_probability : numpy.array
        probability of reduced set of scenarios
    reduced_scenario_set : list
        scenario numbers of reduced set of scenarios

    Example
    -------
    Scenario reduction can be performed as shown below::

        >>> import numpy as np
        >>> import random
        >>> scenarios = np.array([[random.randint(500,1000) for i in range(0,24)],
        >>>         [random.randint(500,1000) for i in range(0,24)],
        >>>         [random.randint(500,1000) for i in range(0,24)],
        >>>         [random.randint(500,1000) for i in range(0,24)],
        >>>         [random.randint(500,1000) for i in range(0,24)],
        >>>         [random.randint(500,1000) for i in range(0,24)],
        >>>         [random.randint(500,1000) for i in range(0,24)],
        >>>         [random.randint(500,1000) for i in range(0,24)],
        >>>         [random.randint(500,1000) for i in range(0,24)],
        >>>         [random.randint(500,1000) for i in range(0,24)]])
        >>> import psst.scenario
        >>> reduced_scenarios, reduced_probability, reduced_scenario_numbers = psst.scenario.fast_forward_selection(scenarios, probability, 2)


def simultaneous_backward_reduction(scenarios, number_of_reduced_scenarios, probability=None):

print("<STR_LIT>")<EOL>number_of_scenarios = scenarios.shape[<NUM_LIT:1>]<EOL>logger.debug("<STR_LIT>", number_of_scenarios)<EOL>if probability is None:<EOL><INDENT>probability = np.array([<NUM_LIT:1>/number_of_scenarios for i in range(<NUM_LIT:0>, number_of_scenarios)])<EOL><DEDENT>z = np.array([np.inf for i in range(<NUM_LIT:0>, number_of_scenarios)])<EOL>c = np.zeros((number_of_scenarios, number_of_scenarios))<EOL>J = []<EOL>if number_of_reduced_scenarios >= number_of_scenarios:<EOL><INDENT>return(scenarios, probability, J)<EOL><DEDENT>"""<STR_LIT>"""<EOL>for scenario_k in range(<NUM_LIT:0>, number_of_scenarios):<EOL><INDENT>for scenario_j in range(<NUM_LIT:0>, number_of_scenarios):<EOL><INDENT>c[scenario_k, scenario_j] = distance(scenarios[:, scenario_k], scenarios[:, scenario_j])<EOL><DEDENT><DEDENT>for scenario_l in range(<NUM_LIT:0>, number_of_scenarios):<EOL><INDENT>lowest_value = np.inf<EOL>for scenario_j in range(<NUM_LIT:0>, number_of_scenarios):<EOL><INDENT>if scenario_l == scenario_j:<EOL><INDENT>continue<EOL><DEDENT>lowest_value = min(lowest_value, c[scenario_l, scenario_j])<EOL><DEDENT>c[scenario_l, scenario_l] = lowest_value<EOL>z[scenario_l] = probability[scenario_l]*c[scenario_l, scenario_l]<EOL><DEDENT>J.append(np.argmin(z))<EOL>for _ in range(<NUM_LIT:0>, number_of_scenarios - number_of_reduced_scenarios - <NUM_LIT:1>):<EOL><INDENT>for scenario_l in range(<NUM_LIT:0>, number_of_scenarios):<EOL><INDENT>for scenario_k in range(<NUM_LIT:0>, number_of_scenarios):<EOL><INDENT>if scenario_k in J or scenario_k == scenario_l:<EOL><INDENT>if scenario_l not in J:<EOL><INDENT>lowest_value = np.inf<EOL>for scenario_j in range(<NUM_LIT:0>, number_of_scenarios):<EOL><INDENT>if scenario_j not in J and scenario_j != scenario_l:<EOL><INDENT>lowest_value = min(lowest_value, c[scenario_k, scenario_j])<EOL><DEDENT><DEDENT>c[scenario_k, scenario_l] = lowest_value<EOL><DEDENT><DEDENT><DEDENT><DEDENT>for scenario_l in range(<NUM_LIT:0>, number_of_scenarios):<EOL><INDENT>if scenario_l not in J:<EOL><INDENT>summation = <NUM_LIT:0><EOL>for scenario_k in range(<NUM_LIT:0>, number_of_scenarios):<EOL><INDENT>if scenario_k in J or scenario_k == scenario_l:<EOL><INDENT>summation = summation + probability[scenario_k]*c[scenario_k, scenario_l]<EOL><DEDENT><DEDENT>z[scenario_l] = summation<EOL><DEDENT><DEDENT>J.append(np.argmin([item if i not in J else np.inf for i, item in enumerate(z)]))<EOL><DEDENT>reduced_scenario_set = []<EOL>for scenario_number in range(<NUM_LIT:0>, number_of_scenarios):<EOL><INDENT>if scenario_number not in J:<EOL><INDENT>reduced_scenario_set.append(scenario_number)<EOL><DEDENT><DEDENT>reduced_probability = []<EOL>reduced_probability = copy.deepcopy(probability)<EOL>for deleted_scenario_number in J:<EOL><INDENT>lowest_value = np.inf<EOL>for scenario_j in reduced_scenario_set:<EOL><INDENT>if c[deleted_scenario_number, scenario_j] < lowest_value:<EOL><INDENT>closest_scenario_number = scenario_j<EOL>lowest_value = c[deleted_scenario_number, scenario_j]<EOL><DEDENT><DEDENT>reduced_probability[closest_scenario_number] = reduced_probability[closest_scenario_number] + reduced_probability[deleted_scenario_number]<EOL><DEDENT>reduced_scenarios = copy.deepcopy(scenarios[:, reduced_scenario_set])<EOL>reduced_probability = reduced_probability[reduced_scenario_set]<EOL>return(reduced_scenarios, reduced_probability, reduced_scenario_set)<EOL>

Simultaneous backward reduction algorithm

    Parameters
    ----------
    scenarios : numpy.array
        Contain the input scenarios.
        The columns representing the individual scenarios
        The rows are the vector of values in each scenario
    number_of_reduced_scenarios : int
        final number of scenarios that
        the reduced scenarios contain.
        If number of scenarios is equal to or greater than the input scenarios,
        then the original input scenario set is returned as the reduced set
    probability : numpy.array (default=None)
        probability is a numpy.array with length equal to number of scenarios.
        if probability is not defined, all scenarios get equal probabilities

    Returns
    -------
    reduced_scenarios : numpy.array
        reduced set of scenarios
    reduced_probability : numpy.array
        probability of reduced set of scenarios
    reduced_scenario_set : list
        scenario numbers of reduced set of scenarios

    Example
    -------

    Scenario reduction can be performed as shown below::

        >>> import numpy as np
        >>> import random
        >>> scenarios = np.array([[random.randint(500,1000) for i in range(0,24)],
        >>>         [random.randint(500,1000) for i in range(0,24)],
        >>>         [random.randint(500,1000) for i in range(0,24)],
        >>>         [random.randint(500,1000) for i in range(0,24)],
        >>>         [random.randint(500,1000) for i in range(0,24)],
        >>>         [random.randint(500,1000) for i in range(0,24)],
        >>>         [random.randint(500,1000) for i in range(0,24)],
        >>>         [random.randint(500,1000) for i in range(0,24)],
        >>>         [random.randint(500,1000) for i in range(0,24)],
        >>>         [random.randint(500,1000) for i in range(0,24)]])
        >>> import psst.scenario
        >>> reduced_scenarios, reduced_probability, reduced_scenario_numbers = psst.scenario.simultaneous_backward_reduction(scenarios, probability, 2)


<EOL>return(np.linalg.norm(a-b))<EOL>


def plot_line_power(obj, results, hour, ax=None):

if ax is None:<EOL><INDENT>fig, ax = plt.subplots(<NUM_LIT:1>, <NUM_LIT:1>, figsize=(<NUM_LIT:16>, <NUM_LIT:10>))<EOL>ax.axis('<STR_LIT>')<EOL><DEDENT>case, network = _return_case_network(obj)<EOL>network.draw_buses(ax=ax)<EOL>network.draw_loads(ax=ax)<EOL>network.draw_generators(ax=ax)<EOL>network.draw_connections('<STR_LIT>', ax=ax)<EOL>network.draw_connections('<STR_LIT>', ax=ax)<EOL>edgelist, edge_color, edge_width, edge_labels = _generate_edges(results, case, hour)<EOL>branches = network.draw_branches(ax=ax, edgelist=edgelist, edge_color=edge_color, width=edge_width, edge_labels=edge_labels)<EOL>divider = make_axes_locatable(ax)<EOL>cax = divider.append_axes('<STR_LIT:right>', size='<STR_LIT>', pad=<NUM_LIT>)<EOL>cb = plt.colorbar(branches, cax=cax, orientation='<STR_LIT>')<EOL>cax.yaxis.set_label_position('<STR_LIT:left>')<EOL>cax.yaxis.set_ticks_position('<STR_LIT:left>')<EOL>cb.set_label('<STR_LIT>')<EOL>return ax<EOL>


template = self.get_template()<EOL>return template.substitute({"<STR_LIT:class>": self.__class__.__name__,<EOL>"<STR_LIT:label>": self.label}).strip()<EOL>

Returns the material definition as a string in Abaqus INP format.


template = self.get_template()<EOL>return template.substitute({"<STR_LIT:class>": self.__class__.__name__,<EOL>"<STR_LIT:label>": self.label,<EOL>"<STR_LIT>": self.young_modulus,<EOL>"<STR_LIT>": self.poisson_ratio}).strip()<EOL>


template = self.get_template()<EOL>plastic_table = self.get_plastic_table()<EOL>return template.substitute({<EOL>"<STR_LIT:class>": self.__class__.__name__,<EOL>"<STR_LIT:label>": self.label,<EOL>"<STR_LIT>": self.young_modulus,<EOL>"<STR_LIT>": self.poisson_ratio,<EOL>"<STR_LIT>": (self.get_plastic_table()[["<STR_LIT>", "<STR_LIT>"]]<EOL>.to_csv(header = False, <EOL>index = False,<EOL>sep = "<STR_LIT:U+002C>").strip())}).strip()<EOL>


template = self.get_template()<EOL>return template.substitute({"<STR_LIT:class>": self.__class__.__name__,<EOL>"<STR_LIT:label>": self.label,<EOL>"<STR_LIT>": self.young_modulus,<EOL>"<STR_LIT>": self.poisson_ratio,<EOL>"<STR_LIT>":self.yield_stress}).strip()<EOL>


E = self.young_modulus<EOL>sy = self.yield_stress<EOL>n = self.hardening_exponent<EOL>eps_max = self.max_strain<EOL>Np = self.strain_data_points<EOL>ey = sy/E<EOL>s = <NUM_LIT>**np.linspace(<NUM_LIT:0.>, np.log10(eps_max/ey), Np)<EOL>strain = ey * s<EOL>stress = sy * s**n<EOL>plastic_strain = strain - stress / E <EOL>return pd.DataFrame({"<STR_LIT>": strain, <EOL>"<STR_LIT>": stress, <EOL>"<STR_LIT>": plastic_strain})<EOL>


K = self.consistency<EOL>sy = self.yield_stress<EOL>n = self.hardening_exponent<EOL>eps_max = self.max_strain<EOL>Np = self.strain_data_points<EOL>plastic_strain = np.linspace(<NUM_LIT:0.>, eps_max, Np)<EOL>stress = sy + K * plastic_strain**n <EOL>return pd.DataFrame({"<STR_LIT>": stress, <EOL>"<STR_LIT>": plastic_strain})<EOL>


def set_nodes(self, labels, coords, sets):

columns = pd.MultiIndex.from_tuples((("<STR_LIT>", "<STR_LIT:x>"), <EOL>("<STR_LIT>", "<STR_LIT:y>"), <EOL>("<STR_LIT>", "<STR_LIT:z>")))<EOL>self.nodes = pd.DataFrame(data = coords, <EOL>columns = columns,<EOL>index = labels)<EOL>for k, v in sets.items(): self.nodes["<STR_LIT>", k] = v<EOL>


def set_elements(self, labels= None, types = None, stypes = None, conn = None, <EOL>sets = None, surfaces = None):

tuples = [("<STR_LIT:type>", "<STR_LIT>", self._null)] <EOL>columns = pd.MultiIndex.from_tuples(tuples)<EOL>self.elements = pd.DataFrame(data = types, <EOL>columns = columns,<EOL>index = labels)<EOL>self.elements.loc[:, ("<STR_LIT:type>", "<STR_LIT>", "<STR_LIT:v>")] = None<EOL>for i in range(len(conn[<NUM_LIT:0>])):<EOL><INDENT>self.elements["<STR_LIT>", "<STR_LIT>".format(i), <NUM_LIT:0>] = conn[:, i]<EOL><DEDENT>for k, v in sets.items(): self.elements["<STR_LIT>", k, self._null] = v<EOL>for k, v in surfaces.items():<EOL><INDENT>for fk, vv in v.items():<EOL><INDENT>self.elements["<STR_LIT>", k, fk] = vv<EOL><DEDENT><DEDENT>


self.fields = {}<EOL>for k, v in fields.items():<EOL><INDENT>self.fields[k] = v<EOL><DEDENT>


def split(self, elements, to, at = "<STR_LIT>"):

return<EOL>


def read_h5(hdfstore, group = "<STR_LIT>"):

m = Mesh()<EOL>m.elements.data = hdf["<STR_LIT>"]<EOL>m.nodes.data    = hdf["<STR_LIT>"]<EOL>for key in hdf.keys():<EOL><INDENT>if key.startswith("<STR_LIT>"):<EOL><INDENT>k = key.replace("<STR_LIT>", "<STR_LIT>")<EOL>m.nodes.sets[k] = set(hdf[key])<EOL><DEDENT>if key.startswith("<STR_LIT>"):<EOL><INDENT>k = key.replace("<STR_LIT>", "<STR_LIT>")<EOL>m.elements.sets[k] = set(hdf[key])<EOL><DEDENT>if key.startswith("<STR_LIT>"):<EOL><INDENT>k = key.replace("<STR_LIT>", "<STR_LIT>")<EOL>m.elements.surfaces[k] = hdf[key]<EOL><DEDENT>if key.startswith("<STR_LIT>"):<EOL><INDENT>if key.endswith("<STR_LIT>"):<EOL><INDENT>tag = key.split("<STR_LIT:/>")[<NUM_LIT:2>]<EOL>f = Field()<EOL>f.metadata = hdf["<STR_LIT>".format(tag)]<EOL>f.metadata = hdf["<STR_LIT>".format(tag)]<EOL>f.master = m<EOL>m.add_field(tag, f)<EOL><DEDENT><DEDENT><DEDENT>hdf.close()  <EOL>return m<EOL>

DEPRECATED
Reads a mesh saved in the HDF5 format.


elementMap = { <NUM_LIT:15>:"<STR_LIT>",<EOL><NUM_LIT:1>:"<STR_LIT>",<EOL><NUM_LIT:2>:"<STR_LIT>",<EOL><NUM_LIT:3>:"<STR_LIT>",<EOL><NUM_LIT:4>:"<STR_LIT>",<EOL><NUM_LIT:5>:"<STR_LIT>",<EOL><NUM_LIT:6>:"<STR_LIT>",<EOL><NUM_LIT:7>:"<STR_LIT>",<EOL>}<EOL>lines = np.array(open(path, "<STR_LIT:r>").readlines())<EOL>locs = {}<EOL>nl = len(lines)<EOL>for i in range(nl):<EOL><INDENT>line = lines[i].lower().strip()<EOL>if line.startswith("<STR_LIT:$>"):<EOL><INDENT>if line.startswith("<STR_LIT>"):<EOL><INDENT>locs[env].append(i)<EOL><DEDENT>else:<EOL><INDENT>env = line[<NUM_LIT:1>:] <EOL>locs[env] = [i]<EOL><DEDENT><DEDENT><DEDENT>nodes = pd.read_csv(<EOL>io.StringIO("<STR_LIT:\n>".join(<EOL>lines[locs["<STR_LIT>"][<NUM_LIT:0>]+<NUM_LIT:2>:locs["<STR_LIT>"][<NUM_LIT:1>]])), <EOL>sep = "<STR_LIT:U+0020>",<EOL>names = ["<STR_LIT>", "<STR_LIT:x>", "<STR_LIT:y>", "<STR_LIT:z>"])<EOL>elements = {"<STR_LIT>":[], "<STR_LIT>":[], "<STR_LIT>": [], "<STR_LIT>":[], "<STR_LIT>":{}}<EOL>for line in lines[locs["<STR_LIT>"][<NUM_LIT:0>]+<NUM_LIT:2>:locs["<STR_LIT>"][<NUM_LIT:1>]]:<EOL><INDENT>d = np.array([int(w) for w in line.split()])<EOL>elements["<STR_LIT>"].append( d[<NUM_LIT:0>] )<EOL>elements["<STR_LIT>"].append(elementMap[d[<NUM_LIT:1>]] )<EOL>elements["<STR_LIT>"].append( d[<NUM_LIT:3>: <NUM_LIT:3>+d[<NUM_LIT:2>]] ) <EOL>elements["<STR_LIT>"].append(d[<NUM_LIT:3>+d[<NUM_LIT:2>]:])<EOL><DEDENT>elements["<STR_LIT>"] = np.array(elements["<STR_LIT>"])<EOL>physicalNames = {}<EOL>for line in lines[locs["<STR_LIT>"][<NUM_LIT:0>]+<NUM_LIT:2>:locs["<STR_LIT>"][<NUM_LIT:1>]]:<EOL><INDENT>w = line.split()<EOL>physicalNames[int(w[<NUM_LIT:1>])] = w[<NUM_LIT:2>].replace('<STR_LIT:">', '<STR_LIT>')<EOL><DEDENT>sets = {}<EOL>tags = np.array([t[<NUM_LIT:0>] for t in elements["<STR_LIT>"]])<EOL>for k in physicalNames.keys():<EOL><INDENT>sets[physicalNames[k]] = np.array([t == k for t in tags])     <EOL><DEDENT>

Reads a GMSH MSH file and returns a :class:`Mesh` instance.

:arg path: path to MSH file.
:type path: str


def lineInfo(line):<EOL><INDENT>out =  {"<STR_LIT:type>": "<STR_LIT:data>"}<EOL>if line[<NUM_LIT:0>] == "<STR_LIT:*>":<EOL><INDENT>if line[<NUM_LIT:1>] == "<STR_LIT:*>": <EOL><INDENT>out["<STR_LIT:type>"] = "<STR_LIT>"<EOL>out["<STR_LIT:text>"] = line[<NUM_LIT:2>:]<EOL><DEDENT>else:<EOL><INDENT>out["<STR_LIT:type>"] = "<STR_LIT>"<EOL>words = line[<NUM_LIT:1>:].split("<STR_LIT:U+002C>")<EOL>out["<STR_LIT:value>"] = words[<NUM_LIT:0>].strip()<EOL>out["<STR_LIT>"] = {}<EOL>for word in words[<NUM_LIT:1>:]:<EOL><INDENT>key, value =  [s.strip() for s in word.split("<STR_LIT:=>")]<EOL>out["<STR_LIT>"][key] = value<EOL><DEDENT><DEDENT><DEDENT>return out<EOL><DEDENT>def elementMapper(inpeltype):<EOL><INDENT>if inpeltype == "<STR_LIT>": return "<STR_LIT>"<EOL>if inpeltype[:<NUM_LIT:3>] in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>if inpeltype[<NUM_LIT:3>] == "<STR_LIT:3>": return "<STR_LIT>"<EOL>if inpeltype[<NUM_LIT:3>] == "<STR_LIT:4>": return "<STR_LIT>"<EOL><DEDENT>if inpeltype[:<NUM_LIT:3>] in ["<STR_LIT>"]:<EOL><INDENT>if inpeltype[<NUM_LIT:3>] == "<STR_LIT:4>": return "<STR_LIT>"<EOL>if inpeltype[<NUM_LIT:3>] == "<STR_LIT:5>": return "<STR_LIT>"<EOL>if inpeltype[<NUM_LIT:3>] == "<STR_LIT>": return "<STR_LIT>"<EOL>if inpeltype[<NUM_LIT:3>] == "<STR_LIT>": return "<STR_LIT>"<EOL><DEDENT><DEDENT>nlabels      = []<EOL>coords       = []<EOL>nsets        = {}<EOL>elabels      = []<EOL>etypes       = []<EOL>connectivity = []<EOL>esets        = {}<EOL>surfaces     = {}<EOL>lines = np.array([l.strip().lower() for l in open(path).readlines()])<EOL>lines = [line for line in  lines if len(line) != <NUM_LIT:0>]<EOL>env, setlabel = None, None<EOL>for line in lines: <EOL><INDENT>d = lineInfo(line)<EOL>if d["<STR_LIT:type>"] == "<STR_LIT>": <EOL><INDENT>env = d["<STR_LIT:value>"]<EOL>if env == "<STR_LIT>":<EOL><INDENT>opt = d["<STR_LIT>"]<EOL>currentset = None<EOL>if "<STR_LIT>" in opt.keys(): <EOL><INDENT>currentset = opt["<STR_LIT>"]<EOL>nsets[currentset] = []<EOL><DEDENT><DEDENT>if env == "<STR_LIT>":<EOL><INDENT>opt = d["<STR_LIT>"]<EOL>eltype = elementMapper(opt["<STR_LIT:type>"])<EOL>currentset = None<EOL>if "<STR_LIT>" in opt.keys(): <EOL><INDENT>currentset = opt["<STR_LIT>"]<EOL>esets[currentset] = []<EOL><DEDENT><DEDENT>if env == "<STR_LIT>":<EOL><INDENT>opt = d["<STR_LIT>"]      <EOL>currentset = opt["<STR_LIT>"]<EOL>nsets[currentset] = []<EOL><DEDENT>if env == "<STR_LIT>":<EOL><INDENT>opt = d["<STR_LIT>"]      <EOL>currentset = opt["<STR_LIT>"]<EOL>esets[currentset] = []<EOL><DEDENT>if env == "<STR_LIT>":<EOL><INDENT>opt = d["<STR_LIT>"]<EOL>currentsurface = opt["<STR_LIT:name>"]<EOL>if opt["<STR_LIT:type>"] == "<STR_LIT>":<EOL><INDENT>surfaces[currentsurface] = []  <EOL><DEDENT><DEDENT><DEDENT>if d["<STR_LIT:type>"] == "<STR_LIT:data>": <EOL><INDENT>words = line.strip().split("<STR_LIT:U+002C>")<EOL>if env == "<STR_LIT>":<EOL><INDENT>label = int(words[<NUM_LIT:0>]) <EOL>nlabels.append(label) <EOL>coords.append(<EOL>np.array([np.float64(w) for w in words[<NUM_LIT:1>:<NUM_LIT:4>]])<EOL>)<EOL>if currentset != None: nsets[currentset].append(label)<EOL><DEDENT>if env == "<STR_LIT>": <EOL><INDENT>label  = int(words[<NUM_LIT:0>])<EOL>elabels.append(label)<EOL>connectivity.append(<EOL>np.array( [np.int32(w) for w in words[<NUM_LIT:1>:] if len(w) != <NUM_LIT:0> ])<EOL>)<EOL>etypes.append(eltype)                   <EOL>if currentset != None: esets[currentset].append(label)<EOL><DEDENT>if env == "<STR_LIT>":<EOL><INDENT>nsets[currentset] += [int(w) for w in words if len(w) != <NUM_LIT:0>]   <EOL><DEDENT>if env == "<STR_LIT>":<EOL><INDENT>esets[currentset] += [int(w) for w in words if len(w) != <NUM_LIT:0>]  <EOL><DEDENT>if env == "<STR_LIT>":<EOL><INDENT>if opt["<STR_LIT:type>"] == "<STR_LIT>":<EOL><INDENT>surfaces[currentsurface].append([w.strip() for w in words])<EOL><DEDENT><DEDENT><DEDENT><DEDENT>surfaces2 = {}        <EOL>for tag, surface in surfaces.items():<EOL><INDENT>surfaces2[tag] = []<EOL>for sdata in surface:<EOL><INDENT>labels = esets[sdata[<NUM_LIT:0>]]<EOL>face = int(sdata[<NUM_LIT:1>].split("<STR_LIT:s>")[<NUM_LIT:1>].strip())-<NUM_LIT:1><EOL>for label in labels:<EOL><INDENT>surfaces2[tag].append((label, face))             <EOL><DEDENT><DEDENT><DEDENT>return Mesh(nlabels = nlabels,<EOL>coords  = coords,<EOL>nsets   = nsets,<EOL>elabels = elabels,<EOL>etypes  = etypes,<EOL>connectivity = connectivity,<EOL>esets = esets,)<EOL>


def write_xdmf(mesh, path, dataformat = "<STR_LIT>"):

pattern = Template(open(MODPATH + "<STR_LIT>").read())<EOL>attribute_pattern = Template(open(MODPATH + "<STR_LIT>").read())<EOL>cell_map = {<EOL>"<STR_LIT>":   <NUM_LIT:4>,<EOL>"<STR_LIT>":  <NUM_LIT:5>,<EOL>"<STR_LIT>": <NUM_LIT:6>,<EOL>"<STR_LIT>":  <NUM_LIT:7>,<EOL>"<STR_LIT>": <NUM_LIT:8>,<EOL>"<STR_LIT>":  <NUM_LIT:9>}<EOL>nodes, elements = mesh.nodes.data, mesh.elements.data<EOL>fields = mesh.fields<EOL>Ne, Nn = len(elements), len(nodes)<EOL>nodes_map = np.arange(nodes.index.max()+<NUM_LIT:1>)<EOL>nodes_map[nodes.index] = np.arange(len(nodes.index))<EOL>nodes_map[<NUM_LIT:0>] = -<NUM_LIT:1><EOL>cols = ["<STR_LIT>".format(i) for i in range(elements.shape[<NUM_LIT:1>]-<NUM_LIT:1>)]<EOL>connectivities  = mesh.elements.data[cols].as_matrix()<EOL>connectivities[np.isnan(connectivities)] = <NUM_LIT:0><EOL>connectivities = connectivities.astype(np.int32)<EOL>connectivities = nodes_map[connectivities]<EOL>labels          = np.array(elements.index)<EOL>etypes          = np.array([cell_map[t] for t in elements.etype])<EOL>lconn           = Ne + (connectivities != -<NUM_LIT:1>).sum()<EOL>fields_string = "<STR_LIT>"<EOL>field_data = {}<EOL>for tag, field in fields.items():<EOL><INDENT>field_data[tag] = {}<EOL>field.data.sort_index(inplace = True)<EOL>fshape = field.data.shape[<NUM_LIT:1>]<EOL>if   fshape  == <NUM_LIT:1>: ftype = "<STR_LIT>"<EOL>elif fshape  == <NUM_LIT:3>: ftype = "<STR_LIT>"<EOL>elif fshape  == <NUM_LIT:2>: <EOL><INDENT>ftype = "<STR_LIT>"<EOL>field = copy.copy(field)<EOL>field.data["<STR_LIT>"] = np.zeros_like(field.data.index)<EOL>fields[tag] = field<EOL><DEDENT>elif fshape  == <NUM_LIT:6>: ftype = "<STR_LIT>"<EOL>elif fshape  == <NUM_LIT:4>: <EOL><INDENT>ftype = "<STR_LIT>"<EOL>field = copy.copy(field)<EOL>field.data["<STR_LIT>"] = np.zeros_like(field.data.index)<EOL>field.data["<STR_LIT>"] = np.zeros_like(field.data.index)<EOL>fields[tag] = field<EOL><DEDENT>if field.metadata.position == "<STR_LIT>": <EOL><INDENT>position = "<STR_LIT>"<EOL><DEDENT>if field.metadata.position == "<STR_LIT>":<EOL><INDENT>position = "<STR_LIT>"  <EOL><DEDENT>field_data[tag]["<STR_LIT>"]           = tag<EOL>field_data[tag]["<STR_LIT>"] = ftype<EOL>field_data[tag]["<STR_LIT>"]        = dataformat<EOL>field_data[tag]["<STR_LIT>"] = "<STR_LIT:U+0020>".join([str(l) for l in field.data.shape])<EOL>field_data[tag]["<STR_LIT>"]      = position                             <EOL><DEDENT>if dataformat == "<STR_LIT>":<EOL><INDENT>nodes_string = "<STR_LIT:\n>".join([<NUM_LIT:11>*"<STR_LIT:U+0020>" + "<STR_LIT>".format(<EOL>n.x, <EOL>n.y, <EOL>n.z) <EOL>for i, n in nodes.iterrows()])<EOL>elements_string = "<STR_LIT>"<EOL>for i in range(Ne):<EOL><INDENT>elements_string += <NUM_LIT:11>*"<STR_LIT:U+0020>" + str(etypes[i]) + "<STR_LIT:U+0020>"<EOL>c = connectivities[i]<EOL>c = c[np.where(c != -<NUM_LIT:1>)]<EOL>elements_string += "<STR_LIT:U+0020>".join([str(i) for i in c]) + "<STR_LIT:\n>"<EOL><DEDENT>elements_strings = elements_string[:-<NUM_LIT:1>]  <EOL>for tag, field in fields.items():<EOL><INDENT>fdata = field.data.to_csv(sep = "<STR_LIT:U+0020>", <EOL>index = False, <EOL>header = False).split("<STR_LIT:\n>")<EOL>fdata = [<NUM_LIT:11> * "<STR_LIT:U+0020>" + l for l in fdata]<EOL>fdata = "<STR_LIT:\n>".join(fdata)<EOL>field_data[tag]["<STR_LIT>"] = fdata<EOL>fields_string += attribute_pattern.substitute(**field_data[tag])     <EOL><DEDENT><DEDENT>elif dataformat == "<STR_LIT>":<EOL><INDENT>hdf = pd.HDFStore(path + "<STR_LIT>")<EOL>hdf.put("<STR_LIT>", mesh.nodes.data[list("<STR_LIT>")])<EOL>flatconn = np.zeros(lconn, dtype = np.int32)<EOL>pos = <NUM_LIT:0><EOL>for i in range(Ne):<EOL><INDENT>c = connectivities[i]<EOL>c = c[np.where(c != -<NUM_LIT:1>)]<EOL>lc = len(c)<EOL>flatconn[pos] = etypes[i]<EOL>flatconn[pos + <NUM_LIT:1> + np.arange(lc)] = c<EOL>pos += <NUM_LIT:1> + lc<EOL><DEDENT>hdf.put("<STR_LIT>", pd.DataFrame(flatconn))  <EOL>nodes_string = <NUM_LIT:11>*"<STR_LIT:U+0020>" + "<STR_LIT>".format(path)<EOL>elements_string = <NUM_LIT:11>*"<STR_LIT:U+0020>" + "<STR_LIT>".format(path)<EOL>for tag, field in fields.items():<EOL><INDENT>fstrings[tag] = fstrings[tag].replace("<STR_LIT>", <EOL><NUM_LIT:11>*"<STR_LIT:U+0020>" + "<STR_LIT>".format(path, tag))<EOL>fields_string += fstrings[tag]         <EOL>hdf.put("<STR_LIT>".format(tag), fields.data)<EOL><DEDENT>hdf.close()<EOL><DEDENT>


def write_inp(mesh, path = None, maxwidth = <NUM_LIT>, sections = "<STR_LIT>"):

def set_to_inp(sets, keyword):<EOL><INDENT>ss = "<STR_LIT>"<EOL>for sk in sets.keys():<EOL><INDENT>labels = sets[sk].loc[sets[sk]].index.values<EOL>labels = list(labels)<EOL>labels.sort()<EOL>if len(labels)!= <NUM_LIT:0>:<EOL><INDENT>ss += "<STR_LIT>".format(keyword, sk)<EOL>ss += argiope.utils.list_to_string(labels) + "<STR_LIT:\n>"<EOL><DEDENT><DEDENT>return ss.strip()           <EOL><DEDENT>mesh = mesh.copy()<EOL>nodes_output = (mesh.nodes.coords.to_csv(header = False).split())<EOL>nodes_output = ("<STR_LIT:\n>".join(["<STR_LIT:U+0020>" + s.replace("<STR_LIT:U+002C>", "<STR_LIT:U+002CU+0020>") for s in nodes_output]))<EOL>if "<STR_LIT>" in mesh.nodes.columns.levels[<NUM_LIT:0>]: <EOL><INDENT>nsets = set_to_inp(mesh.nodes.sets, "<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>nsets = "<STR_LIT>"<EOL><DEDENT>surf_output = []<EOL>if "<STR_LIT>" in mesh.elements.keys():<EOL><INDENT>sk = mesh.elements.surfaces.keys()<EOL>for sindex in  np.unique(sk.labels[<NUM_LIT:0>]):<EOL><INDENT>slabel = sk.levels[<NUM_LIT:0>][sindex]<EOL>surface = mesh.elements.surfaces[slabel]<EOL>if surface.values.sum() != <NUM_LIT:0>:<EOL><INDENT>mesh.surface_to_element_sets(slabel)<EOL>surf_output.append( "<STR_LIT>".format(slabel))<EOL>for findex in surface.keys():<EOL><INDENT>if surface[findex].sum() != <NUM_LIT:0>:<EOL><INDENT>surf_output.append("<STR_LIT>".format(slabel, <EOL>findex[<NUM_LIT:1>:])) <EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>surf_output.append("<STR_LIT>")<EOL><DEDENT>elements_output = "<STR_LIT>"<EOL>for etype, group in mesh.elements.groupby((("<STR_LIT:type>", "<STR_LIT>", "<STR_LIT>"),)):<EOL><INDENT>els = group.conn.replace(<NUM_LIT:0>, np.nan).to_csv(header = False, <EOL>float_format='<STR_LIT>').split()<EOL>elements_output += "<STR_LIT>".format(etype)<EOL>elements_output += ("<STR_LIT:\n>".join(["<STR_LIT:U+0020>" + s.strip().strip("<STR_LIT:U+002C>").<EOL>replace("<STR_LIT:U+002C>", "<STR_LIT:U+002CU+0020>") for s in els]))<EOL>elements_output += "<STR_LIT:\n>"<EOL><DEDENT>elements_output = elements_output.strip() <EOL>el_sets = {} <EOL>section_output = "<STR_LIT>"<EOL>for material, group in mesh.elements.groupby("<STR_LIT>"):<EOL><INDENT>slabel = "<STR_LIT>".format(material)<EOL>section_output += "<STR_LIT>".format(<EOL>material,<EOL>argiope.utils.list_to_string(group.index.values))<EOL>if sections == "<STR_LIT>":<EOL><INDENT>section_output += "<STR_LIT>".format(<EOL>material)<EOL><DEDENT><DEDENT>if "<STR_LIT>" in mesh.elements.columns.levels[<NUM_LIT:0>]: <EOL><INDENT>esets = set_to_inp(mesh.elements.sets.swaplevel(<NUM_LIT:1>,<NUM_LIT:0>, axis = <NUM_LIT:1>)["<STR_LIT>"],"<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>esets = "<STR_LIT>"<EOL><DEDENT>


shape = np.array(shape)<EOL>Ne = shape.prod()<EOL>if len(shape) == <NUM_LIT:2>:<EOL><INDENT>nx, ny = np.array(shape) +<NUM_LIT:1> <EOL>conn = np.zeros((Ne, <NUM_LIT:4>), dtype = np.int32)<EOL>counter = <NUM_LIT:0><EOL>pattern = np.array([<NUM_LIT:0>,<NUM_LIT:1>,<NUM_LIT:1>+nx,nx])<EOL>for j in range(shape[<NUM_LIT:1>]):<EOL><INDENT>for i in range(shape[<NUM_LIT:0>]):<EOL><INDENT>conn[counter] = pattern + <NUM_LIT:1> + i + j*nx<EOL>counter += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>if len(shape) == <NUM_LIT:3>:<EOL><INDENT>nx, ny, nz  = np.array(shape) +<NUM_LIT:1> <EOL>conn = np.zeros((Ne, <NUM_LIT:8>), dtype = np.int32)<EOL>counter = <NUM_LIT:0><EOL>pattern = np.array([<NUM_LIT:0>,<NUM_LIT:1>,<NUM_LIT:1>+nx,nx,nx*ny,<NUM_LIT:1>+nx*ny,<NUM_LIT:1>+(nx+<NUM_LIT:1>)*ny,(nx+<NUM_LIT:1>)*ny])<EOL>for k in range(shape[<NUM_LIT:2>]):<EOL><INDENT>for j in range(shape[<NUM_LIT:1>]):<EOL><INDENT>for i in range(shape[<NUM_LIT:0>]):<EOL><INDENT>conn[counter] = pattern + <NUM_LIT:1> + i + j*nx+ k*nx*ny<EOL>counter += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT><DEDENT>return conn<EOL>

Connectivity builder using Numba for speed boost.


def structured_mesh(shape = (<NUM_LIT:2>,<NUM_LIT:2>,<NUM_LIT:2>), dim = (<NUM_LIT:1.>,<NUM_LIT:1.>,<NUM_LIT:1.>)):

<EOL>shape = np.array(shape)<EOL>dim   = np.array(dim) <EOL>Ne = shape.prod()<EOL>Nn = (shape + <NUM_LIT:1>).prod()<EOL>nindex = np.arange(Nn) + <NUM_LIT:1><EOL>eindex = np.arange(Ne) + <NUM_LIT:1><EOL>coords = [ np.linspace(<NUM_LIT:0.>, dim[i], shape[i] + <NUM_LIT:1>) for i in range(len(shape))]<EOL>coords = np.array(np.meshgrid(*coords))<EOL>coords = np.array([c.swapaxes(<NUM_LIT:0>,<NUM_LIT:1>).flatten("<STR_LIT:F>") for c in coords]).T<EOL>if len(shape) == <NUM_LIT:2>:<EOL><INDENT>c = coords<EOL>coords = np.zeros((Nn, <NUM_LIT:3>))<EOL>coords[:, :<NUM_LIT:2>] = c  <EOL><DEDENT>conn = _make_conn(shape)<EOL>mesh = Mesh(nlabels = nindex,<EOL>coords  = coords,<EOL>elabels = eindex,<EOL>conn = conn,)<EOL>if len(shape) == <NUM_LIT:2>: mesh.elements[("<STR_LIT:type>", "<STR_LIT>")] = "<STR_LIT>"<EOL>if len(shape) == <NUM_LIT:3>: mesh.elements[("<STR_LIT:type>", "<STR_LIT>")] = "<STR_LIT>"    <EOL>return mesh<EOL>

Returns a structured mesh.

:arg shape: 2 or 3 integers (eg: shape = (10, 10, 10)).
:type shape: tuple
:arg dim: 2 or 3 floats (eg: dim = (4., 2., 1.))
:type dim: tuple

.. note::

   This function does not use GMSH for mesh generation.

>>> import argiope as ag
>>> mesh = ag.mesh.structured_mesh(shape =(10,10,10), dim=(1.,1.,1.)))


return<EOL>


def set_nodes(self, nlabels = [], coords = [], nsets = {}, **kwargs):

<EOL>nlabels = np.array(nlabels).astype(np.int64)<EOL>coords = np.array(coords).astype(np.float64)<EOL>if (nlabels < <NUM_LIT:0>).sum() > <NUM_LIT:0>: <EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if len(nlabels) != len(coords):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if coords.shape[<NUM_LIT:1>] != <NUM_LIT:3>:<EOL><INDENT>raise ValueError("<STR_LIT>")    <EOL><DEDENT>columns = pd.MultiIndex.from_tuples((("<STR_LIT>", "<STR_LIT:x>"), <EOL>("<STR_LIT>", "<STR_LIT:y>"), <EOL>("<STR_LIT>", "<STR_LIT:z>")))<EOL>self.nodes = pd.DataFrame(data = coords, <EOL>columns = columns,<EOL>index = nlabels)<EOL>self.nodes.index.name = "<STR_LIT>"<EOL>for k, v in nsets.items(): <EOL><INDENT>v = np.array(v)<EOL>if v.dtype != '<STR_LIT:bool>':<EOL><INDENT>raise ValueError("<STR_LIT>")   <EOL><DEDENT>self.nodes["<STR_LIT>", k] = v<EOL><DEDENT>self.nodes["<STR_LIT>", "<STR_LIT:all>"] = True<EOL>

r"""
        Sets the node data.

        :arg nlabels: node labels. Items be strictly positive and int typed
                      in 1D array-like with shape :math:`(N_n)`.
        :type nlabels: 1D uint typed array-like
        :arg coords: node coordinates. Must be float typed 2D array-like of shape
                     :math:`(N_n \times 3)`.
        :type coords: 2D float typed array-like
        :arg nsets: node sets. Contains boolean array-like of shape :math:`(N_n)`.
        :type nsets: dict


def set_elements(self, elabels = None, <EOL>types = None, <EOL>stypes = "<STR_LIT>", <EOL>conn = None, <EOL>esets = {}, <EOL>surfaces = {}, <EOL>materials = "<STR_LIT>",<EOL>**kwargs):

<EOL>if elabels is None:<EOL><INDENT>warnings.warn(<EOL>"<STR_LIT>", <EOL>Warning)<EOL>self.elements = None<EOL><DEDENT>else:   <EOL><INDENT>columns = pd.MultiIndex.from_tuples([("<STR_LIT:type>", "<STR_LIT>", "<STR_LIT>")])<EOL>self.elements = pd.DataFrame(data = types,<EOL>columns = columns,<EOL>index = elabels)<EOL>self.elements.index.name = "<STR_LIT>"<EOL>self.elements.loc[:, ("<STR_LIT:type>", "<STR_LIT>", "<STR_LIT>")] = stypes<EOL>c = pd.DataFrame(conn, index = elabels)<EOL>c.fillna(<NUM_LIT:0>, inplace = True)<EOL>c[:] = c.values.astype(np.int32)<EOL>c.columns = pd.MultiIndex.from_product([["<STR_LIT>"], <EOL>["<STR_LIT>".format(n) for <EOL>n in np.arange(c.shape[<NUM_LIT:1>])], <EOL>["<STR_LIT>"]])<EOL>self.elements = self.elements.join(c)<EOL>for k, v in esets.items(): self.elements[("<STR_LIT>", k, "<STR_LIT>")] = v<EOL>self.elements["<STR_LIT>", "<STR_LIT:all>", "<STR_LIT>"] = True  <EOL>for k, v in surfaces.items():<EOL><INDENT>for fk, vv in v.items():<EOL><INDENT>self.elements[("<STR_LIT>", k, "<STR_LIT>".format(fk))] = vv<EOL><DEDENT><DEDENT>self.elements[("<STR_LIT>", "<STR_LIT>", "<STR_LIT>") ] = materials<EOL>self.elements.sort_index(axis = <NUM_LIT:1>, inplace = True)<EOL><DEDENT>

Sets the element data.

:arg elabels: element labels. Items be strictly positive and int typed
              in 1D array-like with shape :math:`(N_e)`.
:type elabels: 1D uint typed array-like
:arg types: element types chosen among argiope specific element types.
:type types: str typed array-like
:arg stypes: element types chosen in solver (depends on the chosen solver) specific element types.
:type stypes: str typed array-like
:arg conn: connectivity table. In order to deal with non rectangular tables, :math:`0` can be used to fill missing data.
:type conn: uint typed array-like
:arg esets: element sets. Contains boolean array-like of shape :math:`(N_e)`.
:type esets: dict
:arg surfaces: surfaces. Contains boolean array-like of shape :math:`(N_e, N_s )` with :math:`N_s` being the maximum number of faces on a single element.
:type surfaces: dict
:arg materials: material keys. Any number a of materials can be used.
:type materials: str typed array-like


def set_fields(self, fields = None, **kwargs):

self.fields = []<EOL>if fields != None:<EOL><INDENT>for field in fields: <EOL><INDENT>self.fields.append(field)<EOL><DEDENT><DEDENT>


def add_fields(self, fields = None, **kwargs):

if fields != None:<EOL><INDENT>for field in fields: <EOL><INDENT>self.fields.append(field)<EOL><DEDENT><DEDENT>


<EOL>existing_types = set(self.elements.type.argiope.values.flatten())<EOL>allowed_types = set(ELEMENTS.keys())<EOL>if (existing_types <= allowed_types) == False:<EOL><INDENT>raise ValueError("<STR_LIT>".format(<EOL>existing_types - allowed_types, allowed_types))<EOL><DEDENT>print("<STR_LIT>")<EOL>


return self.elements.type.argiope.map(<EOL>lambda t: ELEMENTS[t].space)<EOL>

Returns the dimension of the embedded space of each element.


return self.elements.type.argiope.map(<EOL>lambda t: ELEMENTS[t].nvert)<EOL>

Returns the number of vertices of eache element according to its type/


def split(self, into = "<STR_LIT>", loc = None, <EOL>at = "<STR_LIT>", sort_index = True):

if type(loc) == type(None):<EOL><INDENT>elements = self.elements<EOL><DEDENT>else:  <EOL><INDENT>elements = self.elements.loc[loc]<EOL><DEDENT>out = []<EOL>for etype, group in elements.groupby([("<STR_LIT:type>", "<STR_LIT>", "<STR_LIT>")]):<EOL><INDENT>try:<EOL><INDENT>output_maps = getattr(ELEMENTS[etype], into)<EOL>for om in range(len(output_maps)):<EOL><INDENT>oshape = len(output_maps[om])<EOL>conn = group.conn<EOL>columns = pd.MultiIndex.from_product([(om,), np.arange(oshape)], <EOL>names = [into, "<STR_LIT>"])<EOL>data = (conn.values[:, output_maps[om]].reshape(len(conn), oshape))<EOL>df = pd.DataFrame(data = data, <EOL>columns = columns,<EOL>index = conn.index).stack((<NUM_LIT:0>,<NUM_LIT:1>))<EOL>out.append(df)<EOL><DEDENT><DEDENT>except:<EOL><INDENT>print("<STR_LIT>".format(into, etype))                           <EOL><DEDENT><DEDENT>if len(out) != <NUM_LIT:0>:<EOL><INDENT>out = pd.concat(out)<EOL>out.sort_index(inplace = True)<EOL>if at == "<STR_LIT>":<EOL><INDENT>data = self.nodes.coords.loc[out.values].values<EOL>out = pd.DataFrame(index = out.index, data = data, <EOL>columns = ["<STR_LIT:x>", "<STR_LIT:y>", "<STR_LIT:z>"])<EOL><DEDENT>return out<EOL><DEDENT>

Returns the decomposition of the elements.

Inputs:
* into: must be in ['edges', 'faces', 'simplices', 'angles']
* loc: None or labels of the chosen elements.
* at: must be in ['labels', 'coords']


def centroids_and_volumes(self, sort_index = True):

elements = self.elements<EOL>out = []<EOL>for etype, group in self.elements.groupby([("<STR_LIT:type>", "<STR_LIT>", "<STR_LIT>")]):<EOL><INDENT>etype_info = ELEMENTS[etype]<EOL>simplices_info = etype_info.simplices<EOL>index = group.index<EOL>simplices_data = self.split(into = "<STR_LIT>", <EOL>loc = index,<EOL>at = "<STR_LIT>") <EOL>simplices = simplices_data.values.reshape(<EOL>index.size, <EOL>simplices_info.shape[<NUM_LIT:0>], <EOL>simplices_info.shape[<NUM_LIT:1>], <EOL><NUM_LIT:3>) <EOL>edges = simplices[:,:,<NUM_LIT:1>:] - simplices[:,:,:<NUM_LIT:1>] <EOL>simplices_centroids = simplices.mean(axis = <NUM_LIT:2>)<EOL>if etype_info.space == <NUM_LIT:2>:<EOL><INDENT>simplices_volumes = np.linalg.norm(<EOL>np.cross(edges[:,:,<NUM_LIT:0>], <EOL>edges[:,:,<NUM_LIT:1>], <EOL>axis = <NUM_LIT:2>),<EOL>axis = <NUM_LIT:2>)/<NUM_LIT><EOL><DEDENT>elif etype_info.space == <NUM_LIT:3>:          <EOL><INDENT>simplices_volumes =  (np.cross(edges[:,:,<NUM_LIT:0>], <EOL>edges[:,:,<NUM_LIT:1>], axis = <NUM_LIT:2>) <EOL>* edges[:,:, <NUM_LIT:2>]).sum(axis = <NUM_LIT:2>) / <NUM_LIT><EOL><DEDENT>elements_volumes = simplices_volumes.sum(axis = <NUM_LIT:1>)<EOL>elements_centroids = ((simplices_volumes.reshape(*simplices_volumes.shape, <NUM_LIT:1>) <EOL>* simplices_centroids).sum(axis = <NUM_LIT:1>) <EOL>/ elements_volumes.reshape(*elements_volumes.shape,<NUM_LIT:1>))<EOL>volumes_df = pd.DataFrame(index = index,<EOL>data = elements_volumes,<EOL>columns = pd.MultiIndex.from_product(<EOL>[["<STR_LIT>"], ["<STR_LIT>"]]))<EOL>centroids_df = pd.DataFrame(index = index,<EOL>data = elements_centroids,<EOL>columns = pd.MultiIndex.from_product(<EOL>[["<STR_LIT>"], ["<STR_LIT:x>", "<STR_LIT:y>", "<STR_LIT:z>"]]))                          <EOL>out.append(pd.concat([volumes_df, centroids_df], axis = <NUM_LIT:1>))             <EOL><DEDENT>out = pd.concat(out)  <EOL>if sort_index: out.sort_index(inplace = True)<EOL>return out.sort_index(axis= <NUM_LIT:1>)<EOL>

Returns a dataframe containing volume and centroids of all the elements.


elements = self.elements.sort_index(axis = <NUM_LIT:1>)<EOL>etypes = elements[("<STR_LIT:type>", "<STR_LIT>")].unique()<EOL>out = []<EOL>for etype in etypes:<EOL><INDENT>etype_info = ELEMENTS[etype]<EOL>angles_info = etype_info.angles<EOL>loc = elements[("<STR_LIT:type>", "<STR_LIT>", "<STR_LIT>")] == etype<EOL>index = elements.loc[loc].index<EOL>angles_data = self.split(into = "<STR_LIT>", <EOL>loc = loc,<EOL>at = "<STR_LIT>")<EOL>data = angles_data.values.reshape(index.size, <EOL>angles_info.shape[<NUM_LIT:0>],<EOL>angles_info.shape[<NUM_LIT:1>],<EOL><NUM_LIT:3>)        <EOL>edges = data[:,:,[<NUM_LIT:0>,<NUM_LIT:2>],:] - data[:,:,<NUM_LIT:1>:<NUM_LIT:2>,:]<EOL>edges /= np.linalg.norm(edges, axis = <NUM_LIT:3>).reshape(<EOL>index.size, angles_info.shape[<NUM_LIT:0>], <NUM_LIT:2>, <NUM_LIT:1>)<EOL>angles = np.degrees(np.arccos((<EOL>edges[:,:,<NUM_LIT:0>] * edges[:,:,<NUM_LIT:1>]).sum(axis = <NUM_LIT:2>)))<EOL>deviation = angles - etype_info.optimal_angles<EOL>angles_df = pd.DataFrame(index = index, <EOL>data = angles, <EOL>columns = pd.MultiIndex.from_product(<EOL>[["<STR_LIT>"], ["<STR_LIT:a>" + "<STR_LIT>".format(s).zfill(zfill) <EOL>for s in range(angles_info.shape[<NUM_LIT:0>])]]))<EOL>deviation_df = pd.DataFrame(index = index, <EOL>data = deviation, <EOL>columns = pd.MultiIndex.from_product(<EOL>[["<STR_LIT>"], ["<STR_LIT:d>" + "<STR_LIT>".format(s).zfill(zfill) <EOL>for s in range(angles_info.shape[<NUM_LIT:0>])]]))<EOL>df = pd.concat([angles_df, deviation_df], axis = <NUM_LIT:1>).sort_index(axis = <NUM_LIT:1>)<EOL>df["<STR_LIT>", "<STR_LIT>"] = df.angles.max(axis = <NUM_LIT:1>)<EOL>df["<STR_LIT>", "<STR_LIT>"] = df.angles.min(axis = <NUM_LIT:1>)<EOL>df["<STR_LIT>", "<STR_LIT>"] = df.deviation.max(axis = <NUM_LIT:1>)<EOL>df["<STR_LIT>", "<STR_LIT>"] = df.deviation.min(axis = <NUM_LIT:1>)<EOL>df["<STR_LIT>", "<STR_LIT>"] = abs(df.deviation).max(axis = <NUM_LIT:1>)    <EOL>df = df.sort_index(axis = <NUM_LIT:1>)  <EOL>out.append(df)<EOL><DEDENT>out = pd.concat(out).sort_index(axis = <NUM_LIT:1>)<EOL>return out<EOL>

Returns the internal angles of all elements and the associated statistics


edges = self.split("<STR_LIT>", at = "<STR_LIT>").unstack()<EOL>edges["<STR_LIT>"] = edges.x[<NUM_LIT:1>]-edges.x[<NUM_LIT:0>]<EOL>edges["<STR_LIT>"] = edges.y[<NUM_LIT:1>]-edges.y[<NUM_LIT:0>]<EOL>edges["<STR_LIT>"] = edges.z[<NUM_LIT:1>]-edges.z[<NUM_LIT:0>]<EOL>edges["<STR_LIT:l>"] = np.linalg.norm(edges[["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]], axis = <NUM_LIT:1>)<EOL>edges = (edges.l).unstack()<EOL>edges.columns = pd.MultiIndex.from_product([["<STR_LIT>"], <EOL>["<STR_LIT:e>" + "<STR_LIT>".format(s).zfill(zfill) <EOL>for s in np.arange(edges.shape[<NUM_LIT:1>])]])<EOL>edges[("<STR_LIT>", "<STR_LIT>")] = edges.length.max(axis = <NUM_LIT:1>)<EOL>edges[("<STR_LIT>", "<STR_LIT>")] = edges.length.min(axis = <NUM_LIT:1>)<EOL>edges[("<STR_LIT>", "<STR_LIT>")] = edges.stats.lmax / edges.stats.lmin<EOL>return edges.sort_index(axis = <NUM_LIT:1>)<EOL>

Returns the aspect ratio of all elements.


cv = self.centroids_and_volumes()<EOL>angles  = self.angles()<EOL>edges = self.edges()<EOL>return pd.concat([cv , angles[["<STR_LIT>"]], edges[["<STR_LIT>"]] ], <EOL>axis = <NUM_LIT:1>).sort_index(axis = <NUM_LIT:1>)<EOL>

Returns mesh quality and geometric stats.


nodes, elements = self.nodes, self.elements<EOL>loc = (elements.conn[elements[("<STR_LIT>", tag, "<STR_LIT>")]]<EOL>.stack().stack().unique())<EOL>loc = loc[loc != <NUM_LIT:0>]<EOL>nodes[("<STR_LIT>", tag)] = False<EOL>nodes.loc[loc, ("<STR_LIT>", tag) ] = True<EOL>


<EOL>nodes = self.nodes.copy()<EOL>dummy = nodes.iloc[<NUM_LIT:0>].copy()<EOL>dummy["<STR_LIT>"] *= np.nan<EOL>dummy["<STR_LIT>"] = True<EOL>nodes.loc[<NUM_LIT:0>] = dummy<EOL>element_surfaces= self.split("<STR_LIT>").unstack()<EOL>surf = pd.DataFrame(<EOL>nodes.sets[tag].loc[element_surfaces.values.flatten()]<EOL>.values.reshape(element_surfaces.shape)<EOL>.prod(axis = <NUM_LIT:1>)<EOL>.astype(np.bool),<EOL>index = element_surfaces.index).unstack().fillna(False)<EOL>for k in surf.keys():<EOL><INDENT>self.elements["<STR_LIT>", tag, "<STR_LIT>".format(k[<NUM_LIT:1>]+<NUM_LIT:1>) ] = surf.loc[:, k]<EOL><DEDENT>


surface = self.elements.surfaces[tag]<EOL>for findex in surface.keys():<EOL><INDENT>if surface[findex].sum() != <NUM_LIT:0>:<EOL><INDENT>self.elements[("<STR_LIT>", "<STR_LIT>"<EOL>.format(tag, findex[<NUM_LIT:1>:]), "<STR_LIT>")] = surface[findex]<EOL><DEDENT><DEDENT>

Creates elements sets corresponding to a surface.


def to_polycollection(self, *args, **kwargs):

from matplotlib import collections<EOL>nodes, elements = self.nodes, self.elements.reset_index()<EOL>verts = []<EOL>index = []<EOL>for etype, group in elements.groupby([("<STR_LIT:type>", "<STR_LIT>", "<STR_LIT>")]):<EOL><INDENT>index += list(group.index)<EOL>nvert = ELEMENTS[etype].nvert<EOL>conn = group.conn.values[:, :nvert].flatten()<EOL>coords = nodes.coords[["<STR_LIT:x>", "<STR_LIT:y>"]].loc[conn].values.reshape(<EOL>len(group), nvert, <NUM_LIT:2>)<EOL>verts += list(coords)<EOL><DEDENT>verts = np.array(verts)<EOL>verts= verts[np.argsort(index)]<EOL>return collections.PolyCollection(verts, *args,**kwargs )<EOL>

Returns the mesh as matplotlib polygon collection. (tested only for 2D meshes)


from matplotlib.tri import Triangulation<EOL>conn = self.split("<STR_LIT>").unstack()<EOL>coords = self.nodes.coords.copy()<EOL>node_map  = pd.Series(data = np.arange(len(coords)), index = coords.index)<EOL>conn = node_map.loc[conn.values.flatten()].values.reshape(*conn.shape)<EOL>return Triangulation(coords.x.values, coords.y.values, conn)<EOL>

Returns the mesh as a matplotlib.tri.Triangulation instance. (2D only)


return write_inp(self, *args, **kwargs)<EOL>

Exports the mesh to the Abaqus INP format.


return (pd.concat([f.metadata() for f in self.fields], axis = <NUM_LIT:1>)<EOL>.transpose()<EOL>.sort_values(["<STR_LIT>", "<STR_LIT>", "<STR_LIT:label>", "<STR_LIT>"]))<EOL>


return pd.Series({<EOL>"<STR_LIT>": self.part,<EOL>"<STR_LIT>": self.step_num,<EOL>"<STR_LIT>": self.step_label,<EOL>"<STR_LIT>": self.frame,<EOL>"<STR_LIT>": self.frame_value,<EOL>"<STR_LIT:label>": self.label,<EOL>"<STR_LIT>": self.position,                    <EOL>})<EOL>


return pickle.load(gzip.open(path))<EOL>


def list_to_string(l = range(<NUM_LIT:200>), width = <NUM_LIT>, indent = "<STR_LIT:U+0020>"):

l = [str(v) + "<STR_LIT:U+002C>" for v in l]<EOL>counter = <NUM_LIT:0><EOL>out = "<STR_LIT>" + indent<EOL>for w in l:<EOL><INDENT>s = len(w)<EOL>if counter + s > width: <EOL><INDENT>out += "<STR_LIT:\n>" + indent<EOL>counter = <NUM_LIT:0><EOL><DEDENT>out += w<EOL>counter += s<EOL><DEDENT>return out.strip("<STR_LIT:U+002C>")<EOL>

Converts a list-like to string with given line width.


def _equation(nodes = (<NUM_LIT:1>, <NUM_LIT:2>), dofs = (<NUM_LIT:1>, <NUM_LIT:1>), coefficients = (<NUM_LIT:1.>, <NUM_LIT:1.>), <EOL>comment = None):

N = len(nodes)<EOL>if comment == None:<EOL><INDENT>out = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>out = "<STR_LIT>".format(comment)  <EOL><DEDENT>out+= "<STR_LIT>".format(N)<EOL>out += "<STR_LIT>".join([ "<STR_LIT:U+002C>".join([ str(nodes[i]), <EOL>str(int(dofs[i])), <EOL>str(coefficients[i]) ]) for i in range(N)])<EOL>return out<EOL>

Returns an Abaqus INP formated string for a given linear equation.


out = "<STR_LIT>".format(label)<EOL>labels = df.index.values<EOL>return out + argiope.utils.list_to_string(labels, **kwargs)<EOL>

Returns a set as inp string with unsorted option.


pickle.dump(self, gzip.open(path, "<STR_LIT:w>"), <NUM_LIT:3>)<EOL>

Saves the instance into a compressed serialized file.


return copy.deepcopy(self)<EOL>


if os.path.isdir(self.workdir) == False: os.mkdir(self.workdir)<EOL>

Checks if required directories exist and creates them if needed.


self.make_directories()<EOL>t0 = time.time()<EOL>if self.verbose: <EOL><INDENT>print('<STR_LIT>'.format(self.label, <EOL>self.solver.upper() ))  <EOL><DEDENT>if self.solver == "<STR_LIT>":<EOL><INDENT>command = '<STR_LIT>'.format(<EOL>self.solver_path, <EOL>self.label) <EOL>process = subprocess.Popen(command, <EOL>cwd    = self.workdir, <EOL>shell  = True, <EOL>stdout = subprocess.PIPE,<EOL>stderr = subprocess.STDOUT)<EOL>for line in iter(process.stdout.readline, b'<STR_LIT>'):<EOL><INDENT>line = line.rstrip().decode('<STR_LIT:utf8>')<EOL>print("<STR_LIT:U+0020>", line)<EOL><DEDENT><DEDENT>t1 = time.time()<EOL>if self.verbose: <EOL><INDENT>print('<STR_LIT>'.format(self.label, t1 - t0))<EOL><DEDENT>


t0 = time.time()<EOL>if self.verbose: <EOL><INDENT>print('<STR_LIT>'.format(self.label, <EOL>self.solver.upper()))  <EOL><DEDENT>if self.solver == "<STR_LIT>":<EOL><INDENT>command = '<STR_LIT>'.format(self.solver_path, self.label)<EOL>process = subprocess.Popen( <EOL>command, <EOL>cwd    = self.workdir,<EOL>shell  = True,<EOL>stdout = subprocess.PIPE,<EOL>stderr = subprocess.STDOUT)<EOL>for line in iter(process.stdout.readline, b'<STR_LIT>'):<EOL><INDENT>line = line.rstrip().decode('<STR_LIT:utf8>')<EOL>print("<STR_LIT:U+0020>", line)<EOL><DEDENT><DEDENT>t1 = time.time()<EOL>if self.verbose: <EOL><INDENT>print('<STR_LIT>'.format(self.label, <EOL>t1 - t0))<EOL><DEDENT>


argiope.utils.run_gmsh(gmsh_path = self.gmsh_path,<EOL>gmsh_space = self.gmsh_space,<EOL>gmsh_options = self.gmsh_options,<EOL>name = self.file_name + "<STR_LIT>",<EOL>workdir = self.workdir)  <EOL>self.mesh = argiope.mesh.read_msh(self.workdir + self.file_name + "<STR_LIT>")<EOL>


def read_history_report(path, steps, x_name = None):

data = pd.read_csv(path, delim_whitespace = True)<EOL>if x_name != None:<EOL><INDENT>data[x_name] = data.X<EOL>del data["<STR_LIT:X>"]<EOL><DEDENT>data["<STR_LIT>"] = <NUM_LIT:0><EOL>t = <NUM_LIT:0.><EOL>for i in range(len(steps)):<EOL><INDENT>dt = steps[i].duration<EOL>loc = data[data.t == t].index<EOL>if len(loc) == <NUM_LIT:2>:<EOL><INDENT>data.loc[loc[<NUM_LIT:1>]:, "<STR_LIT>"] = i<EOL><DEDENT>t += dt <EOL><DEDENT>return data<EOL>


def read_field_report(path, data_flag = "<STR_LIT>", meta_data_flag = "<STR_LIT>"):

text = open(path).read()<EOL>mdpos = text.find(meta_data_flag)<EOL>dpos = text.find(data_flag)<EOL>mdata = io.StringIO( "<STR_LIT:\n>".join(text[mdpos:dpos].split("<STR_LIT:\n>")[<NUM_LIT:1>:]))<EOL>data = io.StringIO( "<STR_LIT:\n>".join(text[dpos:].split("<STR_LIT:\n>")[<NUM_LIT:1>:]))<EOL>data = pd.read_csv(data, index_col = <NUM_LIT:0>)<EOL>data = data.groupby(data.index).mean()<EOL>mdata = pd.read_csv(mdata, sep = "<STR_LIT:=>", header = None, index_col = <NUM_LIT:0>)[<NUM_LIT:1>]<EOL>mdata = mdata.to_dict()<EOL>out = {}<EOL>out["<STR_LIT>"] = int(mdata["<STR_LIT>"])<EOL>out["<STR_LIT>"] = mdata["<STR_LIT>"]<EOL>out["<STR_LIT>"] = int(mdata["<STR_LIT>"])<EOL>out["<STR_LIT>"] = float(mdata["<STR_LIT>"])<EOL>out["<STR_LIT>"] = mdata["<STR_LIT>"]<EOL>position_map = {"<STR_LIT>": "<STR_LIT>", <EOL>"<STR_LIT>": "<STR_LIT>", <EOL>"<STR_LIT>": "<STR_LIT>"}<EOL>out["<STR_LIT>"] = position_map[mdata["<STR_LIT>"]]<EOL>out["<STR_LIT:label>"] = mdata["<STR_LIT:label>"]  <EOL>out["<STR_LIT:data>"] = data<EOL>field_class = getattr(argiope.mesh, mdata["<STR_LIT>"])<EOL>return field_class(**out)<EOL>


return odb.steps.keys()<EOL>

Retrieves the steps keys in an odb object


return len(odb.steps[stepKey].frames)<EOL>

Retrieves the number of frames in a step.


def write_xy_report(odb, path, tags, columns, steps):

xyData = [session.XYDataFromHistory(name = columns[i], <EOL>odb = odb, <EOL>outputVariableName = tags[i],<EOL>steps = steps) <EOL>for i in xrange(len(tags))]<EOL>session.xyReportOptions.setValues(numDigits=<NUM_LIT:8>, numberFormat=SCIENTIFIC)<EOL>session.writeXYReport(fileName=path, appendMode=OFF, xyData=xyData)<EOL>


def write_field_report(odb, path, label, argiope_class, variable, instance, output_position, <EOL>step = -<NUM_LIT:1>, frame = -<NUM_LIT:1>, sortItem='<STR_LIT>'):

stepKeys = get_steps(odb)<EOL>step = xrange(len(stepKeys))[step]<EOL>frame = xrange(get_frames(odb, stepKeys[step]))[frame]<EOL>nf = NumberFormat(numDigits=<NUM_LIT:9>, <EOL>precision=<NUM_LIT:0>, <EOL>format=SCIENTIFIC)<EOL>session.fieldReportOptions.setValues(<EOL>printTotal=OFF, <EOL>printMinMax=OFF, <EOL>numberFormat=nf)<EOL>leaf = dgo.LeafFromPartInstance(<EOL>partInstanceName = instance)<EOL>session.viewports['<STR_LIT>'].odbDisplay.displayGroup.replace(leaf=leaf)<EOL>session.writeFieldReport(<EOL>fileName       = path, <EOL>append         = OFF, <EOL>sortItem       = sortItem,<EOL>odb            = odb, <EOL>step           = step, <EOL>frame          = frame, <EOL>outputPosition = output_position, <EOL>variable       = variable)<EOL>lines = [line.strip() for line in open(path).readlines()]<EOL>isdata = -<NUM_LIT:1><EOL>data = []<EOL>for line in lines:<EOL><INDENT>if isdata == <NUM_LIT:1>:<EOL><INDENT>if len(line) == <NUM_LIT:0>: <EOL><INDENT>isdata -= <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>data.append(line)   <EOL><DEDENT><DEDENT>elif isdata < <NUM_LIT:1>:<EOL><INDENT>if line.startswith("<STR_LIT>"):<EOL><INDENT>isdata += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>data = "<STR_LIT:\n>".join(["<STR_LIT:U+002C>".join(line.split()) for line in data if len(line) != <NUM_LIT:0>])<EOL>header = str(output_position).lower() + "<STR_LIT:U+002C>" <EOL>header += "<STR_LIT:U+002C>".join([v[<NUM_LIT:1>] for v in variable[<NUM_LIT:0>][<NUM_LIT:2>]]) + "<STR_LIT:\n>"<EOL>metadata = (<EOL>("<STR_LIT:label>", label),<EOL>("<STR_LIT>", argiope_class) ,<EOL>("<STR_LIT>", odb.path), <EOL>("<STR_LIT>", instance),<EOL>("<STR_LIT>", output_position),<EOL>("<STR_LIT>", step),<EOL>("<STR_LIT>", stepKeys[step]),<EOL>("<STR_LIT>", frame),<EOL>("<STR_LIT>", odb.steps[stepKeys[step]].frames[frame].frameValue)<EOL>)<EOL>out = "<STR_LIT>".format(<EOL>"<STR_LIT:\n>".join(["<STR_LIT>".format(k, v) for k, v in metadata]),<EOL>header + data)           <EOL>open(path, "<STR_LIT:w>").write(out)<EOL>

Writes a field report and rewrites it in a cleaner format.


_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)<EOL>_socket.settimeout(<NUM_LIT>)<EOL>if self._interface != '<STR_LIT>':<EOL><INDENT>_socket.bind((self._interface, <NUM_LIT:0>))<EOL><DEDENT>for gateway in self._gateways_config:<EOL><INDENT>host = gateway.get('<STR_LIT:host>')<EOL>port = gateway.get('<STR_LIT:port>')<EOL>sid = gateway.get('<STR_LIT>')<EOL>if not (host and port and sid):<EOL><INDENT>continue<EOL><DEDENT>try:<EOL><INDENT>ip_address = socket.gethostbyname(host)<EOL>if gateway.get('<STR_LIT>'):<EOL><INDENT>_LOGGER.info(<EOL>'<STR_LIT>', sid)<EOL>self.disabled_gateways.append(ip_address)<EOL>continue<EOL><DEDENT>_LOGGER.info(<EOL>'<STR_LIT>',<EOL>sid, ip_address, port)<EOL>self.gateways[ip_address] = XiaomiGateway(<EOL>ip_address, port, sid,<EOL>gateway.get('<STR_LIT:key>'), self._device_discovery_retries,<EOL>self._interface, gateway.get('<STR_LIT>'))<EOL><DEDENT>except OSError as error:<EOL><INDENT>_LOGGER.error(<EOL>"<STR_LIT>", host, error)<EOL><DEDENT><DEDENT>try:<EOL><INDENT>_socket.sendto('<STR_LIT>'.encode(),<EOL>(self.MULTICAST_ADDRESS, self.GATEWAY_DISCOVERY_PORT))<EOL>while True:<EOL><INDENT>data, (ip_add, _) = _socket.recvfrom(<NUM_LIT>)<EOL>if len(data) is None or ip_add in self.gateways:<EOL><INDENT>continue<EOL><DEDENT>if ip_add in self.gateways.keys() or ip_add in self.disabled_gateways:<EOL><INDENT>continue<EOL><DEDENT>resp = json.loads(data.decode())<EOL>if resp["<STR_LIT>"] != '<STR_LIT>':<EOL><INDENT>_LOGGER.error("<STR_LIT>")<EOL>continue<EOL><DEDENT>if resp["<STR_LIT>"] not in GATEWAY_MODELS:<EOL><INDENT>_LOGGER.error("<STR_LIT>")<EOL>continue<EOL><DEDENT>disabled = False<EOL>gateway_key = None<EOL>for gateway in self._gateways_config:<EOL><INDENT>sid = gateway.get('<STR_LIT>')<EOL>if sid is None or sid == resp["<STR_LIT>"]:<EOL><INDENT>gateway_key = gateway.get('<STR_LIT:key>')<EOL><DEDENT>if sid and sid == resp['<STR_LIT>'] and gateway.get('<STR_LIT>'):<EOL><INDENT>disabled = True<EOL><DEDENT><DEDENT>sid = resp["<STR_LIT>"]<EOL>if disabled:<EOL><INDENT>_LOGGER.info("<STR_LIT>",<EOL>sid)<EOL>self.disabled_gateways.append(ip_add)<EOL><DEDENT>else:<EOL><INDENT>_LOGGER.info('<STR_LIT>', sid, ip_add)<EOL>self.gateways[ip_add] = XiaomiGateway(<EOL>ip_add, resp["<STR_LIT:port>"], sid, gateway_key,<EOL>self._device_discovery_retries, self._interface,<EOL>resp["<STR_LIT>"] if "<STR_LIT>" in resp else None)<EOL><DEDENT><DEDENT><DEDENT>except socket.timeout:<EOL><INDENT>_LOGGER.info("<STR_LIT>")<EOL>_socket.close()<EOL><DEDENT>


_LOGGER.info('<STR_LIT>')<EOL>self._mcastsocket = self._create_mcast_socket()<EOL>self._listening = True<EOL>thread = Thread(target=self._listen_to_msg, args=())<EOL>self._threads.append(thread)<EOL>thread.daemon = True<EOL>thread.start()<EOL>


self._listening = False<EOL>if self._mcastsocket is not None:<EOL><INDENT>_LOGGER.info('<STR_LIT>')<EOL>self._mcastsocket.close()<EOL>self._mcastsocket = None<EOL><DEDENT>for thread in self._threads:<EOL><INDENT>thread.join()<EOL><DEDENT>


if self.key is None:<EOL><INDENT>_LOGGER.error('<STR_LIT>')<EOL>return False<EOL><DEDENT>data = {}<EOL>for key in kwargs:<EOL><INDENT>data[key] = kwargs[key]<EOL><DEDENT>if not self.token:<EOL><INDENT>_LOGGER.debug('<STR_LIT>')<EOL>return False<EOL><DEDENT>cmd = dict()<EOL>cmd['<STR_LIT>'] = '<STR_LIT>'<EOL>cmd['<STR_LIT>'] = sid<EOL>if int(self.proto[<NUM_LIT:0>:<NUM_LIT:1>]) == <NUM_LIT:1>:<EOL><INDENT>data['<STR_LIT:key>'] = self._get_key()<EOL>cmd['<STR_LIT:data>'] = data<EOL><DEDENT>else:<EOL><INDENT>cmd['<STR_LIT:key>'] = self._get_key()<EOL>cmd['<STR_LIT>'] = [data]<EOL><DEDENT>resp = self._send_cmd(json.dumps(cmd), "<STR_LIT>") if int(self.proto[<NUM_LIT:0>:<NUM_LIT:1>]) == <NUM_LIT:1>else self._send_cmd(json.dumps(cmd), "<STR_LIT>")<EOL>_LOGGER.debug("<STR_LIT>", resp)<EOL>if _validate_data(resp):<EOL><INDENT>return True<EOL><DEDENT>if not _validate_keyerror(resp):<EOL><INDENT>return False<EOL><DEDENT>resp = self._send_cmd('<STR_LIT>', "<STR_LIT>") if int(self.proto[<NUM_LIT:0>:<NUM_LIT:1>]) == <NUM_LIT:1>else self._send_cmd('<STR_LIT>', "<STR_LIT>")<EOL>_LOGGER.debug("<STR_LIT>", resp)<EOL>if resp is None or "<STR_LIT>" not in resp:<EOL><INDENT>_LOGGER.error('<STR_LIT>')<EOL>return False<EOL><DEDENT>self.token = resp['<STR_LIT>']<EOL>if int(self.proto[<NUM_LIT:0>:<NUM_LIT:1>]) == <NUM_LIT:1>:<EOL><INDENT>data['<STR_LIT:key>'] = self._get_key()<EOL>cmd['<STR_LIT:data>'] = data<EOL><DEDENT>else:<EOL><INDENT>cmd['<STR_LIT:key>'] = self._get_key()<EOL>cmd['<STR_LIT>'] = [data]<EOL><DEDENT>resp = self._send_cmd(json.dumps(cmd), "<STR_LIT>") if int(self.proto[<NUM_LIT:0>:<NUM_LIT:1>]) == <NUM_LIT:1>else self._send_cmd(json.dumps(cmd), "<STR_LIT>")<EOL>_LOGGER.debug("<STR_LIT>", resp)<EOL>return _validate_data(resp)<EOL>

Send data to gateway to turn on / off device


cmd = '<STR_LIT>' + sid + '<STR_LIT>'<EOL>resp = self._send_cmd(cmd, "<STR_LIT>") if int(self.proto[<NUM_LIT:0>:<NUM_LIT:1>]) == <NUM_LIT:1> else self._send_cmd(cmd, "<STR_LIT>")<EOL>_LOGGER.debug("<STR_LIT>", resp)<EOL>return self.push_data(resp)<EOL>


if not _validate_data(data):<EOL><INDENT>return False<EOL><DEDENT>jdata = json.loads(data['<STR_LIT:data>']) if int(self.proto[<NUM_LIT:0>:<NUM_LIT:1>]) == <NUM_LIT:1> else _list2map(data['<STR_LIT>'])<EOL>if jdata is None:<EOL><INDENT>return False<EOL><DEDENT>sid = data['<STR_LIT>']<EOL>for func in self.callbacks[sid]:<EOL><INDENT>func(jdata, data)<EOL><DEDENT>return True<EOL>

Push data broadcasted from gateway to device


init_vector = bytes(bytearray.fromhex('<STR_LIT>'))<EOL>encryptor = Cipher(algorithms.AES(self.key.encode()), modes.CBC(init_vector),<EOL>backend=default_backend()).encryptor()<EOL>ciphertext = encryptor.update(self.token.encode()) + encryptor.finalize()<EOL>if isinstance(ciphertext, str):  <EOL><INDENT>return '<STR_LIT>'.join('<STR_LIT>'.format(ord(x)) for x in ciphertext)<EOL><DEDENT>return '<STR_LIT>'.join('<STR_LIT>'.format(x) for x in ciphertext)<EOL>


def _make_repr(class_name, *args, **kwargs):

arguments = [repr(arg) for arg in args]<EOL>arguments.extend(<EOL>"<STR_LIT>".format(name, value)<EOL>for name, (value, default) in sorted(kwargs.items())<EOL>if value != default<EOL>)<EOL>return "<STR_LIT>".format(class_name, "<STR_LIT:U+002CU+0020>".join(arguments))<EOL>

Generate a repr string.

Positional arguments should be the positional arguments used to
construct the class. Keyword arguments should consist of tuples of
the attribute value and default. If the value is the default, then
it won't be rendered in the output.

Here's an example::

    def __repr__(self):
        return make_repr('MyClass', 'foo', name=(self.name, None))

The output of this would be something line ``MyClass('foo',
name='Will')``.


try:<EOL><INDENT>yield<EOL><DEDENT>except ClientError as error:<EOL><INDENT>_error = error.response.get("<STR_LIT>", {})<EOL>error_code = _error.get("<STR_LIT>", None)<EOL>response_meta = error.response.get("<STR_LIT>", {})<EOL>http_status = response_meta.get("<STR_LIT>", <NUM_LIT:200>)<EOL>error_msg = _error.get("<STR_LIT>", None)<EOL>if error_code == "<STR_LIT>":<EOL><INDENT>raise errors.ResourceError(path, exc=error, msg=error_msg)<EOL><DEDENT>if http_status == <NUM_LIT>:<EOL><INDENT>raise errors.ResourceNotFound(path)<EOL><DEDENT>elif http_status == <NUM_LIT>:<EOL><INDENT>raise errors.PermissionDenied(path=path, msg=error_msg)<EOL><DEDENT>else:<EOL><INDENT>raise errors.OperationFailed(path=path, exc=error)<EOL><DEDENT><DEDENT>except SSLError as error:<EOL><INDENT>raise errors.OperationFailed(path, exc=error)<EOL><DEDENT>except EndpointConnectionError as error:<EOL><INDENT>raise errors.RemoteConnectionError(path, exc=error, msg="<STR_LIT:{}>".format(error))<EOL><DEDENT>


@classmethod<EOL><INDENT>def factory(cls, filename, mode, on_close):<DEDENT>

_temp_file = tempfile.TemporaryFile()<EOL>proxy = cls(_temp_file, filename, mode, on_close=on_close)<EOL>return proxy<EOL>

Create a S3File backed with a temporary file.


_path = relpath(normpath(path))<EOL>_key = (<EOL>"<STR_LIT>".format(self._prefix, _path).lstrip("<STR_LIT:/>").replace("<STR_LIT:/>", self.delimiter)<EOL>)<EOL>return _key<EOL>


_path = relpath(normpath(path))<EOL>_key = (<EOL>forcedir("<STR_LIT>".format(self._prefix, _path))<EOL>.lstrip("<STR_LIT:/>")<EOL>.replace("<STR_LIT:/>", self.delimiter)<EOL>)<EOL>return _key<EOL>


def _info_from_object(self, obj, namespaces):

key = obj.key<EOL>path = self._key_to_path(key)<EOL>name = basename(path.rstrip("<STR_LIT:/>"))<EOL>is_dir = key.endswith(self.delimiter)<EOL>info = {"<STR_LIT>": {"<STR_LIT:name>": name, "<STR_LIT>": is_dir}}<EOL>if "<STR_LIT>" in namespaces:<EOL><INDENT>_type = int(ResourceType.directory if is_dir else ResourceType.file)<EOL>info["<STR_LIT>"] = {<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT>": datetime_to_epoch(obj.last_modified),<EOL>"<STR_LIT:size>": obj.content_length,<EOL>"<STR_LIT:type>": _type,<EOL>}<EOL><DEDENT>if "<STR_LIT>" in namespaces:<EOL><INDENT>s3info = info["<STR_LIT>"] = {}<EOL>for name in self._object_attributes:<EOL><INDENT>value = getattr(obj, name, None)<EOL>if isinstance(value, datetime):<EOL><INDENT>value = datetime_to_epoch(value)<EOL><DEDENT>s3info[name] = value<EOL><DEDENT><DEDENT>if "<STR_LIT>" in namespaces:<EOL><INDENT>url = self.client.generate_presigned_url(<EOL>ClientMethod="<STR_LIT>",<EOL>Params={"<STR_LIT>": self._bucket_name, "<STR_LIT>": key},<EOL>)<EOL>info["<STR_LIT>"] = {"<STR_LIT>": url}<EOL><DEDENT>return info<EOL>


def _getinfo(self, path, namespaces=None):

namespaces = namespaces or ()<EOL>_path = self.validatepath(path)<EOL>_key = self._path_to_key(_path)<EOL>if _path == "<STR_LIT:/>":<EOL><INDENT>return Info(<EOL>{<EOL>"<STR_LIT>": {"<STR_LIT:name>": "<STR_LIT>", "<STR_LIT>": True},<EOL>"<STR_LIT>": {"<STR_LIT:type>": int(ResourceType.directory)},<EOL>}<EOL>)<EOL><DEDENT>obj = self._get_object(path, _key)<EOL>info = self._info_from_object(obj, namespaces)<EOL>return Info(info)<EOL>

Gets info without checking for parent dir.


if ds.find_executable('<STR_LIT>') is None:<EOL><INDENT>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>sys.exit(-<NUM_LIT:1>)<EOL><DEDENT>print("<STR_LIT>")<EOL>cmake_args = arg<EOL>try:<EOL><INDENT>build_dir = op.join(op.split(__file__)[<NUM_LIT:0>], '<STR_LIT>')<EOL>dd.mkpath(build_dir)<EOL>os.chdir("<STR_LIT>")<EOL>ds.spawn(['<STR_LIT>', '<STR_LIT:..>'] + cmake_args.split())<EOL>ds.spawn(['<STR_LIT>', '<STR_LIT>'])<EOL>ds.spawn(['<STR_LIT>'])<EOL>os.chdir("<STR_LIT:..>")<EOL><DEDENT>except ds.DistutilsExecError:<EOL><INDENT>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>sys.exit(-<NUM_LIT:1>)<EOL><DEDENT>


def create_queue(self, name, strict=True, auto_delete=False, auto_delete_timeout=<NUM_LIT:0>):

content = {"<STR_LIT>": {"<STR_LIT>": self.object_name},<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": {"<STR_LIT:type>": "<STR_LIT>",<EOL>"<STR_LIT:name>": name,<EOL>"<STR_LIT:strict>": strict,<EOL>"<STR_LIT>": {"<STR_LIT>": auto_delete,<EOL>"<STR_LIT>": auto_delete_timeout}}}<EOL>logger.debug("<STR_LIT>".format(content))<EOL>return content, self.method_properties<EOL>

Create message content and properties to create queue with QMFv2

        :param name: Name of queue to create
        :type name: str
        :param strict: Whether command should fail when unrecognized properties are provided
            Not used by QMFv2
            Default: True
        :type strict: bool
        :param auto_delete: Whether queue should be auto deleted
            Default: False
        :type auto_delete: bool
        :param auto_delete_timeout: Timeout in seconds for auto deleting queue
            Default: 10
        :type auto_delete_timeout: int

        :returns: Tuple containing content and method properties


def create_exchange(self, name, type_="<STR_LIT>", strict=True, auto_delete=False, auto_delete_timeout=<NUM_LIT:10>):

content = {"<STR_LIT>": {"<STR_LIT>": self.object_name},<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": {"<STR_LIT:type>": "<STR_LIT>",<EOL>"<STR_LIT:name>": name,<EOL>"<STR_LIT:strict>": strict,<EOL>"<STR_LIT>": {"<STR_LIT>": auto_delete,<EOL>"<STR_LIT>": auto_delete_timeout,<EOL>"<STR_LIT>": type_}}}<EOL>logger.debug("<STR_LIT>".format(content))<EOL>return content, self.method_properties<EOL>

Create message content and properties to create exchange with QMFv2

        :param name: Name of exchange to create
        :type name: str
        :param type_: Type of exchange to create
            Possible values are: direct, fanout, topic?
        :type type_: str
        :param strict: Whether command should fail when unrecognized properties are provided
            Not used by QMFv2
            Default: True
        :type strict: bool
        :param auto_delete: Whether exchange should be auto deleted
            Default: False
        :type auto_delete: bool
        :param auto_delete_timeout: Timeout in seconds for auto deleting exchange
            Default: 10
        :type auto_delete_timeout: int

        :returns: Tuple containing content and method properties


def create_binding(self, name, strict=True, auto_delete=False, auto_delete_timeout=<NUM_LIT:10>):

Create message content and properties to create binding with QMFv2

        :param name: Name of binding to create in format "exchange/queue/key"
        :type name: str
        :param strict: Whether command should fail when unrecognized properties are provided
            Not used by QMFv2
            Default: True
        :type strict: bool
        :param auto_delete: Whether exchange should be auto deleted
            Default: False
        :type auto_delete: bool
        :param auto_delete_timeout: Timeout in seconds for auto deleting exchange
            Default: 10
        :type auto_delete_timeout: int

        :returns: Tuple containing content and method properties


content = {"<STR_LIT>": {"<STR_LIT>": self.object_name},<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": {"<STR_LIT:type>": "<STR_LIT>",<EOL>"<STR_LIT:name>": name,<EOL>"<STR_LIT>": dict()}}  <EOL>logger.debug("<STR_LIT>".format(content))<EOL>return content, self.method_properties<EOL>

Create message content and properties to delete queue with QMFv2

        :param name: Name of queue to delete
        :type name: str

        :returns: Tuple containing content and method properties


content = {"<STR_LIT>": {"<STR_LIT>": self.object_name},<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": {"<STR_LIT:type>": "<STR_LIT>", "<STR_LIT:name>": name,<EOL>"<STR_LIT>": dict()}}  <EOL>logger.debug("<STR_LIT>".format(content))<EOL>return content, self.method_properties<EOL>

Create message content and properties to delete exchange with QMFv2

        :param name: Name of exchange to delete
        :type name: str

        :returns: Tuple containing content and method properties


content = {"<STR_LIT>": {"<STR_LIT>": self.object_name},<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": {"<STR_LIT:type>": "<STR_LIT>", "<STR_LIT:name>": name, "<STR_LIT>": dict()}}<EOL>logger.debug("<STR_LIT>".format(content))<EOL>return content, self.method_properties<EOL>

Create message content and properties to delete exchange with QMFv2

        :param name: Name of exchange to delete in format "exchange/queue/key"
        :type name: str

        :returns: Tuple containing content and method properties


content = {"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": {"<STR_LIT>": "<STR_LIT>"}}<EOL>logger.debug("<STR_LIT>".format(content))<EOL>return content, self.query_properties<EOL>

Create message content and properties to list all queues with QMFv2

        :returns: Tuple containing content and query properties


Create message content and properties to list all exchanges with QMFv2

        :returns: Tuple containing content and query properties


content = {"<STR_LIT>": {"<STR_LIT>": "<STR_LIT>".format(name)},<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": {"<STR_LIT:type>": "<STR_LIT>",<EOL>"<STR_LIT:name>": name,<EOL>"<STR_LIT>": dict()}}<EOL>logger.debug("<STR_LIT>".format(content))<EOL>return content, self.method_properties<EOL>

Create message content and properties to purge queue with QMFv2

        :param name: Name of queue to purge
        :type name: str

        :returns: Tuple containing content and method properties


with contextlib.closing(socket.socket()) as sock:<EOL><INDENT>sock.bind(('<STR_LIT:127.0.0.1>', <NUM_LIT:0>))<EOL>return sock.getsockname()[<NUM_LIT:1>]<EOL><DEDENT>

Find an unused localhost TCP port from 1024-65535 and return it.


def send_action(self, action, as_list=None, **kwargs):

action.update(kwargs)<EOL>return self.protocol.send(action, as_list=as_list)<EOL>

Send an :class:`~panoramisk.actions.Action` to the server:

        :param action: an Action or dict with action name and parameters to
                       send
        :type action: Action or dict or Command
        :param as_list: If True, the action Future will retrieve all responses
        :type as_list: boolean
        :return: a Future that will receive the response
        :rtype: asyncio.Future

        :Example:

        To retrieve answer in a coroutine::

            manager = Manager()
            resp = yield from manager.send_action({'Action': 'Status'})

        With a callback::

            manager = Manager()
            future = manager.send_action({'Action': 'Status'})
            future.add_done_callback(handle_status_response)

        See https://wiki.asterisk.org/wiki/display/AST/AMI+Actions for
        more information on actions


def send_command(self, command, as_list=False):

action = actions.Action({'<STR_LIT>': command, '<STR_LIT>': '<STR_LIT>'},<EOL>as_list=as_list)<EOL>return self.send_action(action)<EOL>

Send a :class:`~panoramisk.actions.Command` to the server::

            manager = Manager()
            resp = manager.send_command('http show status')

        Return a response :class:`~panoramisk.message.Message`.
        See https://wiki.asterisk.org/wiki/display/AST/ManagerAction_Command