Parses a plist key value.

    Args:
      knowledge_base (KnowledgeBase): to fill with preprocessing information.
      name (str): name of the plist key.
      value (str): value of the plist key.
493176
def _ParsePlistKeyValue(self, knowledge_base, name, value):
    
    if not knowledge_base.GetValue('operating_system_version'):
      if name in self._PLIST_KEYS:
        knowledge_base.SetValue('operating_system_version', value)
217905
def parse_value_object(self, tup_tree):
        

        self.check_node(tup_tree, 'VALUE.OBJECT')

        child = self.one_child(tup_tree, ('CLASS', 'INSTANCE'))

        return (name(tup_tree), attrs(tup_tree), child)
253199
def get_attribute(self, name):
        
        assert isinstance(name, basestring)
        value = None
        if self.__attributes and name in self.__attributes.keys():
            value = self.__attributes[name]
        return value
1128237
def Parse(self, stat, knowledge_base):
    """"""
    _ = knowledge_base
    value = stat.registry_data.GetValue()
    result = ZONE_LIST.get(value.strip())
    if not result:
      yield rdfvalue.RDFString("Unknown (%s)" % value.strip())

    yield rdfvalue.RDFString(result)
1346168
def process_base_field(cls, field, key):
        
        if not field.name:
            field.name = key
        elif key != field.name:
            if not isinstance(field.alias, list):
                field.alias = [key]
            else:
                field.alias.insert(0, key)
            setattr(cls, field.name, field)

        cls.prepare_field(field)

        if field.alias:
            for alias_name in field.alias:
                if key is not alias_name:
                    setattr(cls, alias_name, field)
732543
def _process_name(self, node, **kwargs):
        

        with self._interpolation():
            with self._python_bool_wrapper(**kwargs):

                if node.name not in self.stored_names and node.ctx != 'store':
                    self.output.write(self.context_name)
                    self.output.write('.')

                if node.ctx == 'store':
                    self.stored_names.add(node.name)

                self.output.write(node.name)
38283
def Parse(self, stat, knowledge_base):
    """"""
    _ = knowledge_base  # Unused.
    sid_str = stat.pathspec.Dirname().Basename()

    if SID_RE.match(sid_str):
      kb_user = rdf_client.User()
      kb_user.sid = sid_str
      if stat.pathspec.Basename() == "ProfileImagePath":
        if stat.resident:
          # Support old clients.
          kb_user.homedir = utils.SmartUnicode(stat.resident)
        else:
          kb_user.homedir = stat.registry_data.GetValue()

        kb_user.userprofile = kb_user.homedir
        try:
          # Assume username is the last component of the path. This is not
          # robust, but other user artifacts will override it if there is a
          # better match.
          kb_user.username = kb_user.homedir.rsplit("\\", 1)[-1]
        except IndexError:
          pass

      yield kb_user
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)
540143
def Parse(self, statentry, file_object, knowledge_base):
    """"""
    _ = knowledge_base
    kwargs = {}
    try:
      kwargs["aff4path"] = file_object.urn
    except AttributeError:
      pass

    direct_copy_items = [
        "Label", "Disabled", "UserName", "GroupName", "Program",
        "StandardInPath", "StandardOutPath", "StandardErrorPath",
        "LimitLoadToSessionType", "EnableGlobbing", "EnableTransactions",
        "OnDemand", "RunAtLoad", "RootDirectory", "WorkingDirectory", "Umask",
        "TimeOut", "ExitTimeOut", "ThrottleInterval", "InitGroups",
        "StartOnMount", "StartInterval", "Debug", "WaitForDebugger", "Nice",
        "ProcessType", "AbandonProcessGroup", "LowPriorityIO", "LaunchOnlyOnce"
    ]

    string_array_items = [
        "LimitLoadToHosts", "LimitLoadFromHosts", "LimitLoadToSessionType",
        "ProgramArguments", "WatchPaths", "QueueDirectories"
    ]

    flag_only_items = ["SoftResourceLimits", "HardResourceLimits", "Sockets"]

    plist = {}

    try:
      plist = biplist.readPlist(file_object)
    except (biplist.InvalidPlistException, ValueError, IOError) as e:
      plist["Label"] = "Could not parse plist: %s" % e

    # These are items that can be directly copied
    for key in direct_copy_items:
      kwargs[key] = plist.get(key)

    # These could be a string, they could be an array, we don't know and neither
    # does Apple so we check.
    for key in string_array_items:
      elements = plist.get(key)
      if isinstance(elements, string_types):
        kwargs[key] = [elements]
      else:
        kwargs[key] = elements

    # These are complex items that can appear in multiple data structures
    # so we only flag on their existence
    for key in flag_only_items:
      if plist.get(key):
        kwargs[key] = True

    if plist.get("inetdCompatability") is not None:
      kwargs["inetdCompatabilityWait"] = plist.get("inetdCompatability").get(
          "Wait")

    keepalive = plist.get("KeepAlive")
    if isinstance(keepalive, bool) or keepalive is None:
      kwargs["KeepAlive"] = keepalive
    else:
      keepalivedict = {}
      keepalivedict["SuccessfulExit"] = keepalive.get("SuccessfulExit")
      keepalivedict["NetworkState"] = keepalive.get("NetworkState")

      pathstates = keepalive.get("PathState")
      if pathstates is not None:
        keepalivedict["PathState"] = []
        for pathstate in pathstates:
          keepalivedict["PathState"].append(
              rdf_plist.PlistBoolDictEntry(
                  name=pathstate, value=pathstates[pathstate]))

      otherjobs = keepalive.get("OtherJobEnabled")
      if otherjobs is not None:
        keepalivedict["OtherJobEnabled"] = []
        for otherjob in otherjobs:
          keepalivedict["OtherJobEnabled"].append(
              rdf_plist.PlistBoolDictEntry(
                  name=otherjob, value=otherjobs[otherjob]))
      kwargs["KeepAliveDict"] = rdf_plist.LaunchdKeepAlive(**keepalivedict)

    envvars = plist.get("EnvironmentVariables")
    if envvars is not None:
      kwargs["EnvironmentVariables"] = []
      for envvar in envvars:
        kwargs["EnvironmentVariables"].append(
            rdf_plist.PlistStringDictEntry(name=envvar, value=envvars[envvar]))

    startcalendarinterval = plist.get("StartCalendarInterval")
    if startcalendarinterval is not None:
      if isinstance(startcalendarinterval, dict):
        kwargs["StartCalendarInterval"] = [
            rdf_plist.LaunchdStartCalendarIntervalEntry(
                Minute=startcalendarinterval.get("Minute"),
                Hour=startcalendarinterval.get("Hour"),
                Day=startcalendarinterval.get("Day"),
                Weekday=startcalendarinterval.get("Weekday"),
                Month=startcalendarinterval.get("Month"))
        ]
      else:
        kwargs["StartCalendarInterval"] = []
        for entry in startcalendarinterval:
          kwargs["StartCalendarInterval"].append(
              rdf_plist.LaunchdStartCalendarIntervalEntry(
                  Minute=entry.get("Minute"),
                  Hour=entry.get("Hour"),
                  Day=entry.get("Day"),
                  Weekday=entry.get("Weekday"),
                  Month=entry.get("Month")))

    yield rdf_plist.LaunchdPlist(**kwargs)
1245797
def parse_entry(self, name):
        

        # calculate schema mode
        # if ':name' or '' or '[]:name' or '[]' found, it'll be treat as multiple Schema query
        alias = name
        if ':' in name:
            name, alias = name.split(':')
        if name.endswith('[]'):
            need_list = True
            name = name[:-2]
        else:
            need_list = False
        return alias, name, need_list
389015
def set(self, name, value):
        

        name = str(name)
        if name not in self._properties:
            raise ArgumentError("Unknown property in DeviceModel", name=name)

        self._properties[name] = value
605609
def _dict_to_name_value(data):
    '''
    
    '''
    if isinstance(data, dict):
        sorted_data = sorted(data.items(), key=lambda s: s[0])
        result = []
        for name, value in sorted_data:
            if isinstance(value, dict):
                result.append({name: _dict_to_name_value(value)})
            else:
                result.append({name: value})
    else:
        result = data
    return result
1287371
def set_name(self,name=None):
        
        if name:
            self.name = name[:254]
        else:
            self.name = self.extract_name()[:254]

        self.save()

        return self.name
1116835
def SetCoreGRRKnowledgeBaseValues(kb, client_obj):
  """"""
  client_schema = client_obj.Schema
  kb.fqdn = utils.SmartUnicode(client_obj.Get(client_schema.FQDN, ""))
  if not kb.fqdn:
    kb.fqdn = utils.SmartUnicode(client_obj.Get(client_schema.HOSTNAME, ""))
  versions = client_obj.Get(client_schema.OS_VERSION)
  if versions and versions.versions:
    try:
      kb.os_major_version = versions.versions[0]
      kb.os_minor_version = versions.versions[1]
    except IndexError:
      # Some OSs don't have a minor version.
      pass
  client_os = client_obj.Get(client_schema.SYSTEM)
  if client_os:
    kb.os = utils.SmartUnicode(client_obj.Get(client_schema.SYSTEM))
761722
def get_value(d, name, field):
    
    multiple = core.is_multiple(field)
    value = d.get(name, core.missing)
    if value is core.missing:
        return core.missing
    if multiple and value is not core.missing:
        return [
            decode_argument(v, name) if isinstance(v, basestring) else v for v in value
        ]
    ret = value
    if value and isinstance(value, (list, tuple)):
        ret = value[0]
    if isinstance(ret, basestring):
        return decode_argument(ret, name)
    else:
        return ret
1012
def set(self, name, value):
        
        curr = self.values
        parts = name.split('.')

        for i, part in enumerate(parts[:-1]):
            try:
                curr = curr.setdefault(part, {})
            except AttributeError:
                raise InvalidPath('.'.join(parts[:i + 1]))

        try:
            curr[parts[-1]] = value
        except TypeError:
            raise InvalidPath('.'.join(parts[:-1]))
257292
def _set_attrib(name, key, value, param, root=None, validate=True):
    '''
    
    '''
    pre_info = info(name, root=root)

    # If the user is not present or the attribute is already present,
    # we return early
    if not pre_info['name']:
        return False

    if value == pre_info[key]:
        return True

    cmd = ['chage']

    if root is not None:
        cmd.extend(('-R', root))

    cmd.extend((param, value, name))

    ret = not __salt__['cmd.run'](cmd, python_shell=False)
    if validate:
        ret = info(name, root=root).get(key) == value
    return ret