Thanks to the userId, we can get back from the Db the options set for this user
and fill the fields with them
544551
function getDataForUserId(formName) {
  var userId = pad.getUserId();
  var message = {};
  message.type = 'USERINFO_GET';
  message.padId = pad.getPadId();
  message.userInfo = {};
  message.userInfo.userId = userId;
  message.userInfo.formName = formName;

  pad.collabClient.sendMessage(message);
}
843394
public function save($user_id)
    {
        $validator = $this->validator->make(
            $this->getUserData(app('request')),
            $this->getUserRules(),
            $this->getUserMessages(),
            $this->getUserPlaceholders()
        );

        $validation = $validator->valid();

        foreach ($this->repository->all() as $field) {
            /** @var FieldTypeInterface|BaseType|CanHandleUsers $field */
            $field->setErrorMessageBag($validator->errors());

            if (method_exists($field, 'userSave')) {
                $field->userSave($validation[$field->getName()] ?? null, $user_id);
            } else {
                throw new UserException('Unable to save ['.$field->getName().']. The [userSave] method is missing.');
            }
        }
    }
239300
public function execute() {
        global $DB;

        $userid = $this->get_custom_data()->userid;

        // Get the user's preference.
        $hasbeenmigrated = get_user_preferences('core_message_migrate_data', false, $userid);

        if (!$hasbeenmigrated) {
            // To determine if we should update the preference.
            $updatepreference = true;

            // Get all the users the current user has received a message from.
            $sql = "SELECT DISTINCT(useridfrom)
                      FROM {message} m
                     WHERE useridto = ?
                     UNION
                    SELECT DISTINCT(useridfrom)
                      FROM {message_read} m
                     WHERE useridto = ?";
            $users = $DB->get_records_sql($sql, [$userid, $userid]);

            // Get all the users the current user has messaged.
            $sql = "SELECT DISTINCT(useridto)
                      FROM {message} m
                     WHERE useridfrom = ?
                     UNION
                    SELECT DISTINCT(useridto)
                      FROM {message_read} m
                     WHERE useridfrom = ?";
            $users = $users + $DB->get_records_sql($sql, [$userid, $userid]);
            if (!empty($users)) {
                // Loop through each user and migrate the data.
                foreach ($users as $otheruserid => $user) {
                    $ids = [$userid, $otheruserid];
                    sort($ids);
                    $key = implode('_', $ids);

                    // Set the lock data.
                    $timeout = 5; // In seconds.
                    $locktype = 'core_message_migrate_data';

                    // Get an instance of the currently configured lock factory.
                    $lockfactory = \core\lock\lock_config::get_lock_factory($locktype);

                    // See if we can grab this lock.
                    if ($lock = $lockfactory->get_lock($key, $timeout)) {
                        try {
                            $transaction = $DB->start_delegated_transaction();
                            $this->migrate_data($userid, $otheruserid);
                            $transaction->allow_commit();
                        } catch (\Throwable $e) {
                            throw $e;
                        } finally {
                            $lock->release();
                        }
                    } else {
                        // Couldn't get a lock, move on to next user but make sure we don't update user preference so
                        // we still try again.
                        $updatepreference = false;
                        continue;
                    }
                }
            }

            if ($updatepreference) {
                set_user_preference('core_message_migrate_data', true, $userid);
            } else {
                // Throwing an exception in the task will mean that it isn't removed from the queue and is tried again.
                throw new \moodle_exception('Task failed.');
            }
        }
    }
90488
private function populateOptions()
    {
        $flatOptions = $this->getRawOptions();

        $this->parser->parseInput($flatOptions);

        $parsed = $this->parser->getOptions();

        foreach ($parsed as $optionName => $optionValue) {
            //ignores any options the user sent which were not defined
            $this->options->setValueIfExists($optionName, $optionValue);
        }
    }
1257742
protected function update_users_used() {
        global $DB;

        $this->userfullnames = array();
        $userids = array();

        // For each event cache full username.
        // Get list of userids which will be shown in log report.
        foreach ($this->rawdata as $event) {
            $logextra = $event->get_logextra();
            if (!empty($event->userid) && empty($userids[$event->userid])) {
                $userids[$event->userid] = $event->userid;
            }
            if (!empty($logextra['realuserid']) && empty($userids[$logextra['realuserid']])) {
                $userids[$logextra['realuserid']] = $logextra['realuserid'];
            }
            if (!empty($event->relateduserid) && empty($userids[$event->relateduserid])) {
                $userids[$event->relateduserid] = $event->relateduserid;
            }
        }
        $this->rawdata->close();

        // Get user fullname and put that in return list.
        if (!empty($userids)) {
            list($usql, $uparams) = $DB->get_in_or_equal($userids);
            $users = $DB->get_records_sql("SELECT id," . get_all_user_name_fields(true) . " FROM {user} WHERE id " . $usql,
                    $uparams);
            foreach ($users as $userid => $user) {
                $this->userfullnames[$userid] = fullname($user);
                unset($userids[$userid]);
            }

            // We fill the array with false values for the users that don't exist anymore
            // in the database so we don't need to query the db again later.
            foreach ($userids as $userid) {
                $this->userfullnames[$userid] = false;
            }
        }
    }
247785
def create_user(self, **kwargs):
        """"""
        kwargs = self._prepare_create_user_args(**kwargs)
        user = self.user_model(**kwargs)
        return self.put(user)
839305
function selectUserAttrs(name, fieldData) {
    const { multiple, options, label: labelText, value, class: classname, className, ...restData } = fieldData
    const optis = Object.keys(options).map(val => {
      const attrs = { value: val }
      const optionTextVal = options[val]
      const optionText = Array.isArray(optionTextVal) ? mi18n.get(...optionTextVal) || optionTextVal[0] : optionTextVal
      if (Array.isArray(value) ? value.includes(val) : val === value) {
        attrs.selected = null
      }

      return m('option', optionText, attrs)
    })

    const selectAttrs = {
      id: `${name}-${data.lastID}`,
      title: restData.description || labelText || name.toUpperCase(),
      name,
      className: `fld-${name} form-control ${classname || className || ''}`.trim(),
    }

    if (multiple) {
      selectAttrs.multiple = true
    }

    const label = `<label for="${selectAttrs.id}">${i18n[name]}</label>`

    Object.keys(restData).forEach(function(attr) {
      selectAttrs[attr] = restData[attr]
    })

    const select = m('select', optis, selectAttrs).outerHTML
    const inputWrap = `<div class="input-wrap">${select}</div>`
    return `<div class="form-group ${name}-wrap">${label}${inputWrap}</div>`
  }
7864
def save_user(self, idvalue, options=None):
        
        options = options or {}
        data = options.copy()
        data['id'] = idvalue
        return self.api_post('user', data)
606495
private function _fill()
    {

        if (empty($this->db)) return false;

        $sql = (string)"SHOW VARIABLES";
        $res = $this->db->query((string)$sql);

        if (!$res) return false;

        $data = $this->db->fetch_assoc_list($res);
        if (!empty($data)) {
            foreach ($data as $variable) {
                $this->$variable[(string)'Variable_name'] = (string)$variable['Value'];
            }
            $this->db->free($res);
        }

        // clear all the unecessary variables and the endles recursion of the db
        unset($this->db, $data, $variable);

        return true;
    }
508096
def handle(self, *args, **options):
        

        def get_user(username):
            try:
                return User.objects.get(username=username)
            except ObjectDoesNotExist as e:
                raise CommandError("This user doesn't exist in the database")

        def add_permissions(user_field_permissions, content_type, name):

            p = None
            try:
                p = FieldPermission.objects.get(content_type=content_type, name=name)
            except ObjectDoesNotExist:
                p = FieldPermission(content_type=content_type, name=name)
                p.save()
            finally:
                user_field_permissions.permissions.add(p)



        if len(args) !=1:
             raise CommandError("Specifies a json file created by the fine_permissions_dump command")
        else:
            try:


                with open(args[0], 'r') as json_file:
                    myjson = json.load(json_file)

                    user = get_user(options.get('user')) if options['user'] else get_user(myjson['username'])
                    fields_permissions = myjson['fields_permissions']

                    user_field_permissions = UserFieldPermissions(user=user)
                    user_field_permissions.save()

                    for f in fields_permissions:
                        content_type = ContentType.objects.get(app_label=f["app_label"], model=f["model"])
                        add_permissions(user_field_permissions, content_type, f['name'])


            except Exception as e:
                raise CommandError(e)
740687
private function loadOptionValues(): void
	{
		$this->optionValues = array_merge(
			Option::getDefaults($this->moduleId),
			Option::getForModule($this->moduleId)
		);
	}
21680
function setupDbHelper( user_options ) {
  var options = user_options || {}

  /**
   * @returns {Promise<MongooseThenable>}
   */
  function setupDb() {
    return connection( options.connection )
      .then(
        /**
         * @param {Object} db
         * @param {Function} db.model
         *
         * @throws {Error}
         * @returns {*}
         */
        function ( db ) {
          try {
            if ( Array.isArray( options.schemas ) ) {
              options.schemas.forEach(
                function ( schema ) {
                  var keys = Object.keys( schema );

                  db.model( keys[ 0 ], schema[ keys[ 0 ] ] );
                }
              );
            }

            return db;
          } catch ( err ) {
            throw err;
          }
        }
      )
      .catch(
        function ( err ) {
          throw err
        }
      )
  }

  return setupDb
}
1338402
public function delete_user_option(string $id_option, string $id_user = null): ?int
  {
    if ( $id_option = $this->_get_id_option($id_option) ){
      return $this->db->delete($this->class_cfg['table'], [
        $this->fields['id_option'] => $id_option,
        $this->fields['id_user'] => $id_user ?: $this->id_user
      ]);
    }
    return null;
  }
657406
def pre_save(self, model_instance, add):
        """"""
        value = super(UserField, self).pre_save(model_instance, add)
        if not value and not add:
            # fall back to OS user if not accessing through browser
            # better than nothing ...
            value = self.get_os_username()
            setattr(model_instance, self.attname, value)
            return value
        return value
452917
def load_user(self, uid):
    
        '''
            
        '''
    
        title = '%s.load_user' % self.__class__.__name__
        
    # validate inputs
        input_fields = {
            'uid': uid
        }
        for key, value in input_fields.items():
            if value:
                object_title = '%s(%s=%s)' % (title, key, str(value))
                self.fields.validate(value, '.%s' % key, object_title)
    
    # construct url
        url = self.bucket_url + '/_user/%s' % uid
        
    # send request and unwrap response
        response = requests.get(url)
        response = response.json()
    
        return response
296583
function updateUserDataField(userId, data, overwrite, callback) {
        return _updateUserObjectField(userId, ['data'], data, overwrite)
            .then(function (userData) {
                return userData.data;
            })
            .nodeify(callback);
    }
40361
function getUserFields(selector, sort) {
  var selectorFields = Object.keys(selector);
  var sortFields = sort? sort.map(getKey) : [];
  var userFields;
  if (selectorFields.length >= sortFields.length) {
    userFields = selectorFields;
  } else {
    userFields = sortFields;
  }

  if (sortFields.length === 0) {
    return {
      fields: userFields
    };
  }

  // sort according to the user's preferred sorting
  userFields = userFields.sort(function (left, right) {
    var leftIdx = sortFields.indexOf(left);
    if (leftIdx === -1) {
      leftIdx = Number.MAX_VALUE;
    }
    var rightIdx = sortFields.indexOf(right);
    if (rightIdx === -1) {
      rightIdx = Number.MAX_VALUE;
    }
    return leftIdx < rightIdx ? -1 : leftIdx > rightIdx ? 1 : 0;
  });

  return {
    fields: userFields,
    sortOrder: sort.map(getKey)
  };
}