Instruction:
Given the following Python 3 function, write the documentation
def to_ufo_font_attributes(self, family_name):

    font = self.font

    # "date" can be missing; Glyphs.app removes it on saving if it's empty:
    # https://github.com/googlei18n/glyphsLib/issues/134
    date_created = getattr(font, "date", None)
    if date_created is not None:
        date_created = to_ufo_time(date_created)
    units_per_em = font.upm
    version_major = font.versionMajor
    version_minor = font.versionMinor
    copyright = font.copyright
    designer = font.designer
    designer_url = font.designerURL
    manufacturer = font.manufacturer
    manufacturer_url = font.manufacturerURL
    # XXX note is unused?
    # note = font.note
    glyph_order = list(glyph.name for glyph in font.glyphs)

    for index, master in enumerate(font.masters):
        source = self._designspace.newSourceDescriptor()
        ufo = self.ufo_module.Font()
        source.font = ufo

        ufo.lib[APP_VERSION_LIB_KEY] = font.appVersion
        ufo.lib[KEYBOARD_INCREMENT_KEY] = font.keyboardIncrement

        if date_created is not None:
            ufo.info.openTypeHeadCreated = date_created
        ufo.info.unitsPerEm = units_per_em
        ufo.info.versionMajor = version_major
        ufo.info.versionMinor = version_minor

        if copyright:
            ufo.info.copyright = copyright
        if designer:
            ufo.info.openTypeNameDesigner = designer
        if designer_url:
            ufo.info.openTypeNameDesignerURL = designer_url
        if manufacturer:
            ufo.info.openTypeNameManufacturer = manufacturer
        if manufacturer_url:
            ufo.info.openTypeNameManufacturerURL = manufacturer_url

        ufo.glyphOrder = glyph_order

        self.to_ufo_names(ufo, master, family_name)
        self.to_ufo_family_user_data(ufo)
        self.to_ufo_custom_params(ufo, font)

        self.to_ufo_master_attributes(source, master)

        ufo.lib[MASTER_ORDER_LIB_KEY] = index
        # FIXME: (jany) in the future, yield this UFO (for memory, lazy iter)
        self._designspace.addSource(source)
        self._sources[master.id] = source

Response: Generate a list of UFOs with metadata loaded from. glyphs data.


Instruction:
How would you implement a function in Python 3 that
copies font attributes from source UFO to self. font master.

Response:
def to_glyphs_font_attributes(self, source, master, is_initial):
    """
    Copy font attributes from `ufo` either to `self.font` or to `master`.

    Arguments:
    self -- The UFOBuilder
    ufo -- The current UFO being read
    master -- The current master being written
    is_initial -- True iff this the first UFO that we process
    """
    if is_initial:
        _set_glyphs_font_attributes(self, source)
    else:
        _compare_and_merge_glyphs_font_attributes(self, source)


Instruction:
Given the following Python 3 function, write the documentation
def to_ufo_glyph(self, ufo_glyph, layer, glyph):
    ufo_glyph.unicodes = [int(uval, 16) for uval in glyph.unicodes]

    note = glyph.note
    if note is not None:
        ufo_glyph.note = note

    last_change = glyph.lastChange
    if last_change is not None:
        ufo_glyph.lib[GLYPHLIB_PREFIX + "lastChange"] = to_ufo_time(last_change)

    color_index = glyph.color
    if color_index is not None:
        # .3f is enough precision to round-trip uint8 to float losslessly.
        # https://github.com/unified-font-object/ufo-spec/issues/61
        # #issuecomment-389759127
        if (
            isinstance(color_index, list)
            and len(color_index) == 4
            and all(0 <= v < 256 for v in color_index)
        ):
            ufo_glyph.markColor = ",".join(
                "{:.3f}".format(v / 255) for v in color_index
            )
        elif isinstance(color_index, int) and color_index in range(len(GLYPHS_COLORS)):
            ufo_glyph.markColor = GLYPHS_COLORS[color_index]
        else:
            logger.warning(
                "Glyph {}, layer {}: Invalid color index/tuple {}".format(
                    glyph.name, layer.name, color_index
                )
            )

    export = glyph.export
    if not export:
        if "public.skipExportGlyphs" not in self._designspace.lib:
            self._designspace.lib["public.skipExportGlyphs"] = []
        self._designspace.lib["public.skipExportGlyphs"].append(glyph.name)

    # FIXME: (jany) next line should be an API of GSGlyph?
    glyphinfo = glyphsLib.glyphdata.get_glyph(ufo_glyph.name)
    production_name = glyph.production or glyphinfo.production_name
    if production_name != ufo_glyph.name:
        postscriptNamesKey = PUBLIC_PREFIX + "postscriptNames"
        if postscriptNamesKey not in ufo_glyph.font.lib:
            ufo_glyph.font.lib[postscriptNamesKey] = dict()
        ufo_glyph.font.lib[postscriptNamesKey][ufo_glyph.name] = production_name

    for key in ["leftMetricsKey", "rightMetricsKey", "widthMetricsKey"]:
        value = getattr(layer, key, None)
        if value:
            ufo_glyph.lib[GLYPHLIB_PREFIX + "layer." + key] = value
        value = getattr(glyph, key, None)
        if value:
            ufo_glyph.lib[GLYPHLIB_PREFIX + "glyph." + key] = value

    if glyph.script is not None:
        ufo_glyph.lib[SCRIPT_LIB_KEY] = glyph.script

    # if glyph contains custom 'category' and 'subCategory' overrides, store
    # them in the UFO glyph's lib
    category = glyph.category
    if category is None:
        category = glyphinfo.category
    else:
        ufo_glyph.lib[GLYPHLIB_PREFIX + "category"] = category
    subCategory = glyph.subCategory
    if subCategory is None:
        subCategory = glyphinfo.subCategory
    else:
        ufo_glyph.lib[GLYPHLIB_PREFIX + "subCategory"] = subCategory

    # load width before background, which is loaded with lib data
    width = layer.width
    if width is None:
        pass
    elif category == "Mark" and subCategory == "Nonspacing" and width > 0:
        # zero the width of Nonspacing Marks like Glyphs.app does on export
        # TODO: (jany) check for customParameter DisableAllAutomaticBehaviour
        # FIXME: (jany) also don't do that when rt UFO -> glyphs -> UFO
        ufo_glyph.lib[ORIGINAL_WIDTH_KEY] = width
        ufo_glyph.width = 0
    else:
        ufo_glyph.width = width

    self.to_ufo_background_image(ufo_glyph, layer)
    self.to_ufo_guidelines(ufo_glyph, layer)
    self.to_ufo_glyph_background(ufo_glyph, layer)
    self.to_ufo_annotations(ufo_glyph, layer)
    self.to_ufo_hints(ufo_glyph, layer)
    self.to_ufo_glyph_user_data(ufo_glyph.font, glyph)
    self.to_ufo_layer_user_data(ufo_glyph, layer)
    self.to_ufo_smart_component_axes(ufo_glyph, glyph)

    self.to_ufo_paths(ufo_glyph, layer)
    self.to_ufo_components(ufo_glyph, layer)
    self.to_ufo_glyph_anchors(ufo_glyph, layer.anchors)

Response: Add. glyphs metadata paths components and anchors to a glyph.


Instruction:
Can you tell what is the following Python 3 function doing
def to_glyphs_glyph(self, ufo_glyph, ufo_layer, master):

    # FIXME: (jany) split between glyph and layer attributes
    #        have a write the first time, compare the next times for glyph
    #        always write for the layer

    if ufo_glyph.name in self.font.glyphs:
        glyph = self.font.glyphs[ufo_glyph.name]
    else:
        glyph = self.glyphs_module.GSGlyph(name=ufo_glyph.name)
        # FIXME: (jany) ordering?
        self.font.glyphs.append(glyph)

    if ufo_glyph.unicodes:
        glyph.unicodes = ["{:04X}".format(c) for c in ufo_glyph.unicodes]
    glyph.note = ufo_glyph.note or ""
    if GLYPHLIB_PREFIX + "lastChange" in ufo_glyph.lib:
        last_change = ufo_glyph.lib[GLYPHLIB_PREFIX + "lastChange"]
        # We cannot be strict about the dateformat because it's not an official
        # UFO field mentioned in the spec so it could happen to have a timezone
        glyph.lastChange = from_loose_ufo_time(last_change)
    if ufo_glyph.markColor:
        glyph.color = _to_glyphs_color(ufo_glyph.markColor)

    # The export flag can be stored in the glyph's lib key (for upgrading legacy
    # sources) or the Designspace-level public.skipExportGlyphs lib key (canonical
    # place to store the information). The UFO level lib key is ignored.
    if GLYPHLIB_PREFIX + "Export" in ufo_glyph.lib:
        glyph.export = ufo_glyph.lib[GLYPHLIB_PREFIX + "Export"]
    if ufo_glyph.name in self.designspace.lib.get("public.skipExportGlyphs", []):
        glyph.export = False

    ps_names_key = PUBLIC_PREFIX + "postscriptNames"
    if (
        ps_names_key in ufo_glyph.font.lib
        and ufo_glyph.name in ufo_glyph.font.lib[ps_names_key]
    ):
        glyph.production = ufo_glyph.font.lib[ps_names_key][ufo_glyph.name]
        # FIXME: (jany) maybe put something in glyphinfo? No, it's readonly
        #        maybe don't write in glyph.production if glyphinfo already
        #        has something
        # glyphinfo = glyphsLib.glyphdata.get_glyph(ufo_glyph.name)
        # production_name = glyph.production or glyphinfo.production_name

    glyphinfo = glyphsLib.glyphdata.get_glyph(ufo_glyph.name)

    layer = self.to_glyphs_layer(ufo_layer, glyph, master)

    for key in ["leftMetricsKey", "rightMetricsKey", "widthMetricsKey"]:
        # Also read the old version of the key that didn't have a prefix and
        # store it on the layer (because without the "glyph"/"layer" prefix we
        # didn't know whether it originally came from the layer of the glyph,
        # so it's easier to put it back on the most specific level, i.e. the
        # layer)
        for prefix, glyphs_object in (
            ("glyph.", glyph),
            ("", layer),
            ("layer.", layer),
        ):
            full_key = GLYPHLIB_PREFIX + prefix + key
            if full_key in ufo_glyph.lib:
                value = ufo_glyph.lib[full_key]
                setattr(glyphs_object, key, value)

    if SCRIPT_LIB_KEY in ufo_glyph.lib:
        glyph.script = ufo_glyph.lib[SCRIPT_LIB_KEY]

    if GLYPHLIB_PREFIX + "category" in ufo_glyph.lib:
        # TODO: (jany) store category only if different from glyphinfo?
        category = ufo_glyph.lib[GLYPHLIB_PREFIX + "category"]
        glyph.category = category
    else:
        category = glyphinfo.category
    if GLYPHLIB_PREFIX + "subCategory" in ufo_glyph.lib:
        sub_category = ufo_glyph.lib[GLYPHLIB_PREFIX + "subCategory"]
        glyph.subCategory = sub_category
    else:
        sub_category = glyphinfo.subCategory

    # load width before background, which is loaded with lib data
    if hasattr(layer, "foreground"):
        if ufo_glyph.width:
            # Don't store "0", it's the default in UFO.
            # Store in userData because the background's width is not relevant
            # in Glyphs.
            layer.userData[BACKGROUND_WIDTH_KEY] = ufo_glyph.width
    else:
        layer.width = ufo_glyph.width
    if category == "Mark" and sub_category == "Nonspacing" and layer.width == 0:
        # Restore originalWidth
        if ORIGINAL_WIDTH_KEY in ufo_glyph.lib:
            layer.width = ufo_glyph.lib[ORIGINAL_WIDTH_KEY]
            # TODO: (jany) check for customParam DisableAllAutomaticBehaviour?

    self.to_glyphs_background_image(ufo_glyph, layer)
    self.to_glyphs_guidelines(ufo_glyph, layer)
    self.to_glyphs_annotations(ufo_glyph, layer)
    self.to_glyphs_hints(ufo_glyph, layer)
    self.to_glyphs_glyph_user_data(ufo_glyph.font, glyph)
    self.to_glyphs_layer_user_data(ufo_glyph, layer)
    self.to_glyphs_smart_component_axes(ufo_glyph, glyph)

    self.to_glyphs_paths(ufo_glyph, layer)
    self.to_glyphs_components(ufo_glyph, layer)
    self.to_glyphs_glyph_anchors(ufo_glyph, layer)

Response: Add a UFO glyph to the GSLayer.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def to_designspace_instances(self):
    for instance in self.font.instances:
        if self.minimize_glyphs_diffs or (
            is_instance_active(instance)
            and _is_instance_included_in_family(self, instance)
        ):
            _to_designspace_instance(self, instance)

Response: Write instance data from self. font to self. designspace.


Instruction:
How would you explain what the following Python 3 function does
def apply_instance_data(designspace, include_filenames=None, Font=defcon.Font):
    from fontTools.designspaceLib import DesignSpaceDocument
    from os.path import normcase, normpath

    if hasattr(designspace, "__fspath__"):
        designspace = designspace.__fspath__()
    if isinstance(designspace, basestring):
        designspace = DesignSpaceDocument.fromfile(designspace)

    basedir = os.path.dirname(designspace.path)
    instance_ufos = []
    if include_filenames is not None:
        include_filenames = {normcase(normpath(p)) for p in include_filenames}

    for designspace_instance in designspace.instances:
        fname = designspace_instance.filename
        assert fname is not None, "instance %r missing required filename" % getattr(
            designspace_instance, "name", designspace_instance
        )
        if include_filenames is not None:
            fname = normcase(normpath(fname))
            if fname not in include_filenames:
                continue

        logger.debug("Applying instance data to %s", fname)
        # fontmake <= 1.4.0 compares the ufo paths returned from this function
        # to the keys of a dict of designspace locations that have been passed
        # through normpath (but not normcase). We do the same.
        ufo = Font(normpath(os.path.join(basedir, fname)))

        set_weight_class(ufo, designspace, designspace_instance)
        set_width_class(ufo, designspace, designspace_instance)

        glyphs_instance = InstanceDescriptorAsGSInstance(designspace_instance)
        to_ufo_custom_params(None, ufo, glyphs_instance)
        ufo.save()
        instance_ufos.append(ufo)
    return instance_ufos

Response: Open UFO instances referenced by designspace and apply Glyphs instancedata to the UFOs and return updated UFOs.


Instruction:
How would you explain what the following Python 3 function does
def _to_ufo_features(self, master, ufo):

    # Recover the original feature code if it was stored in the user data
    original = master.userData[ORIGINAL_FEATURE_CODE_KEY]
    if original is not None:
        ufo.features.text = original
        return

    prefixes = []
    for prefix in self.font.featurePrefixes:
        strings = []
        if prefix.name != ANONYMOUS_FEATURE_PREFIX_NAME:
            strings.append("# Prefix: %s\n" % prefix.name)
        strings.append(autostr(prefix.automatic))
        strings.append(prefix.code)
        prefixes.append("".join(strings))

    prefix_str = "\n\n".join(prefixes)

    class_defs = []
    for class_ in self.font.classes:
        prefix = "@" if not class_.name.startswith("@") else ""
        name = prefix + class_.name
        class_defs.append(
            "{}{} = [ {} ];".format(autostr(class_.automatic), name, class_.code)
        )
    class_str = "\n\n".join(class_defs)

    feature_defs = []
    for feature in self.font.features:
        code = feature.code
        lines = ["feature %s {" % feature.name]
        if feature.notes:
            lines.append("# notes:")
            lines.extend("# " + line for line in feature.notes.splitlines())
        if feature.automatic:
            lines.append("# automatic")
        if feature.disabled:
            lines.append("# disabled")
            lines.extend("#" + line for line in code.splitlines())
        else:
            lines.append(code)
        lines.append("} %s;" % feature.name)
        feature_defs.append("\n".join(lines))
    fea_str = "\n\n".join(feature_defs)

    # Don't add a GDEF table when planning to round-trip. To get Glyphs.app-like
    # results, we would need anchor propagation or user intervention. Glyphs.app
    # only generates it on generating binaries.
    gdef_str = None
    if self.generate_GDEF:
        if re.search(r"^\s*table\s+GDEF\s+{", prefix_str, flags=re.MULTILINE):
            raise ValueError(
                "The features already contain a `table GDEF {...}` statement. "
                "Either delete it or set generate_GDEF to False."
            )
        gdef_str = _build_gdef(
            ufo, self._designspace.lib.get("public.skipExportGlyphs")
        )

    # make sure feature text is a unicode string, for defcon
    full_text = (
        "\n\n".join(filter(None, [class_str, prefix_str, fea_str, gdef_str])) + "\n"
    )
    ufo.features.text = full_text if full_text.strip() else ""

Response: Write an UFO s OpenType feature file.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _build_gdef(ufo, skipExportGlyphs=None):
    from glyphsLib import glyphdata

    bases, ligatures, marks, carets = set(), set(), set(), {}
    category_key = GLYPHLIB_PREFIX + "category"
    subCategory_key = GLYPHLIB_PREFIX + "subCategory"

    for glyph in ufo:
        # Do not generate any entries for non-export glyphs, as looking them up on
        # compilation will fail.
        if skipExportGlyphs is not None:
            if glyph.name in skipExportGlyphs:
                continue

        has_attaching_anchor = False
        for anchor in glyph.anchors:
            name = anchor.name
            if name and not name.startswith("_"):
                has_attaching_anchor = True
            if name and name.startswith("caret_") and "x" in anchor:
                carets.setdefault(glyph.name, []).append(round(anchor["x"]))

        # First check glyph.lib for category/subCategory overrides. Otherwise,
        # use global values from GlyphData.
        glyphinfo = glyphdata.get_glyph(glyph.name)
        category = glyph.lib.get(category_key) or glyphinfo.category
        subCategory = glyph.lib.get(subCategory_key) or glyphinfo.subCategory

        if subCategory == "Ligature" and has_attaching_anchor:
            ligatures.add(glyph.name)
        elif category == "Mark" and (
            subCategory == "Nonspacing" or subCategory == "Spacing Combining"
        ):
            marks.add(glyph.name)
        elif has_attaching_anchor:
            bases.add(glyph.name)

    if not any((bases, ligatures, marks, carets)):
        return None

    def fmt(g):
        return ("[%s]" % " ".join(sorted(g, key=ufo.glyphOrder.index))) if g else ""

    lines = [
        "table GDEF {",
        "  # automatic",
        "  GlyphClassDef",
        "    %s, # Base" % fmt(bases),
        "    %s, # Liga" % fmt(ligatures),
        "    %s, # Mark" % fmt(marks),
        "    ;",
    ]
    for glyph, caretPos in sorted(carets.items()):
        lines.append(
            "  LigatureCaretByPos %s %s;"
            % (glyph, " ".join(unicode(p) for p in sorted(caretPos)))
        )
    lines.append("} GDEF;")

    return "\n".join(lines)

Response: Build a GDEF table statement for a UFO.


Instruction:
Can you create a Python 3 function that
looks for the comment that matches the given regex. If it does not match return the regex match object and list of statements without the special one.

Response:
def _pop_comment(self, statements, comment_re):
        """Look for the comment that matches the given regex.
        If it matches, return the regex match object and list of statements
        without the special one.
        """
        res = []
        match = None
        for st in statements:
            if match or not isinstance(st, ast.Comment):
                res.append(st)
                continue
            match = comment_re.match(st.text)
            if not match:
                res.append(st)
        return match, res


Instruction:
Explain what the following Python 3 code does
def _pop_comment_block(self, statements, header_re):
        res = []
        comments = []
        match = None
        st_iter = iter(statements)
        # Look for the header
        for st in st_iter:
            if isinstance(st, ast.Comment):
                match = header_re.match(st.text)
                if match:
                    # Drop this comment an move on to consuming the block
                    break
                else:
                    res.append(st)
            else:
                res.append(st)
        # Consume consecutive comments
        for st in st_iter:
            if isinstance(st, ast.Comment):
                comments.append(st)
            else:
                # The block is over, keep the rest of the statements
                res.append(st)
                break
        # Keep the rest of the statements
        res.extend(list(st_iter))
        # Inside the comment block, drop the pound sign and any common indent
        return match, dedent("".join(c.text[1:] + "\n" for c in comments)), res

Response:
Look for a series of comments that start with one that matches the
        regex and return the match and the dedented version of the comments.


Instruction:
Write a Python 3 function that can
get the schema name.

Response:
def get_marshmallow_schema_name(self, plugin, schema):
        """Get the schema name.

        If the schema doesn't exist, create it.
        """
        try:
            return plugin.openapi.refs[schema]
        except KeyError:
            plugin.spec.definition(schema.__name__, schema=schema)
            return schema.__name__


Instruction:
Explain what the following Python 3 code does
def to_ufo_components(self, ufo_glyph, layer):
    pen = ufo_glyph.getPointPen()

    for index, component in enumerate(layer.components):
        pen.addComponent(component.name, component.transform)

        if component.anchor:
            if COMPONENT_INFO_KEY not in ufo_glyph.lib:
                ufo_glyph.lib[COMPONENT_INFO_KEY] = []
            ufo_glyph.lib[COMPONENT_INFO_KEY].append(
                {"name": component.name, "index": index, "anchor": component.anchor}
            )

    # data related to components stored in lists of booleans
    # each list's elements correspond to the components in order
    for key in ["alignment", "locked", "smartComponentValues"]:
        values = [getattr(c, key) for c in layer.components]
        if any(values):
            ufo_glyph.lib[_lib_key(key)] = values

Response: Draw. glyphs components onto a pen adding them to the parent glyph.


Instruction:
Can you implement a function in Python 3 that
uses args_schema to parse request query arguments.

Response:
def request_args(self):
        """Use args_schema to parse request query arguments."""
        args = flask.request.args
        data_raw = {}

        for field_name, field in self.args_schema.fields.items():
            alternate_field_name = field.load_from if MA2 else field.data_key

            if alternate_field_name and alternate_field_name in args:
                field_name = alternate_field_name
            elif field_name not in args:
                # getlist will return an empty list instead of raising a
                # KeyError for args that aren't present.
                continue

            value = args.getlist(field_name)
            if not self.is_list_field(field) and len(value) == 1:
                value = value[0]

            data_raw[field_name] = value

        return self.deserialize_args(data_raw)


Instruction:
Can you write a function in Python 3 where it
returns the options to apply to the query for the view.

Response:
def query_options(self):
        """Options to apply to the query for the view.

        Set this to configure relationship and column loading.

        By default, this calls the ``get_query_options`` method on the
        serializer with a `Load` object bound to the model, if that serializer
        method exists.
        """
        if not hasattr(self.serializer, 'get_query_options'):
            return ()

        return self.serializer.get_query_options(Load(self.model))


Instruction:
Write a Python 3 script for
drawing glyphs paths onto a pen.

Response:
def to_ufo_paths(self, ufo_glyph, layer):
    """Draw .glyphs paths onto a pen."""
    pen = ufo_glyph.getPointPen()

    for path in layer.paths:
        # the list is changed below, otherwise you can't draw more than once
        # per session.
        nodes = list(path.nodes)
        for node in nodes:
            self.to_ufo_node_user_data(ufo_glyph, node)

        pen.beginPath()
        if not nodes:
            pen.endPath()
            continue
        if not path.closed:
            node = nodes.pop(0)
            assert node.type == "line", "Open path starts with off-curve points"
            pen.addPoint(tuple(node.position), segmentType="move")
        else:
            # In Glyphs.app, the starting node of a closed contour is always
            # stored at the end of the nodes list.
            nodes.insert(0, nodes.pop())
        for node in nodes:
            node_type = _to_ufo_node_type(node.type)
            pen.addPoint(
                tuple(node.position), segmentType=node_type, smooth=node.smooth
            )
        pen.endPath()


Instruction:
Make a summary of the following Python 3 code
def request_cached_property(func):
    @property
    @functools.wraps(func)
    def wrapped(self):
        cached_value = context.get_for_view(self, func.__name__, UNDEFINED)
        if cached_value is not UNDEFINED:
            return cached_value

        value = func(self)
        context.set_for_view(self, func.__name__, value)

        return value

    return wrapped

Response: Make the given method a per - request cached property.


Instruction:
How would you implement a function in Python 3 that
returns a string that can identify this UFO in logs.

Response:
def _ufo_logging_ref(ufo):
    """Return a string that can identify this UFO in logs."""
    if ufo.path:
        return os.path.basename(ufo.path)
    return ufo.info.styleName


Instruction:
Explain what the following Python 3 code does
def parse_datetime(src=None):
    if src is None:
        return None
    string = src.replace('"', "")
    # parse timezone ourselves, since %z is not always supported
    # see: http://bugs.python.org/issue6641
    m = UTC_OFFSET_RE.match(string)
    if m:
        sign = 1 if m.group("sign") == "+" else -1
        tz_hours = sign * int(m.group("hours"))
        tz_minutes = sign * int(m.group("minutes"))
        offset = datetime.timedelta(hours=tz_hours, minutes=tz_minutes)
        string = string[:-6]
    else:
        # no explicit timezone
        offset = datetime.timedelta(0)
    if "AM" in string or "PM" in string:
        datetime_obj = datetime.datetime.strptime(string, "%Y-%m-%d %I:%M:%S %p")
    else:
        datetime_obj = datetime.datetime.strptime(string, "%Y-%m-%d %H:%M:%S")
    return datetime_obj + offset

Response: Parse a datetime object from a string.


Instruction:
How would you explain what the following Python 3 function does
def parse_color(src=None):
    # type: (Optional[str]) -> Optional[Union[Tuple[int, ...], int]]
    """Parse a string representing a color value.

    Color is either a fixed color (when coloring something from the UI, see
    the GLYPHS_COLORS constant) or a list of the format [u8, u8, u8, u8],

    Glyphs does not support an alpha channel as of 2.5.1 (confirmed by Georg
    Seifert), and always writes a 1 to it. This was brought up and is probably
    corrected in the next versions.
    https://github.com/googlei18n/glyphsLib/pull/363#issuecomment-390418497
    """
    if src is None:
        return None

    # Tuple.
    if src[0] == "(":
        rgba = tuple(int(v) for v in src[1:-1].split(",") if v)

        if not (len(rgba) == 4 and all(0 <= v < 256 for v in rgba)):
            raise ValueError(
                "Broken color tuple: {}. Must have four values from 0 to 255.".format(
                    src
                )
            )

        return rgba

    # Constant.
    return int(src)

Response: Parses a string representing a color value.


Instruction:
Write a Python 3 script to
write a GSFont object to a. glyphs file.

Response:
def dump(obj, fp):
    """Write a GSFont object to a .glyphs file.
    'fp' should be a (writable) file object.
    """
    writer = Writer(fp)
    logger.info("Writing .glyphs file")
    writer.write(obj)


Instruction:
Make a summary of the following Python 3 code
def loads(s):
    p = Parser(current_type=glyphsLib.classes.GSFont)
    logger.info("Parsing .glyphs file")
    data = p.parse(s)
    return data

Response:
Read a. glyphs file from a ( unicode ) str object or from
    a UTF - 8 encoded bytes object. Return a GSFont object.


Instruction:
Can you implement a function in Python 3 that
parses data into an existing GSFont instance.

Response:
def parse_into_object(self, res, text):
        """Parse data into an existing GSFont instance."""

        text = tounicode(text, encoding="utf-8")

        m = self.start_dict_re.match(text, 0)
        if m:
            i = self._parse_dict_into_object(res, text, 1)
        else:
            self._fail("not correct file format", text, 0)
        if text[i:].strip():
            self._fail("Unexpected trailing content", text, i)
        return i


Instruction:
Can you generate the documentation for the following Python 3 function
def _parse(self, text, i):

        m = self.start_dict_re.match(text, i)
        if m:
            parsed = m.group(0)
            i += len(parsed)
            return self._parse_dict(text, i)

        m = self.start_list_re.match(text, i)
        if m:
            parsed = m.group(0)
            i += len(parsed)
            return self._parse_list(text, i)

        m = self.value_re.match(text, i)
        if m:
            parsed = m.group(0)
            i += len(parsed)
            if hasattr(self.current_type, "read"):
                reader = self.current_type()
                # Give the escaped value to `read` to be symetrical with
                # `plistValue` which handles the escaping itself.
                value = reader.read(m.group(1))
                return value, i

            value = self._trim_value(m.group(1))

            if self.current_type in (None, dict, OrderedDict):
                self.current_type = self._guess_current_type(parsed, value)

            if self.current_type == bool:
                value = bool(int(value))  # bool(u'0') returns True
                return value, i

            value = self.current_type(value)

            return value, i

        m = self.hex_re.match(text, i)
        if m:
            from glyphsLib.types import BinaryData

            parsed, value = m.group(0), m.group(1)
            decoded = BinaryData.fromHex(value)
            i += len(parsed)
            return decoded, i
        else:
            self._fail("Unexpected content", text, i)

Response: Recursive function to parse a single dictionary list or value.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _parse_dict(self, text, i):
        old_current_type = self.current_type
        new_type = self.current_type
        if new_type is None:
            # customparameter.value needs to be set from the found value
            new_type = dict
        elif type(new_type) == list:
            new_type = new_type[0]
        res = new_type()
        i = self._parse_dict_into_object(res, text, i)
        self.current_type = old_current_type
        return res, i

Response: Parse a dictionary from source text starting at i.


Instruction:
Write a Python 3 script for
parsing a list from source text starting at i.

Response:
def _parse_list(self, text, i):
        """Parse a list from source text starting at i."""

        res = []
        end_match = self.end_list_re.match(text, i)
        old_current_type = self.current_type
        while not end_match:
            list_item, i = self._parse(text, i)
            res.append(list_item)

            end_match = self.end_list_re.match(text, i)

            if not end_match:
                m = self.list_delim_re.match(text, i)
                if not m:
                    self._fail("Missing delimiter in list before content", text, i)
                parsed = m.group(0)
                i += len(parsed)
            self.current_type = old_current_type

        parsed = end_match.group(0)
        i += len(parsed)
        return res, i


Instruction:
Create a Python 3 function to
trim double quotes off the ends of a value and convert escapes to unicode.

Response:
def _trim_value(self, value):
        """Trim double quotes off the ends of a value, un-escaping inner
        double quotes and literal backslashes. Also convert escapes to unicode.
        If the string is not quoted, return it unmodified.
        """

        if value[0] == '"':
            assert value[-1] == '"'
            value = value[1:-1].replace('\\"', '"').replace("\\\\", "\\")
            return Parser._unescape_re.sub(Parser._unescape_fn, value)
        return value


Instruction:
Make a summary of the following Python 3 code
def _fail(self, message, text, i):

        raise ValueError("{}:\n{}".format(message, text[i : i + 79]))

Response: Raise an exception with given message and text at i.


Instruction:
Here you have a function in Python 3, explain what it does
def build_stylemap_names(
    family_name, style_name, is_bold=False, is_italic=False, linked_style=None
):
    """Build UFO `styleMapFamilyName` and `styleMapStyleName` based on the
    family and style names, and the entries in the "Style Linking" section
    of the "Instances" tab in the "Font Info".

    The value of `styleMapStyleName` can be either "regular", "bold", "italic"
    or "bold italic", depending on the values of `is_bold` and `is_italic`.

    The `styleMapFamilyName` is a combination of the `family_name` and the
    `linked_style`.

    If `linked_style` is unset or set to 'Regular', the linked style is equal
    to the style_name with the last occurrences of the strings 'Regular',
    'Bold' and 'Italic' stripped from it.
    """

    styleMapStyleName = (
        " ".join(
            s for s in ("bold" if is_bold else "", "italic" if is_italic else "") if s
        )
        or "regular"
    )
    if not linked_style or linked_style == "Regular":
        linked_style = _get_linked_style(style_name, is_bold, is_italic)
    if linked_style:
        styleMapFamilyName = (family_name or "") + " " + linked_style
    else:
        styleMapFamilyName = family_name
    return styleMapFamilyName, styleMapStyleName

Response: Build the UFO styleMapFamilyName and styleMapStyleName from family_name and style_name.


Instruction:
Can you write a function in Python 3 where it
sets postscript blue values from Glyphs alignment zones.

Response:
def to_ufo_blue_values(self, ufo, master):
    """Set postscript blue values from Glyphs alignment zones."""

    alignment_zones = master.alignmentZones
    blue_values = []
    other_blues = []
    for zone in sorted(alignment_zones):
        pos = zone.position
        size = zone.size
        val_list = blue_values if pos == 0 or size >= 0 else other_blues
        val_list.extend(sorted((pos, pos + size)))

    ufo.info.postscriptBlueValues = blue_values
    ufo.info.postscriptOtherBlues = other_blues


Instruction:
Can you write a function in Python 3 where it
sets the GSFontMaster alignmentZones from the postscript blue values.

Response:
def to_glyphs_blue_values(self, ufo, master):
    """Sets the GSFontMaster alignmentZones from the postscript blue values."""

    zones = []
    blue_values = _pairs(ufo.info.postscriptBlueValues)
    other_blues = _pairs(ufo.info.postscriptOtherBlues)
    for y1, y2 in blue_values:
        size = y2 - y1
        if y2 == 0:
            pos = 0
            size = -size
        else:
            pos = y1
        zones.append(self.glyphs_module.GSAlignmentZone(pos, size))
    for y1, y2 in other_blues:
        size = y1 - y2
        pos = y2
        zones.append(self.glyphs_module.GSAlignmentZone(pos, size))

    master.alignmentZones = sorted(zones, key=lambda zone: -zone.position)


Instruction:
Make a summary of the following Python 3 code
def parse_glyphs_filter(filter_str, is_pre=False):
    elements = filter_str.split(";")

    if elements[0] == "":
        logger.error(
            "Failed to parse glyphs filter, expecting a filter name: \
             %s",
            filter_str,
        )
        return None

    result = {"name": elements[0]}
    for idx, elem in enumerate(elements[1:]):
        if not elem:
            # skip empty arguments
            continue
        if ":" in elem:
            # Key value pair
            key, value = elem.split(":", 1)
            if key.lower() in ["include", "exclude"]:
                if idx != len(elements[1:]) - 1:
                    logger.error(
                        "{} can only present as the last argument in the filter. "
                        "{} is ignored.".format(key, elem)
                    )
                    continue
                result[key.lower()] = re.split("[ ,]+", value)
            else:
                if "kwargs" not in result:
                    result["kwargs"] = {}
                result["kwargs"][key] = cast_to_number_or_bool(value)
        else:
            if "args" not in result:
                result["args"] = []
            result["args"].append(cast_to_number_or_bool(elem))
    if is_pre:
        result["pre"] = True
    return result

Response: Parses a glyphs custom filter string into a dictionary that can be used to create a new glyph app.


Instruction:
Implement a Python 3 function for
building a UFO path from family_name and style_name.

Response:
def build_ufo_path(out_dir, family_name, style_name):
    """Build string to use as a UFO path."""

    return os.path.join(
        out_dir,
        "%s-%s.ufo"
        % ((family_name or "").replace(" ", ""), (style_name or "").replace(" ", "")),
    )


Instruction:
Create a Python 3 function for
making sure old UFO data is removed.

Response:
def clean_ufo(path):
    """Make sure old UFO data is removed, as it may contain deleted glyphs."""

    if path.endswith(".ufo") and os.path.exists(path):
        shutil.rmtree(path)


Instruction:
Make a summary of the following Python 3 code
def ufo_create_background_layer_for_all_glyphs(ufo_font):
    # type: (defcon.Font) -> None
    """Create a background layer for all glyphs in ufo_font if not present to
    reduce roundtrip differences."""

    if "public.background" in ufo_font.layers:
        background = ufo_font.layers["public.background"]
    else:
        background = ufo_font.newLayer("public.background")

    for glyph in ufo_font:
        if glyph.name not in background:
            background.newGlyph(glyph.name)

Response: Create a background layer for all glyphs in ufo_font.


Instruction:
Can you tell what is the following Python 3 function doing
def cast_to_number_or_bool(inputstr):
    if inputstr.strip().lower() == "true":
        return True
    elif inputstr.strip().lower() == "false":
        return False
    try:
        return int(inputstr)
    except ValueError:
        try:
            return float(inputstr)
        except ValueError:
            return inputstr

Response:
Cast a string to int float or bool. Return original string if it can t be
    converted.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def to_ufo_background_image(self, ufo_glyph, layer):
    image = layer.backgroundImage
    if image is None:
        return
    ufo_image = ufo_glyph.image
    ufo_image.fileName = image.path
    ufo_image.transformation = image.transform
    ufo_glyph.lib[CROP_KEY] = list(image.crop)
    ufo_glyph.lib[LOCKED_KEY] = image.locked
    ufo_glyph.lib[ALPHA_KEY] = image.alpha

Response: Copy the backgound image from the GSLayer to the UFO Glyph.


Instruction:
Explain what the following Python 3 code does
def to_glyphs_background_image(self, ufo_glyph, layer):
    ufo_image = ufo_glyph.image
    if ufo_image.fileName is None:
        return
    image = self.glyphs_module.GSBackgroundImage()
    image.path = ufo_image.fileName
    image.transform = Transform(*ufo_image.transformation)
    if CROP_KEY in ufo_glyph.lib:
        x, y, w, h = ufo_glyph.lib[CROP_KEY]
        image.crop = Rect(Point(x, y), Size(w, h))
    if LOCKED_KEY in ufo_glyph.lib:
        image.locked = ufo_glyph.lib[LOCKED_KEY]
    if ALPHA_KEY in ufo_glyph.lib:
        image.alpha = ufo_glyph.lib[ALPHA_KEY]
    layer.backgroundImage = image

Response: Copy the background image from the UFO Glyph to the GSLayer.


Instruction:
Can you tell what is the following Python 3 function doing
def add_resource(
        self,
        base_rule,
        base_view,
        alternate_view=None,
        alternate_rule=None,
        id_rule=None,
        app=None,
    ):
        """Add route or routes for a resource.

        :param str base_rule: The URL rule for the resource. This will be
            prefixed by the API prefix.
        :param base_view: Class-based view for the resource.
        :param alternate_view: If specified, an alternate class-based view for
            the resource. Usually, this will be a detail view, when the base
            view is a list view.
        :param alternate_rule: If specified, the URL rule for the alternate
            view. This will be prefixed by the API prefix. This is mutually
            exclusive with id_rule, and must not be specified if alternate_view
            is not specified.
        :type alternate_rule: str or None
        :param id_rule: If specified, a suffix to append to base_rule to get
            the alternate view URL rule. If alternate_view is specified, and
            alternate_rule is not, then this defaults to '<id>'. This is
            mutually exclusive with alternate_rule, and must not be specified
            if alternate_view is not specified.
        :type id_rule: str or None
        :param app: If specified, the application to which to add the route(s).
            Otherwise, this will be the bound application, if present.
        """
        if alternate_view:
            if not alternate_rule:
                id_rule = id_rule or DEFAULT_ID_RULE
                alternate_rule = posixpath.join(base_rule, id_rule)
            else:
                assert id_rule is None
        else:
            assert alternate_rule is None
            assert id_rule is None

        app = self._get_app(app)
        endpoint = self._get_endpoint(base_view, alternate_view)

        # Store the view rules for reference. Doesn't support multiple routes
        # mapped to same view.
        views = app.extensions['resty'].views

        base_rule_full = '{}{}'.format(self.prefix, base_rule)
        base_view_func = base_view.as_view(endpoint)

        if not alternate_view:
            app.add_url_rule(base_rule_full, view_func=base_view_func)
            views[base_view] = Resource(base_view, base_rule_full)
            return

        alternate_rule_full = '{}{}'.format(self.prefix, alternate_rule)
        alternate_view_func = alternate_view.as_view(endpoint)

        @functools.wraps(base_view_func)
        def view_func(*args, **kwargs):
            if flask.request.url_rule.rule == base_rule_full:
                return base_view_func(*args, **kwargs)
            else:
                return alternate_view_func(*args, **kwargs)

        app.add_url_rule(
            base_rule_full, view_func=view_func, endpoint=endpoint,
            methods=base_view.methods,
        )
        app.add_url_rule(
            alternate_rule_full, view_func=view_func, endpoint=endpoint,
            methods=alternate_view.methods,
        )

        views[base_view] = Resource(base_view, base_rule_full)
        views[alternate_view] = Resource(alternate_view, alternate_rule_full)

Response: Add a resource to the resource cache.


Instruction:
How would you explain what the following Python 3 function does
def add_ping(self, rule, status_code=200, app=None):
        app = self._get_app(app)

        @app.route(rule)
        def ping():
            return '', status_code

Response: Add a ping route.


Instruction:
How would you explain what the following Python 3 function does
def masters(self):
        if self._sources:
            for source in self._sources.values():
                yield source.font
            return

        # Store set of actually existing master (layer) ids. This helps with
        # catching dangling layer data that Glyphs may ignore, e.g. when
        # copying glyphs from other fonts with, naturally, different master
        # ids. Note: Masters have unique ids according to the Glyphs
        # documentation and can therefore be stored in a set.
        master_layer_ids = {m.id for m in self.font.masters}

        # stores background data from "associated layers"
        supplementary_layer_data = []

        # TODO(jamesgk) maybe create one font at a time to reduce memory usage
        # TODO: (jany) in the future, return a lazy iterator that builds UFOs
        #     on demand.
        self.to_ufo_font_attributes(self.family_name)

        # Generate the main (master) layers first.
        for glyph in self.font.glyphs:
            for layer in glyph.layers.values():
                if layer.associatedMasterId != layer.layerId:
                    # The layer is not the main layer of a master
                    # Store all layers, even the invalid ones, and just skip
                    # them and print a warning below.
                    supplementary_layer_data.append((glyph, layer))
                    continue

                ufo_layer = self.to_ufo_layer(glyph, layer)
                ufo_glyph = ufo_layer.newGlyph(glyph.name)
                self.to_ufo_glyph(ufo_glyph, layer, glyph)

        # And sublayers (brace, bracket, ...) second.
        for glyph, layer in supplementary_layer_data:
            if (
                layer.layerId not in master_layer_ids
                and layer.associatedMasterId not in master_layer_ids
            ):
                if self.minimize_glyphs_diffs:
                    self.logger.warning(
                        '{}, glyph "{}": Layer "{}" is dangling and will be '
                        "skipped. Did you copy a glyph from a different font?"
                        " If so, you should clean up any phantom layers not "
                        "associated with an actual master.".format(
                            self.font.familyName, glyph.name, layer.layerId
                        )
                    )
                continue

            if not layer.name:
                # Empty layer names are invalid according to the UFO spec.
                if self.minimize_glyphs_diffs:
                    self.logger.warning(
                        '{}, glyph "{}": Contains layer without a name which '
                        "will be skipped.".format(self.font.familyName, glyph.name)
                    )
                continue

            # Save processing bracket layers for when designspace() is called, as we
            # have to extract them to free-standing glyphs.
            if (
                "[" in layer.name
                and "]" in layer.name
                and ".background" not in layer.name
            ):
                self.bracket_layers.append(layer)
            else:
                ufo_layer = self.to_ufo_layer(glyph, layer)
                ufo_glyph = ufo_layer.newGlyph(glyph.name)
                self.to_ufo_glyph(ufo_glyph, layer, layer.parent)

        for source in self._sources.values():
            ufo = source.font
            if self.propagate_anchors:
                self.to_ufo_propagate_font_anchors(ufo)
            for layer in ufo.layers:
                self.to_ufo_layer_lib(layer)

        # Sanitize skip list and write it to both Designspace- and UFO-level lib keys.
        # The latter is unnecessary when using e.g. the `ufo2ft.compile*FromDS`
        # functions, but the data may take a different path. Writing it everywhere can
        # save on surprises/logic in other software.
        skip_export_glyphs = self._designspace.lib.get("public.skipExportGlyphs")
        if skip_export_glyphs is not None:
            skip_export_glyphs = sorted(set(skip_export_glyphs))
            self._designspace.lib["public.skipExportGlyphs"] = skip_export_glyphs
            for source in self._sources.values():
                source.font.lib["public.skipExportGlyphs"] = skip_export_glyphs

        self.to_ufo_features()  # This depends on the glyphOrder key
        self.to_ufo_groups()
        self.to_ufo_kerning()

        for source in self._sources.values():
            yield source.font

Response: Get an iterator over master UFOs that match the family_name.


Instruction:
Explain what the following Python 3 code does
def designspace(self):
        if self._designspace_is_complete:
            return self._designspace

        self._designspace_is_complete = True
        list(self.masters)  # Make sure that the UFOs are built
        self.to_designspace_axes()
        self.to_designspace_sources()
        self.to_designspace_instances()
        self.to_designspace_family_user_data()

        if self.bracket_layers:
            self._apply_bracket_layers()

        # append base style shared by all masters to designspace file name
        base_family = self.family_name or "Unnamed"
        base_style = find_base_style(self.font.masters)
        if base_style:
            base_style = "-" + base_style
        name = (base_family + base_style).replace(" ", "") + ".designspace"
        self.designspace.filename = name

        return self._designspace

Response:
Get a designspace Document instance that links the masters together
        and holds instance data.


Instruction:
Write a Python 3 script for
applying bracket layers to a free -standing UFO glyph.

Response:
def _apply_bracket_layers(self):
        """Extract bracket layers in a GSGlyph into free-standing UFO glyphs with
        Designspace substitution rules.

        As of Glyphs.app 2.6, only single axis bracket layers are supported, we
        assume the axis to be the first axis in the Designspace. Bracket layer
        backgrounds are not round-tripped.

        A glyph can have more than one bracket layer but Designspace
        rule/OpenType variation condition sets apply all substitutions in a rule
        in a range, so we have to potentially sort bracket layers into rule
        buckets. Example: if a glyph "x" has two bracket layers [300] and [600]
        and glyph "a" has bracket layer [300] and the bracket axis tops out at
        1000, we need the following Designspace rules:

        - BRACKET.300.600  # min 300, max 600 on the bracket axis.
          - x -> x.BRACKET.300
        - BRACKET.600.1000
          - x -> x.BRACKET.600
        - BRACKET.300.1000
          - a -> a.BRACKET.300
        """
        if not self._designspace.axes:
            raise ValueError(
                "Cannot apply bracket layers unless at least one axis is defined."
            )
        bracket_axis = self._designspace.axes[0]

        # Determine the axis scale in design space because crossovers/locations are
        # in design space (axis.default/minimum/maximum may be user space).
        if bracket_axis.map:
            axis_scale = [design_location for _, design_location in bracket_axis.map]
            bracket_axis_min = min(axis_scale)
            bracket_axis_max = max(axis_scale)
        else:  # No mapping means user and design space are the same.
            bracket_axis_min = bracket_axis.minimum
            bracket_axis_max = bracket_axis.maximum

        # 1. bracket_layer_map: Organize all bracket layers by crossover value, so
        #    we can go through the layers by location and copy them to free-standing
        #    glyphs.
        # 2. glyph_crossovers: Keep track of the crossover values of a single glyph, so
        #    we can easily sort them into rule buckets.
        # 3. glyph_sanity_counter: Count the number of master layers providing
        #    bracket layers per glyph and crossover value. We currently only support
        #    the situation where there is a bracket layer for _all_ masters, what the
        #    Glyphs.app tutorial calls 'Changing All Masters'.
        bracket_layer_map = defaultdict(list)  # type: Dict[int, List[classes.GSLayer]]
        glyph_crossovers = defaultdict(set)  # type: Dict[str, Set[int]]
        glyph_sanity_counter = defaultdict(
            list
        )  # type: Dict[Tuple[str, int], List[str]]
        for layer in self.bracket_layers:
            glyph_name = layer.parent.name
            n = layer.name
            try:
                bracket_crossover = int(n[n.index("[") + 1 : n.index("]")])
            except ValueError:
                raise ValueError(
                    "Only bracket layers with one numerical (design space) location "
                    "(meaning the first axis in the designspace file) are currently "
                    "supported."
                )
            if not bracket_axis_min <= bracket_crossover <= bracket_axis_max:
                raise ValueError(
                    "Glyph {glyph_name}: Bracket layer {layer_name} must be within the "
                    "design space bounds of the {bracket_axis_name} axis: minimum "
                    "{bracket_axis_minimum}, maximum {bracket_axis_maximum}.".format(
                        glyph_name=glyph_name,
                        layer_name=n,
                        bracket_axis_name=bracket_axis.name,
                        bracket_axis_minimum=bracket_axis_min,
                        bracket_axis_maximum=bracket_axis_max,
                    )
                )
            bracket_layer_map[bracket_crossover].append(layer)
            glyph_crossovers[glyph_name].add(bracket_crossover)
            glyph_sanity_counter[(glyph_name, bracket_crossover)].append(
                layer.associatedMasterId
            )

        # Check that each bracket layer is present in all master layers.
        unbalanced_bracket_layers = []
        n_masters = len(list(self.masters))
        for ((glyph_name, _), master_layer_ids) in glyph_sanity_counter.items():
            if not len(master_layer_ids) == n_masters:
                unbalanced_bracket_layers.append(glyph_name)
        if unbalanced_bracket_layers:
            raise ValueError(
                "Currently, we only support bracket layers that are present on all "
                "masters, i.e. what the Glyphs.app tutorial calls 'Changing All "
                "Masters'. There is a/are bracket layer(s) missing "
                "for glyph(s) {unbalanced_glyphs}.".format(
                    unbalanced_glyphs=unbalanced_bracket_layers
                )
            )

        # Sort crossovers into buckets.
        rule_bucket = defaultdict(list)  # type: Dict[Tuple[int, int], List[int]]
        for glyph_name, crossovers in sorted(glyph_crossovers.items()):
            for crossover_min, crossover_max in util.pairwise(
                sorted(crossovers) + [bracket_axis_max]
            ):
                rule_bucket[(int(crossover_min), int(crossover_max))].append(glyph_name)

        # Generate rules for the bracket layers.
        for (axis_range_min, axis_range_max), glyph_names in sorted(
            rule_bucket.items()
        ):
            rule_name = "BRACKET.{}.{}".format(axis_range_min, axis_range_max)
            glyph_sub_suffix = ".BRACKET.{}".format(axis_range_min)
            rule = designspaceLib.RuleDescriptor()
            rule.name = rule_name
            rule.conditionSets.append(
                [
                    {
                        "name": bracket_axis.name,
                        "minimum": axis_range_min,
                        "maximum": axis_range_max,
                    }
                ]
            )
            rule.subs.extend(
                [
                    (glyph_name, glyph_name + glyph_sub_suffix)
                    for glyph_name in glyph_names
                ]
            )
            self._designspace.addRule(rule)

        # Finally, copy bracket layers to their own glyphs.
        for location, layers in bracket_layer_map.items():
            for layer in layers:
                ufo_font = self._sources[
                    layer.associatedMasterId or layer.layerId
                ].font.layers.defaultLayer
                ufo_glyph_name = "{glyph_name}.BRACKET.{location}".format(
                    glyph_name=layer.parent.name, location=location
                )
                ufo_glyph = ufo_font.newGlyph(ufo_glyph_name)
                self.to_ufo_glyph(ufo_glyph, layer, layer.parent)
                ufo_glyph.unicodes = []  # Avoid cmap interference
                ufo_glyph.lib[GLYPHLIB_PREFIX + "_originalLayerName"] = layer.name


Instruction:
Create a Python 3 function to
return the GSFont object for this Glyphs file.

Response:
def font(self):
        """Get the GSFont built from the UFOs + designspace."""
        if self._font is not None:
            return self._font

        # Sort UFOS in the original order from the Glyphs file
        sorted_sources = self.to_glyphs_ordered_masters()

        # Convert all full source UFOs to Glyphs masters. Sources with layer names
        # are assumed to be sparse or "brace" layers and are ignored because Glyphs
        # considers them to be special layers and will handle them itself.
        self._font = self.glyphs_module.GSFont()
        self._sources = OrderedDict()  # Same as in UFOBuilder
        for index, source in enumerate(s for s in sorted_sources if not s.layerName):
            master = self.glyphs_module.GSFontMaster()

            # Filter bracket glyphs out of public.glyphOrder.
            if GLYPH_ORDER_KEY in source.font.lib:
                source.font.lib[GLYPH_ORDER_KEY] = [
                    glyph_name
                    for glyph_name in source.font.lib[GLYPH_ORDER_KEY]
                    if ".BRACKET." not in glyph_name
                ]

            self.to_glyphs_font_attributes(source, master, is_initial=(index == 0))
            self.to_glyphs_master_attributes(source, master)
            self._font.masters.insert(len(self._font.masters), master)
            self._sources[master.id] = source

            # First, move free-standing bracket glyphs back to layers to avoid dealing
            # with GSLayer transplantation.
            for bracket_glyph in [g for g in source.font if ".BRACKET." in g.name]:
                base_glyph, threshold = bracket_glyph.name.split(".BRACKET.")
                try:
                    int(threshold)
                except ValueError:
                    raise ValueError(
                        "Glyph '{}' has malformed bracket layer name. Must be '<glyph "
                        "name>.BRACKET.<crossover value>'.".format(bracket_glyph)
                    )
                layer_name = bracket_glyph.lib.get(
                    GLYPHLIB_PREFIX + "_originalLayerName", "[{}]".format(threshold)
                )
                if layer_name not in source.font.layers:
                    ufo_layer = source.font.newLayer(layer_name)
                else:
                    ufo_layer = source.font.layers[layer_name]
                bracket_glyph_new = ufo_layer.newGlyph(base_glyph)
                bracket_glyph_new.copyDataFromGlyph(bracket_glyph)

                # Remove all freestanding bracket layer glyphs from all layers.
                for layer in source.font.layers:
                    if bracket_glyph.name in layer:
                        del layer[bracket_glyph.name]

            for layer in _sorted_backgrounds_last(source.font.layers):
                self.to_glyphs_layer_lib(layer)
                for glyph in layer:
                    self.to_glyphs_glyph(glyph, layer, master)

        self.to_glyphs_features()
        self.to_glyphs_groups()
        self.to_glyphs_kerning()

        # Now that all GSGlyph are built, restore the glyph order
        if self.designspace.sources:
            first_ufo = self.designspace.sources[0].font
            if GLYPH_ORDER_KEY in first_ufo.lib:
                glyph_order = first_ufo.lib[GLYPH_ORDER_KEY]
                lookup = {name: i for i, name in enumerate(glyph_order)}
                self.font.glyphs = sorted(
                    self.font.glyphs, key=lambda glyph: lookup.get(glyph.name, 1 << 63)
                )
            # FIXME: (jany) We only do that on the first one. Maybe we should
            # merge the various `public.glyphorder` values?

            # Restore the layer ordering in each glyph
            for glyph in self._font.glyphs:
                self.to_glyphs_layer_order(glyph)

        self.to_glyphs_family_user_data_from_designspace()
        self.to_glyphs_axes()
        self.to_glyphs_sources()
        self.to_glyphs_instances()

        return self._font


Instruction:
Create a Python 3 function to
make sure that the user - provided designspace has loaded fonts and that the UFOs and UFOs are not already loaded.

Response:
def _valid_designspace(self, designspace):
        """Make sure that the user-provided designspace has loaded fonts and
        that names are the same as those from the UFOs.
        """
        # TODO: (jany) really make a copy to avoid modifying the original object
        copy = designspace
        # Load only full UFO masters, sparse or "brace" layer sources are assumed
        # to point to existing layers within one of the full masters.
        for source in (s for s in copy.sources if not s.layerName):
            if not hasattr(source, "font") or source.font is None:
                if source.path:
                    # FIXME: (jany) consider not changing the caller's objects
                    source.font = defcon.Font(source.path)
                else:
                    dirname = os.path.dirname(designspace.path)
                    ufo_path = os.path.join(dirname, source.filename)
                    source.font = defcon.Font(ufo_path)
            if source.location is None:
                source.location = {}
            for name in ("familyName", "styleName"):
                if getattr(source, name) != getattr(source.font.info, name):
                    self.logger.warning(
                        dedent(
                            """\
                    The {name} is different between the UFO and the designspace source:
                        source filename: {filename}
                        source {name}: {source_name}
                        ufo {name}: {ufo_name}

                    The UFO name will be used.
                    """
                        ).format(
                            name=name,
                            filename=source.filename,
                            source_name=getattr(source, name),
                            ufo_name=getattr(source.font.info, name),
                        )
                    )
                    setattr(source, name, getattr(source.font.info, name))
        return copy


Instruction:
Given the following Python 3 function, write the documentation
def _fake_designspace(self, ufos):
        designspace = designspaceLib.DesignSpaceDocument()

        ufo_to_location = defaultdict(dict)

        # Make weight and width axis if relevant
        for info_key, axis_def in zip(
            ("openTypeOS2WeightClass", "openTypeOS2WidthClass"),
            (WEIGHT_AXIS_DEF, WIDTH_AXIS_DEF),
        ):
            axis = designspace.newAxisDescriptor()
            axis.tag = axis_def.tag
            axis.name = axis_def.name
            mapping = []
            for ufo in ufos:
                user_loc = getattr(ufo.info, info_key)
                if user_loc is not None:
                    design_loc = class_to_value(axis_def.tag, user_loc)
                    mapping.append((user_loc, design_loc))
                    ufo_to_location[ufo][axis_def.name] = design_loc

            mapping = sorted(set(mapping))
            if len(mapping) > 1:
                axis.map = mapping
                axis.minimum = min([user_loc for user_loc, _ in mapping])
                axis.maximum = max([user_loc for user_loc, _ in mapping])
                axis.default = min(
                    axis.maximum, max(axis.minimum, axis_def.default_user_loc)
                )
                designspace.addAxis(axis)

        for ufo in ufos:
            source = designspace.newSourceDescriptor()
            source.font = ufo
            source.familyName = ufo.info.familyName
            source.styleName = ufo.info.styleName
            # source.name = '%s %s' % (source.familyName, source.styleName)
            source.path = ufo.path
            source.location = ufo_to_location[ufo]
            designspace.addSource(source)

        # UFO-level skip list lib keys are usually ignored, except when we don't have a
        # Designspace file to start from. If they exist in the UFOs, promote them to a
        # Designspace-level lib key. However, to avoid accidents, expect the list to
        # exist in none or be the same in all UFOs.
        if any("public.skipExportGlyphs" in ufo.lib for ufo in ufos):
            skip_export_glyphs = {
                frozenset(ufo.lib.get("public.skipExportGlyphs", [])) for ufo in ufos
            }
            if len(skip_export_glyphs) == 1:
                designspace.lib["public.skipExportGlyphs"] = sorted(
                    next(iter(skip_export_glyphs))
                )
            else:
                raise ValueError(
                    "The `public.skipExportGlyphs` list of all UFOs must either not "
                    "exist or be the same in every UFO."
                )

        return designspace

Response: Build a fake designspace with the given UFOs as sources.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _to_ufo_kerning(self, ufo, kerning_data):

    warning_msg = "Non-existent glyph class %s found in kerning rules."

    for left, pairs in kerning_data.items():
        match = re.match(r"@MMK_L_(.+)", left)
        left_is_class = bool(match)
        if left_is_class:
            left = "public.kern1.%s" % match.group(1)
            if left not in ufo.groups:
                self.logger.warning(warning_msg % left)
        for right, kerning_val in pairs.items():
            match = re.match(r"@MMK_R_(.+)", right)
            right_is_class = bool(match)
            if right_is_class:
                right = "public.kern2.%s" % match.group(1)
                if right not in ufo.groups:
                    self.logger.warning(warning_msg % right)
            ufo.kerning[left, right] = kerning_val

Response: Add. glyphs kerning to an UFO.


Instruction:
Given the following Python 3 function, write the documentation
def to_glyphs_kerning(self):
    for master_id, source in self._sources.items():
        for (left, right), value in source.font.kerning.items():
            left_match = UFO_KERN_GROUP_PATTERN.match(left)
            right_match = UFO_KERN_GROUP_PATTERN.match(right)
            if left_match:
                left = "@MMK_L_{}".format(left_match.group(2))
            if right_match:
                right = "@MMK_R_{}".format(right_match.group(2))
            self.font.setKerningForPair(master_id, left, right, value)

Response: Add UFO kerning to GSFont.


Instruction:
How would you implement a function in Python 3 that
normalizes a custom parameter name.

Response:
def _normalize_custom_param_name(name):
    """Replace curved quotes with straight quotes in a custom parameter name.
    These should be the only keys with problematic (non-ascii) characters,
    since they can be user-generated.
    """

    replacements = (("\u2018", "'"), ("\u2019", "'"), ("\u201C", '"'), ("\u201D", '"'))
    for orig, replacement in replacements:
        name = name.replace(orig, replacement)
    return name


Instruction:
Here you have a function in Python 3, explain what it does
def _set_default_params(ufo):
    for _, ufo_name, default_value in DEFAULT_PARAMETERS:
        if getattr(ufo.info, ufo_name) is None:
            if isinstance(default_value, list):
                # Prevent problem if the same default value list is put in
                # several unrelated objects.
                default_value = default_value[:]
            setattr(ufo.info, ufo_name, default_value)

Response: Set Glyphs. app s default parameters when different from ufo2ft ones.


Instruction:
Write a Python 3 function that can
return the first and only custom parameter matching the given name.

Response:
def get_custom_value(self, key):
        """Return the first and only custom parameter matching the given name."""
        self._handled.add(key)
        values = self._lookup[key]
        if len(values) > 1:
            raise RuntimeError(
                "More than one value for this customParameter: {}".format(key)
            )
        if values:
            return values[0]
        return None


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_custom_values(self, key):
        self._handled.add(key)
        return self._lookup[key]

Response: Return a set of values for the given customParameter name.


Instruction:
How would you implement a function in Python 3 that
sets one custom parameter with the given value.

Response:
def set_custom_value(self, key, value):
        """Set one custom parameter with the given value.
        We assume that the list of custom parameters does not already contain
        the given parameter so we only append.
        """
        self._owner.customParameters.append(
            self._glyphs_module.GSCustomParameter(name=key, value=value)
        )


Instruction:
How would you code a function in Python 3 to
set several values for the given key.

Response:
def set_custom_values(self, key, values):
        """Set several values for the customParameter with the given key.
        We append one GSCustomParameter per value.
        """
        for value in values:
            self.set_custom_value(key, value)


Instruction:
Write a Python 3 function that can
cast some known data in custom parameters.

Response:
def setValue(self, value):
        """Cast some known data in custom parameters."""
        if self.name in self._CUSTOM_INT_PARAMS:
            value = int(value)
        elif self.name in self._CUSTOM_FLOAT_PARAMS:
            value = float(value)
        elif self.name in self._CUSTOM_BOOL_PARAMS:
            value = bool(value)
        elif self.name in self._CUSTOM_INTLIST_PARAMS:
            value = readIntlist(value)
        elif self.name in self._CUSTOM_DICT_PARAMS:
            parser = Parser()
            value = parser.parse(value)
        elif self.name == "note":
            value = unicode(value)
        self._value = value


Instruction:
Can you generate a brief explanation for the following Python 3 code
def name(self, name):
        weight, width, custom_name = self._splitName(name)
        self.set_all_name_components(name, weight, width, custom_name)

Response: This function will take the given name and split it into weight width customName and possibly the full name.


Instruction:
Can you generate the documentation for the following Python 3 function
def set_all_name_components(self, name, weight, width, custom_name):
        self.weight = weight or "Regular"
        self.width = width or "Regular"
        self.customName = custom_name or ""
        # Only store the requested name if we can't build it from the parts
        if self._joinName() == name:
            self._name = None
            del self.customParameters["Master Name"]
        else:
            self._name = name
            self.customParameters["Master Name"] = name

Response: This function sets the master. name weight and width and custom name of the master.


Instruction:
Write a Python 3 function for
taking the PLIST string of a dict and returns the same string representation

Response:
def _encode_dict_as_string(value):
        """Takes the PLIST string of a dict, and returns the same string
        encoded such that it can be included in the string representation
        of a GSNode."""
        # Strip the first and last newlines
        if value.startswith("{\n"):
            value = "{" + value[2:]
        if value.endswith("\n}"):
            value = value[:-2] + "}"
        # escape double quotes and newlines
        return value.replace('"', '\\"').replace("\\n", "\\\\n").replace("\n", "\\n")


Instruction:
Can you tell what is the following Python 3 function doing
def _indices(self):
        path = self.parent
        layer = path.parent
        for path_index in range(len(layer.paths)):
            if path == layer.paths[path_index]:
                for node_index in range(len(path.nodes)):
                    if self == path.nodes[node_index]:
                        return Point(path_index, node_index)
        return None

Response: Find the path_index and node_index that identify the given node.


Instruction:
Can you write a function in Python 3 where it
finds the GSNode that is refered to by the given indices.

Response:
def _find_node_by_indices(self, point):
        """"Find the GSNode that is refered to by the given indices.

        See GSNode::_indices()
        """
        path_index, node_index = point
        path = self.paths[int(path_index)]
        node = path.nodes[int(node_index)]
        return node


Instruction:
Write a Python 3 function that can
propagate anchors from parent glyphs components to the parent glyphs.

Response:
def to_ufo_propagate_font_anchors(self, ufo):
    """Copy anchors from parent glyphs' components to the parent."""

    processed = set()
    for glyph in ufo:
        _propagate_glyph_anchors(self, ufo, glyph, processed)


Instruction:
Write a Python 3 function for
propagating anchors for a single parent glyph.

Response:
def _propagate_glyph_anchors(self, ufo, parent, processed):
    """Propagate anchors for a single parent glyph."""

    if parent.name in processed:
        return
    processed.add(parent.name)

    base_components = []
    mark_components = []
    anchor_names = set()
    to_add = {}
    for component in parent.components:
        try:
            glyph = ufo[component.baseGlyph]
        except KeyError:
            self.logger.warning(
                "Anchors not propagated for inexistent component {} in glyph {}".format(
                    component.baseGlyph, parent.name
                )
            )
        else:
            _propagate_glyph_anchors(self, ufo, glyph, processed)
            if any(a.name.startswith("_") for a in glyph.anchors):
                mark_components.append(component)
            else:
                base_components.append(component)
                anchor_names |= {a.name for a in glyph.anchors}

    for anchor_name in anchor_names:
        # don't add if parent already contains this anchor OR any associated
        # ligature anchors (e.g. "top_1, top_2" for "top")
        if not any(a.name.startswith(anchor_name) for a in parent.anchors):
            _get_anchor_data(to_add, ufo, base_components, anchor_name)

    for component in mark_components:
        _adjust_anchors(to_add, ufo, component)

    # we sort propagated anchors to append in a deterministic order
    for name, (x, y) in sorted(to_add.items()):
        anchor_dict = {"name": name, "x": x, "y": y}
        parent.appendAnchor(glyph.anchorClass(anchorDict=anchor_dict))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _adjust_anchors(anchor_data, ufo, component):

    glyph = ufo[component.baseGlyph]
    t = Transform(*component.transformation)
    for anchor in glyph.anchors:
        # only adjust if this anchor has data and the component also contains
        # the associated mark anchor (e.g. "_top" for "top")
        if anchor.name in anchor_data and any(
            a.name == "_" + anchor.name for a in glyph.anchors
        ):
            anchor_data[anchor.name] = t.transformPoint((anchor.x, anchor.y))

Response: Adjust anchor data to which a mark component may have been attached.


Instruction:
Given the following Python 3 function, write the documentation
def to_ufo_glyph_anchors(self, glyph, anchors):

    for anchor in anchors:
        x, y = anchor.position
        anchor_dict = {"name": anchor.name, "x": x, "y": y}
        glyph.appendAnchor(anchor_dict)

Response: Add. glyphs anchors to a glyph.


Instruction:
Here you have a function in Python 3, explain what it does
def to_glyphs_glyph_anchors(self, ufo_glyph, layer):
    for ufo_anchor in ufo_glyph.anchors:
        anchor = self.glyphs_module.GSAnchor()
        anchor.name = ufo_anchor.name
        anchor.position = Point(ufo_anchor.x, ufo_anchor.y)
        layer.anchors.append(anchor)

Response: Add UFO glif anchors to a GSLayer.


Instruction:
Can you tell what is the following Python 3 function doing
def cached_property(func):
    name = func.__name__
    doc = func.__doc__

    def getter(self, name=name):
        try:
            return self.__dict__[name]
        except KeyError:
            self.__dict__[name] = value = func(self)
            return value

    getter.func_name = name
    return property(getter, doc=doc)

Response:
A property decorator that caches the computed
    property value in the object s instance dict the first
alues time it is accessed.


Instruction:
Write a Python 3 script to
return the cosine and sin for the given angle in degrees.

Response:
def cos_sin_deg(deg):
    """Return the cosine and sin for the given angle
    in degrees, with special-case handling of multiples
    of 90 for perfect right angles
    """
    deg = deg % 360.0
    if deg == 90.0:
        return 0.0, 1.0
    elif deg == 180.0:
        return -1.0, 0
    elif deg == 270.0:
        return 0, -1.0
    rad = math.radians(deg)
    return math.cos(rad), math.sin(rad)


Instruction:
Given the following Python 3 function, write the documentation
def scale(cls, *scaling):
        if len(scaling) == 1:
            sx = sy = float(scaling[0])
        else:
            sx, sy = scaling
        return tuple.__new__(cls, (sx, 0.0, 0.0, 0.0, sy, 0.0, 0.0, 0.0, 1.0))

Response: Create a scaling transform from a scalar or vector.


Instruction:
How would you explain what the following Python 3 function does
def shear(cls, x_angle=0, y_angle=0):
        sx = math.tan(math.radians(x_angle))
        sy = math.tan(math.radians(y_angle))
        return tuple.__new__(cls, (1.0, sy, 0.0, sx, 1.0, 0.0, 0.0, 0.0, 1.0))

Response: Create a shear transform along one or both axes.


Instruction:
Make a summary of the following Python 3 code
def rotation(cls, angle, pivot=None):
        ca, sa = cos_sin_deg(angle)
        if pivot is None:
            return tuple.__new__(cls, (ca, sa, 0.0, -sa, ca, 0.0, 0.0, 0.0, 1.0))
        else:
            px, py = pivot
            return tuple.__new__(
                cls,
                (
                    ca,
                    sa,
                    px - px * ca + py * sa,
                    -sa,
                    ca,
                    py - px * sa - py * ca,
                    0.0,
                    0.0,
                    1.0,
                ),
            )

Response: Create a rotation transform at the specified angle about the specified pivot point.


Instruction:
How would you explain what the following Python 3 function does
def determinant(self):
        a, b, c, d, e, f, g, h, i = self
        return a * e - b * d

Response: The determinant of the transform matrix. This is equal to the area scaling factor when the transform matrix is applied to a shape.


Instruction:
Write a Python 3 function for
truing if the transform is rectilinear.

Response:
def is_rectilinear(self):
        """True if the transform is rectilinear, i.e., whether a shape would
        remain axis-aligned, within rounding limits, after applying the
        transform.
        """
        a, b, c, d, e, f, g, h, i = self
        return (abs(a) < EPSILON and abs(e) < EPSILON) or (
            abs(d) < EPSILON and abs(b) < EPSILON
        )


Instruction:
How would you implement a function in Python 3 that
trues if the transform is conformal i. e. angles between points are preserved after applying the transform.

Response:
def is_conformal(self):
        """True if the transform is conformal, i.e., if angles between points
        are preserved after applying the transform, within rounding limits.
        This implies that the transform has no effective shear.
        """
        a, b, c, d, e, f, g, h, i = self
        return abs(a * b + d * e) < EPSILON


Instruction:
Explain what the following Python 3 code does
def is_orthonormal(self):
        a, b, c, d, e, f, g, h, i = self
        return (
            self.is_conformal
            and abs(1.0 - (a * a + d * d)) < EPSILON
            and abs(1.0 - (b * b + e * e)) < EPSILON
        )

Response: True if the transform is orthonormal.


Instruction:
Write a Python 3 script for
comparing transforms for approximate equality.

Response:
def almost_equals(self, other):
        """Compare transforms for approximate equality.

        :param other: Transform being compared.
        :type other: Affine
        :return: True if absolute difference between each element
            of each respective tranform matrix < ``EPSILON``.
        """
        for i in (0, 1, 2, 3, 4, 5):
            if abs(self[i] - other[i]) >= EPSILON:
                return False
        return True


Instruction:
Implement a function in Python 3 to
transform a sequence of points or vectors in place.

Response:
def itransform(self, seq):
        """Transform a sequence of points or vectors in place.

        :param seq: Mutable sequence of :class:`~planar.Vec2` to be
            transformed.
        :returns: None, the input sequence is mutated in place.
        """
        if self is not identity and self != identity:
            sa, sb, sc, sd, se, sf, _, _, _ = self
            for i, (x, y) in enumerate(seq):
                seq[i] = (x * sa + y * sd + sc, x * sb + y * se + sf)


Instruction:
How would you explain what the following Python 3 function does
def get_glyph(glyph_name, data=None):

    # Read data on first use.
    if data is None:
        global GLYPHDATA
        if GLYPHDATA is None:
            GLYPHDATA = GlyphData.from_files(
                os.path.join(
                    os.path.dirname(glyphsLib.__file__), "data", "GlyphData.xml"
                ),
                os.path.join(
                    os.path.dirname(glyphsLib.__file__),
                    "data",
                    "GlyphData_Ideographs.xml",
                ),
            )
        data = GLYPHDATA

    # Look up data by full glyph name first.
    attributes = _lookup_attributes(glyph_name, data)

    production_name = attributes.get("production")
    if production_name is None:
        production_name = _construct_production_name(glyph_name, data=data)

    unicode_value = attributes.get("unicode")

    category = attributes.get("category")
    sub_category = attributes.get("subCategory")
    if category is None:
        category, sub_category = _construct_category(glyph_name, data)

    # TODO: Determine script in ligatures.
    script = attributes.get("script")
    description = attributes.get("description")

    return Glyph(
        glyph_name,
        production_name,
        unicode_value,
        category,
        sub_category,
        script,
        description,
    )

Response: Return a named tuple containing information derived from a glyph name akin to GSGlyphInfo.


Instruction:
Write a Python 3 script for
looking up glyph attributes in data by glyph name alternative name or production name in order or return empty dictionary.

Response:
def _lookup_attributes(glyph_name, data):
    """Look up glyph attributes in data by glyph name, alternative name or
    production name in order or return empty dictionary.

    Look up by alternative and production names for legacy projects and
    because of issue #232.
    """
    attributes = (
        data.names.get(glyph_name)
        or data.alternative_names.get(glyph_name)
        or data.production_names.get(glyph_name)
        or {}
    )
    return attributes


Instruction:
Can you create a Python 3 function that
returns an AGL - compliant name string or None if we can t make one.

Response:
def _agl_compliant_name(glyph_name):
    """Return an AGL-compliant name string or None if we can't make one."""
    MAX_GLYPH_NAME_LENGTH = 63
    clean_name = re.sub("[^0-9a-zA-Z_.]", "", glyph_name)
    if len(clean_name) > MAX_GLYPH_NAME_LENGTH:
        return None
    return clean_name


Instruction:
Create a Python 3 function for
deriving ( sub ) category of a glyph name.

Response:
def _construct_category(glyph_name, data):
    """Derive (sub)category of a glyph name."""
    # Glyphs creates glyphs that start with an underscore as "non-exportable" glyphs or
    # construction helpers without a category.
    if glyph_name.startswith("_"):
        return None, None

    # Glyph variants (e.g. "fi.alt") don't have their own entry, so we strip e.g. the
    # ".alt" and try a second lookup with just the base name. A variant is hopefully in
    # the same category as its base glyph.
    base_name = glyph_name.split(".", 1)[0]
    base_attribute = data.names.get(base_name) or {}
    if base_attribute:
        category = base_attribute.get("category")
        sub_category = base_attribute.get("subCategory")
        return category, sub_category

    # Detect ligatures.
    if "_" in base_name:
        base_names = base_name.split("_")
        base_names_attributes = [_lookup_attributes(name, data) for name in base_names]
        first_attribute = base_names_attributes[0]

        # If the first part is a Mark, Glyphs 2.6 declares the entire glyph a Mark
        if first_attribute.get("category") == "Mark":
            category = first_attribute.get("category")
            sub_category = first_attribute.get("subCategory")
            return category, sub_category

        # If the first part is a Letter...
        if first_attribute.get("category") == "Letter":
            # ... and the rest are only marks or separators or don't exist, the
            # sub_category is that of the first part ...
            if all(
                a.get("category") in (None, "Mark", "Separator")
                for a in base_names_attributes[1:]
            ):
                category = first_attribute.get("category")
                sub_category = first_attribute.get("subCategory")
                return category, sub_category
            # ... otherwise, a ligature.
            category = first_attribute.get("category")
            sub_category = "Ligature"
            return category, sub_category

        # TODO: Cover more cases. E.g. "one_one" -> ("Number", "Ligature") but
        # "one_onee" -> ("Number", "Composition").

    # Still nothing? Maybe we're looking at something like "uni1234.alt", try
    # using fontTools' AGL module to convert the base name to something meaningful.
    # Corner case: when looking at ligatures, names that don't exist in the AGLFN
    # are skipped, so len("acutecomb_o") == 2 but len("dotaccentcomb_o") == 1.
    character = fontTools.agl.toUnicode(base_name)
    if character:
        category, sub_category = _translate_category(
            glyph_name, unicodedata.category(character[0])
        )
        return category, sub_category

    return None, None


Instruction:
Can you implement a function in Python 3 that
returns a translation from Unicode category letters to Glyphs categories.

Response:
def _translate_category(glyph_name, unicode_category):
    """Return a translation from Unicode category letters to Glyphs
    categories."""
    DEFAULT_CATEGORIES = {
        None: ("Letter", None),
        "Cc": ("Separator", None),
        "Cf": ("Separator", "Format"),
        "Cn": ("Symbol", None),
        "Co": ("Letter", "Compatibility"),
        "Ll": ("Letter", "Lowercase"),
        "Lm": ("Letter", "Modifier"),
        "Lo": ("Letter", None),
        "Lt": ("Letter", "Uppercase"),
        "Lu": ("Letter", "Uppercase"),
        "Mc": ("Mark", "Spacing Combining"),
        "Me": ("Mark", "Enclosing"),
        "Mn": ("Mark", "Nonspacing"),
        "Nd": ("Number", "Decimal Digit"),
        "Nl": ("Number", None),
        "No": ("Number", "Decimal Digit"),
        "Pc": ("Punctuation", None),
        "Pd": ("Punctuation", "Dash"),
        "Pe": ("Punctuation", "Parenthesis"),
        "Pf": ("Punctuation", "Quote"),
        "Pi": ("Punctuation", "Quote"),
        "Po": ("Punctuation", None),
        "Ps": ("Punctuation", "Parenthesis"),
        "Sc": ("Symbol", "Currency"),
        "Sk": ("Mark", "Spacing"),
        "Sm": ("Symbol", "Math"),
        "So": ("Symbol", None),
        "Zl": ("Separator", None),
        "Zp": ("Separator", None),
        "Zs": ("Separator", "Space"),
    }

    glyphs_category = DEFAULT_CATEGORIES.get(unicode_category, ("Letter", None))

    # Exception: Something like "one_two" should be a (_, Ligature),
    # "acutecomb_brevecomb" should however stay (Mark, Nonspacing).
    if "_" in glyph_name and glyphs_category[0] != "Mark":
        return glyphs_category[0], "Ligature"

    return glyphs_category


Instruction:
Write a Python 3 function that can
return the production name for a glyph name from the GlyphData. xml database according to the AGL specification.

Response:
def _construct_production_name(glyph_name, data=None):
    """Return the production name for a glyph name from the GlyphData.xml
    database according to the AGL specification.

    This should be run only if there is no official entry with a production
    name in it.

    Handles single glyphs (e.g. "brevecomb") and ligatures (e.g.
    "brevecomb_acutecomb"). Returns None when a valid and semantically
    meaningful production name can't be constructed or when the AGL
    specification would be violated, get_glyph() will use the bare glyph
    name then.

    Note:
    - Glyph name is the full name, e.g. "brevecomb_acutecomb.case".
    - Base name is the base part, e.g. "brevecomb_acutecomb"
    - Suffix is e.g. "case".
    """

    # At this point, we have already checked the data for the full glyph name, so
    # directly go to the base name here (e.g. when looking at "fi.alt").
    base_name, dot, suffix = glyph_name.partition(".")
    glyphinfo = _lookup_attributes(base_name, data)
    if glyphinfo and glyphinfo.get("production"):
        # Found the base glyph.
        return glyphinfo["production"] + dot + suffix

    if glyph_name in fontTools.agl.AGL2UV or base_name in fontTools.agl.AGL2UV:
        # Glyph name is actually an AGLFN name.
        return glyph_name

    if "_" not in base_name:
        # Nothing found so far and the glyph name isn't a ligature ("_"
        # somewhere in it). The name does not carry any discernable Unicode
        # semantics, so just return something sanitized.
        return _agl_compliant_name(glyph_name)

    # So we have a ligature that is not mapped in the data. Split it up and
    # look up the individual parts.
    base_name_parts = base_name.split("_")

    # If all parts are in the AGLFN list, the glyph name is our production
    # name already.
    if all(part in fontTools.agl.AGL2UV for part in base_name_parts):
        return _agl_compliant_name(glyph_name)

    # Turn all parts of the ligature into production names.
    _character_outside_BMP = False
    production_names = []
    for part in base_name_parts:
        if part in fontTools.agl.AGL2UV:
            # A name present in the AGLFN is a production name already.
            production_names.append(part)
        else:
            part_entry = data.names.get(part) or {}
            part_production_name = part_entry.get("production")
            if part_production_name:
                production_names.append(part_production_name)

                # Take note if there are any characters outside the Unicode
                # BMP, e.g. "u10FFF" or "u10FFFF". Do not catch e.g. "u013B"
                # though.
                if len(part_production_name) > 5 and _is_unicode_u_value(
                    part_production_name
                ):
                    _character_outside_BMP = True
            else:
                # We hit a part that does not seem to be a valid glyph name known to us,
                # so the entire glyph name can't carry Unicode meaning. Return it
                # sanitized.
                return _agl_compliant_name(glyph_name)

    # Some names Glyphs uses resolve to other names that are not uniXXXX names and may
    # contain dots (e.g. idotaccent -> i.loclTRK). If there is any name with a "." in
    # it before the last element, punt. We'd have to introduce a "." into the ligature
    # midway, which is invalid according to the AGL. Example: "a_i.loclTRK" is valid,
    # but "a_i.loclTRK_a" isn't.
    if any("." in part for part in production_names[:-1]):
        return _agl_compliant_name(glyph_name)

    # If any production name starts with a "uni" and there are none of the
    # "uXXXXX" format, try to turn all parts into "uni" names and concatenate
    # them.
    if not _character_outside_BMP and any(
        part.startswith("uni") for part in production_names
    ):
        uni_names = []

        for part in production_names:
            if part.startswith("uni"):
                uni_names.append(part[3:])
            elif len(part) == 5 and _is_unicode_u_value(part):
                uni_names.append(part[1:])
            elif part in fontTools.agl.AGL2UV:
                uni_names.append("{:04X}".format(fontTools.agl.AGL2UV[part]))
            else:
                return None

        final_production_name = "uni" + "".join(uni_names) + dot + suffix
    else:
        final_production_name = "_".join(production_names) + dot + suffix

    return _agl_compliant_name(final_production_name)


Instruction:
Implement a function in Python 3 to
return GlyphData holding data from a list of XML file paths.

Response:
def from_files(cls, *glyphdata_files):
        """Return GlyphData holding data from a list of XML file paths."""
        name_mapping = {}
        alt_name_mapping = {}
        production_name_mapping = {}

        for glyphdata_file in glyphdata_files:
            glyph_data = xml.etree.ElementTree.parse(glyphdata_file).getroot()
            for glyph in glyph_data:
                glyph_name = glyph.attrib["name"]
                glyph_name_alternatives = glyph.attrib.get("altNames")
                glyph_name_production = glyph.attrib.get("production")

                name_mapping[glyph_name] = glyph.attrib
                if glyph_name_alternatives:
                    alternatives = glyph_name_alternatives.replace(" ", "").split(",")
                    for glyph_name_alternative in alternatives:
                        alt_name_mapping[glyph_name_alternative] = glyph.attrib
                if glyph_name_production:
                    production_name_mapping[glyph_name_production] = glyph.attrib

        return cls(name_mapping, alt_name_mapping, production_name_mapping)


Instruction:
Make a summary of the following Python 3 code
def load_to_ufos(
    file_or_path, include_instances=False, family_name=None, propagate_anchors=True
):
    """Load an unpacked .glyphs object to UFO objects."""

    if hasattr(file_or_path, "read"):
        font = load(file_or_path)
    else:
        with open(file_or_path, "r", encoding="utf-8") as ifile:
            font = load(ifile)
    logger.info("Loading to UFOs")
    return to_ufos(
        font,
        include_instances=include_instances,
        family_name=family_name,
        propagate_anchors=propagate_anchors,
    )

Response: Load an unpacked. glyphs object to UFOs objects.


Instruction:
Write a Python 3 script to
write and return UFOs from the masters and designspace defined in a. glyphs file.

Response:
def build_masters(
    filename,
    master_dir,
    designspace_instance_dir=None,
    designspace_path=None,
    family_name=None,
    propagate_anchors=True,
    minimize_glyphs_diffs=False,
    normalize_ufos=False,
    create_background_layers=False,
    generate_GDEF=True,
    store_editor_state=True,
):
    """Write and return UFOs from the masters and the designspace defined in a
    .glyphs file.

    Args:
        master_dir: Directory where masters are written.
        designspace_instance_dir: If provided, a designspace document will be
            written alongside the master UFOs though no instances will be built.
        family_name: If provided, the master UFOs will be given this name and
            only instances with this name will be included in the designspace.

    Returns:
        A named tuple of master UFOs (`ufos`) and the path to the designspace
        file (`designspace_path`).
    """

    font = GSFont(filename)

    if not os.path.isdir(master_dir):
        os.mkdir(master_dir)

    if designspace_instance_dir is None:
        instance_dir = None
    else:
        instance_dir = os.path.relpath(designspace_instance_dir, master_dir)

    designspace = to_designspace(
        font,
        family_name=family_name,
        propagate_anchors=propagate_anchors,
        instance_dir=instance_dir,
        minimize_glyphs_diffs=minimize_glyphs_diffs,
        generate_GDEF=generate_GDEF,
        store_editor_state=store_editor_state,
    )

    # Only write full masters to disk. This assumes that layer sources are always part
    # of another full master source, which must always be the case in a .glyphs file.
    ufos = {}
    for source in designspace.sources:
        if source.filename in ufos:
            assert source.font is ufos[source.filename]
            continue

        if create_background_layers:
            ufo_create_background_layer_for_all_glyphs(source.font)

        ufo_path = os.path.join(master_dir, source.filename)
        clean_ufo(ufo_path)
        source.font.save(ufo_path)

        if normalize_ufos:
            import ufonormalizer

            ufonormalizer.normalizeUFO(ufo_path, writeModTimes=False)

        ufos[source.filename] = source.font

    if not designspace_path:
        designspace_path = os.path.join(master_dir, designspace.filename)
    designspace.write(designspace_path)

    return Masters(ufos, designspace_path)