Internal function to parse common FoLiA attributes and sets up the instance accordingly. Do not invoke directly.
514818
def parsecommonarguments(object, doc, annotationtype, required, allowed, **kwargs):
    """"""

    object.doc = doc #The FoLiA root document

    if required is None:
        required = tuple()
    if allowed is None:
        allowed = tuple()

    supported = required + allowed


    if 'generate_id_in' in kwargs:
        try:
            kwargs['id'] = kwargs['generate_id_in'].generate_id(object.__class__)
        except GenerateIDException:
            pass #ID could not be generated, just skip
        del kwargs['generate_id_in']



    if 'id' in kwargs:
        if Attrib.ID not in supported:
            raise ValueError("ID is not supported on " + object.__class__.__name__)
        isncname(kwargs['id'])
        object.id = kwargs['id']
        del kwargs['id']
    elif Attrib.ID in required:
        raise ValueError("ID is required for " + object.__class__.__name__)
    else:
        object.id = None

    if 'set' in kwargs:
        if Attrib.CLASS not in supported and not object.SETONLY:
            raise ValueError("Set is not supported on " + object.__class__.__name__)
        if not kwargs['set']:
            object.set ="undefined"
        else:
            object.set = kwargs['set']
        del kwargs['set']

        if object.set:
            if doc and (not (annotationtype in doc.annotationdefaults) or not (object.set in doc.annotationdefaults[annotationtype])):
                if object.set in doc.alias_set:
                    object.set = doc.alias_set[object.set]
                elif doc.autodeclare:
                    doc.annotations.append( (annotationtype, object.set ) )
                    doc.annotationdefaults[annotationtype] = {object.set: {} }
                else:
                    raise ValueError("Set '" + object.set + "' is used for " + object.__class__.__name__ + ", but has no declaration!")
    elif annotationtype in doc.annotationdefaults and len(doc.annotationdefaults[annotationtype]) == 1:
        object.set = list(doc.annotationdefaults[annotationtype].keys())[0]
    elif object.ANNOTATIONTYPE == AnnotationType.TEXT:
        object.set = "undefined" #text content needs never be declared (for backward compatibility) and is in set 'undefined'
    elif Attrib.CLASS in required: #or (hasattr(object,'SETONLY') and object.SETONLY):
        raise ValueError("Set is required for " + object.__class__.__name__)


    if 'class' in kwargs:
        if not Attrib.CLASS in supported:
            raise ValueError("Class is not supported for " + object.__class__.__name__)
        object.cls = kwargs['class']
        del kwargs['class']
    elif 'cls' in kwargs:
        if not Attrib.CLASS in supported:
            raise ValueError("Class is not supported on " + object.__class__.__name__)
        object.cls = kwargs['cls']
        del kwargs['cls']
    elif Attrib.CLASS in required:
        raise ValueError("Class is required for " + object.__class__.__name__)

    if object.cls and not object.set:
        if doc and doc.autodeclare:
            if not (annotationtype, 'undefined') in doc.annotations:
                doc.annotations.append( (annotationtype, 'undefined') )
                doc.annotationdefaults[annotationtype] = {'undefined': {} }
            object.set = 'undefined'
        else:
            raise ValueError("Set is required for " + object.__class__.__name__ +  ". Class '" + object.cls + "' assigned without set.")





    if 'annotator' in kwargs:
        if not Attrib.ANNOTATOR in supported:
            raise ValueError("Annotator is not supported for " + object.__class__.__name__)
        object.annotator = kwargs['annotator']
        del kwargs['annotator']
    elif doc and annotationtype in doc.annotationdefaults and object.set in doc.annotationdefaults[annotationtype] and 'annotator' in doc.annotationdefaults[annotationtype][object.set]:
        object.annotator = doc.annotationdefaults[annotationtype][object.set]['annotator']
    elif Attrib.ANNOTATOR in required:
        raise ValueError("Annotator is required for " + object.__class__.__name__)


    if 'annotatortype' in kwargs:
        if not Attrib.ANNOTATOR in supported:
            raise ValueError("Annotatortype is not supported for " + object.__class__.__name__)
        if kwargs['annotatortype'] == 'auto' or kwargs['annotatortype'] == AnnotatorType.AUTO:
            object.annotatortype = AnnotatorType.AUTO
        elif kwargs['annotatortype'] == 'manual' or kwargs['annotatortype']  == AnnotatorType.MANUAL:
            object.annotatortype = AnnotatorType.MANUAL
        else:
            raise ValueError("annotatortype must be 'auto' or 'manual', got "  + repr(kwargs['annotatortype']))
        del kwargs['annotatortype']
    elif doc and annotationtype in doc.annotationdefaults and object.set in doc.annotationdefaults[annotationtype] and 'annotatortype' in doc.annotationdefaults[annotationtype][object.set]:
        object.annotatortype = doc.annotationdefaults[annotationtype][object.set]['annotatortype']
    elif Attrib.ANNOTATOR in required:
        raise ValueError("Annotatortype is required for " + object.__class__.__name__)

    if 'confidence' in kwargs:
        if not Attrib.CONFIDENCE in supported:
            raise ValueError("Confidence is not supported")
        if kwargs['confidence'] is not None:
            try:
                object.confidence = float(kwargs['confidence'])
                assert object.confidence >= 0.0 and object.confidence <= 1.0
            except:
                raise ValueError("Confidence must be a floating point number between 0 and 1, got " + repr(kwargs['confidence']) )
        del kwargs['confidence']
    elif Attrib.CONFIDENCE in required:
        raise ValueError("Confidence is required for " + object.__class__.__name__)



    if 'n' in kwargs:
        if not Attrib.N in supported:
            raise ValueError("N is not supported for " + object.__class__.__name__)
        object.n = kwargs['n']
        del kwargs['n']
    elif Attrib.N in required:
        raise ValueError("N is required for " + object.__class__.__name__)

    if 'datetime' in kwargs:
        if not Attrib.DATETIME in supported:
            raise ValueError("Datetime is not supported")
        if isinstance(kwargs['datetime'], datetime):
            object.datetime = kwargs['datetime']
        else:

            #try:
            object.datetime = parse_datetime(kwargs['datetime'])
            #except:
            #    raise ValueError("Unable to parse datetime: " + str(repr(kwargs['datetime'])))
        del kwargs['datetime']
    elif doc and annotationtype in doc.annotationdefaults and object.set in doc.annotationdefaults[annotationtype] and 'datetime' in doc.annotationdefaults[annotationtype][object.set]:
        object.datetime = doc.annotationdefaults[annotationtype][object.set]['datetime']
    elif Attrib.DATETIME in required:
        raise ValueError("Datetime is required for " + object.__class__.__name__)

    if 'src' in kwargs:
        if not Attrib.SRC in supported:
            raise ValueError("Source is not supported for " + object.__class__.__name__)
        object.src = kwargs['src']
        del kwargs['src']
    elif Attrib.SRC in required:
        raise ValueError("Source is required for " + object.__class__.__name__)

    if 'begintime' in kwargs:
        if not Attrib.BEGINTIME in supported:
            raise ValueError("Begintime is not supported for " + object.__class__.__name__)
        object.begintime = parsetime(kwargs['begintime'])
        del kwargs['begintime']
    elif Attrib.BEGINTIME in required:
        raise ValueError("Begintime is required for " + object.__class__.__name__)

    if 'endtime' in kwargs:
        if not Attrib.ENDTIME in supported:
            raise ValueError("Endtime is not supported for " + object.__class__.__name__)
        object.endtime = parsetime(kwargs['endtime'])
        del kwargs['endtime']
    elif Attrib.ENDTIME in required:
        raise ValueError("Endtime is required for " + object.__class__.__name__)


    if 'speaker' in kwargs:
        if not Attrib.SPEAKER in supported:
            raise ValueError("Speaker is not supported for " + object.__class__.__name__)
        object.speaker = kwargs['speaker']
        del kwargs['speaker']
    elif Attrib.SPEAKER in required:
        raise ValueError("Speaker is required for " + object.__class__.__name__)

    if 'auth' in kwargs:
        if kwargs['auth'] in ('no','false'):
            object.auth = False
        else:
            object.auth = bool(kwargs['auth'])
        del kwargs['auth']
    else:
        object.auth = object.__class__.AUTH



    if 'text' in kwargs:
        if kwargs['text']:
            object.settext(kwargs['text'])
        del kwargs['text']

    if 'phon' in kwargs:
        if kwargs['phon']:
            object.setphon(kwargs['phon'])
        del kwargs['phon']

    if 'textclass' in kwargs:
        if not Attrib.TEXTCLASS in supported:
            raise ValueError("Textclass is not supported for " + object.__class__.__name__)
        object.textclass = kwargs['textclass']
        del kwargs['textclass']
    else:
        if Attrib.TEXTCLASS in supported:
            object.textclass = "current"

    if 'metadata' in kwargs:
        if not Attrib.METADATA in supported:
            raise ValueError("Metadata is not supported for " + object.__class__.__name__)
        object.metadata = kwargs['metadata']
        if doc:
            try:
                doc.submetadata[kwargs['metadata']]
            except KeyError:
                raise KeyError("No such metadata defined: " + kwargs['metadata'])
        del kwargs['metadata']

    if object.XLINK:
        if 'href' in kwargs:
            object.href =kwargs['href']
            del kwargs['href']
        if 'xlinktype' in kwargs:
            object.xlinktype = kwargs['xlinktype']
            del kwargs['xlinktype']
        if 'xlinkrole' in kwargs:
            object.xlinkrole = kwargs['xlinkrole']
            del kwargs['xlinkrole']
        if 'xlinklabel' in kwargs:
            object.xlinklabel = kwargs['xlinklabel']
            del kwargs['xlinklabel']
        if 'xlinkshow' in kwargs:
            object.xlinkshow = kwargs['xlinkshow']
            del kwargs['xlinklabel']
        if 'xlinktitle' in kwargs:
            object.xlinktitle = kwargs['xlinktitle']
            del kwargs['xlinktitle']

    if doc and doc.debug >= 2:
        print("   @id           = ", repr(object.id),file=stderr)
        print("   @set          = ", repr(object.set),file=stderr)
        print("   @class        = ", repr(object.cls),file=stderr)
        print("   @annotator    = ", repr(object.annotator),file=stderr)
        print("   @annotatortype= ", repr(object.annotatortype),file=stderr)
        print("   @confidence   = ", repr(object.confidence),file=stderr)
        print("   @n            = ", repr(object.n),file=stderr)
        print("   @datetime     = ", repr(object.datetime),file=stderr)



    #set index
    if object.id and doc:
        if object.id in doc.index:
            if doc.debug >= 1: print("[PyNLPl FoLiA DEBUG] Duplicate ID not permitted:" + object.id,file=stderr)
            raise DuplicateIDError("Duplicate ID not permitted: " + object.id)
        else:
            if doc.debug >= 1: print("[PyNLPl FoLiA DEBUG] Adding to index: " + object.id,file=stderr)
            doc.index[object.id] = object

    #Parse feature attributes (shortcut for feature specification for some elements)
    for c in object.ACCEPTED_DATA:
        if issubclass(c, Feature):
            if c.SUBSET in kwargs:
                if kwargs[c.SUBSET]:
                    object.append(c,cls=kwargs[c.SUBSET])
                del kwargs[c.SUBSET]

    return kwargs
756576
def set_attributes(self, **kwargs):
        
        if not self.Meta.related_resources:
            # Just do what the normal BaseResource does
            super(HypermediaResource, self).set_attributes(**kwargs)
            return

        # Extract all the values that are URLs
        url_values = {}
        for k, v in kwargs.items():
            try:
                if isinstance(v, list):
                    [self._parse_url_and_validate(i) for i in v]
                else:
                    self._parse_url_and_validate(v)
                url_values[k] = v
            except BadURLException:
                # This is a badly formed URL or not a URL at all, so skip
                pass
        # Assign the valid method values and then remove them from the kwargs
        assigned_values = self.match_urls_to_resources(url_values)
        for k in assigned_values.keys():
            kwargs.pop(k, None)
        # Assign the rest as attributes.
        for field, value in kwargs.items():
            if field in self.Meta.attributes:
                setattr(self, field, value)
1356530
def init(filename=ConfigPath):
    """"""
    section, parts = "DEFAULT", filename.rsplit(":", 1)
    if len(parts) > 1 and os.path.isfile(parts[0]): filename, section = parts
    if not os.path.isfile(filename): return

    vardict, parser = globals(), configparser.RawConfigParser()
    parser.optionxform = str # Force case-sensitivity on names
    try:
        def parse_value(raw):
            try: return json.loads(raw) # Try to interpret as JSON
            except ValueError: return raw # JSON failed, fall back to raw
        txt = open(filename).read() # Add DEFAULT section if none present
        if not re.search("\\[\\w+\\]", txt): txt = "[DEFAULT]\n" + txt
        parser.readfp(StringIO.StringIO(txt), filename)
        for k, v in parser.items(section): vardict[k] = parse_value(v)
    except Exception:
        logging.warn("Error reading config from %s.", filename, exc_info=True)
456040
def _AtNonLeaf(self, attr_value, path):
    """"""
    if isinstance(attr_value, dict):
      for value in self.Expand(attr_value, path[1:]):
        yield value
    else:
      for v in objectfilter.ValueExpander._AtNonLeaf(self, attr_value, path):
        yield v
2297
def handle_common_arguments(parsed_args):
    
    # Setup the logger
    logging.basicConfig(
        level=logging.DEBUG if parsed_args.verbose else logging.WARNING
    )

    # Framework properties dictionary
    props = {}

    # Read the initial configuration script
    init = InitFileHandler()
    if not parsed_args.init_empty:
        if not parsed_args.init_conf_exclusive:
            # Load default configuration
            init.load()

        # Load the given configuration file
        conf_file = parsed_args.init_conf_exclusive or parsed_args.init_conf
        if conf_file:
            init.load(conf_file)

        # Normalize configuration
        init.normalize()

        # Set initial framework properties
        props.update(init.properties)

    # Compute framework properties
    for prop_def in parsed_args.properties or []:
        key, value = prop_def.split("=", 1)
        props[key] = value

    # Check initial run script(s)
    if parsed_args.init_script:
        path = props[PROP_INIT_FILE] = _resolve_file(parsed_args.init_script)
        if not path:
            raise IOError(
                "Initial script file not found: {0}".format(
                    parsed_args.init_script
                )
            )

    if parsed_args.run_script:
        # Find the file
        path = props[PROP_RUN_FILE] = _resolve_file(parsed_args.run_script)
        if not path:
            raise IOError(
                "Script file not found: {0}".format(parsed_args.run_script)
            )

    # Update the stored configuration
    init.properties.update(props)
    return init
1310921
def _set_attrs(self, attrs, allow_ro=False, from_json=True):
    
    for k, v in attrs.iteritems():
      attr = self._check_attr(k, allow_ro)
      if attr and from_json:
        v = attr.from_json(self._get_resource_root(), v)
      object.__setattr__(self, k, v)
260804
def _set_attr(self, name, doc=None, preload=False):
        ""

        if doc is None:
            doc = 'The {name} attribute.'.format(name=name)

        if not hasattr(self._attr_func_, name):
            attr_prop = property(
                functools.partial(self._setable_get_, name),
                functools.partial(self._setable_set_, name),
                doc=doc
            )

        elif preload:
            func = getattr(self._attr_func_, name)
            setattr(self._attr_data_, name, func())
            delattr(self._attr_func_, name)
            attr_prop = property(
                functools.partial(self._simple_get_, name),
                doc=doc
            )

        else:
            attr_prop = property(
                functools.partial(self._loadable_get_, name),
                doc=doc
            )

        setattr(type(self), name, attr_prop)
661871
def _parse_attribute_details(self, prop=ATTRIBUTES):
        

        parsed_attributes = self._parse_attribute_details_file(prop)
        if parsed_attributes is None:
            # If not in the (official) remote location, try the tree itself
            parsed_attributes = self._parse_complex_list(prop)

        for attribute in (a for a in parsed_attributes if not a['aliases']):
            # Aliases are not in ISO standard: default to label
            attribute['aliases'] = attribute['label']

        return get_default_for_complex(prop, parsed_attributes)
612981
function() {
    // the attributes for multi-profile itself
    this.attr = trait({
      path: {
        value: this.path,
        type: {
          readOnly: true,
          setup: function(value) {
            if (!fs.isDir(value)) {
              fs.mkdir(value);
            }

            var profiles = this.profiles_file = node_path.join(value, 'profiles');
            var current = this.current_file = node_path.join(value, 'current_profile');

            profile.touchFile(profiles);
            profile.touchFile(current);
          }
        }
      },

      // get or set the names of profiles
      profiles: {
        type: {
          getter: function() {
            return fs.read(this.profiles_file).split(/[\r\n]+/).filter(Boolean);
          },

          setter: function(profiles) {
            fs.write(this.profiles_file, profiles.join('\n'));

            return profiles;
          }
        }
      },

      // get or set the name of the current profile
      current: {
        type: {
          getter: function() {
            return fs.read(this.current_file).trim() || null;
          },

          setter: function(v) {
            fs.write(this.current_file, v);

            return v;
          }
        }
      }
    }, {
      host: this
    });
  }
199582
def parse_attribute_values
      values = []
      each_property do |name, value|
        values << AttributeValue.new(name, value)
      end

      DEFAULTS.each do |default|
        if values.find { |v| v.attribute.name == default.attribute.name }.nil?
          values << default
        end
      end

      values
    end
661074
function _handleAttributes(oldNode, newNode, rule, clearInternals) {
    var attributes          = {},                         // fresh new set of attributes to set on newNode
        setClass            = rule.set_class,             // classes to set
        addClass            = rule.add_class,             // add classes based on existing attributes
        addStyle            = rule.add_style,             // add styles based on existing attributes
        setAttributes       = rule.set_attributes,        // attributes to set on the current node
        allowedClasses      = currentRules.classes,
        i                   = 0,
        classes             = [],
        styles              = [],
        newClasses          = [],
        oldClasses          = [],
        classesLength,
        newClassesLength,
        currentClass,
        newClass,
        attributeName,
        method;

    if (setAttributes) {
      attributes = wysihtml5.lang.object(setAttributes).clone();
    }

    // check/convert values of attributes
    attributes = wysihtml5.lang.object(attributes).merge(_checkAttributes(oldNode,  rule.check_attributes)).get();

    if (setClass) {
      classes.push(setClass);
    }

    if (addClass) {
      for (attributeName in addClass) {
        method = addClassMethods[addClass[attributeName]];
        if (!method) {
          continue;
        }
        newClass = method(wysihtml5.dom.getAttribute(oldNode, attributeName));
        if (typeof(newClass) === "string") {
          classes.push(newClass);
        }
      }
    }

    if (addStyle) {
      for (attributeName in addStyle) {
        method = addStyleMethods[addStyle[attributeName]];
        if (!method) {
          continue;
        }

        newStyle = method(wysihtml5.dom.getAttribute(oldNode, attributeName));
        if (typeof(newStyle) === "string") {
          styles.push(newStyle);
        }
      }
    }


    if (typeof(allowedClasses) === "string" && allowedClasses === "any" && oldNode.getAttribute("class")) {
      if (currentRules.classes_blacklist) {
        oldClasses = oldNode.getAttribute("class");
        if (oldClasses) {
          classes = classes.concat(oldClasses.split(WHITE_SPACE_REG_EXP));
        }

        classesLength = classes.length;
        for (; i<classesLength; i++) {
          currentClass = classes[i];
          if (!currentRules.classes_blacklist[currentClass]) {
            newClasses.push(currentClass);
          }
        }

        if (newClasses.length) {
          attributes["class"] = wysihtml5.lang.array(newClasses).unique().join(" ");
        }

      } else {
        attributes["class"] = oldNode.getAttribute("class");
      }
    } else {
      // make sure that wysihtml5 temp class doesn't get stripped out
      if (!clearInternals) {
        allowedClasses["_wysihtml5-temp-placeholder"] = 1;
        allowedClasses["_rangySelectionBoundary"] = 1;
        allowedClasses["wysiwyg-tmp-selected-cell"] = 1;
      }

      // add old classes last
      oldClasses = oldNode.getAttribute("class");
      if (oldClasses) {
        classes = classes.concat(oldClasses.split(WHITE_SPACE_REG_EXP));
      }
      classesLength = classes.length;
      for (; i<classesLength; i++) {
        currentClass = classes[i];
        if (allowedClasses[currentClass]) {
          newClasses.push(currentClass);
        }
      }

      if (newClasses.length) {
        attributes["class"] = wysihtml5.lang.array(newClasses).unique().join(" ");
      }
    }

    // remove table selection class if present
    if (attributes["class"] && clearInternals) {
      attributes["class"] = attributes["class"].replace("wysiwyg-tmp-selected-cell", "");
      if ((/^\s*$/g).test(attributes["class"])) {
        delete attributes["class"];
      }
    }

    if (styles.length) {
      attributes["style"] = wysihtml5.lang.array(styles).unique().join(" ");
    }

    // set attributes on newNode
    for (attributeName in attributes) {
      // Setting attributes can cause a js error in IE under certain circumstances
      // eg. on a <img> under https when it's new attribute value is non-https
      // TODO: Investigate this further and check for smarter handling
      try {
        newNode.setAttribute(attributeName, attributes[attributeName]);
      } catch(e) {}
    }

    // IE8 sometimes loses the width/height attributes when those are set before the "src"
    // so we make sure to set them again
    if (attributes.src) {
      if (typeof(attributes.width) !== "undefined") {
        newNode.setAttribute("width", attributes.width);
      }
      if (typeof(attributes.height) !== "undefined") {
        newNode.setAttribute("height", attributes.height);
      }
    }
  }
677253
def set_common_attributes(span):
    """"""
    common = {
        attributes_helper.COMMON_ATTRIBUTES.get('AGENT'): AGENT,
    }
    common_attrs = Attributes(common)\
        .format_attributes_json()\
        .get('attributeMap')

    _update_attr_map(span, common_attrs)
240464
@Override
  protected void initParser() throws MtasConfigException {
    namespaceURI = "http://ilk.uvt.nl/folia";
    namespaceURI_id = "http://www.w3.org/XML/1998/namespace";
    rootTag = "FoLiA";
    contentTag = "text";
    allowNonContent = true;
    super.initParser();
  }
113689
def parse_attributes!
      self.attributes = (attributes || []).map do |key_value|
        name, type, index, default = key_value.split(/:/)
        opts = {}
        if default
          opts[:default] = default
        end
        if index
          index_type, constraint = index.split(/,/)
          if constraint == 'not_null'
            opts[:null] = false
          end
        end
        create_attribute(name, type, index_type, opts)
      end
    end
236044
def igetattr(self, name, context=None, class_context=True):
        
        # set lookup name since this is necessary to infer on import nodes for
        # instance
        context = contextmod.copy_context(context)
        context.lookupname = name
        try:
            attr = self.getattr(name, context, class_context=class_context)[0]
            for inferred in bases._infer_stmts([attr], context, frame=self):
                # yield Uninferable object instead of descriptors when necessary
                if not isinstance(inferred, node_classes.Const) and isinstance(
                    inferred, bases.Instance
                ):
                    try:
                        inferred._proxied.getattr("__get__", context)
                    except exceptions.AttributeInferenceError:
                        yield inferred
                    else:
                        yield util.Uninferable
                else:
                    yield function_to_method(inferred, self)
        except exceptions.AttributeInferenceError as error:
            if not name.startswith("__") and self.has_dynamic_getattr(context):
                # class handle some dynamic attributes, return a Uninferable object
                yield util.Uninferable
            else:
                raise exceptions.InferenceError(
                    error.message, target=self, attribute=name, context=context
                )
711997
def set_rule(self, name, properties):
        
        self._rule_attrs.append(name)
        setattr(self, name, properties)
1081049
def igetattr(self, name, context=None):
        """"""
        if not context:
            context = contextmod.InferenceContext()
        try:
            # avoid recursively inferring the same attr on the same class
            if context.push((self._proxied, name)):
                raise exceptions.InferenceError(
                    message="Cannot infer the same attribute again",
                    node=self,
                    context=context,
                )

            # XXX frame should be self._proxied, or not ?
            get_attr = self.getattr(name, context, lookupclass=False)
            yield from _infer_stmts(
                self._wrap_attr(get_attr, context), context, frame=self
            )
        except exceptions.AttributeInferenceError as error:
            try:
                # fallback to class.igetattr since it has some logic to handle
                # descriptors
                # But only if the _proxied is the Class.
                if self._proxied.__class__.__name__ != "ClassDef":
                    raise exceptions.InferenceError(**vars(error)) from error
                attrs = self._proxied.igetattr(name, context, class_context=False)
                yield from self._wrap_attr(attrs, context)
            except exceptions.AttributeInferenceError as error:
                raise exceptions.InferenceError(**vars(error)) from error