Submit either a file from disk, or a in-memory file to the solver service, and
		return the request ID associated with the new captcha task.
554683
def _submit(self, pathfile, filedata, filename):
		'''
		
		'''
		if pathfile and os.path.exists(pathfile):
			files = {'file': open(pathfile, 'rb')}
		elif filedata:
			assert filename
			files = {'file' : (filename, io.BytesIO(filedata))}
		else:
			raise ValueError("You must pass either a valid file path, or a bytes array containing the captcha image!")

		payload = {
			'key'    : self.api_key,
			'method' : 'post',
			'json'   : True,
			}

		self.log.info("Uploading to 2Captcha.com.")

		url = self.getUrlFor('input', {})

		request = requests.post(url, files=files, data=payload)

		if not request.ok:
			raise exc.CaptchaSolverFailure("Posting captcha to solve failed!")

		resp_json = json.loads(request.text)
		return self._process_response(resp_json)
1216410
def _compute_filename(self, request: BaseRequest):
        ''''''
        path = self._path_namer.get_filename(request.url_info)

        if os.path.isdir(path):
            path += '.f'
        else:
            dir_name, name = os.path.split(path)
            path = os.path.join(anti_clobber_dir_path(dir_name), name)

        return path
376792
def submission_storage_path(instance, filename):
    
    string = '/'.join(['submissions', instance.submission_user.user_nick, str(instance.submission_question.question_level), str(instance.submission_question.question_level_id)])
    string += '/'+datetime.datetime.now().strftime("%I:%M%p-%m-%d-%Y")
    string += filename
    return string
460434
def submit(opts={})
      response = Hubspot::FormsConnection.submit(SUBMIT_DATA_PATH, params: { form_guid: @guid }, body: opts)
      [204, 302, 200].include?(response.code)
    end
435645
def ruokuai_captcha_handler(self, params, image_url):
        

        headers = {
            'Connection': 'Keep-Alive',
            'Expect': '100-continue',
            'User-Agent': 'ben',
        }
        image_data = requests.get(image_url).content
        files = {'image': ('check_code.png', image_data)}
        r = requests.post(
            'http://api.ruokuai.com/create.json',
            data=params,
            files=files,
            headers=headers
        )
        verify_code_dict = r.json()
        if verify_code_dict:
            if 'Error' in verify_code_dict.keys():
                print (verify_code_dict['Error'])
                return ''
            verify_code = verify_code_dict.get('Result', '')
        else:
            print ('rk failed ', verify_code_dict)
            return ''

        return verify_code
957829
def submit(recaptcha_response, private_key, remoteip):
    
    params = urlencode({
        "secret": private_key,
        "response": recaptcha_response,
        "remoteip": remoteip,
    })

    if not PY2:
        params = params.encode("utf-8")

    response = recaptcha_request(params)
    data = json.loads(response.read().decode("utf-8"))
    response.close()
    return RecaptchaResponse(
        is_valid=data["success"],
        error_codes=data.get("error-codes")
    )
1357671
def	adGet(file_id, archive="CFHT", extno=None, cutout=None ):
    """"""
    
    import os, string, re,urllib


    #proxy="http://www1.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/authProxy/getData"
    proxy="http://test.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/authProxy/getData"

    if file_id is None:
        return(-1)

    if  extno is None:
        filename=file_id+".fits"
    else:
        filename="%s%s.fits" % (file_id, string.zfill(extno,2))
    print filename

    if os.access(filename,os.R_OK):
    	return filename

    args={
        "file_id": file_id,
        "archive": archive
        }

    if extno is not None:
        args['cutout']="["+str(extno+1)+"]"
    else:
        args['cutout']=''

    if cutout is not None:
        args['cutout']=args['cutout']+cutout
        
    argline=""
    sep=""
    import sys

    ### get the directory that may contain the data
    mop_data_path=os.curdir
    if os.environ.has_key('MOP_DATA_PATH'):
        mop_data_path=os.environ['MOP_DATA_PATH']

    suffix="fits"
    basefile=mop_data_path+"/"+file_id+".fits"
    print basefile
    if not os.access(basefile,os.R_OK):
    	argdict={}
	argline=''
	sep=''
        for arg in args:
            if not args[arg]:
                continue
	    argline+=sep+"%s=%s" % ( arg, args[arg])
	    sep='&'


        url=proxy+"?"+argline
        command="curl --silent -g  --fail --max-time 1800 --user jkavelaars:newone '"+url+"' | gunzip > "+filename
    else:
        command="imcopy %s%s %s" % ( basefile,args['cutout'],filename)


    print command
    try:
        status=os.system(command)
    except:
        sys.stderr.write("Failed to execute command: %s\n" % ( command))
    	raise TaskError, "getData failed"
    if status!=0:
        sys.stderr.write("Failed while executing command: %s\n" % ( command))
    	raise TaskError, "getData failed"

    return filename
310922
def _request(self, method, *relative_path_parts, **kwargs):
        
        uri = self._create_api_uri(*relative_path_parts)
        data = kwargs.get('data', None)
        if data and isinstance(data, dict):
            kwargs['data'] = encode_params(data)
        if self.VERIFY_SSL:
            kwargs.setdefault('verify', COINBASE_CRT_PATH)
        else:
            kwargs.setdefault('verify', False)
        kwargs.update(verify=self.VERIFY_SSL)
        response = getattr(self.session, method)(uri, **kwargs)
        return self._handle_response(response)
479805
def ajax_submit(self):
        

        # Get AR required fields (including extended fields)
        fields = self.get_ar_fields()

        # extract records from request
        records = self.get_records()

        fielderrors = {}
        errors = {"message": "", "fielderrors": {}}

        attachments = {}
        valid_records = []

        # Validate required fields
        for n, record in enumerate(records):

            # Process UID fields first and set their values to the linked field
            uid_fields = filter(lambda f: f.endswith("_uid"), record)
            for field in uid_fields:
                name = field.replace("_uid", "")
                value = record.get(field)
                if "," in value:
                    value = value.split(",")
                record[name] = value

            # Extract file uploads (fields ending with _file)
            # These files will be added later as attachments
            file_fields = filter(lambda f: f.endswith("_file"), record)
            attachments[n] = map(lambda f: record.pop(f), file_fields)

            # Process Specifications field (dictionary like records instance).
            # -> Convert to a standard Python dictionary.
            specifications = map(
                lambda x: dict(x), record.pop("Specifications", []))
            record["Specifications"] = specifications

            # Required fields and their values
            required_keys = [field.getName() for field in fields
                             if field.required]
            required_values = [record.get(key) for key in required_keys]
            required_fields = dict(zip(required_keys, required_values))

            # Client field is required but hidden in the AR Add form. We remove
            # it therefore from the list of required fields to let empty
            # columns pass the required check below.
            if record.get("Client", False):
                required_fields.pop('Client', None)

            # Contacts get pre-filled out if only one contact exists.
            # We won't force those columns with only the Contact filled out to
            # be required.
            contact = required_fields.pop("Contact", None)

            # None of the required fields are filled, skip this record
            if not any(required_fields.values()):
                continue

            # Re-add the Contact
            required_fields["Contact"] = contact

            # Missing required fields
            missing = [f for f in required_fields if not record.get(f, None)]

            # If there are required fields missing, flag an error
            for field in missing:
                fieldname = "{}-{}".format(field, n)
                msg = _("Field '{}' is required".format(field))
                fielderrors[fieldname] = msg

            # Process valid record
            valid_record = dict()
            for fieldname, fieldvalue in record.iteritems():
                # clean empty
                if fieldvalue in ['', None]:
                    continue
                valid_record[fieldname] = fieldvalue

            # append the valid record to the list of valid records
            valid_records.append(valid_record)

        # return immediately with an error response if some field checks failed
        if fielderrors:
            errors["fielderrors"] = fielderrors
            return {'errors': errors}

        # Process Form
        actions = ActionHandlerPool.get_instance()
        actions.queue_pool()
        ARs = OrderedDict()
        for n, record in enumerate(valid_records):
            client_uid = record.get("Client")
            client = self.get_object_by_uid(client_uid)

            if not client:
                actions.resume()
                raise RuntimeError("No client found")

            # get the specifications and pass them to the AR create function.
            specifications = record.pop("Specifications", {})

            # Create the Analysis Request
            try:
                ar = crar(
                    client,
                    self.request,
                    record,
                    specifications=specifications
                )
            except (KeyError, RuntimeError) as e:
                actions.resume()
                errors["message"] = e.message
                return {"errors": errors}
            # We keep the title to check if AR is newly created
            # and UID to print stickers
            ARs[ar.Title()] = ar.UID()
            for attachment in attachments.get(n, []):
                if not attachment.filename:
                    continue
                att = _createObjectByType("Attachment", client, tmpID())
                att.setAttachmentFile(attachment)
                att.processForm()
                ar.addAttachment(att)
        actions.resume()

        level = "info"
        if len(ARs) == 0:
            message = _('No Samples could be created.')
            level = "error"
        elif len(ARs) > 1:
            message = _('Samples ${ARs} were successfully created.',
                        mapping={'ARs': safe_unicode(', '.join(ARs.keys()))})
        else:
            message = _('Sample ${AR} was successfully created.',
                        mapping={'AR': safe_unicode(ARs.keys()[0])})

        # Display a portal message
        self.context.plone_utils.addPortalMessage(message, level)

        # Automatic label printing
        bika_setup = api.get_bika_setup()
        auto_print = bika_setup.getAutoPrintStickers()
        if 'register' in auto_print and ARs:
            return {
                'success': message,
                'stickers': ARs.values(),
                'stickertemplate': bika_setup.getAutoStickerTemplate()
            }
        else:
            return {'success': message}
265003
def request(self, method, args, response_cb):
        
        request_id = self._next_request_id
        self._next_request_id = request_id + 1
        self._msgpack_stream.send([0, request_id, method, args])
        self._pending_requests[request_id] = response_cb
1233277
def submit(self):
        
        body = request.body.read()
        indata = cjson.decode(body)
        try:
            indata = validateJSONInputNoCopy("migration_rqst", indata)
            indata.update({"creation_date": dbsUtils().getTime(),
                "last_modification_date" : dbsUtils().getTime(),
                "create_by" : dbsUtils().getCreateBy() ,
                "last_modified_by" : dbsUtils().getCreateBy(),
                "migration_status": 0})
            return self.dbsMigrate.insertMigrationRequest(indata)
        except dbsException as de:
            dbsExceptionHandler(de.eCode, de.message, self.logger.exception, de.serverError)
        except Exception as ex:
            sError = "DBSMigrateModle/submit. %s\n Exception trace: \n %s." \
                     % (ex, traceback.format_exc() )
            if hasattr(ex, 'status') and ex.status == 400:
		dbsExceptionHandler('dbsException-invalid-input2', str(ex), self.logger.exception, sError)
	    else:	
		dbsExceptionHandler('dbsException-server-error',  str(ex), self.logger.exception, sError)
460270
def get_captcha_key(self, captcha_image_url):
        """"""

        if self.interactive:
            print('Open CAPTCHA image url in your browser and enter it below: ',
                  captcha_image_url)
            captcha_key = raw_input('Enter CAPTCHA key: ')
            return captcha_key
        else:
            raise VkAuthError(
                'Captcha is required. Use interactive mode to enter it '
                'manually')
661620
def get_input_from_submission(self, submission, only_input=False):
        
        inp = bson.BSON.decode(self._gridfs.get(submission['input']).read())
        if only_input:
            return inp
        else:
            submission["input"] = inp
            return submission
863896
def _assemble_and_send_request(self):
            

            # Fire off the query.
            return self.client.service.uploadDocuments(
                    WebAuthenticationDetail=self.WebAuthenticationDetail,
                    ClientDetail=self.ClientDetail,
                    TransactionDetail=self.TransactionDetail,
                    Version=self.VersionId,
                    Documents=self.Documents,
                    Usage = self.Usage,
                    OriginCountryCode = self.OriginCountryCode,
                    DestinationCountryCode = self.DestinationCountryCode,
                )
1036049
def submit_create_and_upload(self, halt_on_error=True):
        
        # check global setting for override
        if self.halt_on_batch_error is not None:
            halt_on_error = self.halt_on_batch_error

        content = self.data
        # store the length of the batch data to use for poll interval calculations
        self.tcex.log.info('Batch Group Size: {:,}.'.format(len(content.get('group'))))
        self.tcex.log.info('Batch Indicator Size {:,}.'.format(len(content.get('indicator'))))
        if self.debug:
            # special code for debugging App using batchV2.
            self.write_batch_json(content)
        if content.get('group') or content.get('indicator'):
            try:
                files = (('config', json.dumps(self.settings)), ('content', json.dumps(content)))
                params = {'includeAdditional': 'true'}
                r = self.tcex.session.post('/v2/batch/createAndUpload', files=files, params=params)
                self.tcex.log.debug('Batch Status Code: {}'.format(r.status_code))
                if not r.ok or 'application/json' not in r.headers.get('content-type', ''):
                    self.tcex.handle_error(10510, [r.status_code, r.text], halt_on_error)
                return r.json()
            except Exception as e:
                self.tcex.handle_error(10505, [e], halt_on_error)
        return {}
1023600
function mergeSubmissionFiles(params, cb) {
  logger.debug("cacheFiles: mergeSubmissionFiles", params);
  var submission = params.submission;

  //No submission, cannot continue.
  if (!_.isObject(submission)) {
    return cb(buildErrorResponse({
      err: new Error("Expected Submission Object To Cache Files For"),
      msg: "Error Exporting Submission As PDF",
      httpCode: 500
    }));
  }

  var form = submission.formSubmittedAgainst;


  var fileFieldDetails = _.filter(submission.formFields, function(field) {
    return isFileFieldType(field.fieldId.type);
  });
  fileFieldDetails = _.flatten(fileFieldDetails);


  var fieldTypes = _.groupBy(fileFieldDetails, function(field) {
    return field.fieldId.type;
  });

  //Files That Have To Be Loaded From Mbaas
  var mbaasTypes = _.union(fieldTypes.photo, fieldTypes.signature);

  //Only Interested In The File Ids To Download
  var filesToDownload = _.map(mbaasTypes, function(field) {
    return _.map(field.fieldValues, function(fieldValue) {
      return fieldValue.groupId;
    });
  });

  filesToDownload = _.flatten(filesToDownload);

  logger.debug("cacheFiles: mergeSubmissionFiles filesToDownload", filesToDownload);


  //Now download all of the files..
  async.mapSeries(filesToDownload, function(fileIdOrUrl, cb) {
    //Only want the callback to be called once.
    cb = _.once(cb);

    var fileUri = path.join(params.options.pdfExportDir, 'image_binary_' + fileIdOrUrl);
    var localFile = fs.createWriteStream(fileUri);

    //Loading The Submission File From THe Database / MbaaS
    cacheSubmissionFile({
      fileId: fileIdOrUrl,
      connections: params.connections,
      options: params.options,
      submission: submission
    }, localFile, function(err, fileDetails) {
      if (err) {
        logger.error("cacheFiles: cacheSubmissionFile", {error: err});
      }
      fileDetails = fileDetails || {};
      fileDetails.url = "file://" + fileUri;
      fileDetails.fileId = fileIdOrUrl;

      logger.debug("cacheFiles: mergeSubmissionFiles fileDetails", fileDetails);

      return cb(err, _.omit(fileDetails, "stream"));
    });
  }, function(err, cachedFiles) {
    if (err) {
      return cb(buildErrorResponse({
        error: err,
        msg: "Error Cacheing Files For Submission Export",
        code: constants.ERROR_CODES.FH_FORMS_ERR_CODE_PDF_GENERATION,
        httpCode: 500
      }));
    }

    //No Errors, all files are now cached for the submission

    submission.formSubmittedAgainst =  populateSubmissionFileData({
      form: form,
      submissionFiles: cachedFiles,
      downloadUrl: params.options.downloadUrl,
      fileUriPath: params.options.fileUriPath,
      submission: submission
    });

    logger.debug("cacheFiles: mergeSubmissionFiles submission", submission);

    cb(undefined, submission);
  });
}
888733
function onRequest(request, response) {
  var filename = path.join(__dirname, request.url);

  // Serving server.js from cache. Useful for microbenchmarks.
  if (request.url === cachedUrl) {
    if (response.push) {
      // Also push down the client js, since it's possible if the requester wants
      // one, they want both.
      var push = response.push('/client.js');
      push.writeHead(200);
      fs.createReadStream(path.join(__dirname, '/client.js')).pipe(push);
    }
    response.end(cachedFile);
  }

  // Reading file from disk if it exists and is safe.
  else if ((filename.indexOf(__dirname) === 0) && fs.existsSync(filename) && fs.statSync(filename).isFile()) {
    response.writeHead(200);
    var fileStream = fs.createReadStream(filename);
    fileStream.pipe(response);
    fileStream.on('finish',response.end);
  }

  // Example for testing large (boundary-sized) frames.
  else if (request.url === "/largeframe") {
    response.writeHead(200);
    var body = 'a';
    for (var i = 0; i < 14; i++) {
      body += body;
    }
    body = body + 'a';
    response.end(body);
  }

  // Otherwise responding with 404.
  else {
    response.writeHead(404);
    response.end();
  }
}