<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def get_types_by_attr(resource, template_id=None):
 """ Using the attributes of the resource, get all the types that this resource matches. @returns a dictionary, keyed on the template name, with the value being the list of type names which match the resources attributes. """


    resource_type_templates = []

    #Create a list of all of this resources attributes.
    attr_ids = []
    for res_attr in resource.attributes:
        attr_ids.append(res_attr.attr_id)
    all_resource_attr_ids = set(attr_ids)

    all_types = db.DBSession.query(TemplateType).options(joinedload_all('typeattrs')).filter(TemplateType.resource_type==resource.ref_key)
    if template_id is not None:
        all_types = all_types.filter(TemplateType.template_id==template_id)

    all_types = all_types.all()

    #tmpl type attrs must be a subset of the resource's attrs
    for ttype in all_types:
        type_attr_ids = []
        for typeattr in ttype.typeattrs:
            type_attr_ids.append(typeattr.attr_id)
        if set(type_attr_ids).issubset(all_resource_attr_ids):
            resource_type_templates.append(ttype)

    return resource_type_templates