Send a POST request to the question table.

    Questions store information at the participant level, not the node
    level.
    You should pass the question (string) number (int) and response
    (string) as arguments.
191258
def create_question(participant_id):
    
    # Get the participant.
    try:
        ppt = models.Participant.query.filter_by(id=participant_id).one()
    except NoResultFound:
        return error_response(error_type="/question POST no participant found",
                              status=403)

    # Make sure the participant status is "working"
    if ppt.status != "working":
        error_type = "/question POST, status = {}".format(ppt.status)
        return error_response(error_type=error_type,
                              participant=ppt)

    question = request_parameter(parameter="question")
    response = request_parameter(parameter="response")
    number = request_parameter(parameter="number",
                                    parameter_type="int")
    for x in [question, response, number]:
        if type(x) == Response:
            return x

    try:
        # execute the request
        models.Question(participant=ppt, question=question,
                        response=response, number=number)
        session.commit()
    except:
        return error_response(error_type="/question POST server error",
                              status=403)

    # return the data
    return success_response(request_type="question post")
1326122
public void sendDataRequest(HttpURLConnection httpURLConnection, Hashtable param) throws Exception {
		try {
			// write out parameters, assume parameters are put in the hashtable
			PrintWriter out = new PrintWriter(new OutputStreamWriter(httpURLConnection.getOutputStream()));
			// open up the output stream of the connection
			// DataOutputStream output = new
			// DataOutputStream(conn.getOutputStream() );

			String paramString = "";
			for (Enumeration e = param.keys(); e.hasMoreElements();) {
				String key = (String) e.nextElement();
				String value = (String) param.get(key);
				// no harm for an extra & at the end of the parameter list
				paramString += key + "=" + URLEncoder.encode(value, "UTF-8") + "&";
			}
			paramString = paramString.substring(0, paramString.length() - 1);

			// output.writeBytes( paramString );
			// output.close();

			out.println(paramString);
			out.close();
		} catch (Exception ex) {
			Debug.logError(ex, module);
			throw new Exception(ex);
		}

	}
1008809
private void sendTextToServer() {
        statusLabel.setText("");
        conceptList.clear();

        // don't do anything if we have no text
        final String text = mainTextArea.getText();
        if (text.length() < 1) {
            statusLabel.setText(messages.pleaseEnterTextLabel());
            return;
        }

        // disable interaction while we wait for the response
        glassPanel.setPositionAndShow();

        // build up the AnalysisRequest JSON object
        // start with any options
        final JSONArray options = new JSONArray();
        setSemanticTypesOption(types, options);
        // defaults
        options.set(options.size(), new JSONString("word_sense_disambiguation"));
        options.set(options.size(), new JSONString("composite_phrases 8"));
        options.set(options.size(), new JSONString("no_derivational_variants"));
        options.set(options.size(), new JSONString("strict_model"));
        options.set(options.size(), new JSONString("ignore_word_order"));
        options.set(options.size(), new JSONString("allow_large_n"));
        options.set(options.size(), new JSONString("restrict_to_sources SNOMEDCT_US"));

        final JSONObject analysisRequest = new JSONObject();
        analysisRequest.put("text", new JSONString(text));
        analysisRequest.put("options", options);

        // send the input to the server
        final RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, webserviceUrl);
        builder.setHeader("Content-Type", MediaType.APPLICATION_JSON);
        builder.setRequestData(analysisRequest.toString());

        // create the async callback
        builder.setCallback(new SnomedRequestCallback(conceptList, statusLabel, glassPanel, typeCodeToDescription));

        // send the request
        try { builder.send(); }
        catch (final RequestException e) {
            statusLabel.setText(messages.problemPerformingAnalysisLabel());
            GWT.log("There was a problem performing the analysis: " + e.getMessage(), e);
            glassPanel.hide();
        }
    }
1208554
function sendSessionResponse(req, res, next) {
  // Set the session cookie
  res.cookie('session', req.session.id);

  // Set the Location HTTP header
  res.location('/sessions/' + req.session.id);

  // Send the response
  res.status(201).json(req.session);
}
798533
def _ask(question, default=None, data_type='str', show_hint=False):
    """"""

    data = default

    if data_type == 'bool':
        data = None
        default_string = "Y" if default else "N"

        while data not in ('Y', 'J', 'N', '1', '0'):
            data = input("%s? [%s]: " % (question, default_string)).upper()

            if data == '':
                return default

        return data in ('Y', 'J', '1')

    elif data_type in ('str', 'unicode'):
        if show_hint:
            msg = "%s? [%s] (%s): " % (question, default, data_type)
        else:
            msg = question

        data = input(msg)

        if len(data) == 0:
            data = default
    elif data_type == 'int':
        if show_hint:
            msg = "%s? [%s] (%s): " % (question, default, data_type)
        else:
            msg = question

        data = input(msg)

        if len(data) == 0:
            data = int(default)
        else:
            data = int(data)

    return data
1047847
def _post(self, uri, data):
        
        headers = self._get_headers()

        logging.debug("URI=" + str(uri))
        logging.debug("BODY=" + json.dumps(data))

        response = self.session.post(uri, headers=headers,
                data=json.dumps(data))
        if response.status_code in [200, 204]:
            try:
                return response.json()
            except ValueError:
                return "{}"
        else:
            logging.error(response.content)
            response.raise_for_status()
592442
def _post_query(self, **query_dict):
        """"""
        param_dict = query_dict.copy()
        return self._send_query(do_post=True, **param_dict)
1053095
def run_question(self, question, input_func=_stdin_):
        """"""
        qi = '[%d/%d] ' % (self.qcount, self.qtotal)
        print('%s %s:' % (qi, question['label']))
        while True:
            # ask for user input until we get a valid one
            ans = input_func('%s > ' % self.format_choices())
            if self.is_answer_valid(ans): 
                question['answer'] = int(ans)
                break
            else:
                if ans is '?': print(question['description'])
                else: print('Invalid answer.')
        self.qcount += 1
294749
def dispatch(self, request, **kwargs):
        '''
        
        '''

        # Check if this is a REST query to pusth the answer to responde in JSON
        if bool(self.request.META.get('HTTP_X_REST', False)):
            self.json = True

        # Check if this is a REST query to add an element
        if self.request.method in ['PUT', 'DELETE']:
            if self.request.method == 'PUT':
                action = 'edit'
            else:
                action = 'delete'

            # Set new method
            self.request.method == 'POST'

            # Find the URL
            target = get_class(resolve("{}/{}".format(self.request.META.get("REQUEST_URI"), action)).func)

            # Make sure we will answer as an API
            target.json = True

            # Lets go for it
            return target.as_view()(self.request, pk=kwargs.get('pk'))

        # Detect if we have to answer in json
        self.__authtoken = (bool(getattr(self.request, "authtoken", False)))
        self.json_worker = self.__authtoken or (self.json is True)

        # Check if this is an AJAX request
        if (request.is_ajax() or self.json_worker) and request.body:
            request.POST = json.loads(request.body)

        # Set class internal variables
        self._setup(request)

        # Call the base implementation
        return super(GenDetail, self).dispatch(request, **kwargs)
117273
def sendRequest( api_Request, xmlRequestData = nil )

      fire( "onSendRequest" )

      resetErrorInfo

      # set up the request
      getDBforRequestURL( api_Request )
      getAuthenticationXMLforRequest( api_Request )
      isHTMLRequest = isHTMLRequest?( api_Request )
      api_Request = "API_" + api_Request.to_s if prependAPI?( api_Request )

      xmlRequestData << toXML( :udata, @udata ) if @udata and @udata.length > 0
      xmlRequestData << toXML( :rdr, @rdr ) if @rdr and @rdr.length > 0
      xmlRequestData << toXML( :xsl, @xsl ) if @xsl and @xsl.length > 0
      xmlRequestData << toXML( :encoding, @encoding ) if @encoding and @encoding.length > 0

      if xmlRequestData
         @requestXML = toXML( :qdbapi, @authenticationXML + xmlRequestData )
      else
         @requestXML = toXML( :qdbapi, @authenticationXML )
      end

      @requestHeaders = @standardRequestHeaders
      @requestHeaders["Content-Length"] = "#{@requestXML.length}"
      @requestHeaders["QUICKBASE-ACTION"] = api_Request
      @requestURL = "#{@qbhost}#{@dbidForRequestURL}"

      printRequest( @requestURL, @requestHeaders,  @requestXML ) if @printRequestsAndResponses
      @logger.logRequest( @dbidForRequestURL, api_Request, @requestXML ) if @logger

      begin

         # send the request
         if USING_HTTPCLIENT
            response = @httpConnection.post( @requestURL, @requestXML, @requestHeaders )
            @responseCode = response.status
            @responseXML = response.content
         else  
            if Net::HTTP.version_1_2?
               response = @httpConnection.post( @requestURL, @requestXML, @requestHeaders )
               @responseCode = response.code
               @responseXML = response.body
            else
               @responseCode, @responseXML = @httpConnection.post( @requestURL, @requestXML, @requestHeaders )
            end	
         end
          
         printResponse( @responseCode,  @responseXML ) if @printRequestsAndResponses

         if not isHTMLRequest
            processResponse( @responseXML )
         end

      @logger.logResponse( @lastError, @responseXML ) if @logger

      fireDBChangeEvents

      rescue Net::HTTPBadResponse => error
         @lastError = "Bad HTTP Response: #{error}"
      rescue Net::HTTPHeaderSyntaxError => error
         @lastError = "Bad HTTP header syntax: #{error}"
      rescue StandardError => error
         @lastError = "Error processing #{api_Request} request: #{error}"
      end

      @requestSucceeded = ( @errcode == "0" and @lastError == "" )

      fire( @requestSucceeded ? "onRequestSucceeded" : "onRequestFailed" )

      if @stopOnError and !@requestSucceeded
         raise @lastError
      end
   end
373253
def sendPartialResponse(self):
        
        self.requestProtocol.requestResponse["code"] = (
            self.responseCode
        )
        self.requestProtocol.requestResponse["content"] = (
            self.responseContent
        )
        self.requestProtocol.requestResponse["errors"] = (
            self.responseErrors
        )
        self.requestProtocol.sendPartialRequestResponse()
704828
def pass_acts_as_list_method_to_questionnaires_question(symbol, question)
      raise "A Question is needed to identify the QuestionnairesQuestion" unless question.kind_of? Question
      questionnaires_question = questionnaires_questions.where(:question_id => question.id).first
      questionnaires_question.send(symbol) if questionnaires_question
    end
759862
def send_reminders
      url = ApiRequest.base_path("questionpro.survey.sendReminder")
      result = self.class.get(url, body: self.options)

      self.full_response = result
      self.status = result['status']
      self.message = result['response']['result']
    end
1339698
public void sendData(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
    {
        res.setContentType("text/xml");
        PrintWriter out = res.getWriter();
        this.printXML(req, out);
        out.flush();
    }
847319
@Override
	final protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setBufferSize(BUFFER_SIZE);
		postCount.incrementAndGet();
		try {
			reportingDoPost(req, resp);
		} catch (ThreadDeath t) {
			throw t;
		} catch (RuntimeException | ServletException | IOException e) {
			getLogger().log(Level.SEVERE, null, e);
			throw e;
		} catch (SQLException t) {
			getLogger().log(Level.SEVERE, null, t);
			throw new ServletException(t);
		}
	}
364668
public void sendRequest() throws IOException
    {
        /* Create & Format URL */
        URL url = new URL(CleverBotQuery.formatRequest(CleverBotQuery.URL_STRING, this.key, this.phrase, this.conversationID));

        /* Open Connection */
        URLConnection urlConnection = url.openConnection();

        /* Read input */
        BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        String inputLine = in.readLine();

        /* Create JSON Object */
        JsonObject jsonObject = new JsonParser().parse(inputLine).getAsJsonObject(); // convert to JSON

        /* Get params */
        this.setConversationID(jsonObject.get("cs").getAsString()); // update conversation ID
        this.setResponse(jsonObject.get("output").getAsString()); // get output
        this.setRandomNumber(Integer.parseInt(jsonObject.get("random_number").getAsString())); // get output
        in.close(); // close!
    }
447708
protected void sendPostData(final HttpURLConnection connection, final RpcRequest request)
			throws IOException {
		String post = buildParamsQuery(request.getPost());
		byte[] data = post.getBytes(UTF8);

		connection.setRequestProperty(CONTENT_TYPE_HEADER, APPLICATION_X_WWW_FORM_URLENCODED);
		connection.setRequestProperty(CONTENT_LENGTH_HEADER, String.valueOf(data.length));
		OutputStream out = new BufferedOutputStream(connection.getOutputStream());
		try {
			out.write(data);
		} finally {
			closeLogExc(out);
		}
	}