replace current annos with new then add remainder only users with needsValidation === false can overwrite annos
553101
function replaceThenMergeAnnotations(annos, nannos) {
  var rannos = (annos || []).splice(0);
  var nanno, n, a, anno;
  // Iterate through annos, comparing one nanno at a time. if it's the same and the user doesn't need validation, replace anno with nano.
  for (a = 0; a < rannos.length; a++) {
    anno = rannos[a];
    for (n = nannos.length - 1; n > -1; n--) {
      nanno = nannos[n];
      if (anno.flattened === nanno.flattened) {
        var nuser = GLOBAL.svc.auth.getUserByUsername(nanno.annotatedBy);
        if (!nuser.needsValidation) {
          rannos[a] = nanno;
        }
        nannos.splice(n, 1);
      }
    }
  }
  return rannos.concat(nannos);
}
891904
def absent(name,
           runas=None):
    '''
    
    '''
    ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}

    try:
        user_exists = __salt__['rabbitmq.user_exists'](name, runas=runas)
    except CommandExecutionError as err:
        ret['comment'] = 'Error: {0}'.format(err)
        return ret

    if user_exists:
        if not __opts__['test']:
            try:
                __salt__['rabbitmq.delete_user'](name, runas=runas)
            except CommandExecutionError as err:
                ret['comment'] = 'Error: {0}'.format(err)
                return ret
        ret['changes'].update({'name':
                              {'old': name,
                               'new': ''}})
    else:
        ret['result'] = True
        ret['comment'] = 'The user \'{0}\' is not present.'.format(name)
        return ret

    if __opts__['test'] and ret['changes']:
        ret['result'] = None
        ret['comment'] = 'The user \'{0}\' will be removed.'.format(name)
        return ret

    ret['result'] = True
    ret['comment'] = 'The user \'{0}\' was removed.'.format(name)
    return ret
1305258
def _harvest_validate(self, userkwargs):
        
        # the valideer to parse the
        # user arguemnts when watering
        parser = {}

        userkwargs.update(self.network_kwargs)
        # a simple set of original provided argument keys (used in IGNORES)
        original_kwargs = set(map(lambda k: k.split('_')[1] if k.find('_')>-1 else k, userkwargs.keys()))
        # list of columns that are required from seeds
        requires = []

        # -------------
        # Clean up Aggs
        # -------------
        for key in userkwargs.keys():
            # agg example: "avg_total", "max_tax"
            if key.find('_') > 0:
                agg, base = tuple(key.split('_'))
                if base in userkwargs:
                    if type(userkwargs[base]) is not list:
                        userkwargs[base] = [(None, userkwargs[base])]
                    userkwargs[base].append( (agg, userkwargs.pop(key)) )
                else:
                    userkwargs[base] = [(agg, userkwargs.pop(key))]

        # -----------------
        # Process Arguments
        # -----------------
        for key, seed in self.arguments.iteritems():
            # --------------
            # Argument Alias
            # --------------
            if seed.get('alias') and key in userkwargs:
                # pop the value form the user kwargs (to change the key later)
                value = userkwargs.pop(key) if key in userkwargs else NotImplemented
                # for duplicate keys
                oldkey = key+""
                # change the key
                key = seed.get('alias')
                # change the seed
                seed = get(self.arguments, seed.get('alias'))
                # set the new key:value
                if value is not NotImplemented:
                    if key in userkwargs:
                        raise valideer.ValidationError("Argument alias already specified for `%s` via `%s`" % (oldkey, key), oldkey)
                    userkwargs[key] = value

            # can provide multiple arguments
            if key.endswith('[]'):
                multi = True
                key = key[:-2]
            else:
                multi = False

            # get value(s) from user
            if key in userkwargs:
                value = userkwargs.pop(key)
            elif seed.get('copy'):
                value = userkwargs.get(seed.get('copy'))
            else:
                value = seed.get('default')

            # no argument provided, lets continue)
            if value is None or value == []:
                if seed.get('required'):
                    raise valideer.ValidationError("missing required property: %s" % key, key)
                else:
                    continue

            # add requires
            requires.extend(array(get(seed, 'requires', [])))

            # -----------
            # Inheritance
            # -----------
            # not permited from arguements yet. would need to happen above the ""PROCESS ARGUMENT"" block
            # self._inherit(*array(get(seed, 'inherit', [])))

            if type(value) is list and type(value[0]) is tuple:
                # complex
                for v in value:
                    ud, pd = self._harvest_args(key, seed, v, multi)
                    userkwargs.update(ud)
                    parser.update(pd)
            else:
                ud, pd = self._harvest_args(key, seed, value, multi)
                userkwargs.update(ud)
                parser.update(pd)

        # ------------
        # Ignored Keys
        # ------------
        for seed in self.seeds:
            ignores = set(array(get(seed, 'ignore')))
            if ignores:
                if ignores & original_kwargs:
                    if not get(seed, 'silent'):
                        additionals = ignores & original_kwargs
                        raise valideer.ValidationError("additional properties: %s" % ",".join(additionals), additionals)
                [userkwargs.pop(key) for key in ignores if key in userkwargs]

        # -------------------------
        # Custom Operators (part 1)
        # -------------------------
        operators = {}
        for key, value in userkwargs.items():
            rk = key
            agg = None
            if key.find('_')>-1:
                agg, rk = tuple(key.split('_'))
            seed = self.arguments.get(rk, self.arguments.get(rk+'[]'))
            if seed:
                if type(value) is list:
                    operators[key] = []
                    # need to remove the operator for validating
                    new_values = []
                    for v in value:
                        operator, v = self._operator(v, *seed.get('column', "").rsplit("::", 1))
                        new_values.append(v)
                        operators[key].append((agg, operator) if agg else operator)
                    userkwargs[key] = new_values
                else:
                    operator, value = self._operator(value, *seed.get('column', "").rsplit("::", 1))
                    operators[key] = (agg, operator) if agg else operator
                    userkwargs[key] = value

        # -----------------
        # Plant Sort Method
        # -----------------
        if 'sortby' in userkwargs:
            seed = self.arguments.get(userkwargs['sortby'].lower(), self.arguments.get(userkwargs['sortby'].lower()+'[]'))
            if seed:
                seed['id'] = str(userkwargs['sortby'].lower())

        for r in set(requires):
            if userkwargs.get(r) is None:
                raise valideer.ValidationError("required property not set: %s" % r, r)

        # --------
        # Validate
        # --------
        parser = valideer.parse(parser, additional_properties=False)
        validated = parser.validate(userkwargs, adapt=self.navigator.adapter())
        validated.update(self.network_kwargs)
        #   operators                   validated
        # --------------------------- | --------------------------------
        # {                           {
        #   "type": ["!", "!"],         "type": ['a', 'b'],
        #   "total": "<",               "total": "50",
        #   "tax": ("avg, ">"),         "tax": "1",
        #   "time": None                "time": "2014"
        # }                           }
        return operators, validated
139474
def rename(name, new_name):
    '''
    
    '''
    current_info = info(name)
    if not current_info:
        raise CommandExecutionError('User \'{0}\' does not exist'.format(name))
    new_info = info(new_name)
    if new_info:
        raise CommandExecutionError(
            'User \'{0}\' already exists'.format(new_name)
        )
    cmd = ['pw', 'usermod', '-l', new_name, '-n', name]
    __salt__['cmd.run'](cmd)
    post_info = info(new_name)
    if post_info['name'] != current_info['name']:
        return post_info['name'] == new_name
    return False
797439
function attemptReplacePatterns(token, replacements, measureThreshold) {
  var replacement = null;

  for(var i = 0; i < replacements.length; i++) {
    if(!measureThreshold || measure(attemptReplace(token, replacements[i][0], '')) > measureThreshold)
      replacement = attemptReplace(token, replacements[i][0], replacements[i][1]);

    if(replacement)
      break;
  }

  return replacement;
}
86459
function (userId, doc, fieldNames, modifier) {
			// only admins can update user roles via the client
			return Users.isAdmin(userId) || (doc._id === userId && fieldNames.indexOf("roles") < 0);
		}
689783
function it_replaces_authority_components_with_new_authority()
    {
        $new_authority = $this->withAuthority("corge:grault@quux.qux:9999");

        $new_authority->getAuthority()->shouldReturn("corge:grault@quux.qux:9999");
        $new_authority->getUserInfo()->shouldReturn("corge:grault");
        $new_authority->getHost()->shouldReturn("quux.qux");
        $new_authority->getPort()->shouldReturn(9999);
    }
93121
function(userId, properties, callback) {
      if (!userId) return callback(new Error(utils.i18n.identities.id));
      if (!properties.display_name) return callback(new Error(utils.i18n.identities.displayName));
      utils.debug('Identity replace: ' + userId);

      request.put({
        path: '/users/' + userId + '/identity',
        body: properties
      }, callback || utils.nop);
    }
346186
def can_update(self, user, **kwargs):
        """"""
        if user.is_admin():
            raise Return((True, set([])))

        is_creator = self.created_by == user.id
        if not (user.is_org_admin(self.organisation_id) or is_creator):
            raise Return((False, set([])))

        fields = ({'service_type', 'organisation_id'} & set(kwargs.keys()))
        if fields:
            raise Return((False, fields))
        else:
            raise Return((True, set([])))
275657
def edit(user_name, repo_name, key_id, params={})
      _update_user_repo_params(user_name, repo_name)
      _validate_user_repo_params(user, repo) unless user? && repo?
      _validate_presence_of key_id

      normalize! params
      filter! VALID_KEY_PARAM_NAMES, params

      put_request("/1.0/repositories/#{user}/#{repo.downcase}/deploy-keys/#{key_id}", params)
    end
50989
def assoc(self, key, value):
        
        return self._replace(user_ctx={
            **self.user_ctx,
            key: value,
        })
145153
def replace(self, **kwargs):
        
        if 'usage_key' in kwargs:
            for attr in self.USAGE_KEY_ATTRS:
                kwargs.pop(attr, None)
        else:
            kwargs['usage_key'] = self.usage_key.replace(**{
                key: kwargs.pop(key)
                for key
                in self.USAGE_KEY_ATTRS
                if key in kwargs
            })
        return super(AsideUsageKeyV2, self).replace(**kwargs)
352425
def validate_ok_for_update(update):
    """"""
    validate_is_mapping("update", update)
    # Update can not be {}
    if not update:
        raise ValueError('update only works with $ operators')
    first = next(iter(update))
    if not first.startswith('$'):
        raise ValueError('update only works with $ operators')
879642
def replace_validation(self):
        

        self.validate_profile_exists()
        profile_data = self.profiles.get(self.args.profile_name)

        # check redis
        # if redis is None:
        #     self.handle_error('Could not get connection to Redis')

        # load hash
        redis_hash = profile_data.get('data', {}).get('args', {}).get('tc_playbook_db_context')
        if redis_hash is None:
            self.handle_error('Could not find redis hash (db context).')

        # load data
        data = self.redis.hgetall(redis_hash)
        if data is None:
            self.handle_error('Could not load data for hash {}.'.format(redis_hash))
        validations = {'rules': [], 'outputs': []}
        for v, d in data.items():
            variable = v.decode('utf-8')
            # data = d.decode('utf-8')
            data = json.loads(d.decode('utf-8'))
            # if data == 'null':
            if data is None:
                continue
            validations['outputs'].append(variable)

            # null check
            od = OrderedDict()
            od['data'] = data
            od['data_type'] = 'redis'
            od['operator'] = 'eq'
            od['variable'] = variable
            # if variable.endswith('Array'):
            #     od['data'] = json.loads(data)
            #     od['data_type'] = 'redis'
            #     od['operator'] = 'eq'
            #     od['variable'] = variable
            # elif variable.endswith('Binary'):
            #     od['data'] = json.loads(data)
            #     od['data_type'] = 'redis'
            #     od['operator'] = 'eq'
            #     od['variable'] = variable
            # elif variable.endswith('String'):
            #     od['data'] = json.loads(data)
            #     od['data_type'] = 'redis'
            #     od['operator'] = 'eq'
            #     od['variable'] = variable
            validations['rules'].append(od)

        fqfn = profile_data.get('fqfn')
        with open(fqfn, 'r+') as fh:
            data = json.load(fh)
            for profile in data:
                if profile.get('profile_name') == self.args.profile_name:
                    profile['validations'] = validations.get('rules')
                    profile['args']['default']['tc_playbook_out_variables'] = ','.join(
                        validations.get('outputs')
                    )
            fh.seek(0)
            fh.write(json.dumps(data, indent=2, sort_keys=True))
            fh.truncate()
1228447
function fuseAnnotation (tx, annos) {
  if (!isArray(annos) || annos.length < 2) {
    throw new Error('fuseAnnotation(): at least two annotations are necessary.')
  }
  let sel, annoType
  annos.forEach(function (anno, idx) {
    if (idx === 0) {
      sel = anno.getSelection()
      annoType = anno.type
    } else {
      if (anno.type !== annoType) {
        throw new Error('fuseAnnotation(): all annotations must be of the same type.')
      }
      sel = sel.expand(anno.getSelection())
    }
  })
  // expand the first and delete the others
  for (var i = 1; i < annos.length; i++) {
    tx.delete(annos[i].id)
  }
  expandAnnotation(tx, annos[0], sel)
  tx.setSelection(sel)
}
452463
def _requires_update(self, old_object, new_object):
        
        old_encoded = self.manager._encode(old_object)
        new_encoded = self.manager._encode(new_object)
        return _compare_recursive(old_encoded, new_encoded)
1121991
def modify(self, **params):
        """"""
        data = self.api_client.update_current_user(**params)
        self.update(data)
        return data