generate speech by captcha from session
482186
def generate_speech_captcha
      raise RuntimeError, "espeak disabled" unless EasyCaptcha.espeak?
      if EasyCaptcha.cache
        File.read(speech_captcha_cache_path(current_captcha_code))
      else
        wav_file = Tempfile.new("#{current_captcha_code}.wav")
        EasyCaptcha.espeak.generate(current_captcha_code, wav_file.path)
        File.read(wav_file.path)
      end
    end
250624
async def _process_auth_form(self, html: str) -> (str, str):
        
        # Parse page
        p = AuthPageParser()
        p.feed(html)
        p.close()

        # Get data from hidden inputs
        form_data = dict(p.inputs)
        form_url = p.url
        form_data['email'] = self.login
        form_data['pass'] = self.password
        if p.message:
            # Show form errors
            raise VkAuthError('invalid_data', p.message, form_url, form_data)
        elif p.captcha_url:
            form_data['captcha_key'] = await self.enter_captcha(
                "https://m.vk.com{}".format(p.captcha_url),
                form_data['captcha_sid']
            )
            form_url = "https://m.vk.com{}".format(form_url)

        # Send request
        url, html = await self.driver.post_text(form_url, form_data)
        return url, html
956916
def tabbed_parsing_token_generator(data_dir, tmp_dir, train, prefix,
                                   source_vocab_size, target_vocab_size):
  """"""
  filename = "parsing_{0}.pairs".format("train" if train else "dev")
  source_vocab = generator_utils.get_or_generate_tabbed_vocab(
      data_dir, tmp_dir, filename, 0,
      prefix + "_source.tokens.vocab.%d" % source_vocab_size, source_vocab_size)
  target_vocab = generator_utils.get_or_generate_tabbed_vocab(
      data_dir, tmp_dir, filename, 1,
      prefix + "_target.tokens.vocab.%d" % target_vocab_size, target_vocab_size)
  pair_filepath = os.path.join(tmp_dir, filename)
  return text_problems.text2text_generate_encoded(
      text_problems.text2text_txt_tab_iterator(pair_filepath), source_vocab,
      target_vocab)
1351358
async def handle_natural_language(bot: NoneBot, ctx: Context_T) -> bool:
    
    session = NLPSession(bot, ctx, str(ctx['message']))

    # use msg_text here because CQ code "share" may be very long,
    # at the same time some plugins may want to handle it
    msg_text_length = len(session.msg_text)

    futures = []
    for p in _nl_processors:
        if not p.allow_empty_message and not session.msg:
            # don't allow empty msg, but it is one, so skip to next
            continue

        if p.only_short_message and \
                msg_text_length > bot.config.SHORT_MESSAGE_MAX_LENGTH:
            continue

        if p.only_to_me and not ctx['to_me']:
            continue

        should_run = await perm.check_permission(bot, ctx, p.permission)
        if should_run and p.keywords:
            for kw in p.keywords:
                if kw in session.msg_text:
                    break
            else:
                # no keyword matches
                should_run = False

        if should_run:
            futures.append(asyncio.ensure_future(p.func(session)))

    if futures:
        # wait for intent commands, and sort them by confidence
        intent_commands = []
        for fut in futures:
            try:
                res = await fut
                if isinstance(res, NLPResult):
                    intent_commands.append(res.to_intent_command())
                elif isinstance(res, IntentCommand):
                    intent_commands.append(res)
            except Exception as e:
                logger.error('An exception occurred while running '
                             'some natural language processor:')
                logger.exception(e)

        intent_commands.sort(key=lambda ic: ic.confidence, reverse=True)
        logger.debug(f'Intent commands: {intent_commands}')

        if intent_commands and intent_commands[0].confidence >= 60.0:
            # choose the intent command with highest confidence
            chosen_cmd = intent_commands[0]
            logger.debug(
                f'Intent command with highest confidence: {chosen_cmd}')
            return await call_command(
                bot, ctx, chosen_cmd.name,
                args=chosen_cmd.args,
                current_arg=chosen_cmd.current_arg,
                check_perm=False
            )
        else:
            logger.debug('No intent command has enough confidence')
    return False
424744
def generate_session_token(refresh_token, verbose):
    

    platform = _get_platform(authenticated=False)
    session_token, expires_in = platform.generate_session_token(refresh_token)

    if verbose:
        click.echo("%s\n\n%s" % (session_token, _color('YELLOW', "Expires in %d seconds" % expires_in)))
    else:
        click.echo(session_token)
1284550
function generateSession() {
    const session = {}
    //you can alter the cookie options in nexts
    session.cookie = {}
    for (const prop in cookie) {
      session.cookie[prop] = cookie[prop]
    }
    compatMaxage(session.cookie)
    return session
  }
1296767
def generate_image(self, chars):
        
        background = random_color(238, 255)
        color = random_color(10, 200, random.randint(220, 255))
        im = self.create_captcha_image(chars, color, background)
        self.create_noise_dots(im, color)
        self.create_noise_curve(im, color)
        im = im.filter(ImageFilter.SMOOTH)
        return im
548128
def segment_into_chars(utterance: str) -> str:
    

    if not isinstance(utterance, str):
        raise TypeError("Input type must be a string. Got {}.".format(type(utterance)))

    utterance.strip()
    utterance = utterance.replace(" ", "")
    return " ".join(utterance)
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>';
    
    }
629741
def main():
    """"""
    parser = argparse.ArgumentParser()
    parser.add_argument("path", help="Path to the CAPTCHA image file")
    parser.add_argument("--prefix", help="Checkpoint prefix [Default 'ocr']", default='ocr')
    parser.add_argument("--epoch", help="Checkpoint epoch [Default 100]", type=int, default=100)
    args = parser.parse_args()

    init_state_names, init_state_arrays = lstm_init_states(batch_size=1)
    img = read_img(args.path)

    sample = SimpleBatch(
        data_names=['data'] + init_state_names,
        data=[mx.nd.array(img)] + init_state_arrays)

    mod = load_module(args.prefix, args.epoch, sample.data_names, sample.provide_data)

    mod.forward(sample)
    prob = mod.get_outputs()[0].asnumpy()

    prediction = CtcMetrics.ctc_label(np.argmax(prob, axis=-1).tolist())
    # Predictions are 1 to 10 for digits 0 to 9 respectively (prediction 0 means no-digit)
    prediction = [p - 1 for p in prediction]
    print("Digits:", prediction)
1189416
def _direct_render(self, name, attrs):
        """"""
        context = {
            'image': self.image_url(),
            'name': name,
            'key': self._key,
            'id': u'%s_%s' % (self.id_prefix, attrs.get('id')) if self.id_prefix else attrs.get('id'),
            'audio': self.audio_url(),
        }
        self.image_and_audio = render_to_string(settings.CAPTCHA_IMAGE_TEMPLATE, context)
        self.hidden_field = render_to_string(settings.CAPTCHA_HIDDEN_FIELD_TEMPLATE, context)
        self.text_field = render_to_string(settings.CAPTCHA_TEXT_FIELD_TEMPLATE, context)
        return self.format_output(None)
921882
def generate_captcha
      if EasyCaptcha.cache
        # create cache dir
        FileUtils.mkdir_p(EasyCaptcha.cache_temp_dir)

        # select all generated captchas from cache
        files = Dir.glob(EasyCaptcha.cache_temp_dir + "*.png")

        unless files.size < EasyCaptcha.cache_size
          file              = File.open(files.at(Kernel.rand(files.size)))
          session[:captcha] = File.basename(file.path, '.*')

          if file.mtime < EasyCaptcha.cache_expire.ago
            File.unlink(file.path)
            # remove speech version
            File.unlink(file.path.gsub(/png\z/, "wav")) if File.exists?(file.path.gsub(/png\z/, "wav"))
          else
            return file.readlines.join
          end
        end
        generated_code = generate_captcha_code
        image = Captcha.new(generated_code).image

        # write captcha for caching
        File.open(captcha_cache_path(generated_code), 'w') { |f| f.write image }

        # write speech file if u create a new captcha image
        EasyCaptcha.espeak.generate(generated_code, speech_captcha_cache_path(generated_code)) if EasyCaptcha.espeak?

        # return image
        image
      else
        Captcha.new(generate_captcha_code).image
      end
    end
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()}
1007738
def handle_captcha(self, query_params: dict,
                       html: str,
                       login_data: dict) -> requests.Response:
        
        check_url = get_base_url(html)
        captcha_url = '{}?s={}&sid={}'.format(self.CAPTCHA_URI,
                                              query_params['s'],
                                              query_params['sid'])
        login_data['captcha_sid'] = query_params['sid']
        login_data['captcha_key'] = input(self.CAPTCHA_INPUT_PROMPT
                                          .format(captcha_url))
        return self.post(check_url, login_data)
517801
def say_response_with_reprompt(speech, reprompt_speech, end_session = true, speech_ssml = false, reprompt_ssml = false)
      output_speech = add_speech(speech,speech_ssml)
      reprompt_speech = add_reprompt(reprompt_speech,reprompt_ssml)
      { :outputSpeech => output_speech, :reprompt => reprompt_speech, :shouldEndSession => end_session }
    end
1133364
def request_captcha(size=None, width=None, height=None, ttl=None):
    
    params = {
        'size': size,
        'width': width,
        'height': height,
        'ttl': ttl,
    }
    params = {k: v for k, v in params.items() if v is not None}

    response = leancloud.client.get('/requestCaptcha', params)
    content = response.json()
    return Captcha(content['captcha_token'], content['captcha_url'])
874987
static public function captcha($token_name='_form_token', $apiurl=null, $settings=[])
    {
        if (is_array($token_name)) {
            $settings = $token_name;
            $token_name = null;
        }
        $token_name || $token_name = '_form_token';
        
        if (is_array($apiurl)) {
            $settings = $apiurl;
            $apiurl = null;
        }
        $apiurl || $apiurl = Ioc::url('api:common/getCaptchaImage');
        
        $str = '';
        $class = isset($settings['class']) ? $settings['class'] : 'captcha-image';
        $settings['style'] = isset($settings['style']) ? $settings['style'] : '';
        $settings['style'] .= ';cursor:pointer;';
        foreach ($settings as $k => $v) {
            if (in_array($k, ['width', 'height', 'id', 'style'])) {
                $str .= $k . '="' . $v . '" ';
            }
        }
        $str = '<img src="" class="' . $class . '" title="点击刷新" ' . $str . '/>';
        $isLoad = isset(static::$isLoaded['captcha']) && static::$isLoaded['captcha'] ? true : false;
        if (!$isLoad) {
            $str .= <<<EOF
            <script>
            $(function (){
                var captcha_image_load = function(){
                    var self = $(".${class}");
                    var data = {};
                    var token = self.parents("form").find("input[name=${token_name}]");
                    if (token.length) {
                    	data['_form_token'] = token.val();
                    }
                    
        	    	$.get("{$apiurl}", data, function(data){
                        if (data) {
                            self.attr("src", "data:image/jpg;base64," + data.base64);
                        }
                    });
        	    };
                $(".${class}").on("click", captcha_image_load);
                setTimeout(function () {
                    $(".${class}").first().click();
                }, 1000);
            });
            </script>
EOF;
        }
        
        return $str;
    }