To be used for basic registration, and captcha registration
518069
public function InsertForBasic($FormPostValues, $CheckCaptcha = TRUE, $Options = array()) {
      $RoleIDs = Gdn::Config('Garden.Registration.DefaultRoles');
      if (!is_array($RoleIDs) || count($RoleIDs) == 0)
         throw new Exception(T('The default role has not been configured.'), 400);
      
      if (GetValue('SaveRoles', $Options)) {
         $RoleIDs = GetValue('RoleID', $FormPostValues);
      }

      $UserID = FALSE;

      // Define the primary key in this model's table.
      $this->DefineSchema();

      // Add & apply any extra validation rules.
      if (GetValue('ValidateEmail', $Options, TRUE))
         $this->Validation->ApplyRule('Email', 'Email');

      // TODO: DO I NEED THIS?!
      // Make sure that the checkbox val for email is saved as the appropriate enum
      if (array_key_exists('ShowEmail', $FormPostValues))
         $FormPostValues['ShowEmail'] = ForceBool($FormPostValues['ShowEmail'], '0', '1', '0');
      
      if (array_key_exists('Banned', $FormPostValues))
         $FormPostValues['Banned'] = ForceBool($FormPostValues['Banned'], '0', '1', '0');

      $this->AddInsertFields($FormPostValues);

      if ($this->Validate($FormPostValues, TRUE) === TRUE) {
         $Fields = $this->Validation->ValidationFields(); // All fields on the form that need to be validated (including non-schema field rules defined above)
         $Username = ArrayValue('Name', $Fields);
         $Email = ArrayValue('Email', $Fields);
         $Fields = $this->Validation->SchemaValidationFields(); // Only fields that are present in the schema
         $Fields['Roles'] = $RoleIDs;
         $Fields = RemoveKeyFromArray($Fields, $this->PrimaryKey);

         // If in Captcha registration mode, check the captcha value
         if ($CheckCaptcha && Gdn::Config('Garden.Registration.Method') == 'Captcha') {
            $CaptchaPublicKey = ArrayValue('Garden.Registration.CaptchaPublicKey', $FormPostValues, '');
            $CaptchaValid = ValidateCaptcha($CaptchaPublicKey);
            if ($CaptchaValid !== TRUE) {
               $this->Validation->AddValidationResult('Garden.Registration.CaptchaPublicKey', 'The reCAPTCHA value was not entered correctly. Please try again.');
               return FALSE;
            }
         }

         if (!$this->ValidateUniqueFields($Username, $Email))
            return FALSE;
         
         // Check for spam.
         if (GetValue('ValidateSpam', $Options, TRUE)) {
            $ValidateSpam = $this->ValidateSpamRegistration($FormPostValues);
            if ($ValidateSpam !== TRUE)
               return $ValidateSpam;
         }

         // Define the other required fields:
         $Fields['Email'] = $Email;

         // And insert the new user
         $UserID = $this->_Insert($Fields, $Options);
         if ($UserID && !GetValue('NoActivity', $Options)) {
            $ActivityModel = new ActivityModel();
            $ActivityModel->Save(array(
               'ActivityUserID' => $UserID,
               'ActivityType' => 'Registration',
               'HeadlineFormat' => T('HeadlineFormat.Registration', '{ActivityUserID,You} joined.'),
               'Story' => T('Welcome Aboard!')
                ),
                FALSE,
                array('GroupBy' => 'ActivityTypeID'));
         }
      }
      return $UserID;
   }
458924
function (opt) {
    var cap = new Captcha(opt);
    cap.use(drawBackground);
    cap.use(drawLines);
    cap.use(drawText);
    cap.use(drawLines);
    return cap;
  }
1250005
function toHTML()
    {

        return '<div class="captcha-container"><img src="' . $this->form_properties['assets_url'] . 'process.php?captcha=' . ($this->form_properties['captcha_storage'] == 'session' ? 2 : 1) . '&amp;nocache=' . time() . '" alt=""' . ($this->form_properties['doctype'] == 'xhtml' ? '/' : '') . '><a href="javascript:void(0)" title="' . $this->form_properties['language']['new_captcha'] . '">' . $this->form_properties['language']['new_captcha'] . '</a></div>';
    
    }
945289
def register():
    
    if request.method == "POST":
        username = request.form["username"]
        password = request.form["password"]
        error = None

        if not username:
            error = "Username is required."
        elif not password:
            error = "Password is required."
        elif db.session.query(
            User.query.filter_by(username=username).exists()
        ).scalar():
            error = f"User {username} is already registered."

        if error is None:
            # the name is available, create the user and go to the login page
            db.session.add(User(username=username, password=password))
            db.session.commit()
            return redirect(url_for("auth.login"))

        flash(error)

    return render_template("auth/register.html")
953860
def _get_captcha(reddit_session, captcha_id):
    """"""
    url = urljoin(reddit_session.config['captcha'],
                  captcha_id + '.png')
    sys.stdout.write('Captcha URL: {0}\nCaptcha: '.format(url))
    sys.stdout.flush()
    raw = sys.stdin.readline()
    if not raw:  # stdin has reached the end of file
        # Trigger exception raising next time through. The request is
        # cached so this will not require and extra request and delay.
        sys.stdin.close()
        return None
    return {'iden': captcha_id, 'captcha': raw.strip()}
600186
def main():
    """"""
    args = parse_args()
    if not any(args.loss == s for s in ['ctc', 'warpctc']):
        raise ValueError("Invalid loss '{}' (must be 'ctc' or 'warpctc')".format(args.loss))

    hp = Hyperparams()

    # Start a multiprocessor captcha image generator
    mp_captcha = MPDigitCaptcha(
        font_paths=get_fonts(args.font_path), h=hp.seq_length, w=30,
        num_digit_min=3, num_digit_max=4, num_processes=args.num_proc, max_queue_size=hp.batch_size * 2)
    try:
        # Must call start() before any call to mxnet module (https://github.com/apache/incubator-mxnet/issues/9213)
        mp_captcha.start()

        if args.gpu:
            contexts = [mx.context.gpu(i) for i in range(args.gpu)]
        else:
            contexts = [mx.context.cpu(i) for i in range(args.cpu)]

        init_states = lstm.init_states(hp.batch_size, hp.num_lstm_layer, hp.num_hidden)

        data_train = OCRIter(
            hp.train_epoch_size // hp.batch_size, hp.batch_size, init_states, captcha=mp_captcha, name='train')
        data_val = OCRIter(
            hp.eval_epoch_size // hp.batch_size, hp.batch_size, init_states, captcha=mp_captcha, name='val')

        symbol = lstm.lstm_unroll(
            num_lstm_layer=hp.num_lstm_layer,
            seq_len=hp.seq_length,
            num_hidden=hp.num_hidden,
            num_label=hp.num_label,
            loss_type=args.loss)

        head = '%(asctime)-15s %(message)s'
        logging.basicConfig(level=logging.DEBUG, format=head)

        module = mx.mod.Module(
            symbol,
            data_names=['data', 'l0_init_c', 'l0_init_h', 'l1_init_c', 'l1_init_h'],
            label_names=['label'],
            context=contexts)

        metrics = CtcMetrics(hp.seq_length)
        module.fit(train_data=data_train,
                   eval_data=data_val,
                   # use metrics.accuracy or metrics.accuracy_lcs
                   eval_metric=mx.metric.np(metrics.accuracy, allow_extra_outputs=True),
                   optimizer='sgd',
                   optimizer_params={'learning_rate': hp.learning_rate,
                                     'momentum': hp.momentum,
                                     'wd': 0.00001,
                                     },
                   initializer=mx.init.Xavier(factor_type="in", magnitude=2.34),
                   num_epoch=hp.num_epoch,
                   batch_end_callback=mx.callback.Speedometer(hp.batch_size, 50),
                   epoch_end_callback=mx.callback.do_checkpoint(args.prefix),
                   )
    except KeyboardInterrupt:
        print("W: interrupt received, stopping...")
    finally:
        # Reset multiprocessing captcha generator to stop processes
        mp_captcha.reset()
953837
def register():
    """"""

    if _security.confirmable or request.is_json:
        form_class = _security.confirm_register_form
    else:
        form_class = _security.register_form

    if request.is_json:
        form_data = MultiDict(request.get_json())
    else:
        form_data = request.form

    form = form_class(form_data)

    if form.validate_on_submit():
        user = register_user(**form.to_dict())
        form.user = user

        if not _security.confirmable or _security.login_without_confirmation:
            after_this_request(_commit)
            login_user(user)

        if not request.is_json:
            if 'next' in form:
                redirect_url = get_post_register_redirect(form.next.data)
            else:
                redirect_url = get_post_register_redirect()

            return redirect(redirect_url)
        return _render_json(form, include_auth_token=True)

    if request.is_json:
        return _render_json(form)

    return _security.render_template(config_value('REGISTER_USER_TEMPLATE'),
                                     register_user_form=form,
                                     **_ctx('register'))
62494
def validate(self, form_key="captcha", value=None):
        
        if not self.enabled:
            return True

        session_value = session.get('captcha_answer', None)
        if not session_value:
            return False
        
        if not value and form_key in request.form:
            value = request.form[form_key].strip()

        # invalidate the answer to stop new tries on the same challenge.
        session['captcha_answer'] = None
        return value and value == session_value
523229
def auth_basic(check, realm="private", text="Access denied"):
    '''  '''
    def decorator(func):
      def wrapper(*a, **ka):
        user, password = request.auth or (None, None)
        if user is None or not check(user, password):
          response.headers['WWW-Authenticate'] = 'Basic realm="%s"' % realm
          return HTTPError(401, text)
        return func(*a, **ka)
      return wrapper
    return decorator
825264
def register(context, request, load):
    """"""
    data = request.json
    res = validate(data, dataclass_to_jsl(
        RegistrationSchema).get_schema())
    if res:
        @request.after
        def set_error(response):
            response.status = 422
        return {
            'status': 'error',
            'field_errors': [{'message': res[x]} for x in res.keys()]
        }

    if data['password'] != data['password_validate']:
        @request.after
        def adjust_response(response):
            response.status = 422

        return {'status': 'error',
                'message': 'Password confirmation does not match'}

    if 'state' not in data.keys() or not data['state']:
        data['state'] = request.app.settings.application.new_user_state
    del data['password_validate']
    obj = context.create(data)
    return {'status': 'success'}
950026
def captcha_field(object_name, options = {})
      options.delete(:id)

      hidden_field(object_name, :captcha_challenge, options) + text_field(object_name, :captcha_solution, options)
    end
1032965
def protect_login_with_captcha(func):
    
    @wraps(func)
    def decorated_login(request, *args, **kwargs):
        response = func(request, *args, **kwargs)

        access_attempt = AccessAttempt(request, response)
        access_attempt.inspect()

        return response

    return decorated_login
396620
def require_captcha(function, *args, **kwargs):
    """"""
    raise_captcha_exception = kwargs.pop('raise_captcha_exception', False)
    captcha_id = None

    # Get a handle to the reddit session
    if hasattr(args[0], 'reddit_session'):
        reddit_session = args[0].reddit_session
    else:
        reddit_session = args[0]

    while True:
        try:
            if captcha_id:
                captcha_answer = _get_captcha(reddit_session, captcha_id)

                # When the method is being decorated, all of its default
                # parameters become part of this *args tuple. This means that
                # *args currently contains a None where the captcha answer
                # needs to go. If we put the captcha in the **kwargs,
                # we get a TypeError for having two values of the same param.
                func_args = _make_func_args(function)
                if 'captcha' in func_args:
                    captcha_index = func_args.index('captcha')
                    args = list(args)
                    args[captcha_index] = captcha_answer
                else:
                    kwargs['captcha'] = captcha_answer
            return function(*args, **kwargs)
        except errors.InvalidCaptcha as exception:
            if raise_captcha_exception or \
                    not hasattr(sys.stdin, 'closed') or sys.stdin.closed:
                raise
            captcha_id = exception.response['captcha']
937518
def register(self):
        
        form = self._get_form('SECURITY_REGISTER_FORM')
        if form.validate_on_submit():
            user = self.security_service.user_manager.create(**form.to_dict())
            self.security_service.register_user(user)
            return self.redirect('SECURITY_POST_REGISTER_REDIRECT_ENDPOINT')

        return self.render('register',
                           register_user_form=form,
                           **self.security.run_ctx_processor('register'))
852501
def generate_captcha(self):
        
        # Generate a fresh question
        self._question, answer = self._generate_question()

        # Get the current time, then sign the answer cryptographically
        timestamp = time.time()
        hashed = self.hash_answer(answer, timestamp)

        # Now stash all our values
        self._values = ['', timestamp, hashed]
652074
public function signUp()
  {
    if (isset($_POST['signUp'])) {
      // Сheck for occupancy
      if ($_POST['name'] == '' || $_POST['email'] == '' || $_POST['password'] == '' || $_POST['confirmPassword'] == '') {
        $this->errors[] = 'Fill in all the fields';
      } 

      // Check for existence username
      if (R::count('users', 'name = ?', array($_POST['name'])) > 0) {
        $this->errors[] = 'A user with this name already exists';
      } 

      // Check for existence email in table
      if (R::count('users', 'email = ?', array($_POST['email'])) > 0) {
        $this->errors[] = 'This account is already taken! Please Login';
      }

       // Check for password math
      if ($_POST['password'] != $_POST['confirmPassword']) {
        $this->errors[] = 'The passwords you entered do not match!';
      }

      // Set min symbols 8 on the password
      if (strlen($_POST['password']) < 8) {
        $this->errors[] = 'The password must contain at least 8 characters!';
      }

      // If All ok
      if (empty($this->errors)) {
        $createUser = R::dispense('users');
        $createUser->name = strip_tags($_POST['name']);
        $createUser->email = strip_tags($_POST['email']);
        $createUser->password = password_hash(strip_tags($_POST['password']), PASSWORD_DEFAULT);
        R::store($createUser);

        redirect('/login');
      } else {
        echo "<div class='alert alert-danger' role='alert'>" . array_shift($this->errors) . "</div>";
      }
    }
  }
1116360
def captcha_transmit(self, captcha, uuid):
        """"""

        self.log('Transmitting captcha')

        response = {
            'component': 'hfos.enrol.enrolmanager',
            'action': 'captcha',
            'data': b64encode(captcha['image'].getvalue()).decode('utf-8')
        }
        self.fire(send(uuid, response))