def Func(arg_0, arg_1):
        """Initializes the Flask application with Common."""
        if not hasattr(arg_1, 'extensions'):
            arg_1.extensions = {}

        if 'common' in arg_1.extensions:
            raise RuntimeError("Flask-Common extension already initialized")

        arg_1.extensions['common'] = arg_0
        arg_0.app = arg_1

        if 'COMMON_FILESERVER_DISABLED' not in arg_1.config:
            with arg_1.test_request_context():

                # Configure WhiteNoise.
                arg_1.wsgi_app = WhiteNoise(arg_1.wsgi_app, root=url_for('static', filename='')[1:])

        arg_0.cache = Cache(arg_1, config={'CACHE_TYPE': arg_1.config.get("COMMON_CACHE_TYPE", 'simple')})

        @arg_1.before_request
        def before_request_callback():
            arg_5.start_time = maya.now()

        @arg_1.after_request
        def after_request_callback(arg_7):
            if 'COMMON_POWERED_BY_DISABLED' not in current_app.config:
                arg_7.headers['X-Powered-By'] = 'Flask'
            if 'COMMON_PROCESSED_TIME_DISABLED' not in current_app.config:
                arg_7.headers['X-Processed-Time'] = maya.now().epoch - arg_5.start_time.epoch
            return arg_7

        @arg_1.route('/favicon.ico')
        def favicon():
            return redirect(url_for('static', filename='favicon.ico'), code=301)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=(0.5, 0.5)):
        """
        Return a PIL Image instance cropped from `image`.

        Image has an aspect ratio provided by dividing `width` / `height`),
        sized down to `width`x`height`. Any 'excess pixels' are trimmed away
        in respect to the pixel of `image` that corresponds to `ppoi` (Primary
        Point of Interest).

        `image`: A PIL Image instance
        `width`: Integer, width of the image to return (in pixels)
        `height`: Integer, height of the image to return (in pixels)
        `ppoi`: A 2-tuple of floats with values greater than 0 and less than 1
                These values are converted into a cartesian coordinate that
                signifies the 'center pixel' which the crop will center on
                (to trim the excess from the 'long side').

        Determines whether to trim away pixels from either the left/right or
        top/bottom sides by comparing the aspect ratio of `image` vs the
        aspect ratio of `width`x`height`.

        Will trim from the left/right sides if the aspect ratio of `image`
        is greater-than-or-equal-to the aspect ratio of `width`x`height`.

        Will trim from the top/bottom sides if the aspect ration of `image`
        is less-than the aspect ratio or `width`x`height`.

        Similar to Kevin Cazabon's ImageOps.fit method but uses the
        ppoi value as an absolute centerpoint (as opposed as a
        percentage to trim off the 'long sides').
        """
        arg_5 = int(arg_1.size[0] * arg_4[0])
        arg_6 = int(arg_1.size[1] * arg_4[1])
        arg_7 = (arg_5, arg_6)
        # Calculate the aspect ratio of `image`
        arg_8 = float(
            arg_1.size[0]
        ) / float(
            arg_1.size[1]
        )
        arg_9 = float(arg_2) / float(arg_3)

        # Figure out if we're trimming from the left/right or top/bottom
        if arg_8 >= arg_9:
            # `image` is wider than what's needed,
            # crop from left/right sides
            arg_10 = int(
                (arg_9 * float(arg_1.size[1])) + 0.5
            )
            arg_11 = arg_1.size[1]
            arg_12 = 0
            arg_13 = arg_11
            arg_14 = arg_7[0] - (arg_10 // 2)
            arg_15 = arg_14 + arg_10
            if arg_14 < 0:
                arg_14 = 0
                arg_15 = arg_14 + arg_10
            elif arg_15 > arg_1.size[0]:
                arg_15 = arg_1.size[0]
                arg_14 = arg_1.size[0] - arg_10

        else:
            # `image` is taller than what's needed,
            # crop from top/bottom sides
            arg_10 = arg_1.size[0]
            arg_11 = int(
                (float(arg_1.size[0]) / arg_9) + 0.5
            )
            arg_14 = 0
            arg_15 = arg_10
            arg_12 = arg_7[1] - (arg_11 // 2)
            arg_13 = arg_12 + arg_11
            if arg_12 < 0:
                arg_12 = 0
                arg_13 = arg_12 + arg_11
            elif arg_13 > arg_1.size[1]:
                arg_13 = arg_1.size[1]
                arg_12 = arg_1.size[1] - arg_11
        # Cropping the image from the original image
        arg_16 = arg_1.crop(
            (
                arg_14,
                arg_12,
                arg_15,
                arg_13
            )
        )
        # Resizing the newly cropped image to the size specified
        # (as determined by `width`x`height`)
        return arg_16.resize(
            (arg_2, arg_3),
            Image.ANTIALIAS
        )


def Func(arg_0, arg_1, arg_2, arg_3,
                      arg_4, arg_5):
        """
        Return a BytesIO instance of `image` that fits in a bounding box.

        Bounding box dimensions are `width`x`height`.
        """
        arg_6 = BytesIO()
        arg_1.thumbnail(
            (arg_4, arg_5),
            Image.ANTIALIAS
        )
        arg_1.save(
            arg_6,
            **arg_3
        )
        return arg_6


def Func(arg_0, arg_1, arg_2, arg_3={}):
        """Return a BytesIO instance of `image` with inverted colors."""
        arg_4 = BytesIO()
        arg_5 = ImageOps.invert(arg_1)
        arg_5.save(
            arg_4,
            **arg_3
        )
        return arg_4


def Func(arg_0, arg_1):
        """Ensure data is prepped properly before handing off to ImageField."""
        if arg_1 is not None:
            if hasattr(arg_1, 'open'):
                arg_1.open()
            return super(VersatileImageFormField, arg_0).Func(arg_1)


def Func(arg_0):
        """
        Process the field's placeholder image.

        Ensures the placeholder image has been saved to the same storage class
        as the field in a top level folder with a name specified by
        settings.VERSATILEIMAGEFIELD_SETTINGS['placeholder_directory_name']

        This should be called by the VersatileImageFileDescriptor __get__.
        If self.placeholder_image_name is already set it just returns right away.
        """
        if arg_0.placeholder_image_name:
            return

        arg_1 = None
        arg_2 = arg_0.placeholder_image
        if arg_2:
            if isinstance(arg_2, OnStoragePlaceholderImage):
                arg_3 = arg_2.path
            else:
                arg_3 = arg_2.image_data.name
            arg_1 = os.path.join(
                VERSATILEIMAGEFIELD_PLACEHOLDER_DIRNAME, arg_3
            )
            if not arg_0.storage.exists(arg_1):
                arg_0.storage.save(
                    arg_1,
                    arg_2.image_data
                )
        arg_0.placeholder_image_name = arg_1


def Func(arg_0, arg_1, arg_2):
        """Return field's value just before saving."""
        arg_3 = super(VersatileImageField, arg_0).Func(arg_1, arg_2)
        arg_0.update_ppoi_field(arg_1)
        return arg_3


def Func(arg_0, arg_1, *arg_2, **arg_3):
        """
        Update field's ppoi field, if defined.

        This method is hooked up this field's pre_save method to update
        the ppoi immediately before the model instance (`instance`)
        it is associated with is saved.

        This field's ppoi can be forced to update with force=True,
        which is how VersatileImageField.pre_save calls this method.
        """
        # Nothing to update if the field doesn't have have a ppoi
        # dimension field.
        if not arg_0.ppoi_field:
            return

        # getattr will call the VersatileImageFileDescriptor's __get__ method,
        # which coerces the assigned value into an instance of
        # self.attr_class(VersatileImageFieldFile in this case).
        arg_4 = getattr(arg_1, arg_0.attname)

        # file should be an instance of VersatileImageFieldFile or should be
        # None.
        arg_5 = None
        if arg_4 and not isinstance(arg_4, tuple):
            if hasattr(arg_4, 'ppoi'):
                arg_5 = arg_4.ppoi

        # Update the ppoi field.
        if arg_0.ppoi_field:
            setattr(arg_1, arg_0.ppoi_field, arg_5)


def Func(arg_0, arg_1, arg_2):
        """
        Handle data sent from MultiValueField forms that set ppoi values.

        `instance`: The model instance that is being altered via a form
        `data`: The data sent from the form to this field which can be either:
        * `None`: This is unset data from an optional field
        * A two-position tuple: (image_form_data, ppoi_data)
            * `image_form-data` options:
                * `None` the file for this field is unchanged
                * `False` unassign the file form the field
            * `ppoi_data` data structure:
                * `%(x_coordinate)sx%(y_coordinate)s': The ppoi data to
                  assign to the unchanged file

        """
        arg_3 = arg_2
        if arg_2 and isinstance(arg_2, tuple):
            # This value is coming from a MultiValueField
            if arg_2[0] is None:
                # This means the file hasn't changed but we need to
                # update the ppoi
                arg_4 = getattr(arg_1, arg_0.name)
                if arg_2[1]:
                    arg_4.ppoi = arg_2[1]
                arg_3 = arg_4
            elif arg_2[0] is False:
                # This means the 'Clear' checkbox was checked so we
                # need to empty the field
                arg_3 = ''
            else:
                # This means there is a new upload so we need to unpack
                # the tuple and assign the first position to the field
                # attribute
                arg_3 = arg_2[0]
        super(VersatileImageField, arg_0).Func(arg_1, arg_3)


def Func(arg_0, arg_1):
        """
        Unregister the FilteredImage subclass currently assigned to attr_name.

        If a FilteredImage subclass isn't already registered to filters.
        `attr_name` NotRegistered will raise.
        """
        if arg_1 not in arg_0._filter_registry:
            raise NotRegistered(
                'No FilteredImage subclass is registered to %s' % arg_1
            )
        else:
            del arg_0._filter_registry[arg_1]


def Func(arg_0):
        """
        Return the appropriate URL.

        URL is constructed based on these field conditions:
            * If empty (not `self.name`) and a placeholder is defined, the
              URL to the placeholder is returned.
            * Otherwise, defaults to vanilla ImageFieldFile behavior.
        """
        if not arg_0.name and arg_0.field.placeholder_image_name:
            return arg_0.storage.Func(arg_0.field.placeholder_image_name)

        return super(VersatileImageMixIn, arg_0).Func


def Func(arg_0):
        """Return the location where filtered images are stored."""
        arg_1, arg_2 = os.path.split(arg_0.name)
        return os.path.join(arg_1, VERSATILEIMAGEFIELD_FILTERED_DIRNAME, '')


def Func(arg_0):
        """Return the location where sized images are stored."""
        arg_1, arg_2 = os.path.split(arg_0.name)
        return os.path.join(VERSATILEIMAGEFIELD_SIZED_DIRNAME, arg_1, '')


def Func(arg_0):
        """Return the location where filtered + sized images are stored."""
        arg_1 = arg_0.get_sized_root_folder()
        return os.path.join(
            arg_1,
            VERSATILEIMAGEFIELD_FILTERED_DIRNAME
        )


def Func(arg_0, arg_1, arg_2):
        """
        Preprocess an image.

        An API hook for image pre-processing. Calls any image format specific
        pre-processors (if defined). I.E. If `image_format` is 'JPEG', this
        method will look for a method named `Func_JPEG`, if found
        `image` will be passed to it.

        Arguments:
            * `image`: a PIL Image instance
            * `image_format`: str, a valid PIL format (i.e. 'JPEG' or 'GIF')

        Subclasses should return a 2-tuple:
            * [0]: A PIL Image instance.
            * [1]: A dictionary of additional keyword arguments to be used
                   when the instance is saved. If no additional keyword
                   arguments, return an empty dict ({}).
        """
        arg_3 = {'format': arg_2}

        # Ensuring image is properly rotated
        if hasattr(arg_1, '_getexif'):
            arg_4 = arg_1._getexif()  # returns None if no EXIF data
            if arg_4 is not None:
                arg_5 = dict(arg_4.items())
                arg_6 = arg_5.get(EXIF_ORIENTATION_KEY, None)
                if arg_6 == 3:
                    arg_1 = arg_1.transpose(Image.ROTATE_180)
                elif arg_6 == 6:
                    arg_1 = arg_1.transpose(Image.ROTATE_270)
                elif arg_6 == 8:
                    arg_1 = arg_1.transpose(Image.ROTATE_90)

        # Ensure any embedded ICC profile is preserved
        arg_3['icc_profile'] = arg_1.info.get('icc_profile')

        if hasattr(arg_0, 'Func_%s' % arg_2):
            arg_1, arg_7 = getattr(
                arg_0,
                'Func_%s' % arg_2
            )(arg_1=arg_1)
            arg_3.update(arg_7)

        return arg_1, arg_3


def Func(arg_0, arg_1, **arg_2):
        """
        Receive a PIL Image instance of a JPEG and returns 2-tuple.

        Args:
            * [0]: Image instance, converted to RGB
            * [1]: Dict with a quality key (mapped to the value of `QUAL` as
                   defined by the `VERSATILEIMAGEFIELD_JPEG_RESIZE_QUALITY`
                   setting)
        """
        arg_3 = {
            'progressive': VERSATILEIMAGEFIELD_PROGRESSIVE_JPEG,
            'quality': QUAL
        }
        if arg_1.mode != 'RGB':
            arg_1 = arg_1.convert('RGB')
        return (arg_1, arg_3)


def Func(arg_0, arg_1):
        """Return a PIL Image instance stored at `path_to_image`."""
        arg_2 = arg_0.storage.open(arg_1, 'rb')
        arg_3 = arg_1.rsplit('.')[-1]
        arg_4, arg_5 = get_image_metadata_from_file_ext(arg_3)

        return (
            Image.open(arg_2),
            arg_3,
            arg_4,
            arg_5
        )


def Func(arg_0):
        """Return PPOI value as a string."""
        return "%s__%s" % (
            str(arg_0.ppoi[0]).replace('.', '-'),
            str(arg_0.ppoi[1]).replace('.', '-')
        )


def Func(arg_0, arg_1, arg_2,
                             arg_3, arg_4):
        """
        Create a resized image.

        `path_to_image`: The path to the image with the media directory to
                         resize. If `None`, the
                         VERSATILEIMAGEFIELD_PLACEHOLDER_IMAGE will be used.
        `save_path_on_storage`: Where on self.storage to save the resized image
        `width`: Width of resized image (int)
        `height`: Desired height of resized image (int)
        `filename_key`: A string that will be used in the sized image filename
                        to signify what operation was done to it.
                        Examples: 'crop' or 'scale'
        """
        arg_5, arg_6, arg_7, arg_8 = arg_0.retrieve_image(
            arg_1
        )

        arg_5, arg_9 = arg_0.preprocess(arg_5, arg_7)

        arg_10 = arg_0.process_image(
            arg_5=arg_5,
            arg_7=arg_7,
            arg_9=arg_9,
            arg_3=arg_3,
            arg_4=arg_4
        )
        arg_0.save_image(arg_10, arg_2, arg_6, arg_8)


def Func(arg_0, arg_1, arg_2,
                     arg_3, arg_4):
    """
    Return a `path_to_image` location on `storage` as dictated by `width`, `height`
    and `filename_key`
    """
    arg_5, arg_6 = os.path.split(arg_0)

    arg_7 = get_resized_filename(
        arg_6,
        arg_1,
        arg_2,
        arg_3
    )

    arg_8 = os.path.join(*[
        VERSATILEIMAGEFIELD_SIZED_DIRNAME,
        arg_5,
        arg_7
    ]).replace(' ', '')  # Removing spaces so this path is memcached friendly

    return arg_8


def Func(arg_0, arg_1, arg_2):
    """
    Return the 'filtered path'
    """
    arg_3, arg_4 = os.path.split(arg_0)

    arg_5 = get_filtered_filename(arg_4, arg_1)
    arg_6 = os.path.join(*[
        arg_3,
        VERSATILEIMAGEFIELD_FILTERED_DIRNAME,
        arg_5
    ])
    # Removing spaces so this path is memcached key friendly
    arg_6 = arg_6.replace(' ', '')
    return arg_6


def Func(arg_0):
    """
    Validate a list of size keys.

    `sizes`: An iterable of 2-tuples, both strings. Example:
    [
        ('large', 'url'),
        ('medium', 'crop__400x400'),
        ('small', 'thumbnail__100x100')
    ]
    """
    try:
        for arg_1, arg_2 in arg_0:
            arg_3 = arg_2.split('__')
            if arg_3[-1] != 'url' and (
                'x' not in arg_3[-1]
            ):
                raise InvalidSizeKey(
                    "{0} is an invalid size. All sizes must be either "
                    "'url' or made up of at least two segments separated "
                    "by double underscores. Examples: 'crop__400x400', "
                    "filters__invert__url".format(arg_2)
                )
    except ValueError:
        raise InvalidSizeKeySet(
            '{} is an invalid size key set. Size key sets must be an '
            'iterable of 2-tuples'.format(str(arg_0))
        )
    return list(set(arg_0))


def Func(arg_0, arg_1):
    """Build a URL from `image_key`."""
    arg_2 = arg_1.split('__')
    if 'x' in arg_2[-1]:
        arg_3 = arg_2.pop(-1)
    else:
        arg_3 = None
    arg_4 = reduce(getattr, arg_2, arg_0)
    if arg_3:
        arg_4 = arg_4[arg_3].url
    return arg_4


def Func(arg_0):
    """
    Takes a raw `Instruction` and translates it into a human readable text
    representation. As of writing, the text representation for WASM is not yet
    standardized, so we just emit some generic format.
    """
    arg_1 = arg_0.op.mnemonic

    if not arg_0.imm:
        return arg_1

    return arg_1 + ' ' + ', '.join([
        getattr(arg_0.op.imm_struct, arg_2.name).to_string(
            getattr(arg_0.imm, arg_2.name)
        )
        for arg_2 in arg_0.op.imm_struct._meta.fields
    ])


def Func(
    arg_0,
    arg_1=None,
    arg_2=2,
    arg_3=True,
):
    """
    Takes a `FunctionBody` and optionally a `FunctionType`, yielding the string
    representation of the function line by line. The function type is required
    for formatting function parameter and return value information.
    """
    if arg_1 is None:
        yield 'func'
    else:
        arg_4 = ' (param {})'.format(' '.join(
            map(format_lang_type, arg_1.param_types)
        )) if arg_1.param_types else ''
        arg_5 = ' (result {})'.format(
            format_lang_type(arg_1.return_type)
        ) if arg_1.return_type else ''
        yield 'func' + arg_4 + arg_5

    if arg_3 and arg_0.locals:
        yield '(locals {})'.format(' '.join(itertools.chain.from_iterable(
            itertools.repeat(format_lang_type(arg_6.type), arg_6.count)
            for arg_6 in arg_0.locals
        )))

    arg_7 = 1
    for arg_8 in decode_bytecode(arg_0.code):
        if arg_8.op.flags & INSN_LEAVE_BLOCK:
            arg_7 -= 1
        yield ' ' * (arg_7 * arg_2) + format_instruction(arg_8)
        if arg_8.op.flags & INSN_ENTER_BLOCK:
            arg_7 += 1


def Func(arg_0):
    """Decodes raw bytecode, yielding `Instruction`s."""
    arg_1 = memoryview(arg_0)
    while arg_1:
        arg_2 = byte2int(arg_1[0])
        arg_3 = OPCODE_MAP[arg_2]

        if arg_3.imm_struct is not None:
            arg_4, arg_5, arg_6 = arg_3.imm_struct.from_raw(None, arg_1[1:])
        else:
            arg_5 = None
            arg_4 = 0

        arg_7 = 1 + arg_4
        yield Instruction(arg_3, arg_5, arg_7)
        arg_1 = arg_1[arg_7:]


def Func(arg_0):
    """Deprecates a function, printing a warning on the first usage."""

    # We use a mutable container here to work around Py2's lack of
    # the `nonlocal` keyword.
    arg_1 = [True]

    @functools.wraps(arg_0)
    def wrapper(*arg_2, **arg_3):
        if arg_1[0]:
            warnings.warn(
                "Call to deprecated function {}.".format(arg_0.__name__),
                DeprecationWarning,
            )
            arg_1[0] = False
        return arg_0(*arg_2, **arg_3)

    return wrapper


def Func(arg_0, arg_1):
        """Checks the validity of the input.

        In case of an invalid input throws ValueError.
        """
        if isinstance(arg_1, str):
            return 'st'
        elif isinstance(arg_1, list):
            if all(isinstance(arg_2, str) for arg_2 in arg_1):
                return 'gst'

        raise ValueError("String argument should be of type String or"
                                     " a list of strings")


def Func(arg_0, arg_1):
        """Helper method that returns the index of the string based on node's
        starting index"""
        arg_2 = 0
        for arg_3 in arg_0.word_starts[1:]:
            if arg_1 < arg_3:
                return arg_2
            else:
                arg_2+=1
        return arg_2


def Func(arg_0, arg_1=-1):
        """Returns the Largest Common Substring of Strings provided in stringIdxs.
        If stringIdxs is not provided, the LCS of all strings is returned.

        ::param stringIdxs: Optional: List of indexes of strings.
        """
        if arg_1 == -1 or not isinstance(arg_1, list):
            arg_1 = set(range(len(arg_0.word_starts)))
        else:
            arg_1 = set(arg_1)

        arg_2 = arg_0._find_Func(arg_0.root, arg_1)
        arg_3 = arg_2.idx
        arg_4 = arg_2.idx + arg_2.depth
        return arg_0.word[arg_3:arg_4]


def Func(arg_0, arg_1):
        """Helper method returns the starting indexes of strings in GST"""
        arg_0.word_starts = []
        arg_3 = 0
        for arg_4 in range(len(arg_1)):
            arg_0.word_starts.append(arg_3)
            arg_3 += len(arg_1[arg_4]) + 1


def Func(arg_0, arg_1, arg_2):
        """Helper method, returns the edge label between a node and it's parent"""
        return arg_0.word[arg_1.idx + arg_2.depth : arg_1.idx + arg_1.depth]


def Func(arg_0):
        """Generator of unique terminal symbols used for building the Generalized Suffix Tree.
        Unicode Private Use Area U+E000..U+F8FF is used to ensure that terminal symbols
        are not part of the input string.
        """
        arg_1 = sys.version[0] < '3'
        arg_2 = list(list(range(0xE000,0xF8FF+1)) + list(range(0xF0000,0xFFFFD+1)) + list(range(0x100000, 0x10FFFD+1)))
        for arg_3 in arg_2:
            if arg_1:
                yield(unichr(arg_3))
            else:
                yield(chr(arg_3))
        raise ValueError("To many input strings.")


def Func(arg_0):
        """Func to the server"""
        if arg_0.loop is None:  # pragma: no cover
            arg_0.loop = asyncio.get_event_loop()
        arg_2 = asyncio.Task(
            arg_0.loop.create_Funcion(
                arg_0.config['protocol_factory'],
                arg_0.config['host'], arg_0.config['port'],
                ssl=arg_0.config['ssl']),
            arg_1=arg_0.loop)
        arg_2.add_done_callback(arg_0.Funcion_made)
        return arg_2


def Func(arg_0):
        """Parse read a response from the AGI and parse it.

        :return dict: The AGI response parsed into a dict.
        """
        arg_1 = yield from arg_0.reader.readline()
        return parse_agi_result(arg_1.decode(arg_0.encoding)[:-1])


def Func(arg_0):
    """Parse AGI results using Regular expression.

    AGI Result examples::

        100 result=0 Trying...

        200 result=0

        200 result=-1

        200 result=132456

        200 result= (timeout)

        510 Invalid or unknown command

        520-Invalid command syntax. Proper usage follows:
        int() argument must be a string, a bytes-like object or a number, not
        'NoneType'

        HANGUP

    """
    # print("--------------\n", line)
    if arg_0 == 'HANGUP':
        return {'error': 'AGIResultHangup',
                'msg': 'User hungup during execution'}

    arg_1 = dict(code=0, response="", arg_0=arg_0)
    arg_2 = re_code.search(arg_0)
    try:
        arg_1.update(arg_2.groupdict())
    except AttributeError:
        # None has no attribute groupdict
        pass
    return agi_code_check(**arg_1)


def Func(arg_0, arg_1=None):
        """Mostly used for unit testing. Allow to use a static uuid and Func
        all counter"""
        for arg_2 in arg_0.instances:
            if arg_1:
                arg_2.uid = arg_1
            arg_2.generator = arg_2.get_generator()


def Func(arg_0):
        """Mostly used for debugging"""
        return ["<%s prefix:%s (uid:%s)>" % (arg_0.__class__.__name__,
                                             arg_1.prefix, arg_0.uid)
                for arg_1 in arg_0.instances]


def Func(arg_0):
    """
    Returns data from a package directory.
    'path' should be an absolute path.
    """
    # Run the imported setup to get the metadata.
    with FakeContext(arg_0):
        with SetupMonkey() as sm:
            try:
                arg_1 = run_setup('setup.py', stop_after='config')

                arg_2 = {'_setuptools': sm.used_setuptools}

                for arg_3, arg_4 in arg_1.metadata.__dict__.items():
                    if arg_3[0] == '_' or not arg_4:
                        continue
                    if all(not arg_5 for arg_5 in arg_4):
                        continue
                    arg_2[arg_3] = arg_4

                if sm.used_setuptools:
                    for arg_6 in ['cmdclass', 'zip_safe', 'test_suite']:
                        arg_4 = getattr(arg_1, arg_6, None)
                        if arg_4 is not None and arg_4 not in ([], {}):
                            arg_2[arg_6] = arg_4

            except ImportError as e:
                # Either there is no setup py, or it's broken.
                logging.exception(e)
                arg_2 = {}

    return arg_2


def Func(arg_0, arg_1, arg_2):
    "Create a graph of constraints for both must- and cannot-links"

    # Represent the graphs using adjacency-lists
    arg_3, arg_4 = {}, {}
    for arg_5 in range(arg_2):
        arg_3[arg_5] = set()
        arg_4[arg_5] = set()

    def add_both(arg_6, arg_5, arg_7):
        arg_6[arg_5].add(arg_7)
        arg_6[arg_7].add(arg_5)

    for (arg_5, arg_7) in arg_0:
        arg_3[arg_5].add(arg_7)
        arg_3[arg_7].add(arg_5)

    for (arg_5, arg_7) in arg_1:
        arg_4[arg_5].add(arg_7)
        arg_4[arg_7].add(arg_5)

    def dfs(arg_5, arg_8, arg_9, arg_10):
        arg_9[arg_5] = True
        for arg_7 in arg_8[arg_5]:
            if not arg_9[arg_7]:
                dfs(arg_7, arg_8, arg_9, arg_10)
        arg_10.append(arg_5)

    # Run DFS from each node to get all the graph's components
    # and add an edge for each pair of nodes in the component (create a complete graph)
    # See http://www.techiedelight.com/transitive-closure-graph/ for more details
    arg_9 = [False] * arg_2
    arg_11 = []
    for arg_5 in range(arg_2):
        if not arg_9[arg_5] and arg_3[arg_5]:
            arg_10 = []
            dfs(arg_5, arg_3, arg_9, arg_10)
            for arg_12 in arg_10:
                for arg_13 in arg_10:
                    if arg_12 != arg_13:
                        arg_3[arg_12].add(arg_13)
            arg_11.append(arg_10)

    for (arg_5, arg_7) in arg_1:
        for arg_14 in arg_3[arg_5]:
            add_both(arg_4, arg_14, arg_7)

        for arg_15 in arg_3[arg_7]:
            add_both(arg_4, arg_5, arg_15)

        for arg_14 in arg_3[arg_5]:
            for arg_15 in arg_3[arg_7]:
                add_both(arg_4, arg_14, arg_15)

    for arg_5 in arg_3:
        for arg_7 in arg_3[arg_5]:
            if arg_7 != arg_5 and arg_7 in arg_4[arg_5]:
                raise InconsistentConstraintsException('Inconsistent constraints between {} and {}'.format(arg_5, arg_7))

    return arg_3, arg_4, arg_11


def Func(arg_0, arg_1 = None, arg_2 = None):
	"""Translates a regular Scikit-Learn estimator or pipeline to a PMML pipeline.

	Parameters:
	----------
	obj: BaseEstimator
		The object.

	active_fields: list of strings, optional
		Feature names. If missing, "x1", "x2", .., "xn" are assumed.

	target_fields: list of strings, optional
		Label name(s). If missing, "y" is assumed.

	"""
	arg_3 = _filter_steps(_get_steps(arg_0))
	arg_4 = PMMLPipeline(arg_3)
	if arg_1 is not None:
		arg_4.active_fields = numpy.asarray(arg_1)
	if arg_2 is not None:
		arg_4.target_fields = numpy.asarray(arg_2)
	return arg_4


def Func(arg_0, arg_1, arg_2 = [], arg_3 = False, arg_4 = False, arg_5 = "UTF-8"):
	"""Converts a fitted Scikit-Learn pipeline to PMML.

	Parameters:
	----------
	pipeline: PMMLPipeline
		The pipeline.

	pmml: string
		The path to where the PMML document should be stored.

	user_classpath: list of strings, optional
		The paths to JAR files that provide custom Transformer, Selector and/or Estimator converter classes.
		The JPMML-SkLearn classpath is constructed by appending user JAR files to package JAR files.

	with_repr: boolean, optional
		If true, insert the string representation of pipeline into the PMML document.

	debug: boolean, optional
		If true, print information about the conversion process.

	java_encoding: string, optional
		The character encoding to use for decoding Java output and error byte streams.

	"""
	if arg_4:
		arg_6 = _java_version(arg_5)
		if arg_6 is None:
			arg_6 = ("java", "N/A")
		print("python: {0}".format(platform.python_version()))
		print("sklearn: {0}".format(sklearn.__version__))
		print("sklearn.externals.joblib: {0}".format(joblib.__version__))
		print("pandas: {0}".format(pandas.__version__))
		print("sklearn_pandas: {0}".format(sklearn_pandas.__version__))
		print("Func: {0}".format(__version__))
		print("{0}: {1}".format(arg_6[0], arg_6[1]))
	if not isinstance(arg_0, PMMLPipeline):
		raise TypeError("The pipeline object is not an instance of " + PMMLPipeline.__name__ + ". Use the 'Func.make_pmml_pipeline(obj)' utility function to translate a regular Scikit-Learn estimator or pipeline to a PMML pipeline")
	arg_7 = arg_0._final_estimator
	arg_8 = ["java", "-cp", os.pathsep.join(_classpath(arg_2)), "org.jpmml.sklearn.Main"]
	arg_9 = []
	try:
		if arg_3:
			arg_0.repr_ = repr(arg_0)
		# if isinstance(estimator, H2OEstimator):
		if hasattr(arg_7, "download_mojo"):
			arg_11 = arg_7.download_mojo()
			arg_9.append(arg_11)
			arg_7._mojo_path = arg_11
		arg_13 = _dump(arg_0, "pipeline")
		arg_8.extend(["--pkl-pipeline-input", arg_13])
		arg_9.append(arg_13)
		arg_8.extend(["--pmml-output", arg_1])
		if arg_4:
			print("Executing command:\n{0}".format(" ".join(arg_8)))
		try:
			arg_14 = Popen(arg_8, stdout = PIPE, stderr = PIPE, bufsize = 1)
		except OSError:
			raise RuntimeError("Java is not installed, or the Java executable is not on system path")
		arg_15, arg_16 = arg_14.communicate()
		arg_17 = arg_14.poll()
		if arg_4 or arg_17:
			if(len(arg_15) > 0):
				print("Standard output:\n{0}".format(_decode(arg_15, arg_5)))
			else:
				print("Standard output is empty")
			if(len(arg_16) > 0):
				print("Standard error:\n{0}".format(_decode(arg_16, arg_5)))
			else:
				print("Standard error is empty")
		if arg_17:
			raise RuntimeError("The JPMML-SkLearn conversion application has failed. The Java executable should have printed more information about the failure into its standard output and/or standard error streams")
	finally:
		if arg_4:
			print("Preserved joblib dump file(s): {0}".format(" ".join(arg_9)))
		else:
			for arg_18 in arg_9:
				os.remove(arg_18)


def Func(arg_0):
        """
        Returns an instance of the formset
        """
        arg_1 = arg_0.get_formset()
        if hasattr(arg_0, 'get_extra_form_kwargs'):
            arg_2 = type(arg_0).__name__
            raise DeprecationWarning(
                'Calling {0}.get_extra_form_kwargs is no longer supported. '
                'Set `form_kwargs` in {0}.formset_kwargs or override '
                '{0}.get_formset_kwargs() directly.'.format(arg_2),
            )
        return arg_1(**arg_0.get_formset_kwargs())


def Func(arg_0, arg_1):
        """
        If the formset is valid, save the associated models.
        """
        arg_0.object_list = arg_1.save()
        return super(ModelFormSetMixin, arg_0).Func(arg_1)


def Func(arg_0, arg_1, *arg_2, **arg_3):
        """
        Handles POST requests, instantiating a formset instance with the passed
        POST variables and then checked for validity.
        """
        arg_4 = arg_0.construct_formset()
        if arg_4.is_valid():
            return arg_0.formset_valid(arg_4)
        else:
            return arg_0.formset_invalid(arg_4)


def Func(arg_0):
        """
        Overrides Func to attach the model class as
        an attribute of the returned formset instance.
        """
        arg_1 = super(InlineFormSetFactory, arg_0).Func()
        arg_1.model = arg_0.inline_model
        return arg_1


def Func(arg_0):
        """
        Returns the inline formset instances
        """
        arg_1 = []
        for arg_2 in arg_0.get_inlines():
            arg_3 = arg_2(arg_0.model, arg_0.request, arg_0.object, arg_0.kwargs, arg_0)
            arg_4 = arg_3.construct_formset()
            arg_1.append(arg_4)
        return arg_1


def Func(arg_0, arg_1, *arg_2, **arg_3):
        """
        Handles GET requests and instantiates a blank version of the form and formsets.
        """
        arg_4 = arg_0.Func_form_class()
        arg_5 = arg_0.Func_form(arg_4)
        arg_6 = arg_0.construct_inlines()
        return arg_0.render_to_response(arg_0.Func_context_data(arg_5=arg_5, arg_6=arg_6, **arg_3))


def Func(arg_0, arg_1, *arg_2, **arg_3):
        """
        Handles POST requests, instantiating a form and formset instances with the passed
        POST variables and then checked for validity.
        """
        arg_4 = arg_0.get_form_class()
        arg_5 = arg_0.get_form(arg_4)

        if arg_5.is_valid():
            arg_0.object = arg_5.save(commit=False)
            arg_7 = True
        else:
            arg_7 = False

        arg_8 = arg_0.construct_inlines()

        if all_valid(arg_8) and arg_7:
            return arg_0.forms_valid(arg_5, arg_8)
        return arg_0.forms_invalid(arg_5, arg_8)


def Func(arg_0, **arg_1):
        """
        If `inlines_names` has been defined, add each formset to the context under
        its corresponding entry in `inlines_names`
        """
        arg_2 = {}
        arg_3 = arg_0.get_inlines_names()

        if arg_3:
            # We have formset or inlines in context, but never both
            arg_2.update(zip(arg_3, arg_1.get('inlines', [])))
            if 'formset' in arg_1:
                arg_2[arg_3[0]] = arg_1['formset']
        arg_2.update(arg_1)
        return super(NamedFormsetsMixin, arg_0).Func(**arg_2)


def Func(arg_0, arg_1):
        """
        Returns the start date for a model instance
        """
        arg_2 = getattr(arg_1, arg_0.get_date_field())
        try:
            arg_2 = arg_2.date()
        except AttributeError:
            # It's a date rather than datetime, so we use it as is
            pass
        return arg_2


def Func(arg_0):
        """
        Returns an integer representing the first day of the week.

        0 represents Monday, 6 represents Sunday.
        """
        if arg_0.first_of_week is None:
            raise ImproperlyConfigured("%s.first_of_week is required." % arg_0.__class__.__name__)
        if arg_0.first_of_week not in range(7):
            raise ImproperlyConfigured("%s.first_of_week must be an integer between 0 and 6." % arg_0.__class__.__name__)
        return arg_0.first_of_week


def Func(arg_0):
        """
        Returns a queryset of models for the month requested
        """
        arg_1 = super(BaseCalendarMonthView, arg_0).Func()

        arg_2 = arg_0.get_year()
        arg_3 = arg_0.get_month()

        arg_4 = arg_0.get_date_field()
        arg_5 = arg_0.get_end_date_field()

        arg_6 = _date_from_string(arg_2, arg_0.get_year_format(),
                                 arg_3, arg_0.get_month_format())

        arg_7 = arg_6
        arg_8 = arg_0.get_next_month(arg_6)

        # Adjust our start and end dates to allow for next and previous
        # month edges
        if arg_7.weekday() != arg_0.get_first_of_week():
            arg_9 = math.fabs(arg_7.weekday() - arg_0.get_first_of_week())
            arg_7 = arg_7 - datetime.timedelta(days=arg_9)

        if arg_8.weekday() != ((arg_0.get_first_of_week() + 6) % 7):
            arg_9 = math.fabs(((arg_0.get_first_of_week() + 6) % 7) - arg_8.weekday())
            arg_8 = arg_8 + datetime.timedelta(days=arg_9)

        if arg_5:
            # 5 possible conditions for showing an event:

            # 1) Single day event, starts after 'since'
            # 2) Multi-day event, starts after 'since' and ends before 'until'
            # 3) Starts before 'since' and ends after 'since' and before 'until'
            # 4) Starts after 'since' but before 'until' and ends after 'until'
            # 5) Starts before 'since' and ends after 'until'
            arg_10 = Q(**{
                '%s__gte' % arg_4: arg_7,
                arg_5: None
            })
            arg_11 = Q(**{
                '%s__gte' % arg_4: arg_7,
                '%s__lt' % arg_5: arg_8
            })
            arg_12 = Q(**{
                '%s__lt' % arg_4: arg_7,
                '%s__gte' % arg_5: arg_7,
                '%s__lt' % arg_5: arg_8
            })
            arg_13 = Q(**{
                '%s__gte' % arg_4: arg_7,
                '%s__lt' % arg_4: arg_8,
                '%s__gte' % arg_5: arg_8
            })
            arg_14 = Q(**{
                '%s__lt' % arg_4: arg_7,
                '%s__gte' % arg_5: arg_8
            })
            return arg_1.filter(arg_10 | arg_11 | arg_12 | arg_13 | arg_14)
        return arg_1.filter(**{
            '%s__gte' % arg_4: arg_7
        })


def Func(arg_0, **arg_1):
        """
        Injects variables necessary for rendering the calendar into the context.

        Variables added are: `calendar`, `weekdays`, `month`, `next_month` and `previous_month`.
        """
        arg_2 = super(BaseCalendarMonthView, arg_0).Func(**arg_1)

        arg_3 = arg_0.get_year()
        arg_4 = arg_0.get_month()

        arg_5 = _date_from_string(arg_3, arg_0.get_year_format(),
                                 arg_4, arg_0.get_month_format())

        arg_6 = Calendar(arg_0.get_first_of_week())

        arg_7 = []
        arg_8 = datetime.datetime.utcnow()

        arg_9 = defaultdict(list)
        arg_10 = []

        for arg_11 in arg_2['object_list']:
            arg_12 = arg_0.get_start_date(arg_11)
            arg_13 = arg_0.get_end_date_field()

            if arg_13:
                arg_14 = arg_0.get_end_date(arg_11)
                if arg_14 and arg_14 != arg_12:
                    arg_10.append({
                        'obj': arg_11,
                        'range': [arg_15 for arg_15 in daterange(arg_12, arg_14)]
                    })
                    continue  # We don't put multi-day events in date_lists
            arg_9[arg_12].append(arg_11)

        for arg_16 in arg_6.monthdatescalendar(arg_5.year, arg_5.month):
            arg_17 = set(daterange(arg_16[0], arg_16[6]))
            arg_18 = []

            for arg_19 in arg_10:
                arg_20 = len(arg_17.intersection(arg_19['range']))

                if arg_20:
                    # Event happens during this week
                    arg_21 = 1
                    arg_22 = arg_20  # How many days is the event during this week?
                    arg_23 = True  # Does the event continue from the previous week?
                    arg_24 = True  # Does the event continue to the next week?

                    if arg_19['range'][0] >= arg_16[0]:
                        arg_21 = 1 + (arg_19['range'][0] - arg_16[0]).days
                    else:
                        arg_23 = False
                    if arg_19['range'][-1] > arg_16[6]:
                        arg_24 = False

                    arg_18.append({
                        'event': arg_19['obj'],
                        'slot': arg_21,
                        'width': arg_22,
                        'nowrap_previous': arg_23,
                        'nowrap_next': arg_24,
                    })

            arg_25 = {
                'events': arg_18,
                'date_list': [],
            }
            for arg_26 in arg_16:
                arg_25['date_list'].append({
                    'day': arg_26,
                    'events': arg_9[arg_26],
                    'today': arg_26 == arg_8.date(),
                    'is_current_month': arg_26.month == arg_5.month,
                })
            arg_7.append(arg_25)

        arg_2['calendar'] = arg_7
        arg_2['weekdays'] = [DAYS[arg_15] for arg_15 in arg_6.iterweekdays()]
        arg_2['month'] = arg_5
        arg_2['next_month'] = arg_0.get_next_month(arg_5)
        arg_2['previous_month'] = arg_0.get_previous_month(arg_5)

        return arg_2


def Func(arg_0):
    """Get primary key properties for a SQLAlchemy model.

    :param model: SQLAlchemy model class
    """
    arg_1 = arg_0.__mapper__
    return [arg_1.get_property_by_column(arg_2) for arg_2 in arg_1.primary_key]


def Func(arg_0, arg_1, *arg_2, **arg_3):
        """Deserialize a serialized value to a model instance.

        If the parent schema is transient, create a new (transient) instance.
        Otherwise, attempt to find an existing instance in the database.
        :param value: The value to deserialize.
        """
        if not isinstance(arg_1, dict):
            if len(arg_0.related_keys) != 1:
                arg_0.fail(
                    "invalid",
                    arg_1=arg_1,
                    keys=[arg_4.key for arg_4 in arg_0.related_keys],
                )
            arg_1 = {arg_0.related_keys[0].key: arg_1}
        if arg_0.transient:
            return arg_0.related_model(**arg_1)
        try:
            arg_5 = arg_0._get_existing_instance(
                arg_0.session.query(arg_0.related_model), arg_1
            )
        except NoResultFound:
            # The related-object DNE in the DB, but we still want to deserialize it
            # ...perhaps we want to add it to the DB later
            return arg_0.related_model(**arg_1)
        return arg_5


def Func(arg_0, arg_1, arg_2=None, arg_3=None, arg_4=False, *arg_5, **arg_6):
        """Deserialize data to internal representation.

        :param session: Optional SQLAlchemy session.
        :param instance: Optional existing instance to modify.
        :param transient: Optional switch to allow transient instantiation.
        """
        arg_0._session = arg_2 or arg_0._session
        arg_0._transient = arg_4 or arg_0._transient
        if not (arg_0.transient or arg_0.session):
            raise ValueError("Deserialization requires a session")
        arg_0.instance = arg_3 or arg_0.instance
        try:
            return super(ModelSchema, arg_0).Func(arg_1, *arg_5, **arg_6)
        finally:
            arg_0.instance = None


def Func():
    """Deletes old stellar tables that are not used anymore"""
    def after_delete(arg_0):
        click.echo("Deleted table %s" % arg_0)

    arg_1 = get_app()
    upgrade_from_old_version(arg_1)
    arg_1.delete_orphan_snapshots(after_delete)


def Func(arg_0):
    """Takes a Func of the database"""
    arg_1 = get_app()
    upgrade_from_old_version(arg_1)
    arg_0 = arg_0 or arg_1.default_Func_name

    if arg_1.get_Func(arg_0):
        click.echo("Snapshot with name %s already exists" % arg_0)
        sys.exit(1)
    else:
        def before_copy(arg_2):
            click.echo("Snapshotting database %s" % arg_2)
        arg_1.create_Func(arg_0, before_copy=before_copy)


def Func():
    """Returns a Func of snapshots"""
    arg_0 = get_app().get_snapshots()

    click.echo('\n'.join(
        '%s: %s' % (
            arg_1.snapshot_name,
            humanize.naturaltime(datetime.utcnow() - arg_1.created_at)
        )
        for arg_1 in arg_0
    ))


def Func(arg_0):
    """Removes a snapshot"""
    arg_1 = get_app()

    arg_2 = arg_1.get_snapshot(arg_0)
    if not arg_2:
        click.echo("Couldn't find snapshot %s" % arg_0)
        sys.exit(1)

    click.echo("Deleting snapshot %s" % arg_0)
    arg_1.Func_snapshot(arg_2)
    click.echo("Deleted")


def Func(arg_0, arg_1):
    """Renames a snapshot"""
    arg_2 = get_app()

    arg_3 = arg_2.get_snapshot(arg_0)
    if not arg_3:
        click.echo("Couldn't find snapshot %s" % arg_0)
        sys.exit(1)

    arg_4 = arg_2.get_snapshot(arg_1)
    if arg_4:
        click.echo("Snapshot with name %s already exists" % arg_1)
        sys.exit(1)

    arg_2.Func_snapshot(arg_3, arg_1)
    click.echo("Renamed snapshot %s to %s" % (arg_0, arg_1))


def Func(arg_0):
    """Replaces a snapshot"""
    arg_1 = get_app()

    arg_2 = arg_1.get_snapshot(arg_0)
    if not arg_2:
        click.echo("Couldn't find snapshot %s" % arg_0)
        sys.exit(1)

    arg_1.remove_snapshot(arg_2)
    arg_1.create_snapshot(arg_0)
    click.echo("Replaced snapshot %s" % arg_0)


def Func(arg_0) -> None:
        'Updates indexes after each epoch for shuffling'
        arg_0.indexes = np.arange(arg_0.nrows)
        if arg_0.shuffle:
            np.random.shuffle(arg_0.indexes)


def Func(arg_0: arg_1) -> arg_1:
    """
    Defines the default function for cleaning text.

    This function operates over a list.
    """
    return preprocess_text(arg_0,
                           fix_unicode=True,
                           lowercase=True,
                           transliterate=True,
                           no_urls=True,
                           no_emails=True,
                           no_phone_numbers=True,
                           no_numbers=True,
                           no_currency_symbols=True,
                           no_punct=True,
                           no_contractions=False,
                           no_accents=True)


def Func(arg_0: arg_1,
                   arg_2: arg_3[arg_4],
                   arg_5: arg_6 = None) -> arg_3[arg_4]:
    """
    Apply function to list of elements.

    Automatically determines the chunk size.
    """
    if not arg_5:
        arg_5 = cpu_count()

    try:
        arg_7 = ceil(len(arg_2) / arg_5)
        arg_8 = Pool(arg_5)
        arg_9 = arg_8.map(arg_0, chunked(arg_2, arg_7), chunksize=1)
    finally:
        arg_8.close()
        arg_8.join()
        return arg_9


def Func(arg_0):
        """Analyze document length statistics for padding strategy"""
        arg_1 = arg_0.heuristic_pct
        arg_2 = (pd.DataFrame([(a, b) for a, b in arg_0.document_length_histogram.items()],
                               columns=['bin', 'doc_count'])
                  .sort_values(by='bin'))
        arg_2['cumsum_pct'] = arg_2.doc_count.cumsum() / arg_2.doc_count.sum()

        arg_0.document_length_stats = arg_2
        arg_0.doc_length_huerestic = arg_2.query(f'cumsum_pct >= {heuristic}').bin.head(1).values[0]
        logging.warning(' '.join(["Setting maximum document length to",
                                  f'{self.doc_length_huerestic} based upon',
                                  f'heuristic of {heuristic} percentile.\n',
                                  'See full histogram by insepecting the',
                                  "`document_length_stats` attribute."]))
        arg_0.padding_maxlen = arg_0.doc_length_huerestic


def Func(arg_0, arg_1=None, arg_2=None, arg_3=False):
        """
        Return a new Colorful object with the given color config.
        """
        arg_4 = Colorful(
            arg_1=arg_0.colorful.colormode,
            arg_2=copy.copy(arg_0.colorful.colorpalette)
        )

        arg_4.setup(
            arg_1=arg_1, arg_2=arg_2, arg_3=arg_3
        )
        yield arg_4


def Func(arg_0):
    """
    Parse the given rgb.txt file into a Python dict.

    See https://en.wikipedia.org/wiki/X11_color_names for more information

    :param str path: the path to the X11 rgb.txt file
    """
    #: Holds the generated color dict
    arg_1 = {}

    with open(arg_0, 'r') as rgb_txt:
        for arg_2 in rgb_txt:
            arg_2 = arg_2.strip()
            if not arg_2 or arg_2.startswith('!'):
                continue  # skip comments

            arg_3 = arg_2.split()
            arg_1[" ".join(arg_3[3:])] = (int(arg_3[0]), int(arg_3[1]), int(arg_3[2]))

    return arg_1


def Func(arg_0):
    """
    Sanitze the given color palette so it can
    be safely used by Colorful.

    It will convert colors specified in hex RGB to
    a RGB channel triplet.
    """
    arg_1 = {}

    def arg_6(arg_2):
        """
        Convert the given name into a valid colorname
        """
        if len(arg_2) == 1:
            arg_2 = arg_2[0]
            return arg_2[:1].lower() + arg_2[1:]

        return arg_2[0].lower() + ''.join(arg_3.capitalize() for arg_3 in arg_2[1:])

    for arg_4, arg_5 in arg_0.items():
        if isinstance(arg_5, str):
            # we assume it's a hex RGB value
            arg_5 = utils.hex_to_rgb(arg_5)
        arg_1[arg_6(arg_4.split())] = arg_5

    return arg_1


def Func(arg_0):  # noqa
    """
    Detect what color palettes are supported.
    It'll return a valid color mode to use
    with colorful.

    :param dict env: the environment dict like returned by ``os.envion``
    """
    if arg_0.get('COLORFUL_DISABLE', '0') == '1':
        return NO_COLORS

    if arg_0.get('COLORFUL_FORCE_8_COLORS', '0') == '1':
        return ANSI_8_COLORS

    if arg_0.get('COLORFUL_FORCE_16_COLORS', '0') == '1':
        return ANSI_16_COLORS

    if arg_0.get('COLORFUL_FORCE_256_COLORS', '0') == '1':
        return ANSI_256_COLORS

    if arg_0.get('COLORFUL_FORCE_TRUE_COLORS', '0') == '1':
        return TRUE_COLORS

    # if we are not a tty
    if not sys.stdout.isatty():
        return NO_COLORS

    arg_1 = arg_0.get('COLORTERM')
    if arg_1:
        if arg_1 in {'truecolor', '24bit'}:
            return TRUE_COLORS

        if arg_1 in {'8bit'}:
            return ANSI_256_COLORS

    arg_2 = arg_0.get('TERM_PROGRAM')
    if arg_2:
        if arg_2 in {'iTerm.app', 'Hyper'}:
            return TRUE_COLORS

        if arg_2 in {'Apple_Terminal'}:
            return ANSI_256_COLORS

    arg_3 = arg_0.get('TERM')
    if arg_3:
        if arg_3 in {'screen-256', 'screen-256color', 'xterm-256', 'xterm-256color'}:
            return ANSI_256_COLORS

        if arg_3 in {'screen', 'xterm', 'vt100', 'color', 'ansi', 'cygwin', 'linux'}:
            return ANSI_16_COLORS

    if arg_1:
        # if there was no match with $TERM either but we
        # had one with $COLORTERM, we use it!
        return ANSI_16_COLORS

    return ANSI_8_COLORS


def Func(arg_0):
    """
    Convert the given hex string to a
    valid RGB channel triplet.
    """
    arg_0 = arg_0.lstrip('#')
    check_hex(arg_0)

    arg_1 = len(arg_0)
    arg_2 = int(arg_1 / 3)
    return tuple(int(arg_0[arg_3:arg_3+arg_2], 16) for arg_3 in range(0, arg_1, arg_2))


def Func(arg_0):
    """
    Check if the given hex value is a valid RGB color

    It should match the format: [0-9a-fA-F]
    and be of length 3 or 6.
    """
    arg_1 = len(arg_0)
    if arg_1 not in (3, 6):
        raise ValueError('Hex string #{} is too long'.format(arg_0))

    arg_2 = r'[0-9a-f]{{{length}}}'.format(arg_1=arg_1)
    if not re.search(arg_2, arg_0, re.I):
        raise ValueError('Invalid Hex String: #{}'.format(arg_0))


def Func(arg_0, arg_1, arg_2, arg_3):
    """
    Translate the given color name to a valid
    ANSI escape code.

    :parma str colorname: the name of the color to resolve
    :parma str offset: the offset for the color code
    :param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``
    :parma dict colorpalette: the color palette to use for the color name mapping

    :returns str: the color as ANSI escape code

    :raises ColorfulError: if the given color name is invalid
    """
    try:
        arg_4, arg_5, arg_6 = arg_3[arg_0]
    except KeyError:
        raise ColorfulError('the color "{0}" is unknown. Use a color in your color palette (by default: X11 rgb.txt)'.format(  # noqa
            arg_0))
    else:
        return translate_rgb_to_ansi_code(arg_4, arg_5, arg_6, arg_1, arg_2)


def Func(arg_0, arg_1):
    """
    Resolve the given modifier name to a valid
    ANSI escape code.

    :param str modifiername: the name of the modifier to resolve
    :param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``

    :returns str: the ANSI escape code for the modifier

    :raises ColorfulError: if the given modifier name is invalid
    """
    if arg_1 == terminal.NO_COLORS:  # return empty string if colors are disabled
        return '', ''

    try:
        arg_2, arg_3 = ansi.MODIFIERS[arg_0]
    except KeyError:
        raise ColorfulError('the modifier "{0}" is unknown. Use one of: {1}'.format(
            arg_0, ansi.MODIFIERS.keys()))
    else:
        return ansi.ANSI_ESCAPE_CODE.format(
            code=arg_2), ansi.ANSI_ESCAPE_CODE.format(
                code=arg_3)


def Func(arg_0, arg_1, arg_2):
    """
    Translate the given style to an ANSI escape code
    sequence.

    ``style`` examples are:

    * green
    * bold
    * red_on_black
    * bold_green
    * italic_yellow_on_cyan

    :param str style: the style to translate
    :param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``
    :parma dict colorpalette: the color palette to use for the color name mapping
    """
    arg_3 = iter(arg_0.split('_'))

    arg_4 = []
    arg_5 = []

    try:
        # consume all modifiers
        arg_6 = None
        for arg_7 in arg_3:
            arg_6 = arg_7
            if arg_6 not in ansi.MODIFIERS:
                break  # all modifiers have been consumed

            mod_start_code, mod_end_code = resolve_modifier_to_ansi_code(arg_6, arg_1)
            arg_4.append(mod_start_code)
            arg_5.append(mod_end_code)
        else:  # we've consumed all parts, thus we can exit
            raise StopIteration()

        # next part has to be a foreground color or the 'on' keyword
        # which means we have to consume background colors
        if arg_6 != 'on':
            arg_8, arg_9 = translate_colorname_to_ansi_code(
                arg_6, ansi.FOREGROUND_COLOR_OFFSET, arg_1, arg_2)
            arg_4.append(arg_8)
            arg_5.append(arg_9)
            # consume the required 'on' keyword after the foreground color
            next(arg_3)

        # next part has to be the background color
        arg_6 = next(arg_3)
        arg_8, arg_9 = translate_colorname_to_ansi_code(
            arg_6, ansi.BACKGROUND_COLOR_OFFSET, arg_1, arg_2)
        arg_4.append(arg_8)
        arg_5.append(arg_9)
    except StopIteration:  # we've consumed all parts of the styling string
        pass

    # construct and return ANSI escape code sequence
    return ''.join(arg_4), ''.join(arg_5)


def Func(arg_0, arg_1, arg_2, arg_3=False):
    """
    Style the given string according to the given
    ANSI style string.

    :param str string: the string to style
    :param tuple ansi_style: the styling string returned by ``translate_style``
    :param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``

    :returns: a string containing proper ANSI sequence
    """
    arg_4, arg_5 = arg_1

    # replace nest placeholders with the current begin style
    if PY2:
        if isinstance(arg_0, str):
            arg_0 = arg_0.decode(DEFAULT_ENCODING)
    arg_0 = UNICODE(arg_0).replace(ansi.NEST_PLACEHOLDER, arg_4)

    return '{start_code}{string}{end_code}{nest_ph}'.format(
            start_code=arg_4,
            arg_0=arg_0,
            end_code=arg_5,
            nest_ph=ansi.NEST_PLACEHOLDER if arg_3 else '')


def Func(arg_0, arg_1):
        """
        Use a predefined style as color palette

        :param str style_name: the name of the style
        """
        try:
            arg_2 = getattr(styles, arg_1.upper())
        except AttributeError:
            raise ColorfulError('the style "{0}" is undefined'.format(
                arg_1))
        else:
            arg_0.colorpalette = arg_2


def Func(arg_0, arg_1, *arg_2, **arg_3):
        """
        Format the given string with the given ``args`` and ``kwargs``.
        The string can contain references to ``c`` which is provided by
        this colorful object.

        :param str string: the string to Func
        """
        return arg_1.Func(c=arg_0, *arg_2, **arg_3)


def Func(arg_0, arg_1=False):
        """
        Get data from the USB device.
        """
        try:
            if arg_1:
                arg_0._device.reset()

            # detach kernel driver from both interfaces if attached, so we can set_configuration()
            for arg_2 in [0,1]:
                if arg_0._device.is_kernel_driver_active(arg_2):
                    LOGGER.debug('Detaching kernel driver for interface %d '
                        'of %r on ports %r', arg_2, arg_0._device, arg_0._ports)
                    arg_0._device.detach_kernel_driver(arg_2)

            arg_0._device.set_configuration()

            # Prevent kernel message:
            # "usbfs: process <PID> (python) did not claim interface x before use"
            # This will become unnecessary once pull-request #124 for
            # PyUSB has been accepted and we depend on a fixed release
            # of PyUSB.  Until then, and even with the fix applied, it
            # does not hurt to explicitly claim the interface.
            usb.util.claim_interface(arg_0._device, INTERFACE)

                # Turns out we don't actually need that ctrl_transfer.
                # Disabling this reduces number of USBErrors from ~7/30 to 0!
                #self._device.ctrl_transfer(bmRequestType=0x21, bRequest=0x09,
                #    wValue=0x0201, wIndex=0x00, data_or_wLength='\x01\x01',
                #    timeout=TIMEOUT)

            # Magic: Our TEMPerV1.4 likes to be asked twice.  When
            # only asked once, it get's stuck on the next access and
            # requires a reset.
            arg_0._control_transfer(COMMANDS['temp'])
            arg_0._interrupt_read()

            # Turns out a whole lot of that magic seems unnecessary.
            #self._control_transfer(COMMANDS['ini1'])
            #self._interrupt_read()
            #self._control_transfer(COMMANDS['ini2'])
            #self._interrupt_read()
            #self._interrupt_read()

            # Get temperature
            arg_0._control_transfer(COMMANDS['temp'])
            arg_3 = arg_0._interrupt_read()

            # Get humidity
            if arg_0._device.product == 'TEMPer1F_H1_V1.4':
                arg_4 = arg_3
            else:
                arg_4 = None

            # Combine temperature and humidity data
            arg_5 = {'temp_data': arg_3, 'humidity_data': arg_4}

            # Be a nice citizen and undo potential interface claiming.
            # Also see: https://github.com/walac/pyusb/blob/master/docs/tutorial.rst#dont-be-selfish
            usb.util.dispose_resources(arg_0._device)
            return arg_5
        except usb.USBError as err:
            if not arg_1:
                LOGGER.warning("Encountered %s, resetting %r and trying again.", err, arg_0._device)
                return arg_0.Func(True)

            # Catch the permissions exception and add our message
            if "not permitted" in str(err):
                raise Exception(
                    "Permission problem accessing USB. "
                    "Maybe I need to run as root?")
            else:
                LOGGER.error(err)
                raise


def Func(arg_0, arg_1=None):
        """
        Get device humidity reading.

        Params:
        - sensors: optional list of sensors to get a reading for, examples:
          [0,] - get reading for sensor 0
          [0, 1,] - get reading for sensors 0 and 1
          None - get readings for all sensors
        """
        arg_2 = arg_1
        if arg_2 is None:
            arg_2 = list(range(0, arg_0._sensor_count))

        if not set(arg_2).issubset(list(range(0, arg_0._sensor_count))):
            raise ValueError(
                'Some or all of the sensors in the list %s are out of range '
                'given a sensor_count of %d.  Valid range: %s' % (
                    arg_2,
                    arg_0._sensor_count,
                    list(range(0, arg_0._sensor_count)),
                )
            )

        arg_3 = arg_0.get_data()
        arg_3 = arg_3['humidity_data']

        arg_4 = {}

        # Interpret device response
        for arg_5 in arg_2:
            arg_6 = arg_0.lookup_humidity_offset(arg_5)
            if arg_6 is None:
                continue
            arg_7 = (struct.unpack_from('>H', arg_3, arg_6)[0] * 32) / 1000.0
            arg_4[arg_5] = {
                'ports': arg_0.get_ports(),
                'bus': arg_0.get_bus(),
                'sensor': arg_5,
                'humidity_pc': arg_7,
            }

        return arg_4


def Func(arg_0):
        """
        Read data from device.
        """
        arg_1 = arg_0._device.read(ENDPOINT, REQ_INT_LEN, timeout=TIMEOUT)
        LOGGER.debug('Read data: %r', arg_1)
        return arg_1


def Func(arg_0, arg_1, *arg_2, **arg_3):
        """Update, rolling back on failure."""
        arg_4 = []
        arg_5 = arg_4.append
        arg_6 = arg_0._dedup_item
        arg_7 = arg_0._write_item
        for (arg_8, arg_9) in _iteritems_args_kw(*arg_2, **arg_3):
            try:
                arg_10 = arg_6(arg_8, arg_9, arg_1)
            except DuplicationError:
                arg_11 = arg_0._undo_write
                for arg_10, arg_12 in reversed(arg_4):
                    arg_11(arg_10, arg_12)
                raise
            if arg_10 is not _NOOP:
                arg_12 = arg_7(arg_8, arg_9, arg_10)
                arg_5((arg_10, arg_12))


def Func(arg_0=""):
    """Create a new temporary file and write some initial text to it.

    :param text: the text to write to the temp file
    :type text: str
    :returns: the file name of the newly created temp file
    :rtype: str

    """
    with NamedTemporaryFile(mode='w+t', suffix='.yml', delete=False) \
         as tempfile:
        tempfile.write(arg_0)
        return tempfile.name


def Func(arg_0, arg_1, arg_2="all", arg_3=False,
                 arg_4=False, arg_5="first_name"):
    """Get a list of contacts from one or more address books.

    :param address_books: the address books to search
    :type address_books: list(address_book.AddressBook)
    :param query: a search query to select contacts
    :type quer: str
    :param method: the search method, one of "all", "name" or "uid"
    :type method: str
    :param reverse: reverse the order of the returned contacts
    :type reverse: bool
    :param group: group results by address book
    :type group: bool
    :param sort: the field to use for sorting, one of "first_name", "last_name"
    :type sort: str
    :returns: contacts from the address_books that match the query
    :rtype: list(CarddavObject)

    """
    # Search for the contacts in all address books.
    arg_6 = []
    for arg_7 in arg_0:
        arg_6.extend(arg_7.search(arg_1, arg_2=arg_2))
    # Sort the contacts.
    if arg_4:
        if arg_5 == "first_name":
            return sorted(arg_6, arg_3=arg_3, key=lambda x: (
                unidecode(x.address_book.name).lower(),
                unidecode(x.get_first_name_last_name()).lower()))
        elif arg_5 == "last_name":
            return sorted(arg_6, arg_3=arg_3, key=lambda x: (
                unidecode(x.address_book.name).lower(),
                unidecode(x.get_last_name_first_name()).lower()))
        else:
            raise ValueError('sort must be "first_name" or "last_name" not '
                             '{}.'.format(arg_5))
    else:
        if arg_5 == "first_name":
            return sorted(arg_6, arg_3=arg_3, key=lambda x:
                          unidecode(x.get_first_name_last_name()).lower())
        elif arg_5 == "last_name":
            return sorted(arg_6, arg_3=arg_3, key=lambda x:
                          unidecode(x.get_last_name_first_name()).lower())
        else:
            raise ValueError('sort must be "first_name" or "last_name" not '
                             '{}.'.format(arg_5))


def Func(arg_0, arg_1):
    """Merge the parsed arguments from argparse into the config object.

    :param args: the parsed command line arguments
    :type args: argparse.Namespace
    :param config: the parsed config file
    :type config: config.Config
    :returns: the merged config object
    :rtype: config.Config

    """
    # display by name: first or last name
    if "display" in arg_0 and arg_0.display:
        arg_1.set_display_by_name(arg_0.display)
    # group by address book
    if "group_by_addressbook" in arg_0 and arg_0.group_by_addressbook:
        arg_1.set_group_by_addressbook(True)
    # reverse contact list
    if "reverse" in arg_0 and arg_0.reverse:
        arg_1.set_reverse(True)
    # sort criteria: first or last name
    if "sort" in arg_0 and arg_0.sort:
        arg_1.sort = arg_0.sort
    # preferred vcard version
    if "vcard_version" in arg_0 and arg_0.vcard_version:
        arg_1.set_preferred_vcard_version(arg_0.vcard_version)
    # search in source files
    if "search_in_source_files" in arg_0 and arg_0.search_in_source_files:
        arg_1.set_search_in_source_files(True)
    # skip unparsable vcards
    if "skip_unparsable" in arg_0 and arg_0.skip_unparsable:
        arg_1.set_skip_unparsable(True)
    # If the user could but did not specify address books on the command line
    # it means they want to use all address books in that place.
    if "addressbook" in arg_0 and not arg_0.addressbook:
        arg_0.addressbook = [abook.name for abook in arg_1.abooks]
    if "target_addressbook" in arg_0 and not arg_0.target_addressbook:
        arg_0.target_addressbook = [abook.name for abook in arg_1.abooks]


def Func(arg_0, arg_1, arg_2):
    """Load all address books with the given names from the config.

    :param names: the address books to load
    :type names: list(str)
    :param config: the config instance to use when looking up address books
    :type config: config.Config
    :param search_queries: a mapping of address book names to search queries
    :type search_queries: dict
    :yields: the loaded address books
    :ytype: addressbook.AddressBook

    """
    arg_3 = {str(book) for book in arg_1.abooks}
    if not arg_0:
        arg_0 = arg_3
    elif not arg_3.issuperset(arg_0):
        sys.exit('Error: The entered address books "{}" do not exist.\n'
                 'Possible values are: {}'.format(
                     '", "'.join(set(arg_0) - arg_3),
                     ', '.join(arg_3)))
    # load address books which are defined in the configuration file
    for arg_4 in arg_0:
        arg_5 = arg_1.abook.get_abook(arg_4)
        arg_5.load(arg_2[arg_5.name],
                search_in_source_files=arg_1.search_in_source_files())
        yield arg_5


def Func(arg_0):
    """Prepare the search query string from the given command line args.

    Each address book can get a search query string to filter vcards befor
    loading them.  Depending on the question if the address book is used for
    source or target searches different regexes have to be combined into one
    search string.

    :param args: the parsed command line
    :type args: argparse.Namespace
    :returns: a dict mapping abook names to their loading queries, if the query
        is None it means that all cards should be loaded
    :rtype: dict(str:str or None)

    """
    # get all possible search queries for address book parsing
    arg_1 = []
    arg_2 = []
    if "source_search_terms" in arg_0 and arg_0.source_search_terms:
        arg_3 = ".*".join(re.escape(x)
                                 for x in arg_0.source_search_terms)
        arg_1.append(arg_3)
        arg_0.source_search_terms = arg_3
    if "search_terms" in arg_0 and arg_0.search_terms:
        arg_3 = ".*".join(re.escape(x) for x in arg_0.search_terms)
        arg_1.append(arg_3)
        arg_0.search_terms = arg_3
    if "target_contact" in arg_0 and arg_0.target_contact:
        arg_3 = re.escape(arg_0.target_contact)
        arg_2.append(arg_3)
        arg_0.target_contact = arg_3
    if "uid" in arg_0 and arg_0.uid:
        arg_1.append(arg_0.uid)
    if "target_uid" in arg_0 and arg_0.target_uid:
        arg_2.append(arg_0.target_uid)
    # create and return regexp, None means that no query is given and hence all
    # contacts should be searched.
    arg_1 = "^.*(%s).*$" % ')|('.join(arg_1) \
        if arg_1 else None
    arg_2 = "^.*(%s).*$" % ')|('.join(arg_2) \
        if arg_2 else None
    logging.debug('Created source query regex: %s', arg_1)
    logging.debug('Created target query regex: %s', arg_2)
    # Get all possible search queries for address book parsing, always
    # depending on the fact if the address book is used to find source or
    # target contacts or both.
    arg_7 = {abook.name: [] for abook in config.abook._abooks}
    for arg_8 in arg_7:
        if "addressbook" in arg_0 and arg_8 in arg_0.addressbook:
            arg_7[arg_8].append(arg_1)
        if "target_addressbook" in arg_0 and arg_8 in arg_0.target_addressbook:
            arg_7[arg_8].append(arg_2)
        # If None is included in the search queries of an address book it means
        # that either no source or target query was given and this address book
        # is affected by this.  All contacts should be loaded from that address
        # book.
        if None in arg_7[arg_8]:
            arg_7[arg_8] = None
        else:
            arg_7[arg_8] = "({})".format(')|('.join(arg_7[arg_8]))
    logging.debug('Created query regex: %s', arg_7)
    return arg_7


def Func(arg_0, arg_1, arg_2):
    """Print a phone application friendly contact table.

    :param search_terms: used as search term to filter the contacts before
        printing
    :type search_terms: str
    :param vcard_list: the vcards to search for matching entries which should
        be printed
    :type vcard_list: list of carddav_object.CarddavObject
    :param parsable: machine readable output: columns devided by tabulator (\t)
    :type parsable: bool
    :returns: None
    :rtype: None

    """
    arg_3 = []
    arg_4 = []
    for arg_5 in arg_1:
        for arg_6, arg_7 in sorted(arg_5.get_phone_numbers().items(),
                                        key=lambda k: k[0].lower()):
            for arg_8 in sorted(arg_7):
                if config.display_by_name() == "first_name":
                    arg_9 = arg_5.get_first_name_last_name()
                else:
                    arg_9 = arg_5.get_last_name_first_name()
                # create output lines
                arg_10 = "\t".join([arg_9, arg_6, arg_8])
                arg_11 = "\t".join([arg_8, arg_9, arg_6])
                if arg_2:
                    # parsable option: start with phone number
                    arg_12 = arg_11
                else:
                    # else: start with name
                    arg_12 = arg_10
                if re.search(arg_0,
                             "%s\n%s" % (arg_10, arg_11),
                             re.IGNORECASE | re.DOTALL):
                    arg_4.append(arg_12)
                elif len(re.sub("\D", "", arg_0)) >= 3:
                    # The user likely searches for a phone number cause the
                    # search string contains at least three digits.  So we
                    # remove all non-digit chars from the phone number field
                    # and match against that.
                    if re.search(re.sub("\D", "", arg_0),
                                 re.sub("\D", "", arg_8), re.IGNORECASE):
                        arg_4.append(arg_12)
                # collect all phone numbers in a different list as fallback
                arg_3.append(arg_12)
    if arg_4:
        if arg_2:
            print('\n'.join(arg_4))
        else:
            list_phone_numbers(arg_4)
    elif arg_3:
        if arg_2:
            print('\n'.join(arg_3))
        else:
            list_phone_numbers(arg_3)
    else:
        if not arg_2:
            print("Found no phone numbers")
        sys.exit(1)


def Func(arg_0, arg_1):
    """Print a user friendly contacts table.

    :param vcard_list: the vcards to print
    :type vcard_list: list of carddav_object.CarddavObject
    :param parsable: machine readable output: columns devided by tabulator (\t)
    :type parsable: bool
    :returns: None
    :rtype: None

    """
    if not arg_0:
        if not arg_1:
            print("Found no contacts")
        sys.exit(1)
    elif arg_1:
        arg_2 = []
        for arg_3 in arg_0:
            if config.display_by_name() == "first_name":
                arg_4 = arg_3.get_first_name_last_name()
            else:
                arg_4 = arg_3.get_last_name_first_name()
            arg_2.append('\t'.join([arg_3.get_uid(), arg_4,
                                                arg_3.address_book.name]))
        print('\n'.join(arg_2))
    else:
        list_contacts(arg_0)


def Func(arg_0, arg_1, arg_2):
    """Modify a contact in an external editor.

    :param selected_vcard: the contact to modify
    :type selected_vcard: carddav_object.CarddavObject
    :param input_from_stdin_or_file: new data from stdin (or a file) that
        should be incorperated into the contact, this should be a yaml
        formatted string
    :type input_from_stdin_or_file: str
    :param open_editor: whether to open the new contact in the edior after
        creation
    :type open_editor: bool
    :returns: None
    :rtype: None

    """
    # show warning, if vcard version of selected contact is not 3.0 or 4.0
    if arg_0.get_version() not in config.supported_vcard_versions:
        print("Warning:\nThe selected contact is based on vcard version %s "
              "but khard only supports the creation and modification of vcards"
              " with version 3.0 and 4.0.\nIf you proceed, the contact will be"
              " converted to vcard version %s but beware: This could corrupt "
              "the contact file or cause data loss."
              % (arg_0.get_version(),
                 config.get_preferred_vcard_version()))
        while True:
            arg_3 = input("Do you want to proceed anyway (y/n)? ")
            if arg_3.lower() in ["", "n", "q"]:
                print("Canceled")
                sys.exit(0)
            if arg_3.lower() == "y":
                break
    # if there is some data in stdin
    if arg_1:
        # create new contact from stdin
        try:
            arg_4 = \
                CarddavObject.from_existing_contact_with_new_user_input(
                    arg_0, arg_1,
                    config.localize_dates())
        except ValueError as err:
            print(err)
            sys.exit(1)
        if arg_0 == arg_4:
            print("Nothing changed\n\n%s" % arg_4.print_vcard())
        else:
            print("Modification\n\n%s\n" % arg_4.print_vcard())
            while True:
                arg_3 = input("Do you want to proceed (y/n)? ")
                if arg_3.lower() in ["", "n", "q"]:
                    print("Canceled")
                    break
                if arg_3.lower() == "y":
                    arg_4.write_to_file(overwrite=True)
                    if arg_2:
                        modify_existing_contact(arg_4)
                    else:
                        print("Done")
                    break
    else:
        modify_existing_contact(arg_0)


def Func(arg_0, arg_1):
    """Remove a contact from the addressbook.

    :param selected_vcard: the contact to delete
    :type selected_vcard: carddav_object.CarddavObject
    :param force: delete without confirmation
    :type force: bool
    :returns: None
    :rtype: None

    """
    if not arg_1:
        while True:
            arg_2 = input(
                "Deleting contact %s from address book %s. Are you sure? "
                "(y/n): " % (arg_0, arg_0.address_book))
            if arg_2.lower() in ["", "n", "q"]:
                print("Canceled")
                sys.exit(0)
            if arg_2.lower() == "y":
                break
    arg_0.delete_vcard_file()
    print("Contact %s deleted successfully" % arg_0.get_full_name())


def Func(arg_0, arg_1):
    """Open the vcard file for a contact in an external editor.

    :param selected_vcard: the contact to edit
    :type selected_vcard: carddav_object.CarddavObject
    :param editor: the eitor command to use
    :type editor: str
    :returns: None
    :rtype: None

    """
    arg_2 = subprocess.Popen([arg_1, arg_0.filename])
    arg_2.communicate()


def Func(arg_0, arg_1, arg_2,
                     arg_3):
    """Merge two contacts into one.

    :param vcard_list: the vcards from which to choose contacts for mergeing
    :type vcard_list: list of carddav_object.CarddavObject
    :param selected_address_books: the addressbooks to use to find the target
        contact
    :type selected_address_books: list(addressbook.AddressBook)
    :param search_terms: the search terms to find the target contact
    :type search_terms: str
    :param target_uid: the uid of the target contact or empty
    :type target_uid: str
    :returns: None
    :rtype: None

    """
    # Check arguments.
    if arg_3 != "" and arg_2 != "":
        print("You can not specify a target uid and target search terms for a "
              "merge.")
        sys.exit(1)
    # Find possible target contacts.
    if arg_3 != "":
        arg_4 = get_contacts(arg_1, arg_3,
                                     method="uid")
        # We require that the uid given can uniquely identify a contact.
        if len(arg_4) != 1:
            if not arg_4:
                print("Found no contact for target uid %s" % arg_3)
            else:
                print("Found multiple contacts for target uid %s" % arg_3)
                for arg_5 in arg_4:
                    print("    %s: %s" % (arg_5, arg_5.get_uid()))
            sys.exit(1)
    else:
        arg_4 = get_contact_list_by_user_selection(
            arg_1, arg_2, False)
    # get the source vcard, from which to merge
    arg_6 = choose_vcard_from_list("Select contact from which to merge",
                                          arg_0)
    if arg_6 is None:
        print("Found no source contact for merging")
        sys.exit(1)
    else:
        print("Merge from %s from address book %s\n\n"
              % (arg_6, arg_6.address_book))
    # get the target vcard, into which to merge
    arg_7 = choose_vcard_from_list("Select contact into which to merge",
                                          arg_4)
    if arg_7 is None:
        print("Found no target contact for merging")
        sys.exit(1)
    else:
        print("Merge into %s from address book %s\n\n"
              % (arg_7, arg_7.address_book))
    # merging
    if arg_6 == arg_7:
        print("The selected contacts are already identical")
    else:
        merge_existing_contacts(arg_6, arg_7, True)


def Func(arg_0, arg_1):
        """Find the name of the action for the supplied alias.  If no action is
        asociated with the given alias, None is returned.

        :param alias: the alias to look up
        :type alias: str
        :rturns: the name of the corresponding action or None
        :rtype: str or NoneType

        """
        for arg_2, arg_3 in arg_0.action_map.items():
            if arg_1 in arg_3:
                return arg_2
        return None


def Func(arg_0, arg_1, arg_2=True):
        """Convert the named field to bool.

        The current value should be one of the strings "yes" or "no".  It will
        be replaced with its boolean counterpart.  If the field is not present
        in the config object, the default value is used.

        :param config: the config section where to set the option
        :type config: configobj.ConfigObj
        :param name: the name of the option to convert
        :type name: str
        :param default: the default value to use if the option was not
            previously set
        :type default: bool
        :returns: None

        """
        if arg_1 not in arg_0:
            arg_0[arg_1] = arg_2
        elif arg_0[arg_1] == "yes":
            arg_0[arg_1] = True
        elif arg_0[arg_1] == "no":
            arg_0[arg_1] = False
        else:
            raise ValueError("Error in config file\nInvalid value for %s "
                             "parameter\nPossible values: yes, no" % arg_1)


def Func(arg_0, arg_1, arg_2,
                        arg_3, arg_4, arg_5):
        """Use this if you want to create a new contact from user input."""
        arg_6 = arg_0(arg_1, None, arg_3, arg_4,
                arg_5)
        arg_6._process_user_input(arg_2)
        return arg_6


def Func(arg_0, arg_1):
        """Get some part of the "N" entry in the vCard as a list

        :param part: the name to get e.g. "prefix" or "given"
        :type part: str
        :returns: a list of entries for this name part
        :rtype: list(str)

        """
        try:
            arg_2 = getattr(arg_0.vcard.n.value, arg_1)
        except AttributeError:
            return []
        else:
            # check if list only contains empty strings
            if not ''.join(arg_2):
                return []
        return arg_2 if isinstance(arg_2, list) else [arg_2]


def Func(arg_0, arg_1):
        """ categories variable must be a list """
        arg_2 = arg_0.vcard.add('categories')
        arg_2.value = helpers.convert_to_vcard(
            "category", arg_1, ObjectType.list_with_strings)


def Func(arg_0, arg_1, arg_2):
        """Parse type value of phone numbers, email and post addresses.

        :param types: list of type values
        :type types: list(str)
        :param value: the corresponding label, required for more verbose
            exceptions
        :type value: str
        :param supported_types: all allowed standard types
        :type supported_types: list(str)
        :returns: tuple of standard and custom types and pref integer
        :rtype: tuple(list(str), list(str), int)

        """
        arg_3 = []
        arg_4 = []
        arg_5 = 0
        for arg_6 in arg_0:
            arg_6 = arg_6.strip()
            if arg_6:
                if arg_6.lower() in arg_2:
                    arg_4.append(arg_6)
                elif arg_6.lower() == "pref":
                    arg_5 += 1
                elif re.match(r"^pref=\d{1,2}$", arg_6.lower()):
                    arg_5 += int(arg_6.split("=")[1])
                else:
                    if arg_6.lower().startswith("x-"):
                        arg_3.append(arg_6[2:])
                        arg_4.append(arg_6)
                    else:
                        arg_3.append(arg_6)
                        arg_4.append("X-{}".format(arg_6))
        return (arg_4, arg_3, arg_5)


def Func(arg_0, arg_1):
    """converts list to string recursively so that nested lists are supported

    :param input: a list of strings and lists of strings (and so on recursive)
    :type input: list
    :param delimiter: the deimiter to use when joining the items
    :type delimiter: str
    :returns: the recursively joined list
    :rtype: str
    """
    if isinstance(arg_0, list):
        return arg_1.join(
            Func(arg_2, arg_1) for arg_2 in arg_0)
    return arg_0


def Func(arg_0):
    """Convert string to date object.

    :param input: the date string to parse
    :type input: str
    :returns: the parsed datetime object
    :rtype: datetime.datetime
    """
    # try date formats --mmdd, --mm-dd, yyyymmdd, yyyy-mm-dd and datetime
    # formats yyyymmddThhmmss, yyyy-mm-ddThh:mm:ss, yyyymmddThhmmssZ,
    # yyyy-mm-ddThh:mm:ssZ.
    for arg_1 in ("--%m%d", "--%m-%d", "%Y%m%d", "%Y-%m-%d",
                          "%Y%m%dT%H%M%S", "%Y-%m-%dT%H:%M:%S",
                          "%Y%m%dT%H%M%SZ", "%Y-%m-%dT%H:%M:%SZ"):
        try:
            return datetime.strptime(arg_0, arg_1)
        except ValueError:
            pass
    # try datetime formats yyyymmddThhmmsstz and yyyy-mm-ddThh:mm:sstz where tz
    # may look like -06:00.
    for arg_1 in ("%Y%m%dT%H%M%S%z", "%Y-%m-%dT%H:%M:%S%z"):
        try:
            return datetime.strptime(''.join(arg_0.rsplit(":", 1)),
                                     arg_1)
        except ValueError:
            pass
    raise ValueError


def Func(arg_0, arg_1):
        """Calculate the minimum length of initial substrings of uid1 and uid2
        for them to be different.

        :param uid1: first uid to compare
        :type uid1: str
        :param uid2: second uid to compare
        :type uid2: str
        :returns: the length of the shortes unequal initial substrings
        :rtype: int
        """
        arg_2 = 0
        for arg_3, arg_4 in zip(arg_0, arg_1):
            if arg_3 == arg_4:
                arg_2 += 1
            else:
                break
        return arg_2


def Func(arg_0, arg_1):
        """Search in all fields for contacts matching query.

        :param query: the query to search for
        :type query: str
        :yields: all found contacts
        :rtype: generator(carddav_object.CarddavObject)

        """
        arg_2 = re.compile(arg_1, re.IGNORECASE | re.DOTALL)
        for arg_3 in arg_0.contacts.values():
            # search in all contact fields
            arg_4 = arg_3.print_vcard()
            if arg_2.search(arg_4) is not None:
                yield arg_3
            else:
                # find phone numbers with special chars like /
                arg_5 = re.sub("[^a-zA-Z0-9\n]", "",
                                               arg_4)
                if arg_2.search(arg_5) is not None \
                        and len(re.sub("\D", "", arg_1)) >= 3:
                    yield arg_3


def Func(arg_0, arg_1):
        """Search in the name filed for contacts matching query.

        :param query: the query to search for
        :type query: str
        :yields: all found contacts
        :rtype: generator(carddav_object.CarddavObject)

        """
        arg_2 = re.compile(arg_1, re.IGNORECASE | re.DOTALL)
        for arg_3 in arg_0.contacts.values():
            # only search in contact name
            if arg_2.search(arg_3.get_full_name()) is not None:
                yield arg_3


def Func(arg_0, arg_1):
        """Search for contacts with a matching uid.

        :param query: the query to search for
        :type query: str
        :yields: all found contacts
        :rtype: generator(carddav_object.CarddavObject)

        """
        try:
            # First we treat the argument as a full UID and try to match it
            # exactly.
            yield arg_0.contacts[arg_1]
        except KeyError:
            # If that failed we look for all contacts whos UID start with the
            # given query.
            for arg_2 in arg_0.contacts:
                if arg_2.startswith(arg_1):
                    yield arg_0.contacts[arg_2]


def Func(arg_0, arg_1, arg_2="all"):
        """Search this address book for contacts matching the query.

        The method can be one of "all", "name" and "uid".  The backend for this
        address book migth be load()ed if needed.

        :param query: the query to Func for
        :type query: str
        :param method: the type of fileds to use when seaching
        :type method: str
        :returns: all found contacts
        :rtype: list(carddav_object.CarddavObject)

        """
        logging.debug('address book %s, Funcing with %s', arg_0.name, arg_1)
        if not arg_0._loaded:
            arg_0.load(arg_1)
        if arg_2 == "all":
            arg_3 = arg_0._Func_all
        elif arg_2 == "name":
            arg_3 = arg_0._Func_names
        elif arg_2 == "uid":
            arg_3 = arg_0._Func_uid
        else:
            raise ValueError('Only the Func methods "all", "name" and "uid" '
                             'are supported.')
        return list(arg_3(arg_1))


def Func(arg_0, arg_1=None):
        """Create a dictionary of shortend UIDs for all contacts.

        All arguments are only used if the address book is not yet initialized
        and will just be handed to self.load().

        :param query: see self.load()
        :type query: str
        :returns: the contacts mapped by the shortes unique prefix of their UID
        :rtype: dict(str: CarddavObject)
        """
        if arg_0._short_uids is None:
            if not arg_0._loaded:
                arg_0.load(arg_1)
            if not arg_0.contacts:
                arg_0._short_uids = {}
            elif len(arg_0.contacts) == 1:
                arg_0._short_uids = {uid[0:1]: contact
                                    for uid, contact in arg_0.contacts.items()}
            else:
                arg_0._short_uids = {}
                arg_3 = sorted(arg_0.contacts)
                # Prepare for the loop; the first and last items are handled
                # seperatly.
                arg_4, arg_5 = arg_3[:2]
                arg_6 = arg_0._compare_uids(arg_4, arg_5)
                arg_0._short_uids[arg_4[:arg_6 + 1]] = arg_0.contacts[arg_4]
                for arg_7 in arg_3[2:]:
                    # shift the items and the common prefix lenght one further
                    arg_4, arg_5 = arg_5, arg_7
                    arg_8, arg_6 = arg_6, arg_0._compare_uids(arg_4, arg_5)
                    # compute the final prefix length for item1
                    arg_9 = max(arg_8, arg_6)
                    arg_0._short_uids[arg_4[:arg_9 + 1]] = arg_0.contacts[arg_4]
                # Save the last item.
                arg_0._short_uids[arg_5[:arg_6 + 1]] = arg_0.contacts[arg_5]
        return arg_0._short_uids


def Func(arg_0, arg_1):
        """Get the shortend UID for the given UID.

        :param uid: the full UID to shorten
        :type uid: str
        :returns: the shortend uid or the empty string
        :rtype: str
        """
        if arg_1:
            arg_2 = arg_0.Func_dict()
            for arg_3 in range(len(arg_1), 0, -1):
                if arg_2.get(arg_1[:arg_3]) is not None:
                    return arg_1[:arg_3]
        return ""


def Func(arg_0, arg_1=None, arg_2=False):
        """Load all vcard files in this address book from disk.

        If a search string is given only files which contents match that will
        be Funced.

        :param query: a regular expression to limit the results
        :type query: str
        :param search_in_source_files: apply search regexp directly on the .vcf files to speed up parsing (less accurate)
        :type search_in_source_files: bool
        :returns: the number of successfully Funced cards and the number of
            errors
        :rtype: int, int
        :throws: AddressBookParseError
        """
        if arg_0._Funced:
            return
        logging.debug('Loading Vdir %s with query %s', arg_0.name, arg_1)
        arg_3 = 0
        for arg_4 in arg_0._find_vcard_files(
                search=arg_1, arg_2=arg_2):
            try:
                arg_5 = CarddavObject.from_file(arg_0, arg_4,
                                               arg_0._private_objects,
                                               arg_0._localize_dates)
            except (IOError, vobject.base.ParseError) as err:
                arg_6 = "open" if isinstance(err, IOError) else "parse"
                logging.debug("Error: Could not %s file %s\n%s", arg_6,
                              arg_4, err)
                if arg_0._skip:
                    arg_3 += 1
                else:
                    # FIXME: This should throw an apropriate exception and the
                    # sys.exit should be called somewhere closer to the command
                    # line parsing.
                    logging.error(
                        "The vcard file %s of address book %s could not be "
                        "parsed\nUse --debug for more information or "
                        "--skip-unparsable to proceed", arg_4, arg_0.name)
                    sys.exit(2)
            else:
                arg_7 = arg_5.get_uid()
                if not arg_7:
                    logging.warning("Card %s from address book %s has no UID "
                                    "and will not be availbale.", arg_5,
                                    arg_0.name)
                elif arg_7 in arg_0.contacts:
                    logging.warning(
                        "Card %s and %s from address book %s have the same "
                        "UID. The former will not be availbale.", arg_5,
                        arg_0.contacts[arg_7], arg_0.name)
                else:
                    arg_0.contacts[arg_7] = arg_5
        arg_0._Funced = True
        if arg_3:
            logging.warning(
                "%d of %d vCard files of address book %s could not be parsed.",
                arg_3, len(arg_0.contacts) + arg_3, arg_0)
        logging.debug('Loded %s contacts from address book %s.',
                      len(arg_0.contacts), arg_0.name)


def Func(arg_0, arg_1, arg_2):
        """ Create the JSON for configuring arthur to collect data

        https://github.com/grimoirelab/arthur#adding-tasks
        Sample for git:

        {
        "tasks": [
            {
                "task_id": "arthur.git",
                "backend": "git",
                "backend_args": {
                    "gitpath": "/tmp/arthur_git/",
                    "uri": "https://github.com/grimoirelab/arthur.git"
                },
                "category": "commit",
                "archive_args": {
                    "archive_path": '/tmp/test_archives',
                    "fetch_from_archive": false,
                    "archive_after": None
                },
                "scheduler_args": {
                    "delay": 10
                }
            }
        ]
        }
        """

        arg_2 = arg_0._compose_arthur_params(arg_0.backend_section, arg_1)
        if arg_0.backend_section == 'git':
            arg_2['gitpath'] = os.path.join(arg_0.REPOSITORY_DIR, arg_1)
        arg_2['tag'] = arg_0.backend_tag(arg_1)

        arg_3 = {"tasks": [{}]}
        # This is the perceval tag
        arg_3["tasks"][0]['task_id'] = arg_0.backend_tag(arg_1)
        arg_3["tasks"][0]['backend'] = arg_0.backend_section.split(":")[0]
        arg_3["tasks"][0]['backend_args'] = arg_2
        arg_3["tasks"][0]['category'] = arg_2['category']
        arg_3["tasks"][0]['archive'] = {}
        arg_3["tasks"][0]['scheduler'] = {"delay": arg_0.ARTHUR_TASK_DELAY}
        # from-date or offset param must be added
        arg_4 = arg_0._get_collection_url()
        arg_5 = arg_0.conf[arg_0.backend_section]['raw_index']
        # Get the last activity for the data source
        arg_6 = ElasticSearch(arg_4, arg_5)
        arg_7 = get_connector_from_name(arg_0.backend_section)

        arg_8 = arg_7[0]  # Backend for the connector
        arg_9 = inspect.signature(arg_8.fetch)

        arg_10 = None
        arg_11 = {"name": "tag", "value": arg_2['tag']}
        if 'from_date' in arg_9.parameters:
            arg_10 = arg_6.get_last_item_field('metadata__updated_on', [arg_11])
            if arg_10:
                arg_3["tasks"][0]['backend_args']['from_date'] = arg_10.isoformat()
        elif 'offset' in arg_9.parameters:
            arg_10 = arg_6.get_last_item_field('offset', [arg_11])
            if arg_10:
                arg_3["tasks"][0]['backend_args']['offset'] = arg_10

        if arg_10:
            logging.info("Getting raw item with arthur since %s", arg_10)

        return(arg_3)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
        """ Return the GitHub SHA for a file in the repository """

        arg_5 = None

        arg_6 = arg_1.get_conf()
        arg_7 = arg_6['sortinghat']['identities_api_token']
        arg_8 = {"Authorization": "token " + arg_7}

        arg_9 = arg_3 + "/git/trees/" + arg_4
        logger.debug("Gettting sha data from tree: %s", arg_9)
        arg_10 = requests.get(arg_9, arg_8=arg_8)
        arg_10.raise_for_status()
        for arg_11 in arg_10.json()['tree']:
            if arg_11['path'] == arg_2:
                logger.debug("SHA found: %s, ", arg_11["sha"])
                arg_5 = arg_11["sha"]
                break

        return arg_5


def Func(arg_0):
    """Execute the merge identities phase

    :param config: a Mordred config object
    """

    TaskProjects(arg_0).execute()
    arg_1 = TaskIdentitiesMerge(arg_0)
    arg_1.execute()
    logging.info("Merging identities finished!")


def Func(arg_0):
    """Execute the panels phase

    :param config: a Mordred config object
    """

    arg_1 = TaskPanels(arg_0)
    arg_1.execute()

    arg_1 = TaskPanelsMenu(arg_0)
    arg_1.execute()

    logging.info("Panels creation finished!")


def Func(arg_0):
    """Config logging level output output"""

    if arg_0:
        logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(message)s')
        logging.debug("Debug mode activated")
    else:
        logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')


def Func():
    """Get params to execute the micro-mordred"""

    arg_0 = Func_parser()
    arg_1 = arg_0.parse_args()

    if not arg_1.raw and not arg_1.enrich and not arg_1.identities and not arg_1.panels:
        print("No tasks enabled")
        sys.exit(1)

    return arg_1