def update_item(TableName=None, Key=None, AttributeUpdates=None, Expected=
    None, ConditionalOperator=None, ReturnValues=None,
    ReturnConsumedCapacity=None, ReturnItemCollectionMetrics=None,
    UpdateExpression=None, ConditionExpression=None,
    ExpressionAttributeNames=None, ExpressionAttributeValues=None):
    """
    Edits an existing item's attributes, or adds a new item to the table if it does not already exist. You can put, delete, or add attribute values. You can also perform a conditional update on an existing item (insert a new attribute name-value pair if it doesn't exist, or replace an existing name-value pair if it has certain expected attribute values).
    You can also return the item's attribute values in the same UpdateItem operation using the ReturnValues parameter.
    See also: AWS API Documentation

    Examples
    This example updates an item in the Music table. It adds a new attribute (Year) and modifies the AlbumTitle attribute.  All of the attributes in the item, as they appear after the update, are returned in the response.
    Expected Output:

    :example: response = client.update_item(
        TableName='string',
        Key={
            'string': {
                'S': 'string',
                'N': 'string',
                'B': b'bytes',
                'SS': [
                    'string',
                ],
                'NS': [
                    'string',
                ],
                'BS': [
                    b'bytes',
                ],
                'M': {
                    'string': {'... recursive ...'}
                },
                'L': [
                    {'... recursive ...'},
                ],
                'NULL': True|False,
                'BOOL': True|False
            }
        },
        AttributeUpdates={
            'string': {
                'Value': {
                    'S': 'string',
                    'N': 'string',
                    'B': b'bytes',
                    'SS': [
                        'string',
                    ],
                    'NS': [
                        'string',
                    ],
                    'BS': [
                        b'bytes',
                    ],
                    'M': {
                        'string': {'... recursive ...'}
                    },
                    'L': [
                        {'... recursive ...'},
                    ],
                    'NULL': True|False,
                    'BOOL': True|False
                },
                'Action': 'ADD'|'PUT'|'DELETE'
            }
        },
        Expected={
            'string': {
                'Value': {
                    'S': 'string',
                    'N': 'string',
                    'B': b'bytes',
                    'SS': [
                        'string',
                    ],
                    'NS': [
                        'string',
                    ],
                    'BS': [
                        b'bytes',
                    ],
                    'M': {
                        'string': {'... recursive ...'}
                    },
                    'L': [
                        {'... recursive ...'},
                    ],
                    'NULL': True|False,
                    'BOOL': True|False
                },
                'Exists': True|False,
                'ComparisonOperator': 'EQ'|'NE'|'IN'|'LE'|'LT'|'GE'|'GT'|'BETWEEN'|'NOT_NULL'|'NULL'|'CONTAINS'|'NOT_CONTAINS'|'BEGINS_WITH',
                'AttributeValueList': [
                    {
                        'S': 'string',
                        'N': 'string',
                        'B': b'bytes',
                        'SS': [
                            'string',
                        ],
                        'NS': [
                            'string',
                        ],
                        'BS': [
                            b'bytes',
                        ],
                        'M': {
                            'string': {'... recursive ...'}
                        },
                        'L': [
                            {'... recursive ...'},
                        ],
                        'NULL': True|False,
                        'BOOL': True|False
                    },
                ]
            }
        },
        ConditionalOperator='AND'|'OR',
        ReturnValues='NONE'|'ALL_OLD'|'UPDATED_OLD'|'ALL_NEW'|'UPDATED_NEW',
        ReturnConsumedCapacity='INDEXES'|'TOTAL'|'NONE',
        ReturnItemCollectionMetrics='SIZE'|'NONE',
        UpdateExpression='string',
        ConditionExpression='string',
        ExpressionAttributeNames={
            'string': 'string'
        },
        ExpressionAttributeValues={
            'string': {
                'S': 'string',
                'N': 'string',
                'B': b'bytes',
                'SS': [
                    'string',
                ],
                'NS': [
                    'string',
                ],
                'BS': [
                    b'bytes',
                ],
                'M': {
                    'string': {'... recursive ...'}
                },
                'L': [
                    {'... recursive ...'},
                ],
                'NULL': True|False,
                'BOOL': True|False
            }
        }
    )

    :type TableName: string
    :param TableName: [REQUIRED]
            The name of the table containing the item to update.

    :type Key: dict
    :param Key: [REQUIRED]
            The primary key of the item to be updated. Each element consists of an attribute name and a value for that attribute.
            For the primary key, you must provide all of the attributes. For example, with a simple primary key, you only need to provide a value for the partition key. For a composite primary key, you must provide values for both the partition key and the sort key.
            (string) --
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .
            S (string) --An attribute of type String. For example:
            'S': 'Hello'
            N (string) --An attribute of type Number. For example:
            'N': '123.45'
            Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
            B (bytes) --An attribute of type Binary. For example:
            'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk'
            SS (list) --An attribute of type String Set. For example:
            'SS': ['Giraffe', 'Hippo' ,'Zebra']
            (string) --
            NS (list) --An attribute of type Number Set. For example:
            'NS': ['42.2', '-19', '7.5', '3.14']
            Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
            (string) --
            BS (list) --An attribute of type Binary Set. For example:
            'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k=']
            (bytes) --
            M (dict) --An attribute of type Map. For example:
            'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}}
            (string) --
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .

            L (list) --An attribute of type List. For example:
            'L': ['Cookies', 'Coffee', 3.14159]
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .
            NULL (boolean) --An attribute of type Null. For example:
            'NULL': true
            BOOL (boolean) --An attribute of type Boolean. For example:
            'BOOL': true

    :type AttributeUpdates: dict
    :param AttributeUpdates: This is a legacy parameter. Use UpdateExpression instead. For more information, see AttributeUpdates in the Amazon DynamoDB Developer Guide .
            (string) --
            (dict) --For the UpdateItem operation, represents the attributes to be modified, the action to perform on each, and the new value for each.
            Note
            You cannot use UpdateItem to update any primary key attributes. Instead, you will need to delete the item, and then use PutItem to create a new item with new attributes.
            Attribute values cannot be null; string and binary type attributes must have lengths greater than zero; and set type attributes must not be empty. Requests with empty values will be rejected with a ValidationException exception.
            Value (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data TYpes in the Amazon DynamoDB Developer Guide .
            S (string) --An attribute of type String. For example:
            'S': 'Hello'
            N (string) --An attribute of type Number. For example:
            'N': '123.45'
            Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
            B (bytes) --An attribute of type Binary. For example:
            'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk'
            SS (list) --An attribute of type String Set. For example:
            'SS': ['Giraffe', 'Hippo' ,'Zebra']
            (string) --
            NS (list) --An attribute of type Number Set. For example:
            'NS': ['42.2', '-19', '7.5', '3.14']
            Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
            (string) --
            BS (list) --An attribute of type Binary Set. For example:
            'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k=']
            (bytes) --
            M (dict) --An attribute of type Map. For example:
            'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}}
            (string) --
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .

            L (list) --An attribute of type List. For example:
            'L': ['Cookies', 'Coffee', 3.14159]
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .
            NULL (boolean) --An attribute of type Null. For example:
            'NULL': true
            BOOL (boolean) --An attribute of type Boolean. For example:
            'BOOL': true
            Action (string) --Specifies how to perform the update. Valid values are PUT (default), DELETE , and ADD . The behavior depends on whether the specified primary key already exists in the table.
            If an item with the specified *Key* is found in the table:
            PUT - Adds the specified attribute to the item. If the attribute already exists, it is replaced by the new value.
            DELETE - If no value is specified, the attribute and its value are removed from the item. The data type of the specified value must match the existing value's data type. If a set of values is specified, then those values are subtracted from the old set. For example, if the attribute value was the set [a,b,c] and the DELETE action specified [a,c] , then the final attribute value would be [b] . Specifying an empty set is an error.
            ADD - If the attribute does not already exist, then the attribute and its values are added to the item. If the attribute does exist, then the behavior of ADD depends on the data type of the attribute:
            If the existing attribute is a number, and if Value is also a number, then the Value is mathematically added to the existing attribute. If Value is a negative number, then it is subtracted from the existing attribute.
            Note
            If you use ADD to increment or decrement a number value for an item that doesn't exist before the update, DynamoDB uses 0 as the initial value. In addition, if you use ADD to update an existing item, and intend to increment or decrement an attribute value which does not yet exist, DynamoDB uses 0 as the initial value. For example, suppose that the item you want to update does not yet have an attribute named itemcount , but you decide to ADD the number 3 to this attribute anyway, even though it currently does not exist. DynamoDB will create the itemcount attribute, set its initial value to 0 , and finally add 3 to it. The result will be a new itemcount attribute in the item, with a value of 3 .
            If the existing data type is a set, and if the Value is also a set, then the Value is added to the existing set. (This is a set operation, not mathematical addition.) For example, if the attribute value was the set [1,2] , and the ADD action specified [3] , then the final attribute value would be [1,2,3] . An error occurs if an Add action is specified for a set attribute and the attribute type specified does not match the existing set type. Both sets must have the same primitive data type. For example, if the existing data type is a set of strings, the Value must also be a set of strings. The same holds true for number sets and binary sets.
            This action is only valid for an existing attribute whose data type is number or is a set. Do not use ADD for any other data types.
            If no item with the specified *Key* is found:
            PUT - DynamoDB creates a new item with the specified primary key, and then adds the attribute.
            DELETE - Nothing happens; there is no attribute to delete.
            ADD - DynamoDB creates an item with the supplied primary key and number (or set of numbers) for the attribute value. The only data types allowed are number and number set; no other data types can be specified.

    :type Expected: dict
    :param Expected: This is a legacy parameter. Use ConditionExpresssion instead. For more information, see Expected in the Amazon DynamoDB Developer Guide .
            (string) --
            (dict) --Represents a condition to be compared with an attribute value. This condition can be used with DeleteItem , PutItem or UpdateItem operations; if the comparison evaluates to true, the operation succeeds; if not, the operation fails. You can use ExpectedAttributeValue in one of two different ways:
            Use AttributeValueList to specify one or more values to compare against an attribute. Use ComparisonOperator to specify how you want to perform the comparison. If the comparison evaluates to true, then the conditional operation succeeds.
            Use Value to specify a value that DynamoDB will compare against an attribute. If the values match, then ExpectedAttributeValue evaluates to true and the conditional operation succeeds. Optionally, you can also set Exists to false, indicating that you do not expect to find the attribute value in the table. In this case, the conditional operation succeeds only if the comparison evaluates to false.
            Value and Exists are incompatible with AttributeValueList and ComparisonOperator . Note that if you use both sets of parameters at once, DynamoDB will return a ValidationException exception.
            Value (dict) --Represents the data for the expected attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .
            S (string) --An attribute of type String. For example:
            'S': 'Hello'
            N (string) --An attribute of type Number. For example:
            'N': '123.45'
            Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
            B (bytes) --An attribute of type Binary. For example:
            'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk'
            SS (list) --An attribute of type String Set. For example:
            'SS': ['Giraffe', 'Hippo' ,'Zebra']
            (string) --
            NS (list) --An attribute of type Number Set. For example:
            'NS': ['42.2', '-19', '7.5', '3.14']
            Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
            (string) --
            BS (list) --An attribute of type Binary Set. For example:
            'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k=']
            (bytes) --
            M (dict) --An attribute of type Map. For example:
            'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}}
            (string) --
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .

            L (list) --An attribute of type List. For example:
            'L': ['Cookies', 'Coffee', 3.14159]
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .
            NULL (boolean) --An attribute of type Null. For example:
            'NULL': true
            BOOL (boolean) --An attribute of type Boolean. For example:
            'BOOL': true
            Exists (boolean) --Causes DynamoDB to evaluate the value before attempting a conditional operation:
            If Exists is true , DynamoDB will check to see if that attribute value already exists in the table. If it is found, then the operation succeeds. If it is not found, the operation fails with a ConditionalCheckFailedException .
            If Exists is false , DynamoDB assumes that the attribute value does not exist in the table. If in fact the value does not exist, then the assumption is valid and the operation succeeds. If the value is found, despite the assumption that it does not exist, the operation fails with a ConditionalCheckFailedException .
            The default setting for Exists is true . If you supply a Value all by itself, DynamoDB assumes the attribute exists: You don't have to set Exists to true , because it is implied.
            DynamoDB returns a ValidationException if:
            Exists is true but there is no Value to check. (You expect a value to exist, but don't specify what that value is.)
            Exists is false but you also provide a Value . (You cannot expect an attribute to have a value, while also expecting it not to exist.)
            ComparisonOperator (string) --A comparator for evaluating attributes in the AttributeValueList . For example, equals, greater than, less than, etc.
            The following comparison operators are available:
            EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH | IN | BETWEEN
            The following are descriptions of each comparison operator.
            EQ : Equal. EQ is supported for all data types, including lists and maps. AttributeValueList can contain only one AttributeValue element of type String, Number, Binary, String Set, Number Set, or Binary Set. If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not equal {'NS':['6', '2', '1']} .
            NE : Not equal. NE is supported for all data types, including lists and maps. AttributeValueList can contain only one AttributeValue of type String, Number, Binary, String Set, Number Set, or Binary Set. If an item contains an AttributeValue of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not equal {'NS':['6', '2', '1']} .
            LE : Less than or equal.  AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} .
            LT : Less than.  AttributeValueList can contain only one AttributeValue of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} .
            GE : Greater than or equal.  AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} .
            GT : Greater than.  AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} .
            NOT_NULL : The attribute exists. NOT_NULL is supported for all data types, including lists and maps.
            Note
            This operator tests for the existence of an attribute, not its data type. If the data type of attribute 'a ' is null, and you evaluate it using NOT_NULL , the result is a Boolean true . This result is because the attribute 'a ' exists; its data type is not relevant to the NOT_NULL comparison operator.
            NULL : The attribute does not exist. NULL is supported for all data types, including lists and maps.
            Note
            This operator tests for the nonexistence of an attribute, not its data type. If the data type of attribute 'a ' is null, and you evaluate it using NULL , the result is a Boolean false . This is because the attribute 'a ' exists; its data type is not relevant to the NULL comparison operator.
            CONTAINS : Checks for a subsequence, or value in a set. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If the target attribute of the comparison is of type String, then the operator checks for a substring match. If the target attribute of the comparison is of type Binary, then the operator looks for a subsequence of the target that matches the input. If the target attribute of the comparison is a set ('SS ', 'NS ', or 'BS '), then the operator evaluates to true if it finds an exact match with any member of the set. CONTAINS is supported for lists: When evaluating 'a CONTAINS b ', 'a ' can be a list; however, 'b ' cannot be a set, a map, or a list.
            NOT_CONTAINS : Checks for absence of a subsequence, or absence of a value in a set. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If the target attribute of the comparison is a String, then the operator checks for the absence of a substring match. If the target attribute of the comparison is Binary, then the operator checks for the absence of a subsequence of the target that matches the input. If the target attribute of the comparison is a set ('SS ', 'NS ', or 'BS '), then the operator evaluates to true if it does not find an exact match with any member of the set. NOT_CONTAINS is supported for lists: When evaluating 'a NOT CONTAINS b ', 'a ' can be a list; however, 'b ' cannot be a set, a map, or a list.
            BEGINS_WITH : Checks for a prefix.  AttributeValueList can contain only one AttributeValue of type String or Binary (not a Number or a set type). The target attribute of the comparison must be of type String or Binary (not a Number or a set type).
            IN : Checks for matching elements in a list. AttributeValueList can contain one or more AttributeValue elements of type String, Number, or Binary. These attributes are compared against an existing attribute of an item. If any elements of the input are equal to the item attribute, the expression evaluates to true.
            BETWEEN : Greater than or equal to the first value, and less than or equal to the second value.  AttributeValueList must contain two AttributeValue elements of the same type, either String, Number, or Binary (not a set type). A target attribute matches if the target value is greater than, or equal to, the first element and less than, or equal to, the second element. If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not compare to {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']}
            AttributeValueList (list) --One or more values to evaluate against the supplied attribute. The number of values in the list depends on the ComparisonOperator being used.
            For type Number, value comparisons are numeric.
            String value comparisons for greater than, equals, or less than are based on ASCII character code values. For example, a is greater than A , and a is greater than B . For a list of code values, see http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters .
            For Binary, DynamoDB treats each byte of the binary data as unsigned when it compares binary values.
            For information on specifying data types in JSON, see JSON Data Format in the Amazon DynamoDB Developer Guide .
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .
            S (string) --An attribute of type String. For example:
            'S': 'Hello'
            N (string) --An attribute of type Number. For example:
            'N': '123.45'
            Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
            B (bytes) --An attribute of type Binary. For example:
            'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk'
            SS (list) --An attribute of type String Set. For example:
            'SS': ['Giraffe', 'Hippo' ,'Zebra']
            (string) --
            NS (list) --An attribute of type Number Set. For example:
            'NS': ['42.2', '-19', '7.5', '3.14']
            Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
            (string) --
            BS (list) --An attribute of type Binary Set. For example:
            'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k=']
            (bytes) --
            M (dict) --An attribute of type Map. For example:
            'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}}
            (string) --
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .

            L (list) --An attribute of type List. For example:
            'L': ['Cookies', 'Coffee', 3.14159]
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .
            NULL (boolean) --An attribute of type Null. For example:
            'NULL': true
            BOOL (boolean) --An attribute of type Boolean. For example:
            'BOOL': true

    :type ConditionalOperator: string
    :param ConditionalOperator: This is a legacy parameter. Use ConditionExpression instead. For more information, see ConditionalOperator in the Amazon DynamoDB Developer Guide .

    :type ReturnValues: string
    :param ReturnValues: Use ReturnValues if you want to get the item attributes as they appeared either before or after they were updated. For UpdateItem , the valid values are:
            NONE - If ReturnValues is not specified, or if its value is NONE , then nothing is returned. (This setting is the default for ReturnValues .)
            ALL_OLD - Returns all of the attributes of the item, as they appeared before the UpdateItem operation.
            UPDATED_OLD - Returns only the updated attributes, as they appeared before the UpdateItem operation.
            ALL_NEW - Returns all of the attributes of the item, as they appear after the UpdateItem operation.
            UPDATED_NEW - Returns only the updated attributes, as they appear after the UpdateItem operation.
            There is no additional cost associated with requesting a return value aside from the small network and processing overhead of receiving a larger response. No Read Capacity Units are consumed.
            Values returned are strongly consistent

    :type ReturnConsumedCapacity: string
    :param ReturnConsumedCapacity: Determines the level of detail about provisioned throughput consumption that is returned in the response:
            INDEXES - The response includes the aggregate ConsumedCapacity for the operation, together with ConsumedCapacity for each table and secondary index that was accessed. Note that some operations, such as GetItem and BatchGetItem , do not access any indexes at all. In these cases, specifying INDEXES will only return ConsumedCapacity information for table(s).
            TOTAL - The response includes only the aggregate ConsumedCapacity for the operation.
            NONE - No ConsumedCapacity details are included in the response.

    :type ReturnItemCollectionMetrics: string
    :param ReturnItemCollectionMetrics: Determines whether item collection metrics are returned. If set to SIZE , the response includes statistics about item collections, if any, that were modified during the operation are returned in the response. If set to NONE (the default), no statistics are returned.

    :type UpdateExpression: string
    :param UpdateExpression: An expression that defines one or more attributes to be updated, the action to be performed on them, and new value(s) for them.
            The following action values are available for UpdateExpression .
            SET - Adds one or more attributes and values to an item. If any of these attribute already exist, they are replaced by the new values. You can also use SET to add or subtract from an attribute that is of type Number. For example: SET myNum = myNum + :val SET supports the following functions:
            if_not_exists (path, operand) - if the item does not contain an attribute at the specified path, then if_not_exists evaluates to operand; otherwise, it evaluates to path. You can use this function to avoid overwriting an attribute that may already be present in the item.
            list_append (operand, operand) - evaluates to a list with a new element added to it. You can append the new element to the start or the end of the list by reversing the order of the operands.
            These function names are case-sensitive.
            REMOVE - Removes one or more attributes from an item.
            ADD - Adds the specified value to the item, if the attribute does not already exist. If the attribute does exist, then the behavior of ADD depends on the data type of the attribute:
            If the existing attribute is a number, and if Value is also a number, then Value is mathematically added to the existing attribute. If Value is a negative number, then it is subtracted from the existing attribute.
            Note
            If you use ADD to increment or decrement a number value for an item that doesn't exist before the update, DynamoDB uses 0 as the initial value. Similarly, if you use ADD for an existing item to increment or decrement an attribute value that doesn't exist before the update, DynamoDB uses 0 as the initial value. For example, suppose that the item you want to update doesn't have an attribute named itemcount , but you decide to ADD the number 3 to this attribute anyway. DynamoDB will create the itemcount attribute, set its initial value to 0 , and finally add 3 to it. The result will be a new itemcount attribute in the item, with a value of 3 .
            If the existing data type is a set and if Value is also a set, then Value is added to the existing set. For example, if the attribute value is the set [1,2] , and the ADD action specified [3] , then the final attribute value is [1,2,3] . An error occurs if an ADD action is specified for a set attribute and the attribute type specified does not match the existing set type. Both sets must have the same primitive data type. For example, if the existing data type is a set of strings, the Value must also be a set of strings.

            Warning
            The ADD action only supports Number and set data types. In addition, ADD can only be used on top-level attributes, not nested attributes.
            DELETE - Deletes an element from a set. If a set of values is specified, then those values are subtracted from the old set. For example, if the attribute value was the set [a,b,c] and the DELETE action specifies [a,c] , then the final attribute value is [b] . Specifying an empty set is an error.
            Warning
            The DELETE action only supports set data types. In addition, DELETE can only be used on top-level attributes, not nested attributes.
            You can have many actions in a single expression, such as the following: SET a=:value1, b=:value2 DELETE :value3, :value4, :value5
            For more information on update expressions, see Modifying Items and Attributes in the Amazon DynamoDB Developer Guide .

    :type ConditionExpression: string
    :param ConditionExpression: A condition that must be satisfied in order for a conditional update to succeed.
            An expression can contain any of the following:
            Functions: attribute_exists | attribute_not_exists | attribute_type | contains | begins_with | size  These function names are case-sensitive.
            Comparison operators: = | | | | = | = | BETWEEN | IN
            Logical operators: AND | OR | NOT
            For more information on condition expressions, see Specifying Conditions in the Amazon DynamoDB Developer Guide .

    :type ExpressionAttributeNames: dict
    :param ExpressionAttributeNames: One or more substitution tokens for attribute names in an expression. The following are some use cases for using ExpressionAttributeNames :
            To access an attribute whose name conflicts with a DynamoDB reserved word.
            To create a placeholder for repeating occurrences of an attribute name in an expression.
            To prevent special characters in an attribute name from being misinterpreted in an expression.
            Use the # character in an expression to dereference an attribute name. For example, consider the following attribute name:
            Percentile
            The name of this attribute conflicts with a reserved word, so it cannot be used directly in an expression. (For the complete list of reserved words, see Reserved Words in the Amazon DynamoDB Developer Guide ). To work around this, you could specify the following for ExpressionAttributeNames :
            {'#P':'Percentile'}
            You could then use this substitution in an expression, as in this example:
            #P = :val
            Note
            Tokens that begin with the : character are expression attribute values , which are placeholders for the actual value at runtime.
            For more information on expression attribute names, see Accessing Item Attributes in the Amazon DynamoDB Developer Guide .
            (string) --
            (string) --

    :type ExpressionAttributeValues: dict
    :param ExpressionAttributeValues: One or more values that can be substituted in an expression.
            Use the : (colon) character in an expression to dereference an attribute value. For example, suppose that you wanted to check whether the value of the ProductStatus attribute was one of the following:
            Available | Backordered | Discontinued
            You would first need to specify ExpressionAttributeValues as follows:
            { ':avail':{'S':'Available'}, ':back':{'S':'Backordered'}, ':disc':{'S':'Discontinued'} }
            You could then use these values in an expression, such as this:
            ProductStatus IN (:avail, :back, :disc)
            For more information on expression attribute values, see Specifying Conditions in the Amazon DynamoDB Developer Guide .
            (string) --
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .
            S (string) --An attribute of type String. For example:
            'S': 'Hello'
            N (string) --An attribute of type Number. For example:
            'N': '123.45'
            Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
            B (bytes) --An attribute of type Binary. For example:
            'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk'
            SS (list) --An attribute of type String Set. For example:
            'SS': ['Giraffe', 'Hippo' ,'Zebra']
            (string) --
            NS (list) --An attribute of type Number Set. For example:
            'NS': ['42.2', '-19', '7.5', '3.14']
            Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
            (string) --
            BS (list) --An attribute of type Binary Set. For example:
            'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k=']
            (bytes) --
            M (dict) --An attribute of type Map. For example:
            'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}}
            (string) --
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .

            L (list) --An attribute of type List. For example:
            'L': ['Cookies', 'Coffee', 3.14159]
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .
            NULL (boolean) --An attribute of type Null. For example:
            'NULL': true
            BOOL (boolean) --An attribute of type Boolean. For example:
            'BOOL': true

    :rtype: dict
    :return: {
        'Attributes': {
            'string': {
                'S': 'string',
                'N': 'string',
                'B': b'bytes',
                'SS': [
                    'string',
                ],
                'NS': [
                    'string',
                ],
                'BS': [
                    b'bytes',
                ],
                'M': {
                    'string': {'... recursive ...'}
                },
                'L': [
                    {'... recursive ...'},
                ],
                'NULL': True|False,
                'BOOL': True|False
            }
        },
        'ConsumedCapacity': {
            'TableName': 'string',
            'CapacityUnits': 123.0,
            'Table': {
                'CapacityUnits': 123.0
            },
            'LocalSecondaryIndexes': {
                'string': {
                    'CapacityUnits': 123.0
                }
            },
            'GlobalSecondaryIndexes': {
                'string': {
                    'CapacityUnits': 123.0
                }
            }
        },
        'ItemCollectionMetrics': {
            'ItemCollectionKey': {
                'string': {
                    'S': 'string',
                    'N': 'string',
                    'B': b'bytes',
                    'SS': [
                        'string',
                    ],
                    'NS': [
                        'string',
                    ],
                    'BS': [
                        b'bytes',
                    ],
                    'M': {
                        'string': {'... recursive ...'}
                    },
                    'L': [
                        {'... recursive ...'},
                    ],
                    'NULL': True|False,
                    'BOOL': True|False
                }
            },
            'SizeEstimateRangeGB': [
                123.0,
            ]
        }
    }

    :returns:
    (string) --

    """
    pass


@classmethod
def enterprise_console(cls, val):
    """
        Create an instance of this class set to the ``enterprise_console`` tag
        with value ``val``.

        :param WebSessionLogInfo val:
        :rtype: AccessMethodLogInfo
        """
    return cls('enterprise_console', val)


@classmethod
def addValidator(klass, func):
    """
        Add a function to the given classes validation list.

        @param klass: The Class to add the validator to.
        @param func: A function that accepts a single parameter that is the object
        to test for validity.  If the object is invalid, then this function should
        add errors to it's C{errors} property.

        @see: L{Errors}
        """
    klass.VALIDATIONS = klass.VALIDATIONS + [func]


def free_bake_all():
    """Delete all baked caches of all objects in the current scene

    """
    pass


def chain(*args):
    """TODO: chain docstring.

  :param *args: TODO

  """
    pass


def DaCeSyntaxError(visitor, node, err):
    """ Reports errors with their corresponding file/line information. """
    try:
        line = node.lineno
        col = node.col_offset
    except AttributeError:
        line = 0
        col = 0
    return SyntaxError(err + '\n  in File ' + str(visitor.filename) +
        ', line ' + str(line) + ':' + str(col) + ', in function ' + str(
        visitor.curnode.name if visitor.curnode is not None else visitor.
        program_name))


def _find_alias_and_replace(some_string):
    """ Find placeholder for alias in string. If found - replace with alias
    value.

    :type some_string: str
    """
    from syndicate.core import CONFIG
    first_index = some_string.index('${')
    second_index = some_string.index('}')
    alias_name = some_string[first_index + 2:second_index]
    res_alias = CONFIG.resolve_alias(alias_name)
    if not res_alias:
        raise AssertionError('Can not found alias for {0}'.format(alias_name))
    result = some_string[:first_index] + res_alias + some_string[
        second_index + 1:]
    return result


def cma_on_space(function_space, arguments):
    """ Returns the corresponding argument if the supplied list of arguments
    contains a cma operator that maps to/from the specified space. Otherwise
    returns None."""
    if function_space.mangled_name in arguments.unique_fs_names:
        for arg in arguments.args:
            if (arg.type == 'gh_columnwise_operator' and function_space.
                orig_name in [arg.function_space_to.orig_name, arg.
                function_space_from.orig_name]):
                return arg
    return None


def get_window_tuple(tpl, window_size):
    """Given a tuple (window_name, window_size) parse start and end to that window sequence."""
    aln, distance = tpl
    aln_start = aln
    aln_end = aln_start + window_size
    aln_tpl = aln_start, aln_end
    return aln_tpl


def uniquify(resource_ids):
    """Ensure the list of objects has unique resource ids maintaining the
       priority order found by reify

    """
    unique_objects = []
    for resource_id in reversed(resource_ids):
        if not resource_id in unique_objects:
            unique_objects.append(resource_id)
    return unique_objects


@classmethod
def can_exist_under(cls, parent):
    """
        Checks if this page type can exist as a subpage under a parent page
        instance.

        See also: :func:`Page.can_create_at` and :func:`Page.can_move_to`
        """
    return cls in parent.specific_class.allowed_subpage_models()


@classmethod
def _read(cls, path):
    """Read contents of a file, strip whitespace."""
    with open(path, 'rt') as fh:
        data = fh.read().strip()
    return data


def padded_insert(items, index, value, null_val=None):
    """
  insert value into the items list at given index
  if index is larger than length of list then
  extend it up to index and pad the extra space with null_val
  """
    if len(items) == index:
        items.append(value)
    elif len(items) > index:
        items[index] = value
    else:
        items.extend([null_val] * (index - len(items)))
        items.append(value)
    return items


def image_clone(image, pixeltype=None):
    """
    Clone an ANTsImage

    ANTsR function: `antsImageClone`

    Arguments
    ---------
    image : ANTsImage
        image to clone

    dtype : string (optional)
        new datatype for image

    Returns
    -------
    ANTsImage
    """
    return image.clone(pixeltype)


def subset_data_stack_variables(data, varset, seatype='total', mode='subset'):
    """
        Subset variables of a dataset stack. This function is just a shorthand to not have to specify all vaiables when subsetting dataframes. Not the most clever way to deal with this honestly.

        :param data: dataframe of data to subset
        :param varset: keyword specifiying the subset to get
        :param seatype: defaults to total. When "wave" parameters are to be retrieved, specify which kind of sea parameters to have
        :param mode: subset : return actual dataframe or returnnames: return only column names per subset
        :returns: either dataframe of data, or list of columns names.
    """
    if (varset.lower() == 'wave') | (varset.lower() == 'waves'):
        cols_total = ['hs', 'tp', 'steep', 'phase_vel', 'age', 'wind']
        cols_wind = ['hs_w', 'tp_w', 'steep_w', 'phase_vel_w', 'age_w', 'wind']
    elif varset.lower() == 'wave_nowind':
        cols_total = ['hs', 'tp', 'steep', 'phase_vel']
        cols_wind = ['hs_w', 'tp_w', 'steep_w', 'phase_vel_w']
    elif varset.lower() == 'wave_reduced':
        cols_total = ['hs', 'tp', 'wind']
        cols_wind = ['hs_w', 'tp_w', 'wind']
    elif varset.lower() == 'wave_ecmwf':
        cols_total = ['hs', 'tp', 'steep', 'phase_vel', 'age', 'wind', 't',
            'slp', 'q', 'v', 'u', 'iwc', 'ps', 'rh', 'th', 'lsp', 'cp',
            'rtot', 'blh', 'blhp', 'td2m', 't2m', 'skt', 'sif', 'the', 'lsm']
        cols_wind = ['hs_w', 'tp_w', 'steep_w', 'phase_vel_w', 'age_w',
            'wind', 't', 'slp', 'q', 'v', 'u', 'iwc', 'ps', 'rh', 'th',
            'lsp', 'cp', 'rtot', 'blh', 'blhp', 'td2m', 't2m', 'skt', 'sif',
            'the', 'lsm']
    elif varset.lower() == 'ecmwf':
        cols_total = ['t', 'slp', 'q', 'v', 'u', 'iwc', 'ps', 'rh', 'th',
            'lsp', 'cp', 'rtot', 'blh', 'blhp', 'td2m', 't2m', 'skt', 'sif',
            'the', 'lsm']
    elif varset.lower() == 'wholeset':
        cols_total = data.columns.tolist()[:-1]
    else:
        print('variables not specified')
        return
    if seatype == 'total':
        cols = cols_total
    elif seatype == 'wind':
        cols = cols_wind
    else:
        print('seatype not correct')
        return
    if mode == 'subset':
        if 'parbin' in data.columns:
            cols.append('parbin')
        return data[cols]
    elif mode == 'returnnames':
        print(cols)
        return cols


def convertSkewToHz(skew, referenceFrequencyHz):
    """
    Convert Fractional Frequency Offset (FFO) in ppb to absolute frequency in Hz.

    The reference frequency in Hz also needs to be specified.
    """
    return skew * referenceFrequencyHz


@property
def __members__(cls):
    """Returns a mapping of member name->value.

        This mapping lists all enum members, including aliases. Note that this
        is a copy of the internal mapping.

        """
    return cls._member_map_.copy()


def _combined_grouping_values(grouping_name, collection_a, collection_b):
    """
    returns a dict with values from both collections for a given grouping name

    Warning: collection2 overrides collection1 if there is a group_key conflict
    """
    new_grouping = collection_a.groupings.get(grouping_name, {}).copy()
    new_grouping.update(collection_b.groupings.get(grouping_name, {}))
    return new_grouping


@staticmethod
def parse_uri(uri):
    """Return the real URI with any protocol prefix stripped."""
    return uri


def calculate_chunks_count(data_size: int, chunk_size: int) ->int:
    """Returns number of chunks needed to transfer the data_size split to maximum of chunk_size blocks.

	:param data_size: total data size
	:param chunk_size: maximum size of one block"""
    return data_size // chunk_size + (1 if data_size % chunk_size > 0 else 0)


def compute_sizes(sizes, size_fn, scaling_factor, scaling_method, base_size):
    """
    Scales point sizes according to a scaling factor,
    base size and size_fn, which will be applied before
    scaling.
    """
    if sizes.dtype.kind not in ('i', 'f'):
        return None
    if scaling_method == 'area':
        pass
    elif scaling_method == 'width':
        scaling_factor = scaling_factor ** 2
    else:
        raise ValueError(
            'Invalid value for argument "scaling_method": "{}". Valid values are: "width", "area".'
            .format(scaling_method))
    sizes = size_fn(sizes)
    return base_size * scaling_factor * sizes


def getSegmentsFromRealPath(real_path):
    """
        Return the segments corresponding to an real absolute path.
        """


def log_training_progress(stats_dict, params_dict, epoch, steps_completed,
    total_steps, log_freq, loggers):
    """Log information about the training progress, and the distribution of the weight tensors.

    Args:
        stats_dict: A tuple of (group_name, dict(var_to_log)).  Grouping statistics variables is useful for logger
          backends such as TensorBoard.  The dictionary of var_to_log has string key, and float values.
          For example:
              stats = ('Peformance/Validation/',
                       OrderedDict([('Loss', vloss),
                                    ('Top1', top1),
                                    ('Top5', top5)]))
        params_dict: A parameter dictionary, such as the one returned by model.named_parameters()
        epoch: The current epoch
        steps_completed: The current step in the epoch
        total_steps: The total number of training steps taken so far
        log_freq: The number of steps between logging records
        loggers: A list of loggers to send the log info to
    """
    if loggers is None:
        return
    if not isinstance(loggers, list):
        loggers = [loggers]
    for logger in loggers:
        logger.log_training_progress(stats_dict, epoch, steps_completed,
            total_steps, freq=log_freq)
        logger.log_weights_distribution(params_dict, steps_completed)


def list_chunks(l, n):
    """ Yield successive n-sized chunks from l.
        Found on: http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python
    """
    for i in range(0, len(l), n):
        yield l[i:i + n]


def clean_ranks(menu_items):
    """
    Resets ranks from 0 to n, n being the number of items.
    """
    rank = 0
    for menu_item in menu_items:
        menu_item.rank = rank
        menu_item.save()
        rank += 1


def mblg_to_mw_atkinson_boore_87(mag):
    """
    Convert magnitude value from Mblg to Mw using Atkinson and Boore 1987
    conversion equation.

    Implements equation as in line 1656 in hazgridXnga2.f
    """
    return 2.715 - 0.277 * mag + 0.127 * mag * mag


def sentences(s):
    """Split the string s into a list of sentences."""
    try:
        s + ''
    except:
        raise TypeError('s must be a string')
    pos = 0
    sentenceList = []
    l = len(s)
    while pos < l:
        try:
            p = s.index('.', pos)
        except:
            p = l + 1
        try:
            q = s.index('?', pos)
        except:
            q = l + 1
        try:
            e = s.index('!', pos)
        except:
            e = l + 1
        end = min(p, q, e)
        sentenceList.append(s[pos:end].strip())
        pos = end + 1
    if len(sentenceList) == 0:
        sentenceList.append(s)
    return sentenceList


def is_binary_file(file_obj):
    """
    Returns True if file has non-ASCII characters (> 0x7F, or 127)
    Should work in both Python 2 and 3
    """
    start = file_obj.tell()
    fbytes = file_obj.read(1024)
    file_obj.seek(start)
    is_str = isinstance(fbytes, str)
    for fbyte in fbytes:
        if is_str:
            code = ord(fbyte)
        else:
            code = fbyte
        if code > 127:
            return True
    return False


def broadcast_lesser(lhs=None, rhs=None, out=None, name=None, **kwargs):
    """Returns the result of element-wise **lesser than** (<) comparison operation with broadcasting.

    Example::

       x = [[ 1.,  1.,  1.],
            [ 1.,  1.,  1.]]

       y = [[ 0.],
            [ 1.]]

       broadcast_lesser(x, y) = [[ 0.,  0.,  0.],
                                 [ 0.,  0.,  0.]]

    Defined in src/operator/tensor/elemwise_binary_broadcast_op_logic.cc:L118

    Parameters
    ----------
    lhs : NDArray
        First input to the function
    rhs : NDArray
        Second input to the function

    out : NDArray, optional
        The output NDArray to hold the result.

    Returns
    -------
    out : NDArray or list of NDArrays
        The output of this function.
    """
    return 0,


def update_config_vars(config_dict, app):
    """
    Use the Heroku API to update config vars

    :param config_dict: dictionary of config vars
    :param app: name of the Heroku app
    :return: None
    """
    updated_config = app.update_config(config_dict)
    return updated_config.to_dict()


def Nu_Xu(Re, Pr, rho_w=None, rho_b=None, mu_w=None, mu_b=None):
    """Calculates internal convection Nusselt number for turbulent vertical
    upward flow in a pipe under supercritical conditions according to [1]_.

    .. math::
        Nu_b = 0.02269 Re_b^{0.8079} \\bar{Pr}_b^{0.9213}
        \\left(\\frac{\\rho_w}{\\rho_b}\\right)^{0.6638}
        \\left(\\frac{\\mu_w}{\\mu_b}\\right)^{0.8687}

    .. math::
        \\bar{Cp} = \\frac{H_w-H_b}{T_w-T_b}

    Parameters
    ----------
    Re : float
        Reynolds number with bulk fluid properties, [-]
    Pr : float
        Prandtl number with bulk fluid properties and an average heat capacity
        between the wall and bulk temperatures [-]
    rho_w : float, optional
        Density at the wall temperature, [kg/m^3]
    rho_b : float, optional
        Density at the bulk temperature, [kg/m^3]
    mu_w : float, optional
        Viscosity at the wall temperature, [Pa*s]
    mu_b : float, optional
        Viscosity at the bulk temperature, [Pa*s]

    Returns
    -------
    Nu : float
        Nusselt number with bulk fluid properties, [-]

    Notes
    -----
    For the data used to develop the correlation, P varied from 23 to 30 MPa,
    and D was 12 mm. G varied from 600-1200 kg/m^2/s and q varied from 100 to
    600 kW/m^2.

    Cp used in the calculation of Prandtl number should be the average value
    of those at the wall and the bulk temperatures.

    For deteriorated heat transfer, this was the third most accurate
    correlation in [2]_ with a MAD of 20.5%.

    If the extra density and viscosity information is not provided, it will
    not be used.

    Examples
    --------
    >>> Nu_Xu(1E5, 1.2, 330, 290., 8e-4, 9e-4)
    289.133054256742

    References
    ----------
    .. [1] Xu, F., Guo, L.J., Mao, Y.F., Jiang, X.E., 2005. "Experimental
       investigation to the heat transfer characteristics of water in vertical
       pipes under supercritical pressure". J. Xi'an Jiaotong University 39,
       468-471.
    .. [2] Chen, Weiwei, Xiande Fang, Yu Xu, and Xianghui Su. "An Assessment of
       Correlations of Forced Convection Heat Transfer to Water at
       Supercritical Pressure." Annals of Nuclear Energy 76 (February 2015):
       451-60. doi:10.1016/j.anucene.2014.10.027.
    """
    Nu = 0.02269 * Re ** 0.8079 * Pr ** 0.9213
    if rho_w and rho_b:
        Nu *= (rho_w / rho_b) ** 0.6638
    if mu_w and mu_b:
        Nu *= (mu_w / mu_b) ** 0.8687
    return Nu


def get_arsc_info(arscobj):
    """
    Return a string containing all resources packages ordered by packagename, locale and type.

    :param arscobj: :class:`~ARSCParser`
    :return: a string
    """
    buff = ''
    for package in arscobj.get_packages_names():
        buff += package + ':\n'
        for locale in arscobj.get_locales(package):
            buff += '\t' + repr(locale) + ':\n'
            for ttype in arscobj.get_types(package, locale):
                buff += '\t\t' + ttype + ':\n'
                try:
                    tmp_buff = getattr(arscobj, 'get_' + ttype + '_resources')(
                        package, locale).decode('utf-8', 'replace').split('\n')
                    for i in tmp_buff:
                        buff += '\t\t\t' + i + '\n'
                except AttributeError:
                    pass
    return buff


def _glsl_mix(controls=None):
    """Generate a GLSL template function from a given interpolation patterns
    and control points."""
    assert (controls[0], controls[-1]) == (0.0, 1.0)
    ncolors = len(controls)
    assert ncolors >= 2
    if ncolors == 2:
        s = '    return mix($color_0, $color_1, t);\n'
    else:
        s = ''
        for i in range(ncolors - 1):
            if i == 0:
                ifs = 'if (t < %.6f)' % controls[i + 1]
            elif i == ncolors - 2:
                ifs = 'else'
            else:
                ifs = 'else if (t < %.6f)' % controls[i + 1]
            adj_t = '(t - %s) / %s' % (controls[i], controls[i + 1] -
                controls[i])
            s += '%s {\n    return mix($color_%d, $color_%d, %s);\n} ' % (ifs,
                i, i + 1, adj_t)
    return 'vec4 colormap(float t) {\n%s\n}' % s


def product(numbers):
    """Return the product of the numbers, e.g. product([2, 3, 10]) == 60"""
    result = 1
    for x in numbers:
        result *= x
    return result


def get_transition_by_name(net, transition_name):
    """
    Get a transition by its name

    Parameters
    ------------
    net
        Petri net
    transition_name
        Transition name

    Returns
    ------------
    transition
        Transition object
    """
    for t in net.transitions:
        if t.name == transition_name:
            return t
    return None


def resolve_name(name):
    """Resolve a name like ``module.object`` to an object and return it.

    Raise `ImportError` if the module or name is not found.
    """
    parts = name.split('.')
    cursor = len(parts) - 1
    module_name = parts[:cursor]
    attr_name = parts[-1]
    while cursor > 0:
        try:
            ret = __import__('.'.join(module_name), fromlist=[attr_name])
            break
        except ImportError:
            if cursor == 0:
                raise
            cursor -= 1
            module_name = parts[:cursor]
            attr_name = parts[cursor]
            ret = ''
    for part in parts[cursor:]:
        try:
            ret = getattr(ret, part)
        except AttributeError:
            raise ImportError(name)
    return ret


def strip_and_uniq(tab):
    """Strip every element of a list and keep a list of ordered unique values

    :param tab: list to strip
    :type tab: list
    :return: stripped list with unique values
    :rtype: list
    """
    _list = []
    for elt in tab:
        val = elt.strip()
        if val and val not in _list:
            _list.append(val)
    return _list


def get_all_score_strings(machine):
    """Given metadata from the model builder this function returns a list of
    strings of the following format:
    {metric_name}-{tag_name}_{fold-fold-number} = {score_val}.  This computes the score for the given tag and
    cross validation split.
    {metric_name}-{tag_name}_{fold-aggregation} = {score_val}. This computes the score for the given tag and aggregates
    the score over all cross validation splits (aggregations currently used are mean, std, min and max)
    {metric_name}_{fold-fold-number} = {score_val}.  This computes the score aggregate across all tags (uses sklearn's default
    aggregation method) for a given cross validation split.
    {metric_name}_{fold-aggregation} = {score_val}.  This computes the score aggregate across all tags (uses sklearn's default
    aggregation method) and cross validation splits (aggregations currently used are mean, std, min and max).

    for katib to pick up.

    Current metric names supported are sklearn score functions: 'r2_score', 'explained_variance_score',
    'mean_squared_error' and 'mean_absolute_error'.  The underscores in such score names are replaced by '-'.

    All spaces in the tag name are also replaced by '-'.

    Parameters
    ----------
    machine : Machine
    """
    all_scores = []
    for metric_name, scores in machine.metadata.build_metadata.model.cross_validation.scores.items(
        ):
        metric_name = metric_name.replace(' ', '-')
        for score_name, score_val in scores.items():
            score_name = score_name.replace(' ', '-')
            all_scores.append(f'{metric_name}_{score_name}={score_val}')
    return all_scores


def set_prefs(prefs):
    """This function is called before opening the project"""
    prefs['ignored_resources'] = ['*.pyc', '*~', '.ropeproject', '.hg',
        '.svn', '_svn', '.git', '.tox', '.env', 'env', 'venv',
        'node_modules', 'bower_components']
    prefs['save_objectdb'] = True
    prefs['compress_objectdb'] = False
    prefs['automatic_soa'] = True
    prefs['soa_followed_calls'] = 0
    prefs['perform_doa'] = True
    prefs['validate_objectdb'] = True
    prefs['max_history_items'] = 32
    prefs['save_history'] = True
    prefs['compress_history'] = False
    prefs['indent_size'] = 4
    prefs['extension_modules'] = []
    prefs['import_dynload_stdmods'] = True
    prefs['ignore_syntax_errors'] = False
    prefs['ignore_bad_imports'] = False
    prefs['prefer_module_from_imports'] = False
    prefs['split_imports'] = False
    prefs['pull_imports_to_top'] = True
    prefs['sort_imports_alphabetically'] = False
    prefs['type_hinting_factory'
        ] = 'rope.base.oi.type_hinting.factory.default_type_hinting_factory'


@staticmethod
def pretty_ratio(value, period):
    """Format the ratio of value / period duration."""
    if len(period) != 2 or period[0] == period[1]:
        return 0.0
    ratio = 100 * 3600 * value / (period[1] - period[0]).total_seconds()
    return round(ratio, 1)


@classmethod
def from_response_data(cls, response_data):
    """
        Response factory

        :param response_data: requests.models.Response
        :return: pybomb.clients.Response
        """
    response_json = response_data.json()
    return cls(response_data.url, response_json['number_of_page_results'],
        response_json['number_of_total_results'], response_json['results'])


def hide(unselected: bool=False):
    """Hide selected curves from Graph Editor view

    :param unselected: Unselected, Hide unselected rather than selected curves
    :type unselected: bool
    """
    pass


def convert_SelfReferenceProperty(model, prop, kwargs):
    """Returns a form field for a ``db.SelfReferenceProperty``."""
    return None


def scan4(alines):
    """mark explicitly paragraphical list items"""
    explicitly_paragraphical = True
    for aline in alines:
        if aline.type == 'empty':
            explicitly_paragraphical = True
        else:
            if aline.type in ['ordered', 'unordered']:
                aline.explicitly_paragraphical = explicitly_paragraphical
            explicitly_paragraphical = False
    return alines


def table_reprocess(cfg, df):
    """
    Reprocesses a table with the given configuration, mainly by filling nas
    with the given configuration.

    Parameters
    ----------
    cfg : dict
        The configuration is specified as a nested dictionary, javascript
        style, and a simple config is given below.  Most parameters should be
        fairly self-explanatory.  "filter" filters the dataframe using the
        query command in Pandas.  The "fill_nas" parameter is another
        dictionary which takes each column and specifies how to fill nas -
        options include "drop", "zero", "median", "mode", and "mean".  The
        "type" must also be specified since items like "median" usually
        return floats but the result is often desired to be an "int" - the
        type is thus specified to avoid ambiguity.::

            {
                "filter": "building_type_id >= 1 and building_type_id <= 14",
                "fill_nas": {
                    "building_type_id": {
                        "how": "drop",
                        "type": "int"
                    },
                    "residential_units": {
                        "how": "zero",
                        "type": "int"
                    },
                    "year_built": {
                        "how": "median",
                        "type": "int"
                    },
                    "building_type_id": {
                        "how": "mode",
                        "type": "int"
                    }
                }
            }

    df : DataFrame to process

    Returns
    -------
    New DataFrame which is reprocessed according the configuration
    """
    df_cnt = len(df)
    if 'filter' in cfg:
        df = df.query(cfg['filter'])
    assert 'fill_nas' in cfg
    cfg = cfg['fill_nas']
    for fname in cfg:
        filltyp, dtyp = cfg[fname]['how'], cfg[fname]['type']
        s_cnt = df[fname].count()
        fill_cnt = df_cnt - s_cnt
        if filltyp == 'zero':
            val = 0
        elif filltyp == 'mode':
            val = df[fname].dropna().value_counts().idxmax()
        elif filltyp == 'median':
            val = df[fname].dropna().quantile()
        elif filltyp == 'mean':
            val = df[fname].dropna().mean()
        elif filltyp == 'drop':
            df = df.dropna(subset=[fname])
        else:
            assert 0, 'Fill type not found!'
        print('Filling column {} with value {} ({} values)'.format(fname,
            val, fill_cnt))
        df[fname] = df[fname].fillna(val).astype(dtyp)
    return df


def get_star_file_header(file_name):
    """
        Load the header information.
        Arguments:
        file_name - Path to the file that contains the header.
        Returns:
        List of header names, rows that are occupied by the header.
    """
    start_header = False
    header_names = []
    idx = None
    with open(file_name, 'r') as read:
        for idx, line in enumerate(read.readlines()):
            if line.startswith('_'):
                if start_header:
                    header_names.append(line.strip().split()[0])
                else:
                    start_header = True
                    header_names.append(line.strip().split()[0])
            elif start_header:
                break
    if not start_header:
        raise IOError(f'No header information found in {file_name}')
    return header_names, idx


def get_motor_offsets(SERVO_OUTPUT_RAW, ofs, motor_ofs):
    """calculate magnetic field strength from raw magnetometer"""
    from . import mavutil
    self = mavutil.mavfile_global
    m = SERVO_OUTPUT_RAW
    motor_pwm = m.servo1_raw + m.servo2_raw + m.servo3_raw + m.servo4_raw
    motor_pwm *= 0.25
    rc3_min = self.param('RC3_MIN', 1100)
    rc3_max = self.param('RC3_MAX', 1900)
    motor = (motor_pwm - rc3_min) / (rc3_max - rc3_min)
    if motor > 1.0:
        motor = 1.0
    if motor < 0.0:
        motor = 0.0
    motor_offsets0 = motor_ofs[0] * motor
    motor_offsets1 = motor_ofs[1] * motor
    motor_offsets2 = motor_ofs[2] * motor
    ofs = ofs[0] + motor_offsets0, ofs[1] + motor_offsets1, ofs[2
        ] + motor_offsets2
    return ofs


def append_activate(idname: str='', filepath: str=''):
    """Append a workspace and make it the active one in the current window

    :param idname: Identifier, Name of the workspace to append and activate
    :type idname: str
    :param filepath: Filepath, Path to the library
    :type filepath: str
    """
    pass


def checksum_tle_line(_line):
    """ Performs TLE-defined checksum on TLE line"""
    check = 0
    for char in _line[:-1]:
        if char.isdigit():
            check += int(char)
        if char == '-':
            check += 1
    _check_val = check % 10
    return _check_val


def _get_template(isamAppliance):
    """
    Retrieve a Junction Mapping Template
    """
    return isamAppliance.invoke_get('Retrieve a Junction Mapping Template',
        '/isam/wga_templates/jmt_template.json')


def getConsensusSequence(first_block):
    """Returns multilevel consensus sequences string.
    """
    for line in first_block:
        if line.upper().startswith('MULTILEVEL'):
            return line.split()[1]


@staticmethod
def listen(data):
    """
        * Do something with the data.
        * :param data:
        * :return: url output
        """
    raise NotImplementedError()


def linalg_sumlogdiag(A=None, name=None, attr=None, out=None, **kwargs):
    """Computes the sum of the logarithms of the diagonal elements of a square matrix.
    Input is a tensor *A* of dimension *n >= 2*.

    If *n=2*, *A* must be square with positive diagonal entries. We sum the natural
    logarithms of the diagonal elements, the result has shape (1,).

    If *n>2*, *sumlogdiag* is performed separately on the trailing two dimensions for all
    inputs (batch mode).

    .. note:: The operator supports float32 and float64 data types only.

    Examples::

       Single matrix reduction
       A = [[1.0, 1.0], [1.0, 7.0]]
       sumlogdiag(A) = [1.9459]

       Batch matrix reduction
       A = [[[1.0, 1.0], [1.0, 7.0]], [[3.0, 0], [0, 17.0]]]
       sumlogdiag(A) = [1.9459, 3.9318]

    Defined in src/operator/tensor/la_op.cc:L445

    Parameters
    ----------
    A : Symbol
        Tensor of square matrices

    name : string, optional.
        Name of the resulting symbol.

    Returns
    -------
    Symbol
        The result symbol.
    """
    return 0,


def psi_K_CO3_OH_HMW84(T, P):
    """c-a-a': potassium carbonate hydroxide [HMW84]."""
    psi = -0.01
    valid = T == 298.15
    return psi, valid


def describe_workspace_directories(DirectoryIds=None, NextToken=None):
    """
    Retrieves information about the AWS Directory Service directories in the region that are registered with Amazon WorkSpaces and are available to your account.
    This operation supports pagination with the use of the NextToken request and response parameters. If more results are available, the NextToken response member contains a token that you pass in the next call to this operation to retrieve the next set of items.
    See also: AWS API Documentation

    :example: response = client.describe_workspace_directories(
        DirectoryIds=[
            'string',
        ],
        NextToken='string'
    )

    :type DirectoryIds: list
    :param DirectoryIds: An array of strings that contains the directory identifiers to retrieve information for. If this member is null, all directories are retrieved.
            (string) --

    :type NextToken: string
    :param NextToken: The NextToken value from a previous call to this operation. Pass null if this is the first call.

    :rtype: dict
    :return: {
        'Directories': [
            {
                'DirectoryId': 'string',
                'Alias': 'string',
                'DirectoryName': 'string',
                'RegistrationCode': 'string',
                'SubnetIds': [
                    'string',
                ],
                'DnsIpAddresses': [
                    'string',
                ],
                'CustomerUserName': 'string',
                'IamRoleId': 'string',
                'DirectoryType': 'SIMPLE_AD'|'AD_CONNECTOR',
                'WorkspaceSecurityGroupId': 'string',
                'State': 'REGISTERING'|'REGISTERED'|'DEREGISTERING'|'DEREGISTERED'|'ERROR',
                'WorkspaceCreationProperties': {
                    'EnableWorkDocs': True|False,
                    'EnableInternetAccess': True|False,
                    'DefaultOu': 'string',
                    'CustomSecurityGroupId': 'string',
                    'UserEnabledAsLocalAdministrator': True|False
                }
            },
        ],
        'NextToken': 'string'
    }

    :returns:
    (string) --

    """
    pass


def isMemberIdAllowed(id):
    """ Return True if 'id' is not in use as a member ID and is not
            reserved, else False.

        o Permission:  Add portal member
        """


@classmethod
def none(cls):
    """Returns an empty interval

        >>> print Interval.none()
        <Empty>
        """
    return cls(0, 0, closed=False)


@staticmethod
def mapper_list_to_map_by_name(mapper_list):
    """
        Convert a list of protocol mappers to a map of mappers by keyed by name.
        :param mapper_list: The list to convert
        :return: The resulting map
        """
    by_name = {}
    for mapper in mapper_list:
        by_name[mapper['name']] = mapper
    return by_name


def __new__(cls, state, hint=None, metric=None):
    """Creates a Result object.

        :param state: state object
        :param hint: reason why this result arose
        :param metric: reference to the
            :class:`~nagiosplugin.metric.Metric` from which this result
            was derived
        """
    return tuple.__new__(cls, (state, hint, metric))


def get_apigateway_sso_id(apigateway_user_id: str) ->str:
    """
    Translates from sso_id to kong consumer.username
    :param apigateway_user_id:
    :return:
    """
    return str(apigateway_user_id).replace('_', '-')


def mun2i_NH3_NH3_NO3_CB89(T, P):
    """n-n-a: ammonia ammonia nitrate [CB89]."""
    mun2i = -0.000437
    valid = T == 298.15
    return mun2i, valid


def no_log_warn(logical_line):
    """Disallow 'LOG.warn('

    Deprecated LOG.warn(), instead use LOG.warning
    https://review.openstack.org/#/c/412768/

    Z352
    """
    msg = 'Z352: LOG.warn is deprecated, please use LOG.warning!'
    if 'LOG.warn(' in logical_line:
        yield 0, msg


def ovn_metadata_name(id_):
    """Return the OVN metadata name based on an id."""
    return 'metadata-%s' % id_


@classmethod
def apply_to(cls, img, color, only_grey_pixels):
    """
            basically a static method for hueing an image.
        :param img: input image
        :param color: arbg color
        :param only_grey_pixels: to be used in conjunction with ItemData -> partial_hue
        :return: hued image
        """
    width = img.size[0]
    height = img.size[1]
    for y in range(height):
        for x in range(width):
            col = img.getpixel((x, y))
            if col == (0, 0, 0, 0):
                continue
            if col[0] == col[1] == col[2] or not only_grey_pixels:
                img.putpixel((x, y), color)
    return img


def add_zero(to_string):
    """Adds a zero to the beginning of string """
    return '0' + str(to_string)


def do_keyword_expansion(alist, pairs):
    """
    Substitute a string in place of certain keywords
    """
    if type(alist) is list or type(alist) is tuple:
        for i, v in enumerate(alist):
            if type(v) == str:
                for k, v in pairs:
                    alist[i] = alist[i].replace(k, v)
    elif type(alist) is dict:
        for a_k, a_v in alist.items():
            if type(a_v) == str:
                for k, v in pairs:
                    alist[a_k] = alist[a_k].replace(k, v)
    else:
        raise


@staticmethod
def _clean_list(data_list: list) ->None:
    """
        Remove empty spaces and null str from a pythons list
        ['',OBJ, OBJ,' '] => [OBJ,OBJ]

        :param data_list: list

        :return: None
        """
    if data_list:
        while '' in data_list:
            data_list.remove('')
        while ' ' in data_list:
            data_list.remove(' ')


def pca_explained_variance_ratio_(pArray, iComponents=1):
    """
	 Input: N x D matrix
	 Output: D x N matrix

	 """
    from sklearn.decomposition import PCA
    pPCA = PCA(n_components=iComponents)
    pPCA.fit(pArray.T)
    return pPCA.explained_variance_ratio_


def flags_to_release(is_minor=False, is_major=False):
    """Convert flags to release type."""
    if is_minor and is_major:
        raise ValueError("Both `is_minor` and `is_major` are set to 'True'.")
    if is_minor:
        return 'minor'
    if is_major:
        return 'major'
    return 'normal'


def abbreviate(s, maxlength=25):
    """Color-aware abbreviator"""
    assert maxlength >= 4
    skip = False
    abbrv = None
    i = 0
    for j, c in enumerate(s):
        if c == '\x1b':
            skip = True
        elif skip:
            if c == 'm':
                skip = False
        else:
            i += 1
        if i == maxlength - 1:
            abbrv = s[:j] + '\x1b[0m...'
        elif i > maxlength:
            break
    if i <= maxlength:
        return s
    else:
        return abbrv


def updateEofZ2(EofZ2, Eof1mt, EofZX, Eof1mt2, EofX2, L):
    """
	Update value of raw 2nd moment of Z based on Lhood value obtained in that NS iteration
	"""
    crossTerm = 2 * Eof1mt * EofZX * L
    X2Term = Eof1mt2 * EofX2 * L ** 2.0
    return EofZ2 + X2Term + crossTerm


def full_qual_class_name(cls) ->str:
    """Получить полный путь класса.
    :param cls: класс, для которого необходимо получить полный путь
    :type cls: класс
    """
    return '.'.join([cls.__module__, cls.__name__])


def div(a, b):
    """ Divide two values, ignoring None """
    if a is None:
        if b is None:
            return None
        else:
            return 1 / b
    elif b is None:
        return a
    return a / b


def prepareHoverSignal(label, type_, posData, posPixel, draggable, selectable):
    """See Plot documentation for content of events"""
    return {'event': 'hover', 'label': label, 'type': type_, 'x': posData[0
        ], 'y': posData[1], 'xpixel': posPixel[0], 'ypixel': posPixel[1],
        'draggable': draggable, 'selectable': selectable}


def _fetch_first_result(fget, fset, fdel, apply_func, value_not_found=None):
    """Fetch first non-none/empty result of applying ``apply_func``."""
    for f in filter(None, (fget, fset, fdel)):
        result = apply_func(f)
        if result:
            return result
    return value_not_found


def get_file_extension_list_from_dict(extensions_dict):
    """
    Return file extension list
    """
    extension_list = []
    for e in extensions_dict.values():
        extension_list += e
    return extension_list


def getToken(value):
    """Return a token for the value."""


def proxied_document_ref(ref_or_document):
    """
    Utility to get reference from document **or** from
    proxied response or return string as is.
    """
    from .document import Document
    if issubclass(type(ref_or_document), Document):
        return ref_or_document.id
    return ref_or_document


def p_testlist_safe_plus_1(p):
    """testlist_safe_plus : COMMA old_test"""
    p[0] = [p[2]]


def psi_H_Cl_HCO3_HMW84(T, P):
    """c-a-a': hydrogen chloride bicarbonate [HMW84]."""
    psi = 0.0
    valid = T == 298.15
    return psi, valid


def _deactivate_multi_threading():
    """ disable multi threading (needed for to reset app environment in unit testing). """
    global _multi_threading_activated
    _multi_threading_activated = False


def pl_inv(P, xm, a):
    """
    Inverse CDF for a pure power-law
    """
    x = (1 - P) ** (1 / (1 - a)) * xm
    return x


def count_correct(scores):
    """Compute number of correct (rank=1) scores for a matrix of scores, where
    the score of the intended "target" is at index 1 of each row.

    N.B. Uses greater-than rather than greater-than-or-equal,
    although this is possibly a bit harsh (you could have achieved
    the correct via some arbitrary tie-breaking function).

    `scores` -- `array[N, C; float]` -- scores of all terms, where
                `scores[:, 0]` are the intended target's scores

    `return` -- `int` -- number of correct (rank=1) results
                (in the range `[0, N]`)
    """
    return int((scores[:, (0)] > scores[:, 1:].max(axis=1)).sum())


@classmethod
def update_many(cls, match_query_dict, update_expression_dict):
    """
        updates multiple documents in the database
        :param match_query_dict: the query expression to match the documents to be updated
        :param update_expression_dict:
        :return: the number of modified documents
        """
    update_result = cls.get_collection().update_many(match_query_dict,
        update_expression_dict)
    return update_result.modified_count


def bindata(n, lst, v=1):
    """
    Bins a list of values into bins of size *n*.

    **Parameters**

    n: *int*
        Number of values to bin together. e.g. ``n = 4`` would bin the first four values into a single value, then the next 4, etc.

    lst: *list*
        List of values to bin.

    v: *int* or *float*, optional
        Bin scalar. The calculated bin values will be divided by this value. e.g. if ``n = v`` the output values will be an average of each bin.

    **Returns**

    binned list: *list*
        A list of binned values.

    **Notes**

    - If the list is not divisible by `n`, the final bin will not be included in the output list. (The last values will be discarded.)

    """
    out = []
    delta = 0
    ttemp = 0
    for ind, val in enumerate(lst):
        delta += 1
        ttemp += val
        if delta == n:
            out.append(ttemp / float(v))
            delta = 0
            ttemp = 0
    return out


def listActionInfos(action_chain=None, object=None, check_visibility=True,
    check_permissions=True, check_condition=True, max=None):
    """ Return a sequence of IActionInfo objects matching given criteria.

        o 'action_chain' is a sequence of one or more action paths
          (e.g. 'object/view');  each path is formatted as
          'category_id/action_id'.  If specified, only matching actions will
          be returned, and in the given order (paths with no matches are
          ignored silently).

        o If 'object' is specified, only actions specific to that object
          are included.

        o If 'check_visibility' is True, return only actions whos "visible"
          flag is set.

        o If 'check_permissions' is True, return only actions for whose
          permissions the current user is authorized.

        o If 'check_condition' is True, return only actions whose condition
          expression evaluates True.

        o If 'max' is specified, return only the first 'max' Actions.

        o Permission:  Public (but not URL-publishable)
        """


def pop_no_diff_fields(latest_config, current_config):
    """Pops off fields that should not be included in the diff."""
    for field in ['userIdentity', 'principalId', 'userAgent',
        'sourceIpAddress', 'requestParameters', 'eventName']:
        latest_config.pop(field, None)
        current_config.pop(field, None)


def _edges_to_adjacency_list(edges):
    """Convert a list of edges into an adjacency list."""
    adj = {}
    for i, j in edges:
        if i in adj:
            ni = adj[i]
        else:
            ni = adj[i] = set()
        if j in adj:
            nj = adj[j]
        else:
            nj = adj[j] = set()
        ni.add(j)
        nj.add(i)
    return adj


@classmethod
def PredefinedType(cls, type):
    """Set 6S to use a predefined aerosol type, one of the constants defined in this class.

        Arguments:

        * ``type`` -- the predefined aerosol type, one of the constants defined in this class

        Example usage::

          s.aeroprofile = AeroProfile.PredefinedType(AeroProfile.Urban)

        """
    return '%d' % type


def gen_wtml(base_dir, depth, **kwargs):
    """
    Create a minimal WTML record for a pyramid generated by toasty

    Parameters
    ----------
    base_dir : str
      The base path to a toast pyramid, as you wish for it to appear
      in the WTML file (i.e., this should be a path visible to a server)
    depth : int
      The maximum depth of the pyramid

    Optional Keywords
    -----------------
    FolderName
    BandPass
    Name
    Credits
    CreditsUrl
    ThumbnailUrl

    Returns
    -------
    wtml : str
      A WTML record
    """
    kwargs.setdefault('FolderName', 'Toasty')
    kwargs.setdefault('BandPass', 'Visible')
    kwargs.setdefault('Name', 'Toasty map')
    kwargs.setdefault('Credits', 'Toasty')
    kwargs.setdefault('CreditsUrl', 'http://github.com/ChrisBeaumont/toasty')
    kwargs.setdefault('ThumbnailUrl', '')
    kwargs['url'] = base_dir
    kwargs['depth'] = depth
    template = """<Folder Name="{FolderName}">
<ImageSet Generic="False" DataSetType="Sky" BandPass="{BandPass}" Name="{Name}" Url="{url}/{{1}}/{{3}}/{{3}}_{{2}}.png" BaseTileLevel="0" TileLevels="{depth}" BaseDegreesPerTile="180" FileType=".png" BottomsUp="False" Projection="Toast" QuadTreeMap="" CenterX="0" CenterY="0" OffsetX="0" OffsetY="0" Rotation="0" Sparse="False" ElevationModel="False">
<Credits> {Credits} </Credits>
<CreditsUrl>{CreditsUrl}</CreditsUrl>
<ThumbnailUrl>{ThumbnailUrl}</ThumbnailUrl>
<Description/>
</ImageSet>
</Folder>"""
    return template.format(**kwargs)


def scan_setup_py():
    """Validate the contents of setup.py against Versioneer's expectations."""
    found = set()
    setters = False
    errors = 0
    with open('setup.py', 'r') as f:
        for line in f.readlines():
            if 'import versioneer' in line:
                found.add('import')
            if 'versioneer.get_cmdclass()' in line:
                found.add('cmdclass')
            if 'versioneer.get_version()' in line:
                found.add('get_version')
            if 'versioneer.VCS' in line:
                setters = True
            if 'versioneer.versionfile_source' in line:
                setters = True
    if len(found) != 3:
        print('')
        print('Your setup.py appears to be missing some important items')
        print('(but I might be wrong). Please make sure it has something')
        print('roughly like the following:')
        print('')
        print(' import versioneer')
        print(' setup( version=versioneer.get_version(),')
        print('        cmdclass=versioneer.get_cmdclass(),  ...)')
        print('')
        errors += 1
    if setters:
        print("You should remove lines like 'versioneer.VCS = ' and")
        print("'versioneer.versionfile_source = ' . This configuration")
        print('now lives in setup.cfg, and should be removed from setup.py')
        print('')
        errors += 1
    return errors


def full_path(root: str, file_name: str, sub_dir: str=None) ->str:
    """
    helper function to return a full
    path instead of writing formatted strs
    """
    if sub_dir is not None:
        return '{}/{}/{}'.format(root, sub_dir, file_name)
    return '{}/{}'.format(root, file_name)


def parse_weight_file(inputFile):
    """The RSCU file contains two columns: codon and weight"""
    weights = {}
    i = 0
    with open(inputFile, 'r') as f:
        for line in f:
            i += 1
            if line.strip() == '':
                continue
            if i == 1:
                continue
            codon = str(line.strip().split('\t')[0])
            weight = float(line.strip().split('\t')[1])
            weights[codon] = weight
    return weights


@classmethod
def data_version(cls, header_chunk):
    """Return the data version, given the first file header chunk"""
    return header_chunk[2], header_chunk[3]


def efit(object, data):
    """Fit an object on data."""
    object.fit(data)


def p_class_name_reference(p):
    """class_name_reference : class_name
                            | dynamic_class_name_reference"""
    p[0] = p[1]


def __delitem__(_, key):
    """ Remove a configuration entry via dictionary access, e.g. del obj[name]. """
    del _.__map[str(key)]


def get_menu_items(content):
    """Class method that return the menu items for the given
        content.
        """


def get_environment():
    """Get the environment in which halo is running

    Returns
    -------
    str
        Environment name
    """
    try:
        from IPython import get_ipython
    except ImportError:
        return 'terminal'
    try:
        shell = get_ipython().__class__.__name__
        if shell == 'ZMQInteractiveShell':
            return 'jupyter'
        elif shell == 'TerminalInteractiveShell':
            return 'ipython'
        else:
            return 'terminal'
    except NameError:
        return 'terminal'


def client():
    """Returns a string representation of this client (as bytes)."""


def _cons_trits(left, right):
    """
    Compares two trits.  If they have the same value, returns that
    value.  Otherwise, returns 0.
    """
    return left if left == right else 0


def dm_subset(dm_sq, idxs):
    """Get subset of distance matrix given list of indices

    Args:
        dm_sq (numpy.array): squareform distance matrix from pdist
        idxs (list of int): list of indices
    Returns:
        numpy.array: subset of `dm_sq` with `shape == (len(idxs), len(idxs))`
    """
    return dm_sq[idxs][:, (idxs)]


def print_help():
    """Prints command line help message.
    """
    print(__doc__)


def givesharmonics(E, _, Emax):
    """
    .. todo:: should consider Emin
    """
    multiples_E = []
    n = 1
    Eh = E
    while Eh <= Emax:
        multiples_E.append(Eh)
        n += 1
        Eh = E * n
    return multiples_E


@classmethod
def request_payload(cls, id_, method, params=None):
    """JSON v1 request payload.  Params is mandatory."""
    return {'method': method, 'params': params or [], 'id': id_}


def show(event):
    """ show dumps of basic objects. """
    import bl
    from . import fleet
    if not event._parsed.rest:
        k = dir(bl)
        event.reply(','.join(k))
        return
    try:
        item, value = event._parsed.rest.split(' ', 1)
    except:
        item = event._parsed.rest
        value = None
    if item == 'bot':
        bots = fleet.get_bot(event.id())
        for bot in bots:
            event.reply(bot)
        return
    if item == 'fleet':
        for bot in fleet:
            if value:
                val = getattr(bot, value, None)
                event.reply('%s=%s' % (value, val))
            else:
                event.reply(bot)
        return
    obj = getattr(bl, item, None)
    if value:
        val = getattr(obj, value, None)
        event.reply('%s: %s' % (value, val))
    else:
        event.reply(obj)


@classmethod
def binder_reorder_section(cls, val):
    """
        Create an instance of this class set to the ``binder_reorder_section``
        tag with value ``val``.

        :param BinderReorderSectionType val:
        :rtype: EventType
        """
    return cls('binder_reorder_section', val)


def fileno(file_or_fd):
    """
    Look for 'fileno' attribute.
    """
    fd = getattr(file_or_fd, 'fileno', lambda : file_or_fd)()
    if not isinstance(fd, int):
        raise ValueError('Expected a file (`.fileno()`) or a file descriptor')
    return fd


@classmethod
def baseline(cls, element):
    """
        Returns a tuple containing the baseline slope and intercept.
        """
    if 'title' in element.attrib:
        matches = cls.baseline_pattern.search(element.attrib['title'])
        if matches:
            return float(matches.group(1)), int(matches.group(2))
    return 0, 0


def soma(números):
    """
    Retorna o resultado da soma da sequência de números dada.

    Examples
    --------

    >>> soma([1, 2, 3, 4])
    10
    """
    return sum(números)


def parent_set():
    """Set the mask’s parenting

    """
    pass


def version_argument(parser, core=core):
    """Version information command line option, allows override of the core
    class instance where required.

    `parser`
        Instance of ArgumentParser.
    `core`
        Package core instance.
    """
    version_kwargs = {'action': 'version', 'version': str('%(prog)s (' +
        core.version + ')')}
    parser.add_argument('-v', '--version', **version_kwargs)


def cs_rad(altitude, et_rad):
    """
    Estimate clear sky radiation from altitude and extraterrestrial radiation.

    Based on equation 37 in Allen et al (1998) which is recommended when
    calibrated Angstrom values are not available.

    :param altitude: Elevation above sea level [m]
    :param et_rad: Extraterrestrial radiation [MJ m-2 day-1]. Can be
        estimated using ``et_rad()``.
    :return: Clear sky radiation [MJ m-2 day-1]
    :rtype: float
    """
    clear_sky_rad = (2e-05 * altitude + 0.75) * et_rad
    return clear_sky_rad


@classmethod
def instance(cls, key, client_id, server):
    """Get an existing instance of the request, if any, from server.active_requests,
        otherwise make a new one."""
    if (key, client_id) in server.active_requests:
        return server.active_requests[key, client_id]
    else:
        inst = cls(key, client_id, server)
        server.active_requests[key, client_id] = inst
        return inst


def S(state, qubit):
    """
    Applies a phase gate (S) rotation to stabilizers and destabilizers

    S = \\sqrt{Z}

    This is P in CHP.

    S = S
    Z = S^2
    S^{\\dagger} = S^3
    I = S^4

    X -> iW = Y
    Z -> Z
    W -> iX
    Y -> -X
    """
    stabs = state.stabs
    stabs.signs_minus ^= stabs.signs_i & stabs.col_x[qubit]
    stabs.signs_i ^= stabs.col_x[qubit]
    for gens in state.gen_list:
        gens.col_z[qubit] ^= gens.col_x[qubit]
        for i in gens.col_x[qubit]:
            gens.row_z[i] ^= {qubit}


def quote_ident(value):
    """Indent the quotes."""
    return '"{}"'.format(value.replace('\\', '\\\\').replace('"', '\\"').
        replace('\n', '\\n'))


def first(func, items):
    """Return the first item in the list for what func returns True"""
    for item in items:
        if func(item):
            return item


@staticmethod
def _check_prob_choice_mode_compat(probability_mode, choice_mode):
    """
        Check that the probability and choice modes are compatibly with
        each other. Currently 'single_chooser' must be paired with
        'aggregate' and 'full_product' must be paired with 'individual'.

        """
    if probability_mode == 'full_product' and choice_mode == 'aggregate':
        raise ValueError(
            "'full_product' probability mode is not compatible with 'aggregate' choice mode"
            )
    if probability_mode == 'single_chooser' and choice_mode == 'individual':
        raise ValueError(
            "'single_chooser' probability mode is not compatible with 'individual' choice mode"
            )