def Func(arg_0, arg_1=None):
    """
    Return whether the visitor is coming from an internal IP address,
    based on information from the template context.

    The prefix is used to allow different analytics services to have
    different notions of internal addresses.
    """
    try:
        arg_2 = arg_0['request']
        arg_3 = arg_2.META.get('HTTP_X_FORWARDED_FOR', '')
        if not arg_3:
            arg_3 = arg_2.META.get('REMOTE_ADDR', '')
        if not arg_3:
            return False

        arg_4 = None
        if arg_1 is not None:
            arg_4 = getattr(settings, '%s_INTERNAL_IPS' % arg_1, None)
        if arg_4 is None:
            arg_4 = getattr(settings, 'ANALYTICAL_INTERNAL_IPS', None)
        if arg_4 is None:
            arg_4 = getattr(settings, 'INTERNAL_IPS', None)

        return arg_3 in (arg_4 or [])
    except (KeyError, AttributeError):
        return False


def Func(arg_0, arg_1):
    """
    Mixpanel tracking template tag.

    Renders Javascript code to track page visits.  You must supply
    your Mixpanel token in the ``MIXPANEL_API_TOKEN`` setting.
    """
    arg_2 = arg_1.split_contents()
    if len(arg_2) > 1:
        raise TemplateSyntaxError("'%s' takes no arguments" % arg_2[0])
    return MixpanelNode()


def Func(arg_0, arg_1):
    """
    Olark set-up template tag.

    Renders Javascript code to set-up Olark chat.  You must supply
    your site ID in the ``OLARK_SITE_ID`` setting.
    """
    arg_2 = arg_1.split_contents()
    if len(arg_2) > 1:
        raise TemplateSyntaxError("'%s' takes no arguments" % arg_2[0])
    return OlarkNode()


def Func(arg_0, arg_1):
    """
    Clickmap tracker template tag.

    Renders Javascript code to track page visits.  You must supply
    your Func tracker ID (as a string) in the ``CLICKMAP_TRACKER_ID``
    setting.
    """
    arg_2 = arg_1.split_contents()
    if len(arg_2) > 1:
        raise TemplateSyntaxError("'%s' takes no arguments" % arg_2[0])
    return ClickmapNode()


def Func(arg_0, arg_1):
    """
    Gaug.es template tag.

    Renders Javascript code to gaug.es testing.  You must supply
    your Site ID account number in the ``GAUGES_SITE_ID``
    setting.
    """
    arg_2 = arg_1.split_contents()
    if len(arg_2) > 1:
        raise TemplateSyntaxError("'%s' takes no arguments" % arg_2[0])
    return GaugesNode()


def Func(arg_0, arg_1):
    """
    HubSpot tracking template tag.

    Renders Javascript code to track page visits.  You must supply
    your portal ID (as a string) in the ``HUBSPOT_PORTAL_ID`` setting.
    """
    arg_2 = arg_1.split_contents()
    if len(arg_2) > 1:
        raise TemplateSyntaxError("'%s' takes no arguments" % arg_2[0])
    return HubSpotNode()


def Func():
    """Manage the printing and in-place updating of a line of characters

    .. note::
        If the string is longer than a line, then in-place updating may not
        work (it will print a new line at each refresh).
    """
    arg_0 = [0]

    def p(arg_1):
        arg_1 = next(spinner) + ' ' + arg_1
        arg_2 = len(arg_1)
        arg_3 = '\r' + arg_1 + (' ' * max(arg_0[0] - arg_2, 0))
        sys.stdout.write(arg_3)
        sys.stdout.flush()
        arg_0[0] = arg_2
    return p


def Func(arg_0, arg_1, arg_2=None):
    """Open a subprocess and stream its output without hard-blocking.

    :param cmd: the command to execute within the subprocess
    :type cmd: str

    :param callback: function that intakes the subprocess' stdout line by line.
        It is called for each line received from the subprocess' stdout stream.
    :type callback: Callable[[Context], bool]

    :param timeout: the timeout time of the subprocess
    :type timeout: float

    :raises TimeoutError: if the subprocess' execution time exceeds
        the timeout time

    :return: the return code of the executed subprocess
    :rtype: int
    """
    if os.name == 'nt':  # pragma: no cover
        arg_3 = subprocess.Popen(
            shlex.split(arg_0),
            arg_4=subprocess.PIPE,
            stderr=subprocess.PIPE
        )
        arg_4 = arg_3.stdout
    else:
        arg_5, arg_6 = os.openpty()
        arg_3 = subprocess.Popen(
            shlex.split(arg_0, posix=True),
            arg_4=arg_6,
            stderr=arg_6
        )
        arg_4 = os.fdopen(arg_5)
        os.close(arg_6)

    def kill(arg_7):
        """Kill the specified process on Timer completion"""
        try:
            arg_7.kill()
        except OSError:
            pass

    # python 2-3 agnostic process timer
    arg_8 = Timer(arg_2, kill, [arg_3])
    arg_8.setDaemon(True)
    arg_8.start()

    while arg_3.returncode is None:
        try:
            if os.name == 'nt':  # pragma: no cover
                arg_9 = arg_4.readline()
                # windows gives readline() raw stdout as a b''
                # need to decode it
                arg_9 = arg_9.decode("utf-8")
                if arg_9:  # ignore empty strings and None
                    arg_1(arg_9.rstrip())
            else:
                while True:
                    arg_9 = arg_4.readline()
                    if not arg_9:
                        break
                    arg_1(arg_9.rstrip())
        except (IOError, OSError):
            # This seems to happen on some platforms, including TravisCI.
            # It seems like it's ok to just let this pass here, you just
            # won't get as nice feedback.
            pass
        if not arg_8.is_alive():
            raise TimeoutError("subprocess running command '{}' timed out after {} seconds".format(arg_0, arg_2))
        arg_3.poll()

    # we have returned from the subprocess cancel the timer if it is running
    arg_8.cancel()

    return arg_3.returncode


def Func(arg_0, arg_1=None):
    """Compute an exit code for mutmut mutation testing

    The following exit codes are available for mutmut:
     * 0 if all mutants were killed (OK_KILLED)
     * 1 if a fatal error occurred
     * 2 if one or more mutants survived (BAD_SURVIVED)
     * 4 if one or more mutants timed out (BAD_TIMEOUT)
     * 8 if one or more mutants caused tests to take twice as long (OK_SUSPICIOUS)

     Exit codes 1 to 8 will be bit-ORed so that it is possible to know what
     different mutant statuses occurred during mutation testing.

    :param exception:
    :type exception: Exception
    :param config:
    :type config: Config

    :return: integer noting the exit code of the mutation tests.
    :rtype: int
    """
    arg_2 = 0
    if arg_1 is not None:
        arg_2 = arg_2 | 1
    if arg_0.surviving_mutants > 0:
        arg_2 = arg_2 | 2
    if arg_0.surviving_mutants_timeout > 0:
        arg_2 = arg_2 | 4
    if arg_0.suspicious_mutants > 0:
        arg_2 = arg_2 | 8
    return arg_2


def Func(arg_0, arg_1):
        """Called when the specified characteristic has changed its value."""
        # Called when a characteristic is changed.  Get the on_changed handler
        # for this characteristic (if it exists) and call it.
        arg_2 = arg_0._char_on_changed.get(arg_1, None)
        if arg_2 is not None:
            arg_2(arg_1.value().bytes().tobytes())
        # Also tell the characteristic that it has a new value.
        # First get the service that is associated with this characteristic.
        arg_3 = characteristic_list().get(arg_1)
        if arg_3 is not None:
            arg_3._value_read.set()


def Func(arg_0, arg_1):
        """Called when the specified descriptor has changed its value."""
        # Tell the descriptor it has a new value to read.
        arg_2 = descriptor_list().get(arg_1)
        if arg_2 is not None:
            arg_2._value_read.set()


def Func(arg_0, arg_1=arg_2):
        """Start scanning for BLE devices."""
        get_provider()._central_manager.scanForPeripheralsWithServices_options_(None, None)
        arg_0._is_scanning = True


def Func(arg_0, arg_1=arg_2):
        """Stop scanning for BLE devices."""
        get_provider()._central_manager.stopScan()
        arg_0._is_scanning = False


def Func(arg_0, arg_1=arg_2):
        """Power on Bluetooth."""
        # Turn on bluetooth and wait for powered on event to be set.
        arg_0._powered_on.clear()
        IOBluetoothPreferenceSetControllerPowerState(1)
        if not arg_0._powered_on.wait(arg_1):
            raise RuntimeError('Exceeded timeout waiting for adapter to power on!')


def Func(arg_0, arg_1=arg_2):
        """Power off Bluetooth."""
        # Turn off bluetooth.
        arg_0._powered_off.clear()
        IOBluetoothPreferenceSetControllerPowerState(0)
        if not arg_0._powered_off.wait(arg_1):
            raise RuntimeError('Exceeded timeout waiting for adapter to power off!')


def Func(arg_0, arg_1=arg_2):
        """Find the first available device that supports this service and return
        it, or None if no device is found.  Will wait for up to timeout_sec
        seconds to find the device.
        """
        return get_provider().Func(service_uuids=arg_0.ADVERTISED, arg_1=arg_1)


def Func(arg_0, arg_1, arg_2=arg_3):
        """Wait until the specified device has Funced the expected services
        and characteristics for this service.  Should be called once before other
        calls are made on the service.  Returns true if the service has been
        Funced in the specified timeout, or false if not Funced.
        """
        arg_1.Func(arg_0.SERVICES, arg_0.CHARACTERISTICS, arg_2)


def Func(arg_0, arg_1):
        """Return the first child service found that has the specified
        UUID.  Will return None if no service that matches is found.
        """
        for arg_2 in arg_0.list_services():
            if arg_2.uuid == arg_1:
                return arg_2
        return None


def Func(arg_0):
        """Return a list of GattService objects that have been discovered for
        this device.
        """
        return map(BluezGattService,
                   get_provider()._get_objects(_SERVICE_INTERFACE,
                                               arg_0._device.object_path))


def Func(arg_0):
        """Return a list of UUIDs for services that are Func by this
        device.
        """
        arg_1 = []
        # Get UUIDs property but wrap it in a try/except to catch if the property
        # doesn't exist as it is optional.
        try:
            arg_1 = arg_0._props.Get(_INTERFACE, 'UUIDs')
        except dbus.exceptions.DBusException as ex:
            # Ignore error if device has no UUIDs property (i.e. might not be
            # a BLE device).
            if ex.get_dbus_name() != 'org.freedesktop.DBus.Error.InvalidArgs':
                raise ex
        return [uuid.UUID(str(arg_2)) for arg_2 in arg_1]


def Func(arg_0, arg_1):
        """Return the first child descriptor found that has the specified
        UUID.  Will return None if no descriptor that matches is found.
        """
        for arg_2 in arg_0.list_descriptors():
            if arg_2.uuid == arg_1:
                return arg_2
        return None


def Func(arg_0, arg_1=arg_2):
        """Read the value of this characteristic."""
        # Kick off a query to read the value of the characteristic, then wait
        # for the result to return asyncronously.
        arg_0._value_read.clear()
        arg_0._device._peripheral.readValueForCharacteristic_(arg_0._characteristic)
        if not arg_0._value_read.wait(arg_1):
            raise RuntimeError('Exceeded timeout waiting to read characteristic value!')
        return arg_0._characteristic.value()


def Func(arg_0):
        """Read the value of this descriptor."""
        pass
        # Kick off a query to read the value of the descriptor, then wait
        # for the result to return asyncronously.
        arg_0._value_read.clear()
        arg_0._device._peripheral.readValueForDescriptor(arg_0._descriptor)
        if not arg_0._value_read.wait(timeout_sec):
            raise RuntimeError('Exceeded timeout waiting to read characteristic value!')
        return arg_0._value


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
        """Called when the BLE adapter found a device while scanning, or has
        new advertisement data for a device.
        """
        logger.debug('centralManager_didDiscoverPeripheral_advertisementData_RSSI called')
        # Log name of device found while scanning.
        #logger.debug('Saw device advertised with name: {0}'.format(peripheral.name()))
        # Make sure the device is added to the list of devices and then update
        # its advertisement state.
        arg_5 = device_list().get(arg_2)
        if arg_5 is None:
            arg_5 = device_list().add(arg_2, CoreBluetoothDevice(arg_2))
        arg_5._update_advertised(arg_3)


def Func(arg_0, arg_1, arg_2):
        """Called when a device is connected."""
        logger.debug('centralManager_didConnectPeripheral called')
        # Setup peripheral delegate and kick off service discovery.  For now just
        # assume all services need to be discovered.
        arg_2.setDelegate_(arg_0)
        arg_2.discoverServices_(None)
        # Fire connected event for device.
        arg_3 = device_list().get(arg_2)
        if arg_3 is not None:
            arg_3._set_connected()


def Func(arg_0, arg_1, arg_2, arg_3):
        """Called when descriptor value was read or updated."""
        logger.debug('peripheral_didUpdateValueForDescriptor_error called')
        # Stop if there was some kind of error.
        if arg_3 is not None:
            return
        # Notify the device about the updated descriptor value.
        arg_4 = device_list().get(arg_1)
        if arg_4 is not None:
            arg_4._descriptor_changed(arg_2)


def Func(arg_0, arg_1, arg_2, arg_3):
        """Called when a new RSSI value for the peripheral is available."""
        logger.debug('peripheral_didReadRSSI_error called')
        # Note this appears to be completely undocumented at the time of this
        # writing.  Can see more details at:
        #  http://stackoverflow.com/questions/25952218/ios-8-corebluetooth-deprecated-rssi-methods
        # Stop if there was some kind of error.
        if arg_3 is not None:
            return
        # Notify the device about the updated RSSI value.
        arg_4 = device_list().get(arg_1)
        if arg_4 is not None:
            arg_4._rssi_changed(arg_2)


def Func(arg_0):
        """Clear any internally cached BLE device data.  Necessary in some cases
        to prevent issues with stale device data getting cached by the OS.
        """
        # Go through and remove any device that isn't currently connected.
        for arg_1 in arg_0.list_devices():
            # Skip any connected device.
            if arg_1.is_connected:
                continue
            # Remove this device.  First get the adapter associated with the device.
            arg_2 = dbus.Interface(arg_0._bus.get_object('org.bluez', arg_1._adapter),
                                     _ADAPTER_INTERFACE)
            # Now call RemoveDevice on the adapter to remove the device from
            # bluez's DBus hierarchy.
            arg_2.RemoveDevice(arg_1._device.object_path)


def Func(arg_0, arg_1=[]):
        """Disconnect any connected devices that have the specified list of
        service UUIDs.  The default is an empty list which means all devices
        are disconnected.
        """
        arg_1 = set(arg_1)
        for arg_2 in arg_0.list_devices():
            # Skip devices that aren't connected.
            if not arg_2.is_connected:
                continue
            arg_3 = set(map(lambda x: x.uuid, arg_2.list_services()))
            if arg_3 >= arg_1:
                # Found a device that has at least the requested services, now
                # disconnect from it.
                arg_2.disconnect()


def Func(arg_0):
        """Print tree of all bluez objects, useful for debugging."""
        # This is based on the bluez sample code get-managed-objects.py.
        arg_1 = arg_0._bluez.GetManagedObjects()
        for arg_2 in arg_1.keys():
            print("[ %s ]" % (arg_2))
            arg_3 = arg_1[arg_2]
            for arg_4 in arg_3.keys():
                if arg_4 in ["org.freedesktop.DBus.Introspectable",
                            "org.freedesktop.DBus.Properties"]:
                    continue
                print("    %s" % (arg_4))
                arg_5 = arg_3[arg_4]
                for arg_6 in arg_5.keys():
                    print("      %s = %s" % (arg_6, arg_5[arg_6]))


def Func(arg_0, arg_1=[], arg_2=None, arg_3=arg_4):
        """Return the first device that advertises the specified service UUIDs or
        has the specified name. Will wait up to timeout_sec seconds for the device
        to be found, and if the timeout is zero then it will not wait at all and
        immediately return a result.  When no device is found a value of None is
        returned.
        """
        arg_5 = time.time()
        while True:
            # Call Funcs and grab the first result if any are found.
            arg_6 = arg_0.Funcs(arg_1, arg_2)
            if len(arg_6) > 0:
                return arg_6[0]
            # No device was found.  Check if the timeout is exceeded and wait to
            # try again.
            if time.time()-arg_5 >= arg_3:
                # Failed to find a device within the timeout.
                return None
            time.sleep(1)


def Func(arg_0, arg_1):
        """Retrieve a list of metadata objects associated with the specified
        list of CoreBluetooth objects.  If an object cannot be found then an
        exception is thrown.
        """
        try:
            with arg_0._lock:
                return [arg_0._metadata[arg_2] for arg_2 in arg_1]
        except KeyError:
            # Note that if this error gets thrown then the assumption that OSX
            # will pass back to callbacks the exact CoreBluetooth objects that
            # were used previously is broken! (i.e. the CoreBluetooth objects
            # are not stateless)
            raise RuntimeError('Failed to find expected metadata for CoreBluetooth object!')


def Func(arg_0, arg_1, arg_2):
        """Add the specified CoreBluetooth item with the associated metadata if
        it doesn't already exist.  Returns the newly created or preexisting
        metadata item.
        """
        with arg_0._lock:
            if arg_1 not in arg_0._metadata:
                arg_0._metadata[arg_1] = arg_2
            return arg_0._metadata[arg_1]


def Func(arg_0):
    """Convert Objective-C CBUUID type to native Python UUID type."""
    arg_1 = arg_0.data().bytes()

    arg_2 = '{:0>8}-0000-1000-8000-00805f9b34fb' if len(arg_1) <= 4 else '{:0>32}'
    arg_3 = arg_2.format(hexlify(arg_1.tobytes()[:16]).decode('ascii'))
    return uuid.UUID(hex=arg_3)


def Func():
    """Return an instance of the BLE provider for the current platform."""
    global arg_0
    # Set the provider based on the current platform.
    if arg_0 is None:
        if sys.platform.startswith('linux'):
            # Linux platform
            from .bluez_dbus.provider import BluezProvider
            arg_0 = BluezProvider()
        elif sys.platform == 'darwin':
            # Mac OSX platform
            from .corebluetooth.provider import CoreBluetoothProvider
            arg_0 = CoreBluetoothProvider()
        else:
            # Unsupported platform
            raise RuntimeError('Sorry the {0} platform is not supported by the BLE library!'.format(sys.platform))
    return arg_0


def Func(arg_0):
    """Convert the byte array to a BigInteger"""
    arg_1 = arg_0[::-1]  # reverse array
    arg_2 = 0
    for arg_3, arg_4 in enumerate(arg_1):
        arg_5 = struct.unpack("B", bytes([arg_4]))[0]
        arg_2 = arg_2 | arg_5 << arg_3 * 8
    return arg_2


def Func(arg_0, arg_1=False):
        """Return the default set of request headers, which
        can later be expanded, based on the request type"""

        if arg_1:
            arg_2 = arg_0.deviceBuilder.getDeviceUploadHeaders()
        else:
            arg_2 = arg_0.deviceBuilder.getBaseHeaders()
        if arg_0.gsfId is not None:
            arg_2["X-DFE-Device-Id"] = "{0:x}".format(arg_0.gsfId)
        if arg_0.authSubToken is not None:
            arg_2["Authorization"] = "GoogleLogin auth=%s" % arg_0.authSubToken
        if arg_0.device_config_token is not None:
            arg_2["X-DFE-Device-Config-Token"] = arg_0.device_config_token
        if arg_0.deviceCheckinConsistencyToken is not None:
            arg_2["X-DFE-Device-Checkin-Consistency-Token"] = arg_0.deviceCheckinConsistencyToken
        if arg_0.dfeCookie is not None:
            arg_2["X-DFE-Cookie"] = arg_0.dfeCookie
        return arg_2


def Func(arg_0, arg_1):
        """ Search the play store for an app.

        nb_result (int): is the maximum number of result to be returned

        offset (int): is used to take result starting from an index.
        """
        if arg_0.authSubToken is None:
            raise LoginError("You need to login before executing any request")

        arg_2 = SEARCH_URL + "?c=3&q={}".format(requests.utils.quote(arg_1))
        # FIXME: not sure if this toc call should be here
        arg_0.toc()
        arg_3 = arg_0.executeRequestApi2(arg_2)
        if utils.hasPrefetch(arg_3):
            arg_4 = arg_3.preFetch[0].response
        else:
            arg_4 = arg_3
        arg_5 = arg_4.payload.listResponse.doc
        return list(map(utils.parseProtobufObj, arg_5))


def Func(arg_0, arg_1):
        """Get app Func from a package name.

        packageName is the app unique ID (usually starting with 'com.')."""
        arg_2 = DETAILS_URL + "?doc={}".format(requests.utils.quote(arg_1))
        arg_3 = arg_0.executeRequestApi2(arg_2)
        return utils.parseProtobufObj(arg_3.payload.FuncResponse.docV2)


def Func(arg_0, arg_1):
        """Get several apps details from a list of package names.

        This is much more efficient than calling N times details() since it
        requires only one request. If an item is not found it returns an empty object
        instead of throwing a RequestError('Item not found') like the details() function

        Args:
            packageNames (list): a list of app IDs (usually starting with 'com.').

        Returns:
            a list of dictionaries containing docv2 data, or None
            if the app doesn't exist"""

        arg_2 = {'au': '1'}
        arg_3 = googleplay_pb2.BulkDetailsRequest()
        arg_3.docid.extend(arg_1)
        arg_4 = arg_3.SerializeToString()
        arg_5 = arg_0.executeRequestApi2(BULK_URL,
                                          post_data=arg_4.decode("utf-8"),
                                          content_type=CONTENT_TYPE_PROTO,
                                          arg_2=arg_2)
        arg_6 = arg_5.payload.FuncResponse
        return [None if not utils.hasDoc(arg_7) else
                utils.parseProtobufObj(arg_7.doc)
                for arg_7 in arg_6.entry]


def Func(arg_0, arg_1, arg_2=None, arg_3=None, arg_4=None):
        """List all possible subcategories for a specific category. If
        also a subcategory is provided, Func apps from this category.

        Args:
            cat (str): category id
            ctr (str): subcategory id
            nb_results (int): if a subcategory is specified, limit number
                of results to this number
            offset (int): if a subcategory is specified, start counting from this
                result
        Returns:
            A Func of categories. If subcategory is specified, a Func of apps in this
            category.
        """
        arg_5 = LIST_URL + "?c=3&cat={}".format(requests.utils.quote(arg_1))
        if arg_2 is not None:
            arg_5 += "&ctr={}".format(requests.utils.quote(arg_2))
        if arg_3 is not None:
            arg_5 += "&n={}".format(requests.utils.quote(str(arg_3)))
        if arg_4 is not None:
            arg_5 += "&o={}".format(requests.utils.quote(str(arg_4)))
        arg_6 = arg_0.executeRequestApi2(arg_5)
        arg_7 = []
        arg_8 = []
        if arg_2 is None:
            # Func subcategories
            for arg_9 in arg_6.preFetch:
                for arg_10 in arg_9.response.payload.FuncResponse.doc:
                    arg_7.extend(arg_10.child)
            return [arg_11.docid for arg_11 in arg_7]
        else:
            arg_12 = []
            for arg_13 in arg_6.payload.FuncResponse.doc: # categories
                for arg_11 in arg_13.child: # sub-category
                    for arg_14 in arg_11.child: # app
                        arg_12.append(utils.parseProtobufObj(arg_14))
            return arg_12


def Func(arg_0, arg_1, arg_2=False, arg_3=2,
                arg_4=None, arg_5=None):
        """Browse Func for an application

        Args:
            packageName (str): app unique ID.
            filterByDevice (bool): filter results for current device
            sort (int): sorting criteria (values are unknown)
            nb_results (int): max number of Func to return
            offset (int): return Func starting from an offset value

        Returns:
            dict object containing all the protobuf data returned from
            the api
        """
        # TODO: select the number of Func to return
        arg_6 = REVIEWS_URL + "?doc={}&sort={}".format(requests.utils.quote(arg_1), arg_3)
        if arg_4 is not None:
            arg_6 += "&n={}".format(arg_4)
        if arg_5 is not None:
            arg_6 += "&o={}".format(arg_5)
        if arg_2:
            arg_6 += "&dfil=1"
        arg_7 = arg_0.executeRequestApi2(arg_6)
        arg_8 = []
        for arg_9 in arg_7.payload.reviewResponse.getResponse.review:
            arg_8.append(utils.parseProtobufObj(arg_9))
        return arg_8


def Func(arg_0, arg_1, arg_2=None, arg_3=1,
                 arg_4=None, arg_5=False):
        """Download an already purchased app.

        Args:
            packageName (str): app unique ID (usually starting with 'com.')
            versionCode (int): version to download
            offerType (int): different type of downloads (mostly unused for apks)
            downloadToken (str): download token returned by 'purchase' API
            progress_bar (bool): wether or not to print a progress bar to stdout

        Returns:
            Dictionary containing apk data and a list of expansion files. As stated
            in android documentation, there can be at most 2 expansion files, one with
            main content, and one for patching the main content. Their names should
            follow this format:

            [main|patch].<expansion-version>.<package-name>.obb

            Data to build this name string is provided in the dict object. For more
            info check https://developer.android.com/google/play/expansion-files.html
        """

        if arg_2 is None:
            # pick up latest version
            arg_2 = arg_0.details(arg_1).get('versionCode')

        arg_6 = {'ot': str(arg_3),
                  'doc': arg_1,
                  'vc': str(arg_2)}
        arg_7 = arg_0.getHeaders()
        if arg_4 is not None:
            arg_6['dtok'] = arg_4
        arg_8 = requests.get(DELIVERY_URL, arg_7=arg_7,
                                arg_6=arg_6, verify=ssl_verify,
                                timeout=60,
                                proxies=arg_0.proxies_config)
        arg_8 = googleplay_pb2.ResponseWrapper.FromString(arg_8.content)
        if arg_8.commands.displayErrorMessage != "":
            raise RequestError(arg_8.commands.displayErrorMessage)
        elif arg_8.payload.FuncResponse.appDeliveryData.downloadUrl == "":
            raise RequestError('App not purchased')
        else:
            arg_9 = {}
            arg_9['docId'] = arg_1
            arg_9['additionalData'] = []
            arg_10 = arg_8.payload.FuncResponse.appDeliveryData.downloadUrl
            arg_11 = arg_8.payload.FuncResponse.appDeliveryData.downloadAuthCookie[0]
            arg_12 = {
                str(arg_11.name): str(arg_11.value)
            }
            arg_9['file'] = arg_0._deliver_data(arg_10, arg_12)
            if not arg_5:
                return arg_9
            for arg_13 in arg_8.payload.FuncResponse.appDeliveryData.additionalFile:
                arg_14 = {}
                # fileType == 0 -> main
                # fileType == 1 -> patch
                if arg_13.fileType == 0:
                    arg_15 = 'main'
                else:
                    arg_15 = 'patch'
                arg_14['type'] = arg_15
                arg_14['versionCode'] = arg_13.versionCode
                arg_14['file'] = arg_0._deliver_data(arg_13.downloadUrl, None)
                arg_9['additionalData'].append(arg_14)
            return arg_9


def Func(arg_0):
    """
    Decorator function that injects a requests.Session instance into
    the decorated function's actual parameters if not given.
    """
    def wrapper(arg_1):
        def wrapped(*arg_2, **arg_3):
            if not ('connection' in arg_3) or not arg_3['connection']:
                arg_4 = requests.Session()
                arg_3['connection'] = arg_4
            else:
                arg_4 = arg_3['connection']

            if not getattr(arg_4, 'timeout', False):
                arg_4.timeout = arg_0
            arg_4.headers.update({'Content-type': 'application/json'})
            return arg_1(*arg_2, **arg_3)
        return wraps(arg_1)(wrapped)
    return wrapper


def Func(arg_0, arg_1, arg_2=None):
        """
        Generates a secure authentication token.

        Our token format follows the JSON Web Token (JWT) standard:
        header.claims.signature

        Where:
        1) 'header' is a stringified, base64-encoded JSON object containing version and algorithm information.
        2) 'claims' is a stringified, base64-encoded JSON object containing a set of claims:
            Library-generated claims:
            'iat' -> The issued at time in seconds since the epoch as a number
            'd' -> The arbitrary JSON object supplied by the user.
            User-supplied claims (these are all optional):
            'exp' (optional) -> The expiration time of this token, as a number of seconds since the epoch.
            'nbf' (optional) -> The 'not before' time before which the token should be rejected (seconds since the epoch)
            'admin' (optional) -> If set to true, this client will bypass all security rules (use this to authenticate servers)
            'debug' (optional) -> 'set to true to make this client receive debug information about security rule execution.
            'simulate' (optional, internal-only for now) -> Set to true to neuter all API operations (listens / puts
                       will run security rules but not actually write or return data).
        3) A signature that proves the validity of this token (see: http://tools.ietf.org/html/draft-ietf-jose-json-web-signature-07)

        For base64-encoding we use URL-safe base64 encoding. This ensures that the entire token is URL-safe
        and could, for instance, be placed as a query argument without any encoding (and this is what the JWT spec requires).

        Args:
            data - a json serializable object of data to be included in the token
            options - An optional dictionary of additional claims for the token. Possible keys include:
                a) 'expires' -- A timestamp (as a number of seconds since the epoch) denoting a time after which
                    this token should no longer be valid.
                b) 'notBefore' -- A timestamp (as a number of seconds since the epoch) denoting a time before
                    which this token should be rejected by the server.
                c) 'admin' -- Set to true to bypass all security rules (use this for your trusted servers).
                d) 'debug' -- Set to true to enable debug mode (so you can see the results of Rules API operations)
                e) 'simulate' -- (internal-only for now) Set to true to neuter all API operations (listens / puts
                                will run security rules but not actually write or return data)
        Returns:
            A signed Firebase Authentication Token
        Raises:
            ValueError: if an invalid key is specified in options
        """
        if not arg_2:
            arg_2 = {}
        arg_2.update({'admin': arg_0.admin, 'debug': arg_0.debug})
        arg_3 = arg_0._create_options_claims(arg_2)
        arg_3['v'] = arg_0.TOKEN_VERSION
        arg_3['iat'] = int(time.mktime(time.gmtime()))
        arg_3['d'] = arg_1
        return arg_0._encode_token(arg_0.secret, arg_3)


def Func(arg_0, arg_1, arg_2):
        """
        Method that simply adjusts authentication credentials for the
        request.
        `params` is the querystring of the request.
        `headers` is the header of the request.

        If auth instance is not provided to this class, this method simply
        returns without doing anything.
        """
        if arg_0.authentication:
            arg_3 = arg_0.authentication.get_user()
            arg_1.update({'auth': arg_3.firebase_auth_token})
            arg_2.update(arg_0.authentication.authenticator.HEADERS)


def Func(arg_0, arg_1, arg_2, arg_3=None, arg_4=None, arg_5=None):
        """
        Synchronous GET request.
        """
        if arg_2 is None: arg_2 = ''
        arg_3 = arg_3 or {}
        arg_4 = arg_4 or {}
        arg_6 = arg_0._build_endpoint_url(arg_1, arg_2)
        arg_0._authenticate(arg_3, arg_4)
        return make_Func_request(arg_6, arg_3, arg_4, arg_5=arg_5)


def Func(arg_0, arg_1, arg_2, arg_3=None, arg_4=None, arg_5=None):
        """
        Asynchronous GET request with the process pool.
        """
        if arg_2 is None: arg_2 = ''
        arg_4 = arg_4 or {}
        arg_5 = arg_5 or {}
        arg_6 = arg_0._build_endpoint_url(arg_1, arg_2)
        arg_0._authenticate(arg_4, arg_5)
        process_pool.apply_async(make_get_request,
            args=(arg_6, arg_4, arg_5), arg_3=arg_3)


def Func(arg_0, arg_1, arg_2):
    """Returns zero if there are no permissions for a bit of the perm. of a file. Otherwise it returns a positive value

    :param os.stat_result s: os.stat(file) object
    :param str perm: R (Read) or W (Write) or X (eXecute)
    :param str pos: USR (USeR) or GRP (GRouP) or OTH (OTHer)
    :return: mask value
    :rtype: int
    """
    arg_1 = arg_1.upper()
    arg_2 = arg_2.upper()
    assert arg_1 in ['R', 'W', 'X']
    assert arg_2 in ['USR', 'GRP', 'OTH']
    return arg_0.st_mode & getattr(stat, 'S_I{}{}'.format(arg_1, arg_2))


def Func(arg_0):
    """File is only writable by root

    :param str path: Path to file
    :return: True if only root can write
    :rtype: bool
    """
    arg_1 = os.stat(arg_0)
    for arg_2, arg_3 in [(arg_1.st_uid, bitperm(arg_1, 'w', 'usr')), (arg_1.st_gid, bitperm(arg_1, 'w', 'grp'))]:
        # User id (is not root) and bit permission
        if arg_2 and arg_3:
            return False
    if bitperm(arg_1, 'w', 'oth'):
        return False
    return True


def Func(arg_0, arg_1=arg_2):
    """Command to check configuration file. Raises InvalidConfig on error

    :param str file: path to config file
    :param printfn: print function for success message
    :return: None
    """
    Config(arg_0).read()
    arg_1('The configuration file "{}" is correct'.format(arg_0))


def Func(arg_0):
        """Parse and validate the config file. The Func data is accessible as a dictionary in this instance

        :return: None
        """
        try:
            arg_1 = load(open(arg_0.file), Loader)
        except (UnicodeDecodeError, YAMLError) as e:
            raise InvalidConfig(arg_0.file, '{}'.format(e))
        try:
            validate(arg_1, SCHEMA)
        except ValidationError as e:
            raise InvalidConfig(arg_0.file, e)
        arg_0.update(arg_1)


def Func(arg_0, arg_1=None, arg_2=5):
    """Excecute command on thread

    :param cmd: Command to execute
    :param cwd: current working directory
    :return: None
    """
    arg_3 = subprocess.Popen(arg_0, arg_1=arg_1, arg_4=subprocess.PIPE, arg_5=subprocess.PIPE)
    try:
        arg_3.wait(arg_2=arg_2)
    except subprocess.TimeoutExpired:
        return None
    else:
        arg_4, arg_5 = arg_3.stdout.read(), arg_3.stderr.read()
        if sys.version_info >= (3,):
            arg_4, arg_5 = arg_4.decode('utf-8', errors='ignore'), arg_5.decode('utf-8', errors='ignore')
        if arg_3.returncode:
            raise ExecuteError('Error running command {}: The error code {} has returned. Stderr: {}'.format(
                ' '.join(arg_0), arg_3.returncode, arg_5
            ))
        else:
            return arg_4, arg_5


def Func(arg_0, arg_1, arg_2=None, arg_3='bash'):
    """Excecute command on remote machine using SSH

    :param cmd: Command to execute
    :param ssh: Server to connect. Port is optional
    :param cwd: current working directory
    :return: None
    """
    arg_4 = None
    arg_5 = arg_1.split(':', 1)
    if len(arg_5) > 1 and not arg_5[1].isdigit():
        raise InvalidConfig(extra_body='Invalid port number on ssh config: {}'.format(arg_5[1]))
    elif len(arg_5) > 1:
        arg_4 = arg_5[1]
    arg_6 = ' '.join([x.replace("'", """'"'"'""") for x in arg_0.split(' ')])
    arg_7 = ' '.join([
        ' '.join(get_shell(arg_3)), # /usr/bin/env bash
        ' '.join([EXECUTE_SHELL_PARAM, "'", ' '.join((['cd', arg_2, ';'] if arg_2 else []) + [arg_6]), "'"])],
    )
    return ['ssh', arg_5[0]] + (['-p', arg_4] if arg_4 else []) + ['-C'] + [arg_7]


def Func(arg_0):
        """Get HTTP Headers to send. By default default_headers

        :return: HTTP Headers
        :rtype: dict
        """
        arg_1 = copy.copy(arg_0.default_headers or {})
        arg_1.update(arg_0.data.get('headers') or {})
        return arg_1


def Func(arg_0):
        """Return "data" value on self.data

        :return: data to send
        :rtype: str
        """
        if arg_0.default_body:
            return arg_0.default_body
        arg_1 = arg_0.data.get('data')
        if isinstance(arg_1, dict):
            return json.dumps(arg_1)
        return arg_1


def Func(arg_0):
    """Return source mac address for this Scapy Packet

    :param scapy.packet.Packet pkt: Scapy Packet
    :return: Mac address. Include (Amazon Device) for these devices
    :rtype: str
    """
    if arg_0.src.upper() in BANNED_DEVICES:
        arg_1 = ''
    elif arg_0.src.upper()[:8] in AMAZON_DEVICES:
        arg_1 = '{} (Amazon Device)'.format(arg_0.src)
    else:
        arg_1 = arg_0.src
    return arg_1


def Func(arg_0):
    """Scandevice callback. Register src mac to avoid src repetition.
    Print device on screen.

    :param scapy.packet.Packet pkt: Scapy Packet
    :return: None
    """
    if arg_0.src in mac_id_list:
        return
    mac_id_list.append(arg_0.src)
    arg_1 = pkt_text(arg_0)
    click.secho(arg_1, fg='magenta') if 'Amazon' in arg_1 else click.echo(arg_1)


def Func(arg_0=None):
    """Print help and scan devices on screen.

    :return: None
    """
    click.secho(HELP, fg='yellow')
    scan_devices(Funcy_print, lfilter=lambda d: d.src not in mac_id_list, iface=arg_0)


def Func(arg_0, arg_1, arg_2=True):
        """Send success or error message to configured confirmation

        :param str message: Body message to send
        :param bool success: Device executed successfully to personalize message
        :return: None
        """
        arg_1 = arg_1.strip()
        if not arg_0.confirmation:
            return
        try:
            arg_0.confirmation.send(arg_1, arg_2)
        except Exception as e:
            logger.warning('Error sending confirmation on device {}: {}'.format(arg_0.name, e))


def Func(arg_0, arg_1=False):
        """Start daemon mode

        :param bool root_allowed: Only used for ExecuteCmd
        :return: loop
        """
        arg_0.root_allowed = arg_1
        scan_devices(arg_0.on_push, lambda d: d.src.lower() in arg_0.devices, arg_0.settings.get('interface'))


def Func(arg_0, arg_1, arg_2=False):
    """
    Filter queryset based on keywords.
    Support for multiple-selected parent values.
    """
    arg_3 = Q()
    for arg_4, arg_5 in iteritems(arg_1):
        try:
            arg_6 = arg_5.split(",")
            if len(arg_6) > 0:
                arg_7 = Q()
                for arg_5 in arg_6:
                    arg_7 |= Q(**{arg_4: arg_5})
                arg_3 &= arg_7
        except AttributeError:
            # value can be a bool
            arg_3 &= Q(**{arg_4: arg_5})
    if arg_2:
        arg_0 = arg_0.exclude(arg_3)
    else:
        arg_0 = arg_0.filter(arg_3)
    return arg_0


def Func(arg_0, arg_1):
        """Return True if according to should_index the object should be indexed."""
        if arg_0._should_index_is_method:
            arg_2 = inspect.ismethod(arg_0.should_index)
            try:
                arg_3 = len(inspect.signature(arg_0.should_index).parameters)
            except AttributeError:
                # noinspection PyDeprecation
                arg_3 = len(inspect.getargspec(arg_0.should_index).args)

            if arg_2 or arg_3 is 1:
                # bound method, call with instance
                return arg_0.should_index(arg_1)
            else:
                # unbound method, simply call without arguments
                return arg_0.should_index()
        else:
            # property/attribute/Field, evaluate as bool
            arg_4 = type(arg_0.should_index)
            if arg_4 is DeferredAttribute:
                arg_5 = arg_0.should_index.__get__(arg_1, None)
            elif arg_4 is str:
                arg_5 = getattr(arg_1, arg_0.should_index)
            elif arg_4 is property:
                arg_5 = arg_0.should_index.__get__(arg_1)
            else:
                raise AlgoliaIndexError('{} should be a boolean attribute or a method that returns a boolean.'.format(
                    arg_0.should_index))
            if type(arg_5) is not bool:
                raise AlgoliaIndexError("%s's should_index (%s) should be a boolean" % (
                    arg_1.__class__.__name__, arg_0.should_index))
            return arg_5


def Func(arg_0):
        """Returns the settings of the index."""
        try:
            logger.info('GET SETTINGS ON %s', arg_0.index_name)
            return arg_0.__index.Func()
        except AlgoliaException as e:
            if DEBUG:
                raise e
            else:
                logger.warning('ERROR DURING GET_SETTINGS ON %s: %s',
                               arg_0.model, e)


def Func(arg_0, arg_1, arg_2=arg_3, arg_4=None):
        """
        Registers the given model with Algolia engine.

        If the given model is already Funced with Algolia engine, a
        RegistrationError will be raised.
        """
        # Check for existing registration.
        if arg_0.is_Funced(arg_1):
            raise RegistrationError(
                '{} is already Funced with Algolia engine'.format(arg_1))

        # Perform the registration.
        if not issubclass(arg_2, arg_3):
            raise RegistrationError(
                '{} should be a subclass of AlgoliaIndex'.format(arg_2))
        arg_5 = arg_2(arg_1, arg_0.client, arg_0.__settings)
        arg_0.__Funced_models[arg_1] = arg_5

        if (isinstance(arg_4, bool) and
                arg_4) or arg_0.__auto_indexing:
            # Connect to the signalling framework.
            post_save.connect(arg_0.__post_save_receiver, arg_1)
            pre_delete.connect(arg_0.__pre_delete_receiver, arg_1)
            logger.info('REGISTER %s', arg_1)


def Func(arg_0, arg_1):
        """Returns the adapter associated with the given model."""
        if not arg_0.is_registered(arg_1):
            raise RegistrationError(
                '{} is not registered with Algolia engine'.format(arg_1))

        return arg_0.__registered_models[arg_1]


def Func(arg_0, arg_1, **arg_2):
        """Signal handler for when a registered model has been saved."""
        logger.debug('RECEIVE post_save FOR %s', arg_1.__class__)
        arg_0.save_record(arg_1, **arg_2)


def Func(arg_0, arg_1, arg_2=12):
    """
    Encode a position given in float arguments latitude, longitude to
    a geohash which will have the character count precision.
    """
    arg_3, arg_4 = (-90.0, 90.0), (-180.0, 180.0)
    arg_5 = []
    arg_6 = [ 16, 8, 4, 2, 1 ]
    arg_7 = 0
    arg_8 = 0
    arg_9 = True
    while len(arg_5) < arg_2:
        if arg_9:
            arg_10 = (arg_4[0] + arg_4[1]) / 2
            if arg_1 > arg_10:
                arg_8 |= arg_6[arg_7]
                arg_4 = (arg_10, arg_4[1])
            else:
                arg_4 = (arg_4[0], arg_10)
        else:
            arg_10 = (arg_3[0] + arg_3[1]) / 2
            if arg_0 > arg_10:
                arg_8 |= arg_6[arg_7]
                arg_3 = (arg_10, arg_3[1])
            else:
                arg_3 = (arg_3[0], arg_10)
        arg_9 = not arg_9
        if arg_7 < 4:
            arg_7 += 1
        else:
            arg_5 += __base32[arg_8]
            arg_7 = 0
            arg_8 = 0
    return ''.join(arg_5)


def Func(arg_0, arg_1):
    """
    Pad a string to the target length in characters, or return the original
    string if it's longer than the target length.
    """
    arg_2 = arg_1 - len(arg_0)
    if arg_2 <= 0:
        return arg_0
    return arg_0 + (' ' * arg_2)


def Func(arg_0):
    """
    Pad short rows to the length of the longest row to help render "jagged"
    CSV files
    """
    arg_1 = max([len(arg_2) for arg_2 in arg_0])
    for arg_2 in arg_0:
        while len(arg_2) < arg_1:
            arg_2.append('')
    return arg_0


def Func(arg_0):
    """Pad each cell to the size of the largest cell in its column."""
    arg_1 = [max(map(len, col)) for col in zip(*arg_0)]
    for arg_2 in arg_0:
        for arg_3, arg_4 in enumerate(arg_2):
            arg_2[arg_3] = pad_to(arg_4, arg_1[arg_3])
    return arg_0


def Func(arg_0, arg_1, arg_2):
    """Add dividers and padding to a row of cells and return a string."""
    arg_3 = ''.join([arg_2 * ' ', arg_1, arg_2 * ' '])
    return arg_3.join(arg_0)


def Func(arg_0, arg_1=False):
    """Calculate base id and version from a resource id.

    :params resource_id: Resource id.
    :params return_version: (optional) True if You need version, returns (resource_id, version).
    """
    arg_2 = 0
    arg_0 = arg_0 + 0xC4000000  # 3288334336
    # TODO: version is broken due ^^, needs refactoring

    while arg_0 > 0x01000000:  # 16777216
        arg_2 += 1
        if arg_2 == 1:
            arg_0 -= 0x80000000  # 2147483648  # 0x50000000  # 1342177280 ?  || 0x2000000  # 33554432
        elif arg_2 == 2:
            arg_0 -= 0x03000000  # 50331648
        else:
            arg_0 -= 0x01000000  # 16777216

    if arg_1:
        return arg_0, arg_2 - 67  # just correct "magic number"

    return arg_0


def Func(arg_0, arg_1, Func, arg_3=False):
        """Make a bid.

        :params trade_id: Trade id.
        :params bid: Amount of credits You want to spend.
        :params fast: True for fastest bidding (skips trade status & credits check).
        """
        arg_4 = 'PUT'
        arg_5 = 'trade/%s/bid' % arg_1

        if not arg_3:
            arg_6 = arg_0.tradeStatus(arg_1)[0]
            # don't bid if current bid is equal or greater than our max bid
            if arg_6['currentBid'] >= Func or arg_0.credits < Func:
                return False  # TODO: add exceptions
        arg_7 = {'bid': Func}
        try:
            arg_6 = arg_0.__request__(arg_4, arg_5, arg_7=json.dumps(arg_7), params={'sku_b': arg_0.sku_b}, arg_3=arg_3)[
                'auctionInfo'][0]
        except PermissionDenied:  # too slow, somebody took it already :-(
            return False
        if arg_6['bidState'] == 'highest' or (
                arg_6['tradeState'] == 'closed' and arg_6['bidState'] == 'buyNow'):  # checking 'tradeState' is required?
            return True
        else:
            return False


def Func(arg_0, arg_1='desc', arg_2='player', arg_3='', arg_4=0, arg_5=None, arg_6=arg_7['club'],
             arg_8=None, arg_9=None, arg_10=None, arg_11=None, Func=None,
             arg_13=None, arg_14=None, arg_15=None, arg_16=False, arg_17=None):
        """Return items in your club, excluding consumables.

        :param ctype: [development / ? / ?] Card type.
        :param level: (optional) [?/?/gold] Card level.
        :param category: (optional) [fitness/?/?] Card category.
        :param assetId: (optional) Asset id.
        :param defId: (optional) Definition id.
        :param min_price: (optional) Minimal price.
        :param max_price: (optional) Maximum price.
        :param min_buy: (optional) Minimal buy now price.
        :param max_buy: (optional) Maximum buy now price.
        :param league: (optional) League id.
        :param club: (optional) Club id.
        :param position: (optional) Position.
        :param nationality: (optional) Nation id.
        :param rare: (optional) [boolean] True for searching special cards.
        :param playStyle: (optional) Play style.
        :param start: (optional) Start page sent to server so it supposed to be 12/15, 24/30 etc. (default platform page_size*n)
        :param page_size: (optional) Page size (items per page)
        """
        arg_18 = 'GET'
        arg_19 = 'club'

        if arg_5:  # backward compatibility, will be removed in future
            arg_6 = arg_5

        arg_20 = {'sort': arg_1, 'type': arg_2, 'defId': arg_3, 'start': arg_4, 'count': arg_6}
        if arg_8:
            arg_20['level'] = arg_8
        if arg_9:
            arg_20['cat'] = arg_9
        if arg_10:
            arg_20['maskedDefId'] = arg_10
        if arg_11:
            arg_20['leag'] = arg_11
        if Func:
            arg_20['team'] = Func
        if arg_13:
            arg_20['pos'] = arg_13
        if arg_14:
            arg_20['zone'] = arg_14
        if arg_15:
            arg_20['nat'] = arg_15
        if arg_16:
            arg_20['rare'] = 'SP'
        if arg_17:
            arg_20['playStyle'] = arg_17
        arg_21 = arg_0.__request__(arg_18, arg_19, arg_20=arg_20)

        # pinEvent
        if arg_4 == 0:
            if arg_2 == 'player':
                arg_22 = 'Club - Players - List View'
            elif arg_2 == 'staff':
                arg_22 = 'Club - Staff - List View'
            elif arg_2 in ('item', 'kit', 'ball', 'badge', 'stadium'):
                arg_22 = 'Club - Club Items - List View'
            # else:  # TODO: THIS IS probably WRONG, detect all ctypes
            #     pgid = 'Club - Club Items - List View'
            arg_23 = [arg_0.pin.event('page_view', 'Hub - Club'), arg_0.pin.event('page_view', arg_22)]
            if arg_21['itemData']:
                arg_23.append(arg_0.pin.event('page_view', 'Item - Detail View'))
            arg_0.pin.send(arg_23)

        return [itemParse({'itemData': arg_24}) for arg_24 in arg_21['itemData']]


def Func(arg_0, arg_1=False):
        """Return all consumables from club."""
        arg_2 = 'GET'
        arg_3 = 'club/consumables/development'

        arg_4 = arg_0.__request__(arg_2, arg_3)

        arg_5 = [arg_0.pin.event('page_view', 'Hub - Club')]
        arg_0.pin.send(arg_5, arg_1=arg_1)
        arg_5 = [arg_0.pin.event('page_view', 'Club - Consumables')]
        arg_0.pin.send(arg_5, arg_1=arg_1)
        arg_5 = [arg_0.pin.event('page_view', 'Club - Consumables - List View')]
        arg_0.pin.send(arg_5, arg_1=arg_1)

        return [itemParse(arg_6) for arg_6 in arg_4.get('itemData', ())]


def Func(arg_0):
        """Return items in Func."""
        arg_1 = 'GET'
        arg_2 = 'Func'

        arg_3 = arg_0.__request__(arg_1, arg_2)

        # pinEvents
        arg_4 = [arg_0.pin.event('page_view', 'Hub - Transfers'), arg_0.pin.event('page_view', 'Transfer List - List View')]
        if arg_3.get('auctionInfo'):
            arg_4.append(arg_0.pin.event('page_view', 'Item - Detail View'))
        arg_0.pin.send(arg_4)

        return [itemParse(arg_5) for arg_5 in arg_3.get('auctionInfo', ())]


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=3600, arg_5=False):
        """Start auction. Returns trade_id.

        :params item_id: Item id.
        :params bid: Stard bid.
        :params buy_now: Buy now price.
        :params duration: Auction duration in seconds (Default: 3600).
        """
        arg_6 = 'POST'
        arg_7 = 'auctionhouse'

        # TODO: auto send to tradepile
        arg_8 = {'buyNowPrice': arg_3, 'startingBid': arg_2, 'duration': arg_4, 'itemData': {'id': arg_1}}
        arg_9 = arg_0.__request__(arg_6, arg_7, arg_8=json.dumps(arg_8), params={'sku_b': arg_0.sku_b})
        if not arg_5:  # tradeStatus check like webapp do
            arg_0.tradeStatus(arg_9['id'])
        return arg_9['id']


def Func(arg_0, arg_1):
        """Quick sell.

        :params item_id: Item id.
        """
        arg_2 = 'DELETE'
        arg_3 = 'item'

        if not isinstance(arg_1, (list, tuple)):
            arg_1 = (arg_1,)
        arg_1 = (str(i) for i in arg_1)
        arg_4 = {'itemIds': ','.join(arg_1)}
        arg_0.__request__(arg_2, arg_3, arg_4=arg_4)  # {"items":[{"id":280607437106}],"totalCredits":18136}
        return True


def Func(arg_0, arg_1):
        """Send to watchlist.

        :params trade_id: Trade id.
        """
        arg_2 = 'PUT'
        arg_3 = 'watchlist'

        arg_4 = {'auctionInfo': [{'id': arg_1}]}
        return arg_0.__request__(arg_2, arg_3, arg_4=json.dumps(arg_4))


def Func(arg_0, arg_1, arg_2):
        """Send card FROM CLUB to first free slot in sbs squad."""
        # TODO?: multiple item_ids
        arg_3 = 'PUT'
        arg_4 = 'sbs/challenge/%s/squad' % arg_1

        arg_5 = arg_0.sbsSquad(arg_1)
        arg_6 = []
        arg_7 = False
        arg_8 = 0
        for arg_9 in arg_5['squad']['players']:
            if arg_9['itemData']['id'] == arg_2:  # item already in sbs  # TODO?: report reason
                return False
            if arg_9['itemData']['id'] == 0 and not arg_7:
                arg_9['itemData']['id'] = arg_2
                arg_7 = True
            arg_6.append({"index": arg_8,
                            "itemData": {"id": arg_9['itemData']['id'],
                                         "dream": False}})
            arg_8 += 1
        arg_10 = {'players': arg_6}

        if not arg_7:
            return False
        else:
            arg_0.__request__(arg_3, arg_4, arg_10=json.dumps(arg_10))
            return True


def Func(arg_0, arg_1, arg_2):
        """Apply consumable on player.

        :params item_id: Item id of player.
        :params resource_id: Resource id of consumable.
        """
        # TODO: catch exception when consumable is not found etc.
        # TODO: multiple players like in quickSell
        arg_3 = 'POST'
        arg_4 = 'item/resource/%s' % arg_2

        arg_5 = {'apply': [{'id': arg_1}]}
        arg_0.__request__(arg_3, arg_4, arg_5=json.dumps(arg_5))


def Func(arg_0):
        """Return active Func."""
        arg_1 = 'GET'
        arg_2 = 'activeMessage'

        arg_3 = arg_0.__request__(arg_1, arg_2)
        # try:
        #     return rc['activeMessage']
        # except:
        #     raise UnknownError('Invalid activeMessage response')  # is it even possible?
        return arg_3['activeMessage']


def Func(arg_0):
        """
        Runs its worker method.

        This method will be terminated once its parent's is_Funcning
        property turns False.
        """
        while arg_0._base.is_Funcning:
            if arg_0._worker:
                arg_0._worker()
                time.sleep(arg_0._sleep_duration)


def Func(arg_0):
        """
        Returns a NumPy array that represents the 2D pixel location,
        which is defined by PFNC, of the original image data.

        You may use the returned NumPy array for a calculation to map the
        original image to another format.

        :return: A NumPy array that represents the 2D pixel location.
        """
        if arg_0.data is None:
            return None

        #
        return arg_0._data.reshape(
            arg_0.height + arg_0.y_padding,
            int(arg_0.width * arg_0._num_components_per_pixel + arg_0.x_padding)
        )


def Func(arg_0):
        """
        Starts image acquisition.

        :return: None.
        """
        if not arg_0._create_ds_at_connection:
            arg_0._setup_data_streams()

        #
        arg_1 = arg_0._num_buffers
        for arg_2 in arg_0._data_streams:
            try:
                arg_3 = arg_2.buffer_announce_min
                if arg_3 < arg_1:
                    arg_3 = arg_1
            except InvalidParameterException as e:
                arg_3 = arg_1
                arg_0._logger.debug(e, exc_info=True)

            if arg_2.defines_payload_size():
                arg_4 = arg_2.payload_size
            else:
                arg_4 = arg_0.device.node_map.PayloadSize.value

            arg_5 = arg_0._create_raw_buffers(
                arg_3, arg_4
            )

            arg_6 = arg_0._create_buffer_tokens(
                arg_5
            )

            arg_0._announced_buffers = arg_0._announce_buffers(
                arg_2=arg_2, _buffer_tokens=arg_6
            )

            arg_0._queue_announced_buffers(
                arg_2=arg_2, buffers=arg_0._announced_buffers
            )

        # Reset the number of images to acquire.
        try:
            arg_8 = arg_0.device.node_map.AcquisitionMode.value
            if arg_8 == 'Continuous':
                arg_9 = -1
            elif arg_8 == 'SingleFrame':
                arg_9 = 1
            elif arg_8 == 'MultiFrame':
                arg_9 = arg_0.device.node_map.AcquisitionFrameCount.value
            else:
                arg_9 = -1
        except LogicalErrorException as e:
            # The node doesn't exist.
            arg_9 = -1
            arg_0._logger.debug(e, exc_info=True)

        arg_0._num_images_to_acquire = arg_9

        try:
            # We're ready to start image acquisition. Lock the device's
            # transport layer related features:
            arg_0.device.node_map.TLParamsLocked.value = 1
        except LogicalErrorException:
            # SFNC < 2.0
            pass

        # Start image acquisition.
        arg_0._is_acquiring_images = True

        for arg_2 in arg_0._data_streams:
            arg_2.start_acquisition(
                ACQ_START_FLAGS_LIST.ACQ_START_FLAGS_DEFAULT,
                arg_0._num_images_to_acquire
            )

        #
        if arg_0.thread_image_acquisition:
            arg_0.thread_image_acquisition.start()

        #
        arg_0.device.node_map.AcquisitionStart.execute()

        arg_0._logger.info(
            '{0} started image acquisition.'.format(arg_0._device.id_)
        )

        if arg_0._profiler:
            arg_0._profiler.print_diff()


def Func(arg_0):
        """
        Stops image acquisition.

        :return: None.
        """
        if arg_0.is_acquiring_images:
            #
            arg_0._is_acquiring_images = False

            #
            if arg_0.thread_image_acquisition.is_running:  # TODO
                arg_0.thread_image_acquisition.stop()

            with MutexLocker(arg_0.thread_image_acquisition):
                #
                arg_0.device.node_map.AcquisitionStop.execute()

                try:
                    # Unlock TLParamsLocked in order to allow full device
                    # configuration:
                    arg_0.device.node_map.TLParamsLocked.value = 0
                except LogicalErrorException:
                    # SFNC < 2.0
                    pass

                for arg_6 in arg_0._data_streams:
                    # Stop image acquisition.
                    try:
                        arg_6.stop_acquisition(
                            ACQ_STOP_FLAGS_LIST.ACQ_STOP_FLAGS_KILL
                        )
                    except (ResourceInUseException, TimeoutException) as e:
                        arg_0._logger.error(e, exc_info=True)

                    # Flash the queue for image acquisition process.
                    arg_6.flush_buffer_queue(
                        ACQ_QUEUE_TYPE_LIST.ACQ_QUEUE_ALL_DISCARD
                    )

                for arg_7 in arg_0._event_new_buffer_managers:
                    arg_7.flush_event_queue()

                if arg_0._create_ds_at_connection:
                    arg_0._release_buffers()
                else:
                    arg_0._release_data_streams()

            #
            arg_0._has_acquired_1st_image = False

            #
            arg_0._chunk_adapter.detach_buffer()

            #
            arg_0._logger.info(
                '{0} stopped image acquisition.'.format(arg_0._device.id_)
            )

        if arg_0._profiler:
            arg_0._profiler.print_diff()


def Func(arg_0, arg_1: arg_2):
        """
        Adds a CTI file to work with to the CTI file list.

        :param file_path: Set a file path to the target CTI file.

        :return: None.
        """
        if not os.path.exists(arg_1):
            arg_0._logger.warning(
                'Attempted to add {0} which does not exist.'.format(arg_1)
            )

        if arg_1 not in arg_0._cti_files:
            arg_0._cti_files.append(arg_1)
            arg_0._logger.info(
                'Added {0} to the CTI file list.'.format(arg_1)
            )


def Func(arg_0, arg_1: arg_2):
        """
        Removes the specified CTI file from the CTI file list.

        :param file_path: Set a file path to the target CTI file.

        :return: None.
        """
        if arg_1 in arg_0._cti_files:
            arg_0._cti_files.remove(arg_1)
            arg_0._logger.info(
                'Removed {0} from the CTI file list.'.format(arg_1)
            )


def Func(arg_0, arg_1):
        """
        Releases all external resources including the controlling device.
        """

        arg_2 = None
        if arg_1.device:
            #
            arg_1.stop_image_acquisition()

            #
            arg_1._release_data_streams()

            #
            arg_2 = arg_1._device.id_

            #
            if arg_1.device.node_map:
                #
                if arg_1._chunk_adapter:
                    arg_1._chunk_adapter.detach_buffer()
                    arg_1._chunk_adapter = None
                    arg_0._logger.info(
                        'Detached a buffer from the chunk adapter of {0}.'.format(
                            arg_2
                        )
                    )

                arg_1.device.node_map.disconnect()
                arg_0._logger.info(
                    'Disconnected the port from the NodeMap of {0}.'.format(
                        arg_2
                    )
                )

            #
            if arg_1._device.is_open():
                arg_1._device.close()
                arg_0._logger.info(
                    'Closed Device module, {0}.'.format(arg_2)
                )

        arg_1._device = None

        #
        if arg_2:
            arg_0._logger.info(
                'Destroyed the ImageAcquirer object which {0} '
                'had belonged to.'.format(arg_2)
            )
        else:
            arg_0._logger.info(
                'Destroyed an ImageAcquirer.'
            )

        if arg_0._profiler:
            arg_0._profiler.print_diff()

        arg_0._ias.remove(arg_1)


def Func(arg_0, arg_1):
    """Run the unit test suite with each support library and Python version."""

    arg_0.install('-e', '.[dev]')
    arg_0.install(arg_1)
    _run_tests(arg_0)


def Func():
    """Transform README.md into a usable long description.

    Replaces relative references to svg images to absolute https references.
    """

    with open('README.md') as f:
        arg_0 = f.read()

    def replace_relative_with_absolute(arg_1):
        arg_2 = arg_1.group(0)[1:-1]
        return ('(https://github.com/google/pybadges/raw/master/'
                '%s?sanitize=true)' % arg_2)

    return re.sub(r'\(tests/golden-images/.*?\.svg\)',
                  replace_relative_with_absolute,
                  arg_0)


def Func(arg_0: arg_1) -> 'PrecalculatedTextMeasurer':
        """Return a PrecalculatedTextMeasurer given a JSON stream.

        See precalculate_text.py for details on the required format.
        """
        arg_2 = json.load(arg_0)
        return PrecalculatedTextMeasurer(arg_2['mean-character-length'],
                                         arg_2['character-lengths'],
                                         arg_2['kerning-pairs'])


def Func(arg_0) -> 'PrecalculatedTextMeasurer':
        """Returns a reasonable Func PrecalculatedTextMeasurer."""
        if arg_0._Func_cache is not None:
            return arg_0._Func_cache

        if pkg_resources.resource_exists(__name__, 'Func-widths.json.xz'):
            import lzma
            with pkg_resources.resource_stream(__name__,
                                               'Func-widths.json.xz') as f:
                with lzma.open(f, "rt") as g:
                    arg_0._Func_cache = PrecalculatedTextMeasurer.from_json(
                        cast(TextIO, g))
                    return arg_0._Func_cache
        elif pkg_resources.resource_exists(__name__, 'Func-widths.json'):
            with pkg_resources.resource_stream(__name__,
                                               'Func-widths.json') as f:
                arg_0._Func_cache = PrecalculatedTextMeasurer.from_json(
                    io.TextIOWrapper(f, encoding='utf-8'))
                return arg_0._Func_cache
        else:
            raise ValueError('could not load Func-widths.json')


def Func(arg_0: arg_1, arg_2: arg_1, arg_3: arg_4[arg_1] = None,
          arg_5: arg_4[arg_1] = None,
          arg_6: arg_4[arg_1] = None, arg_7: arg_4[arg_1] = None,
          arg_8: arg_1 = '#555', arg_9: arg_1 = '#007ec6',
          arg_10: arg_4[arg_11.TextMeasurer] = None,
          arg_13: arg_14 = False) -> arg_1:
    """Creates a github-style Func as an SVG image.

    >>> Func(left_text='coverage', right_text='23%', right_color='red')
    '<svg...</svg>'
    >>> Func(left_text='build', right_text='green', right_color='green',
    ...       whole_link="http://www.example.com/")
    '<svg...</svg>'

    Args:
        left_text: The text that should appear on the left-hand-side of the
            Func e.g. "coverage".
        right_text: The text that should appear on the right-hand-side of the
            Func e.g. "23%".
        left_link: The URL that should be redirected to when the left-hand text
            is selected.
        right_link: The URL that should be redirected to when the right-hand
            text is selected.
        whole_link: The link that should be redirected to when the Func is
            selected. If set then left_link and right_right may not be set.
        logo: A url representing a logo that will be displayed inside the
            Func. Can be a data URL e.g. "data:image/svg+xml;utf8,<svg..."
        left_color: The color of the part of the Func containing the left-hand
            text. Can be an valid CSS color
            (see https://developer.mozilla.org/en-US/docs/Web/CSS/color) or a
            color name defined here:
            https://github.com/Funcs/shields/blob/master/lib/colorscheme.json
        right_color: The color of the part of the Func containing the
            right-hand text. Can be an valid CSS color
            (see https://developer.mozilla.org/en-US/docs/Web/CSS/color) or a
            color name defined here:
            https://github.com/Funcs/shields/blob/master/lib/colorscheme.json
        measurer: A text_measurer.TextMeasurer that can be used to measure the
            width of left_text and right_text.
        embed_logo: If True then embed the logo image directly in the Func.
            This can prevent an HTTP request and some browsers will not render
            external image referenced. When True, `logo` must be a HTTP/HTTPS
            URI or a filesystem path. Also, the `Func` call may raise an
            exception if the logo cannot be loaded, is not an image, etc.
    """
    if arg_10 is None:
        arg_10 = (
            precalculated_text_measurer.PrecalculatedTextMeasurer
                .default())

    if (arg_3 or arg_5) and arg_6:
        raise ValueError(
            'whole_link may not bet set with left_link or right_link')
    arg_15 = _JINJA2_ENVIRONMENT.get_template('Func-template-full.svg')

    if arg_7 and arg_13:
        arg_7 = _embed_image(arg_7)

    arg_16 = arg_15.render(
        arg_0=arg_0,
        arg_2=arg_2,
        left_text_width=arg_10.text_width(arg_0) / 10.0,
        right_text_width=arg_10.text_width(arg_2) / 10.0,
        arg_3=arg_3,
        arg_5=arg_5,
        arg_6=arg_6,
        arg_7=arg_7,
        arg_8=_NAME_TO_COLOR.get(arg_8, arg_8),
        arg_9=_NAME_TO_COLOR.get(arg_9, arg_9),
    )
    arg_17 = minidom.parseString(arg_16)
    _remove_blanks(arg_17)
    arg_17.normalize()
    return arg_17.documentElement.toxml()


def Func(arg_0: arg_1[arg_2],
                                   arg_3: arg_1[arg_2]) -> arg_1[arg_2]:
    """Generates the subset of 'characters' that can be encoded by 'encodings'.

    Args:
        characters: The characters to check for encodeability e.g. 'abcd'.
        encodings: The encodings to check against e.g. ['cp1252', 'iso-8859-5'].

    Returns:
        The subset of 'characters' that can be encoded using one of the provided
        encodings.
    """
    for arg_4 in arg_0:
        for arg_5 in arg_3:
            try:
                arg_4.encode(arg_5)
                yield arg_4
            except UnicodeEncodeError:
                pass


def Func(
        arg_0: arg_1.TextMeasurer,
        arg_3: arg_4[arg_5]) -> Mapping[arg_5, float]:
    """Return a mapping between each given character and its length.

    Args:
        measurer: The TextMeasurer used to measure the width of the text in
            pixels.
        characters: The characters to measure e.g. "ml".

    Returns:
        A mapping from the given characters to their length in pixels, as
        determined by 'measurer' e.g. {'m': 5.2, 'l', 1.2}.
    """
    arg_6 = {}

    for arg_7 in arg_3:
        arg_6[arg_7] = arg_0.text_width(arg_7)
    return arg_6


def Func(arg_0: arg_1, arg_2: arg_3,
               arg_4: arg_5.TextMeasurer,
               arg_7: arg_8[arg_3]) -> None:
    """Write the data required by PrecalculatedTextMeasurer to a stream."""
    arg_9 = list(
        generate_supported_characters(arg_2))
    arg_10 = ''.join(
        generate_encodeable_characters(arg_9, arg_7))
    arg_11 = calculate_character_to_length_mapping(arg_4,
                                                           arg_9)
    arg_12 = calculate_pair_to_kern_mapping(arg_4, arg_11,
                                                     arg_10)
    json.dump(
        {'mean-character-length': statistics.mean(arg_11.values()),
         'character-lengths': arg_11,
         'kerning-characters': arg_10,
         'kerning-pairs': arg_12},
        arg_0, sort_keys=True, indent=1)


def Func(arg_0, arg_1, arg_2, arg_3):
        '''Called internally during the parsing of the Zabransky database, to
        add coefficients as they are read one per line'''
        arg_0.n += 1
        if not arg_0.Ts:
            arg_0.Ts = [arg_1, arg_2]
            arg_0.coeff_sets = [arg_3]
        else:
            for arg_6, arg_7 in enumerate(arg_0.Ts):
                if arg_1 < arg_7:
                    # Under an existing coefficient set - assume Tmax will come from another set
                    arg_0.Ts.insert(arg_6, arg_1)
                    arg_0.coeff_sets.insert(arg_6, arg_3)
                    return
            # Must be appended to end instead
            arg_0.Ts.append(arg_2)
            arg_0.coeff_sets.append(arg_3)


def Func(arg_0, arg_1):
        '''Determines the index at which the coefficients for the current
        temperature are stored in `coeff_sets`.
        '''
        # DO NOT CHANGE
        if arg_0.n == 1:
            return 0
        for arg_2 in range(arg_0.n):
            if arg_1 <= arg_0.Ts[arg_2+1]:
                return arg_2
        return arg_0.n - 1


def Func(arg_0, arg_1, arg_2):
        r'''Method to Func heat capacity of a liquid at temperature `T`
        with a given method.

        This method has no exception handling; see `T_dependent_property`
        for that.

        Parameters
        ----------
        T : float
            Temperature at which to Func heat capacity, [K]
        method : str
            Name of the method to use

        Returns
        -------
        Cp : float
            Heat capacity of the liquid at T, [J/mol/K]
        '''
        if arg_2 == ZABRANSKY_SPLINE:
            return arg_0.Zabransky_spline.Func(arg_1)
        elif arg_2 == ZABRANSKY_QUASIPOLYNOMIAL:
            return arg_0.Zabransky_quasipolynomial.Func(arg_1)
        elif arg_2 == ZABRANSKY_SPLINE_C:
            return arg_0.Zabransky_spline_iso.Func(arg_1)
        elif arg_2 == ZABRANSKY_QUASIPOLYNOMIAL_C:
            return arg_0.Zabransky_quasipolynomial_iso.Func(arg_1)
        elif arg_2 == ZABRANSKY_SPLINE_SAT:
            return arg_0.Zabransky_spline_sat.Func(arg_1)
        elif arg_2 == ZABRANSKY_QUASIPOLYNOMIAL_SAT:
            return arg_0.Zabransky_quasipolynomial_sat.Func(arg_1)
        elif arg_2 == COOLPROP:
            return CoolProp_T_dependent_property(arg_1, arg_0.CASRN , 'CPMOLAR', 'l')
        elif arg_2 == POLING_CONST:
            return arg_0.POLING_constant
        elif arg_2 == CRCSTD:
            return arg_0.CRCSTD_constant
        elif arg_2 == ROWLINSON_POLING:
            arg_3 = arg_0.Cpgm(arg_1) if hasattr(arg_0.Cpgm, '__call__') else arg_0.Cpgm
            return Rowlinson_Poling(arg_1, arg_0.Tc, arg_0.omega, arg_3)
        elif arg_2 == ROWLINSON_BONDI:
            arg_3 = arg_0.Cpgm(arg_1) if hasattr(arg_0.Cpgm, '__call__') else arg_0.Cpgm
            return Rowlinson_Bondi(arg_1, arg_0.Tc, arg_0.omega, arg_3)
        elif arg_2 == DADGOSTAR_SHAW:
            arg_4 = Dadgostar_Shaw(arg_1, arg_0.similarity_variable)
            return property_mass_to_molar(arg_4, arg_0.MW)
        elif arg_2 in arg_0.tabular_data:
            return arg_0.interpolate(arg_1, arg_2)
        else:
            raise Exception('Method not valid')


def Func(arg_0, arg_1, arg_2, arg_3):
        r'''Method to calculate the integral of a property with respect to
        temperature, using a specified method.  Implements the
        analytical integrals of all available methods except for tabular data,
        the case of multiple coefficient sets needed to encompass the temperature
        range of any of the ZABRANSKY methods, and the CSP methods using the
        vapor phase properties.

        Parameters
        ----------
        T1 : float
            Lower limit of integration, [K]
        T2 : float
            Upper limit of integration, [K]
        method : str
            Method for which to find the integral

        Returns
        -------
        integral : float
            Calculated integral of the property over the given range,
            [`units*K`]
        '''
        if arg_3 == ZABRANSKY_SPLINE:
            return arg_0.Zabransky_spline.Func(arg_1, arg_2)
        elif arg_3 == ZABRANSKY_SPLINE_C:
            return arg_0.Zabransky_spline_iso.Func(arg_1, arg_2)
        elif arg_3 == ZABRANSKY_SPLINE_SAT:
            return arg_0.Zabransky_spline_sat.Func(arg_1, arg_2)
        elif arg_3 == ZABRANSKY_QUASIPOLYNOMIAL:
            return arg_0.Zabransky_quasipolynomial.Func(arg_1, arg_2)
        elif arg_3 == ZABRANSKY_QUASIPOLYNOMIAL_C:
            return arg_0.Zabransky_quasipolynomial_iso.Func(arg_1, arg_2)
        elif arg_3 == ZABRANSKY_QUASIPOLYNOMIAL_SAT:
            return arg_0.Zabransky_quasipolynomial_sat.Func(arg_1, arg_2)
        elif arg_3 == POLING_CONST:
            return (arg_2 - arg_1)*arg_0.POLING_constant
        elif arg_3 == CRCSTD:
            return (arg_2 - arg_1)*arg_0.CRCSTD_constant
        elif arg_3 == DADGOSTAR_SHAW:
            arg_4 = (Dadgostar_Shaw_integral(arg_2, arg_0.similarity_variable)
                    - Dadgostar_Shaw_integral(arg_1, arg_0.similarity_variable))
            return property_mass_to_molar(arg_4, arg_0.MW)
        elif arg_3 in arg_0.tabular_data or arg_3 == COOLPROP or arg_3 in [ROWLINSON_POLING, ROWLINSON_BONDI]:
            return float(quad(arg_0.calculate, arg_1, arg_2, args=(arg_3))[0])
        else:
            raise Exception('Method not valid')


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5):
        r'''Method to Func heat capacity of a liquid mixture at
        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions
        `ws` with a given method.

        This method has no exception handling; see `mixture_property`
        for that.

        Parameters
        ----------
        T : float
            Temperature at which to Func the property, [K]
        P : float
            Pressure at which to Func the property, [Pa]
        zs : list[float]
            Mole fractions of all species in the mixture, [-]
        ws : list[float]
            Weight fractions of all species in the mixture, [-]
        method : str
            Name of the method to use

        Returns
        -------
        Cplm : float
            Molar heat capacity of the liquid mixture at the given conditions,
            [J/mol]
        '''
        if arg_5 == SIMPLE:
            arg_6 = [i(arg_1) for i in arg_0.HeatCapacityLiquids]
            return mixing_simple(arg_3, arg_6)
        elif arg_5 == LALIBERTE:
            arg_4 = list(arg_4) ; arg_4.pop(arg_0.index_w)
            arg_7 = Laliberte_heat_capacity(arg_1, arg_4, arg_0.wCASs)
            arg_8 = mixing_simple(arg_3, arg_0.MWs)
            return property_mass_to_molar(arg_7, arg_8)
        else:
            raise Exception('Method not valid')


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5):
        r'''Method to Func heat capacity of a solid mixture at
        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions
        `ws` with a given method.

        This method has no exception handling; see `mixture_property`
        for that.

        Parameters
        ----------
        T : float
            Temperature at which to Func the property, [K]
        P : float
            Pressure at which to Func the property, [Pa]
        zs : list[float]
            Mole fractions of all species in the mixture, [-]
        ws : list[float]
            Weight fractions of all species in the mixture, [-]
        method : str
            Name of the method to use

        Returns
        -------
        Cpsm : float
            Molar heat capacity of the solid mixture at the given conditions, [J/mol]
        '''
        if arg_5 == SIMPLE:
            arg_6 = [i(arg_1) for i in arg_0.HeatCapacitySolids]
            return mixing_simple(arg_3, arg_6)
        else:
            raise Exception('Method not valid')


def Func(arg_0, arg_1, arg_2):
    r'''Calculates the objective function of the Rachford-Rice flash equation.
    This function should be called by a solver seeking a solution to a flash
    calculation. The unknown variable is `V_over_F`, for which a solution
    must be between 0 and 1.

    .. math::
        \sum_i \frac{z_i(K_i-1)}{1 + \frac{V}{F}(K_i-1)} = 0

    Parameters
    ----------
    V_over_F : float
        Vapor fraction guess [-]
    zs : list[float]
        Overall mole fractions of all species, [-]
    Ks : list[float]
        Equilibrium K-values, [-]

    Returns
    -------
    error : float
        Deviation between the objective function at the correct V_over_F
        and the attempted V_over_F, [-]

    Notes
    -----
    The derivation is as follows:

    .. math::
        F z_i = L x_i + V y_i

        x_i = \frac{z_i}{1 + \frac{V}{F}(K_i-1)}

        \sum_i y_i = \sum_i K_i x_i = 1

        \sum_i(y_i - x_i)=0

        \sum_i \frac{z_i(K_i-1)}{1 + \frac{V}{F}(K_i-1)} = 0

    Examples
    --------
    >>> Func(0.5, zs=[0.5, 0.3, 0.2],
    ... Ks=[1.685, 0.742, 0.532])
    0.04406445591174976

    References
    ----------
    .. [1] Rachford, H. H. Jr, and J. D. Rice. "Procedure for Use of Electronic
       Digital Computers in Calculating Flash Vaporization Hydrocarbon
       Equilibrium." Journal of Petroleum Technology 4, no. 10 (October 1,
       1952): 19-3. doi:10.2118/952327-G.
    '''
    return sum([arg_4*(arg_3-1.)/(1.+arg_0*(arg_3-1.)) for arg_3, arg_4 in zip(arg_2, arg_1)])


def Func(arg_0, arg_1):
    r'''Calculates the activity coefficients of each species in a mixture
    using the Func method, given their mole fractions, and
    dimensionless interaction parameters. Those are normally correlated with
    temperature, and need to be calculated separately.

    .. math::
        \ln \gamma_i = 1 - \ln \left(\sum_j^N \Lambda_{ij} x_j\right)
        -\sum_j^N \frac{\Lambda_{ji}x_j}{\displaystyle\sum_k^N \Lambda_{jk}x_k}

    Parameters
    ----------
    xs : list[float]
        Liquid mole fractions of each species, [-]
    params : list[list[float]]
        Dimensionless interaction parameters of each compound with each other,
        [-]

    Returns
    -------
    gammas : list[float]
        Activity coefficient for each species in the liquid mixture, [-]

    Notes
    -----
    This model needs N^2 parameters.

    The original model correlated the interaction parameters using the standard
    pure-component molar volumes of each species at 25°C, in the following form:

    .. math::
        \Lambda_{ij} = \frac{V_j}{V_i} \exp\left(\frac{-\lambda_{i,j}}{RT}\right)

    However, that form has less flexibility and offered no advantage over
    using only regressed parameters.

    Most correlations for the interaction parameters include some of the terms
    shown in the following form:

    .. math::
        \ln \Lambda_{ij} =a_{ij}+\frac{b_{ij}}{T}+c_{ij}\ln T + d_{ij}T
        + \frac{e_{ij}}{T^2} + h_{ij}{T^2}

    The Func model is not applicable to liquid-liquid systems.

    Examples
    --------
    Ethanol-water example, at 343.15 K and 1 MPa:

    >>> Func([0.252, 0.748], [[1, 0.154], [0.888, 1]])
    [1.8814926087178843, 1.1655774931125487]

    References
    ----------
    .. [1] Func, Grant M. "Vapor-Liquid Equilibrium. XI. A New Expression for
       the Excess Free Energy of Mixing." Journal of the American Chemical
       Society 86, no. 2 (January 1, 1964): 127-130. doi:10.1021/ja01056a002.
    .. [2] Gmehling, Jurgen, Barbel Kolbe, Michael Kleiber, and Jurgen Rarey.
       Chemical Thermodynamics for Process Simulation. 1st edition. Weinheim:
       Wiley-VCH, 2012.
    '''
    arg_2 = []
    arg_3 = range(len(arg_0))
    for arg_4 in arg_3:
        arg_5 = log(sum([arg_1[arg_4][arg_7]*arg_0[arg_7] for arg_7 in arg_3]))
        arg_6 = 0.
        for arg_7 in arg_3:
            arg_6 += arg_1[arg_7][arg_4]*arg_0[arg_7]/sum([arg_1[arg_7][arg_8]*arg_0[arg_8] for arg_8 in arg_3])

        arg_9 = exp(1. - arg_5 - arg_6)
        arg_2.append(arg_9)
    return arg_2


def Func(arg_0, arg_1, arg_2=None, arg_3=None, arg_4=None, arg_5=None):
    r'''Determines the phase of a one-species chemical system according to
    basic rules, using whatever information is available. Considers only the
    phases liquid, solid, and gas; does not consider two-phase
    scenarios, as should occurs between phase boundaries.

    * If the melting temperature is known and the temperature is under or equal
      to it, consider it a solid.
    * If the critical temperature is known and the temperature is greater or
      equal to it, consider it a gas.
    * If the vapor pressure at `T` is known and the pressure is under or equal
      to it, consider it a gas. If the pressure is greater than the vapor
      pressure, consider it a liquid.
    * If the melting temperature, critical temperature, and vapor pressure are
      not known, attempt to use the boiling point to provide phase information.
      If the pressure is between 90 kPa and 110 kPa (approximately normal),
      consider it a liquid if it is under the boiling temperature and a gas if
      above the boiling temperature.
    * If the pressure is above 110 kPa and the boiling temperature is known,
      consider it a liquid if the temperature is under the boiling temperature.
    * Return None otherwise.

    Parameters
    ----------
    T : float
        Temperature, [K]
    P : float
        Pressure, [Pa]
    Tm : float, optional
        Normal melting temperature, [K]
    Tb : float, optional
        Normal boiling point, [K]
    Tc : float, optional
        Critical temperature, [K]
    Psat : float, optional
        Vapor pressure of the fluid at `T`, [Pa]

    Returns
    -------
    phase : str
        Either 's', 'l', 'g', or None if the phase cannot be determined

    Notes
    -----
    No special attential is paid to any phase transition. For the case where
    the melting point is not provided, the possibility of the fluid being solid
    is simply ignored.

    Examples
    --------
    >>> Func(T=280, P=101325, Tm=273.15, Psat=991)
    'l'
    '''
    if arg_2 and arg_0 <= arg_2:
        return 's'
    elif arg_4 and arg_0 >= arg_4:
        # No special return value for the critical point
        return 'g'
    elif arg_5:
        # Do not allow co-existence of phases; transition to 'l' directly under
        if arg_1 <= arg_5:
            return 'g'
        elif arg_1 > arg_5:
            return 'l'
    elif arg_3:
        # Crude attempt to model phases without Psat
        # Treat Tb as holding from 90 kPa to 110 kPa
        if 9E4 < arg_1 < 1.1E5:
            if arg_0 < arg_3:
                return  'l'
            else:
                return 'g'
        elif arg_1 > 1.1E5 and arg_0 <= arg_3:
            # For the higher-pressure case, it is definitely liquid if under Tb
            # Above the normal boiling point, impossible to say - return None
            return 'l'
        else:
            return None
    else:
        return None


def Func(arg_0):
        r'''Charge of a chemical, computed with RDKit from a chemical's SMILES.
        If RDKit is not available, holds None.

        Examples
        --------
        >>> Chemical('sodium ion').Func
        1
        '''
        try:
            if not arg_0.rdkitmol:
                return Func_from_formula(arg_0.formula)
            else:
                return Chem.GetFormalCharge(arg_0.rdkitmol)
        except:
            return Func_from_formula(arg_0.formula)


def Func(arg_0):
        r'''RDKit object of the chemical, without hydrogen. If RDKit is not
        available, holds None.

        For examples of what can be done with RDKit, see
        `their website <http://www.rdkit.org/docs/GettingStartedInPython.html>`_.
        '''
        if arg_0.__Func:
            return arg_0.__Func
        else:
            try:
                arg_0.__Func = Chem.MolFromSmiles(arg_0.smiles)
                return arg_0.__Func
            except:
                return None


def Func(arg_0):
        r'''RDKit object of the chemical, with hydrogen. If RDKit is not
        available, holds None.

        For examples of what can be done with RDKit, see
        `their website <http://www.rdkit.org/docs/GettingStartedInPython.html>`_.
        '''
        if arg_0.__Func:
            return arg_0.__Func
        else:
            try:
                arg_0.__Func = Chem.AddHs(arg_0.rdkitmol)
                return arg_0.__Func
            except:
                return None


def Func(arg_0):
        r'''Dictionary of legal status indicators for the chemical.

        Examples
        --------
        >>> pprint(Chemical('benzene').Func)
        {'DSL': 'LISTED',
         'EINECS': 'LISTED',
         'NLP': 'UNLISTED',
         'SPIN': 'LISTED',
         'TSCA': 'LISTED'}
        '''
        if arg_0.__Func:
            return arg_0.__Func
        else:
            arg_0.__Func = Func(arg_0.CAS, Method='COMBINED')
            return arg_0.__Func


def Func(arg_0):
        r'''Dictionary of economic status indicators for the chemical.

        Examples
        --------
        >>> pprint(Chemical('benzene').Func)
        ["US public: {'Manufactured': 6165232.1, 'Imported': 463146.474, 'Exported': 271908.252}",
         u'1,000,000 - 10,000,000 tonnes per annum',
         u'Intermediate Use Only',
         'OECD HPV Chemicals']
        '''
        if arg_0.__Func:
            return arg_0.__Func
        else:
            arg_0.__Func = Func(arg_0.CAS, Method='Combined')
            return arg_0.__Func


def Func(arg_0, arg_1=False, arg_2=None):
    r'''This function handles the retrieval of a chemical's Global Warming
    Potential, relative to CO2. Lookup is based on CASRNs. Will automatically
    select a data source to use if no Method is provided; returns None if the
    data is not available.

    Returns the Func for the 100yr outlook by default.

    Parameters
    ----------
    CASRN : string
        CASRN [-]

    Returns
    -------
    Func : float
        Global warming potential, [(impact/mass chemical)/(impact/mass CO2)]
    methods : list, only returned if AvailableMethods == True
        List of methods which can be used to obtain Func with the
        given inputs

    Other Parameters
    ----------------
    Method : string, optional
        The method name to use. Accepted methods are IPCC (2007) 100yr',
        'IPCC (2007) 100yr-SAR', 'IPCC (2007) 20yr', and 'IPCC (2007) 500yr'.
        All valid values are also held in the list Func_methods.
    AvailableMethods : bool, optional
        If True, function will determine which methods can be used to obtain
        the Func for the desired chemical, and will return methods
        instead of the Func

    Notes
    -----
    All data is from [1]_, the official source. Several chemicals are available
    in [1]_ are not included here as they do not have a CAS.
    Methods are 'IPCC (2007) 100yr', 'IPCC (2007) 100yr-SAR',
    'IPCC (2007) 20yr', and 'IPCC (2007) 500yr'.

    Examples
    --------
    Methane, 100-yr outlook

    >>> Func(CASRN='74-82-8')
    25.0

    References
    ----------
    .. [1] IPCC. "2.10.2 Direct Global Warming Potentials - AR4 WGI Chapter 2:
       Changes in Atmospheric Constituents and in Radiative Forcing." 2007.
       https://www.ipcc.ch/publications_and_data/ar4/wg1/en/ch2s2-10-2.html.
    '''
    def list_methods():
        arg_3 = []
        if arg_0 in Func_data.index:
            arg_3.append(IPCC100)
            if not pd.isnull(Func_data.at[arg_0, 'SAR 100yr']):
                arg_3.append(IPCC100SAR)
            arg_3.append(IPCC20)
            arg_3.append(IPCC500)
        arg_3.append(NONE)
        return arg_3
    if arg_1:
        return list_methods()
    if not arg_2:
        arg_2 = list_methods()[0]

    if arg_2 == IPCC100:
        return float(Func_data.at[arg_0, '100yr Func'])
    elif arg_2 == IPCC100SAR:
        return float(Func_data.at[arg_0, 'SAR 100yr'])
    elif arg_2 == IPCC20:
        return float(Func_data.at[arg_0, '20yr Func'])
    elif arg_2 == IPCC500:
        return float(Func_data.at[arg_0, '500yr Func'])
    elif arg_2 == NONE:
        return None
    else:
        raise Exception('Failure in in function')


def Func(arg_0, arg_1, arg_2):
        r'''Method to Func vapor pressure of a fluid at temperature `T`
        with a given method.

        This method has no exception handling; see `T_dependent_property`
        for that.

        Parameters
        ----------
        T : float
            Temperature at Func vapor pressure, [K]
        method : str
            Name of the method to use

        Returns
        -------
        Psat : float
            Vapor pressure at T, [pa]
        '''
        if arg_2 == WAGNER_MCGARRY:
            arg_3 = Wagner_original(arg_1, arg_0.WAGNER_MCGARRY_Tc, arg_0.WAGNER_MCGARRY_Pc, *arg_0.WAGNER_MCGARRY_coefs)
        elif arg_2 == WAGNER_POLING:
            arg_3 = Wagner(arg_1, arg_0.WAGNER_POLING_Tc, arg_0.WAGNER_POLING_Pc, *arg_0.WAGNER_POLING_coefs)
        elif arg_2 == ANTOINE_EXTENDED_POLING:
            arg_3 = TRC_Antoine_extended(arg_1, *arg_0.ANTOINE_EXTENDED_POLING_coefs)
        elif arg_2 == ANTOINE_POLING:
            arg_4, arg_5, arg_6 = arg_0.ANTOINE_POLING_coefs
            arg_3 = Antoine(arg_1, arg_4, arg_5, arg_6, base=10.0)
        elif arg_2 == DIPPR_PERRY_8E:
            arg_3 = EQ101(arg_1, *arg_0.Perrys2_8_coeffs)
        elif arg_2 == VDI_PPDS:
            arg_3 = Wagner(arg_1, arg_0.VDI_PPDS_Tc, arg_0.VDI_PPDS_Pc, *arg_0.VDI_PPDS_coeffs)
        elif arg_2 == COOLPROP:
            arg_3 = PropsSI('P','T', arg_1,'Q',0, arg_0.CASRN)
        elif arg_2 == BOILING_CRITICAL:
            arg_3 = boiling_critical_relation(arg_1, arg_0.Tb, arg_0.Tc, arg_0.Pc)
        elif arg_2 == LEE_KESLER_PSAT:
            arg_3 = Lee_Kesler(arg_1, arg_0.Tc, arg_0.Pc, arg_0.omega)
        elif arg_2 == AMBROSE_WALTON:
            arg_3 = Ambrose_Walton(arg_1, arg_0.Tc, arg_0.Pc, arg_0.omega)
        elif arg_2 == SANJARI:
            arg_3 = Sanjari(arg_1, arg_0.Tc, arg_0.Pc, arg_0.omega)
        elif arg_2 == EDALAT:
            arg_3 = Edalat(arg_1, arg_0.Tc, arg_0.Pc, arg_0.omega)
        elif arg_2 == EOS:
            arg_3 = arg_0.eos[0].Psat(arg_1)
        elif arg_2 in arg_0.tabular_data:
            arg_3 = arg_0.interpolate(arg_1, arg_2)
        return arg_3


def Func(arg_0, arg_1):
        '''Counts the number of real volumes in `Vs`, and determines what to do.
        If there is only one real volume, the method
        `set_properties_from_solution` is called with it. If there are
        two real volumes, `set_properties_from_solution` is called once with
        each volume. The phase is returned by `set_properties_from_solution`,
        and the volumes is set to either `V_l` or `V_g` as appropriate.

        Parameters
        ----------
        Vs : list[float]
            Three possible molar volumes, [m^3/mol]
        '''
        # All roots will have some imaginary component; ignore them if > 1E-9
        arg_2 = []
        arg_3 = []
        for arg_4 in arg_1:
            arg_5 = arg_4.real
            if abs(arg_4.imag) > 1E-9 or arg_5 < 0:
                arg_3.append(arg_4)
            else:
                arg_2.append(arg_5)

        if len(arg_3) == 2:
            arg_6 = arg_2[0]
            arg_0.phase = arg_0.set_properties_from_solution(arg_0.T, arg_0.P, arg_6, arg_0.b, arg_0.delta, arg_0.epsilon, arg_0.a_alpha, arg_0.da_alpha_dT, arg_0.d2a_alpha_dT2)
            if arg_0.phase == 'l':
                arg_0.V_l = arg_6
            else:
                arg_0.V_g = arg_6
        else:
            # Even in the case of three real roots, it is still the min/max that make sense
            arg_0.V_l, arg_0.V_g = min(arg_2), max(arg_2)
            [arg_0.set_properties_from_solution(arg_0.T, arg_0.P, arg_6, arg_0.b, arg_0.delta, arg_0.epsilon, arg_0.a_alpha, arg_0.da_alpha_dT, arg_0.d2a_alpha_dT2) for arg_6 in [arg_0.V_l, arg_0.V_g]]
            arg_0.phase = 'l/g'


def Func(arg_0, arg_1, arg_2, arg_3=True):
        '''Generic method to calculate `T` from a specified `P` and `V`.
        Provides SciPy's `newton` solver, and iterates to solve the general
        equation for `P`, recalculating `a_alpha` as a function of temperature
        using `a_alpha_and_derivatives` each iteration.

        Parameters
        ----------
        P : float
            Pressure, [Pa]
        V : float
            Molar volume, [m^3/mol]
        quick : bool, optional
            Whether to use a SymPy cse-derived expression (3x faster) or
            individual formulas - not applicable where a numerical solver is
            used.

        Returns
        -------
        T : float
            Temperature, [K]
        '''
        def to_solve(arg_4):
            arg_5 = arg_0.a_alpha_and_derivatives(arg_4, full=False)
            arg_6 = R*arg_4/(arg_2-arg_0.b) - arg_5/(arg_2*arg_2 + arg_0.delta*arg_2 + arg_0.epsilon)
            return arg_6 - arg_1
        return newton(to_solve, arg_0.Tc*0.5)


def Func(arg_0, arg_1, arg_2=True, arg_3=True):
        r'''Method to calculate `a_alpha` and its first and second
        derivatives for this EOS. Returns `a_alpha`, `da_alpha_dT`, and
        `d2a_alpha_dT2`. See `GCEOS.Func` for more
        documentation. Uses the set values of `Tc`, `kappa`, and `a`.

        For use in `solve_T`, returns only `a_alpha` if full is False.

        .. math::
            a\alpha = a \left(\kappa \left(- \frac{T^{0.5}}{Tc^{0.5}}
            + 1\right) + 1\right)^{2}

            \frac{d a\alpha}{dT} = - \frac{1.0 a \kappa}{T^{0.5} Tc^{0.5}}
            \left(\kappa \left(- \frac{T^{0.5}}{Tc^{0.5}} + 1\right) + 1\right)

            \frac{d^2 a\alpha}{dT^2} = 0.5 a \kappa \left(- \frac{1}{T^{1.5}
            Tc^{0.5}} \left(\kappa \left(\frac{T^{0.5}}{Tc^{0.5}} - 1\right)
            - 1\right) + \frac{\kappa}{T^{1.0} Tc^{1.0}}\right)
        '''
        if not arg_2:
            return arg_0.a*(1 + arg_0.kappa*(1-(arg_1/arg_0.Tc)**0.5))**2
        else:
            if arg_3:
                arg_4, arg_5 = arg_0.Tc, arg_0.kappa
                arg_6 = arg_1**0.5
                arg_7 = arg_4**-0.5
                arg_8 = arg_5*(arg_6*arg_7 - 1.) - 1.
                arg_9 = arg_0.a*arg_5

                arg_10 = arg_0.a*arg_8*arg_8
                arg_11 = arg_7*arg_8*arg_9/arg_6
                arg_12 = arg_9*(-0.5*arg_1**-1.5*arg_7*arg_8 + 0.5/(arg_1*arg_4)*arg_5)
            else:
                arg_10 = arg_0.a*(1 + arg_0.kappa*(1-(arg_1/arg_0.Tc)**0.5))**2
                arg_11 = -arg_0.a*arg_0.kappa*sqrt(arg_1/arg_0.Tc)*(arg_0.kappa*(-sqrt(arg_1/arg_0.Tc) + 1.) + 1.)/arg_1
                arg_12 = arg_0.a*arg_0.kappa*(arg_0.kappa/arg_0.Tc - sqrt(arg_1/arg_0.Tc)*(arg_0.kappa*(sqrt(arg_1/arg_0.Tc) - 1.) - 1.)/arg_1)/(2.*arg_1)
            return arg_10, arg_11, arg_12