Question:
Builds domain object from ValueObject returned by Persistence API.

@param \eZ\Publish\SPI\Persistence\URL\URL $data
@return \eZ\Publish\API\Repository\Values\URL\URL

protected function buildDomainObject(SPIUrl $data)
    {
        return new URL([
            'id' => $data->id,
            'url' => $data->url,
            'isValid' => $data->isValid,
            'lastChecked' => $this->createDateTime($data->lastChecked),
            'created' => $this->createDateTime($data->created),
            'modified' => $this->createDateTime($data->modified),
        ]);
    }

def share_extension_with_host(self, publisher_name, extension_name, host_type, host_name):

        route_values = {}
        if publisher_name is not None:
            route_values['publisherName'] = self._serialize.url('publisher_name', publisher_name, 'str')
        if extension_name is not None:
            route_values['extensionName'] = self._serialize.url('extension_name', extension_name, 'str')
        if host_type is not None:
            route_values['hostType'] = self._serialize.url('host_type', host_type, 'str')
        if host_name is not None:
            route_values['hostName'] = self._serialize.url('host_name', host_name, 'str')
        self._send(http_method='POST',
                   location_id='328a3af8-d124-46e9-9483-01690cd415b9',
                   version='5.0-preview.1',
                   route_values=route_values)

Instruction: Given a code description, retrieve the corresponding code.


Question:
Setter for message

@see Fortune.Fields#message

public Fortune setMessage(String value) {
        putDirect(FIELD_Message, String.class, String.class, value, SetMode.DISALLOW_NULL);
        return this;
    }

public static String getMessage(final Class class1, final String string, final String compName) {
		return JKMessage.get(string, compName);
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Keep a count of a response to this question sub part that falls within this class.

@param string     $actualresponse
@param float|null $fraction
@param int        $try
@return \core_question\statistics\responses\analysis_for_actual_response

public function count_response($actualresponse, $fraction, $try) {
        if (!isset($this->actualresponses[$actualresponse])) {
            if ($fraction === null) {
                $fraction = $this->fraction;
            }
            $this->add_response($actualresponse, $fraction);
        }
        $this->get_response($actualresponse)->increment_count($try);
    }

public static function capture(
        array $server = null,
        array $post = null,
        array $files = null,
        array $headers = null,
        array $cookies = null
    ) {
        $server  = $server ?? $_SERVER;
        $post    = $post ?? $_POST;
        $cookies = $cookies ?? $_COOKIE;

        $method = $server['REQUEST_METHOD'] ?? 'GET';
        $url    = Url::capture($server);

        $request = new static($method, $url, $post);
        $request->files   = Upload::capture($files);
        $request->headers = Header::capture($headers);
        $request->cookie  = $cookies;

        return $request;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Check if the number or records in the database exceeds the set limit

@see \Spork\Mvc\Listener\Limit\Storage\StorageInterface::check()
@param string $ip
@param Limit $limit
@return boolean

public function check($ip, Limit $limit)
    {
        $this->assertReady();

        if ($this->cleanOnCheck) {
            $this->clean();
        }

        $sql = sprintf("SELECT count(*) as count FROM %s WHERE %s=:ip AND %s=:type AND %s >= NOW() - INTERVAL %d SECOND",
            $this->dbAdapter->platform->quoteIdentifier($this->table),
            $this->dbAdapter->platform->quoteIdentifier($this->ipColumn),
            $this->dbAdapter->platform->quoteIdentifier($this->typeColumn),
            $this->dbAdapter->platform->quoteIdentifier($this->timestampColumn),
            $limit->getInterval()->toSeconds());

        $parameters = array(
            'ip' => $ip,
            'type' => $limit->getName(),
        );

        $result = $this->dbAdapter->query($sql, $parameters);
        $count = $result->current()->count;
        return $count >= $limit->getLimit();
    }

protected static function storeEntriesAfterWorkerLoop($app)
    {
        $app['events']->listen(JobProcessing::class, function () {
            static::startRecording();

            static::$processingJobs[] = true;
        });

        $app['events']->listen(JobProcessed::class, function ($event) use ($app) {
            static::storeIfDoneProcessingJob($event, $app);
        });

        $app['events']->listen(JobFailed::class, function ($event) use ($app) {
            static::storeIfDoneProcessingJob($event, $app);
        });

        $app['events']->listen(JobExceptionOccurred::class, function () {
            array_pop(static::$processingJobs);
        });
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Removes an organization from a servicedesk for a given servicedesk ID and organization ID

        :param service_desk_id: str
        :param organization_id: int
        :return:

def remove_organization(self, service_desk_id, organization_id):

        log.warning('Removing organization...')
        url = 'rest/servicedeskapi/servicedesk/{}/organization'.format(service_desk_id)
        data = {'organizationId': organization_id}

        return self.delete(url, headers=self.experimental_headers, data=data)

public function update($orgId, OrgBuilder $input, array $queryParams = [])
    {
        $response = $this->api->orgs()->update($orgId, $input->toArray(), $queryParams);

        return new OrgResponse($response);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Show image cropping link for content and options?

def allow_image_cropping?(options = {})
      content && content.settings_value(:crop, options) && picture &&
        picture.can_be_cropped_to(
          content.settings_value(:size, options),
          content.settings_value(:upsample, options)
        )
    end

def send_media(self, path, chatid, caption):

        imgBase64 = self.convert_to_base64(path)
        filename = os.path.split(path)[-1]
        return self.wapi_functions.sendImage(imgBase64, chatid, filename, caption)

Instruction: Given a code description, retrieve the corresponding code.


Question:
@param NotifiableNotification $notifiableNotification

@return $this

public function addNotifiableNotification(NotifiableNotification $notifiableNotification)
    {
        if (!$this->notifiableNotifications->contains($notifiableNotification)) {
            $this->notifiableNotifications[] = $notifiableNotification;
            $notifiableNotification->setNotifiableEntity($this);
        }

        return $this;
    }

public void into(@NonNull RemoteViews remoteViews, @IdRes int viewId, int notificationId,
      @NonNull Notification notification) {
    into(remoteViews, viewId, notificationId, notification, null);
  }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Iteratively solves columnization given constraints in props.
Solution is captured by this.state.

@returns {undefined}

function solve() {
  while (true) {

    // establish vars for current loop
    //----------------------------------------------------------
    const row = this.state.i % this.state.rows
    const col = Math.floor(this.state.i / this.state.rows)
    const str = this.props.ar[this.state.i]
    const len = str.length
    const tooLong = len > this.props.maxRowLen

    // str is too long ? set rows to maximum
    //----------------------------------------------------------
    if (tooLong && this.state.rows !== this.props.arLen) {
      this.bindState(this.props.arLen)
      continue
    }

    // at new col ? indent previous col
    //----------------------------------------------------------
    if (row === 0 && this.state.i !== 0) {
      const prevCol = col - 1
      const reqLen = this.state.widths[prevCol] + this.props.gap.len
      this.state.indices.forEach((ar, i) => {
        const prevLen = this.props.ar[ar[prevCol]].length
        const diff = reqLen - prevLen
        this.state.strs[i] += this.props.gap.ch.repeat(diff)
      })
    }

    // add str to row
    //----------------------------------------------------------
    this.state.strs[row] += str

    // row not too long ? update state : reset state with rows + 1
    //----------------------------------------------------------
    if (
      this.state.strs[row].length <= this.props.maxRowLen ||
      tooLong
    ) {
      if (len > this.state.widths[col]) this.state.widths[col] = len
      this.state.indices[row].push(this.state.i)
      this.state.i++
    }
    else this.bindState(this.state.rows + 1)

    // solution reached ? exit loop
    //----------------------------------------------------------
    if (this.state.i === this.props.arLen) break
  }
}

private function getColumns($data)
        {
            $cols = [];

            foreach ($data[0] as $key => $value) {
                if (is_numeric($key)){
                    if (is_string($data[1][$key])) {
                        $cols[] = ['id' => '', 'label' => $value, 'type' => 'string'];
                    } else {
                        $cols[] = ['id' => '', 'label' => $value, 'type' => 'number'];
                    }

                    $this->_skipFirstRow = true;
                } else {
                    if (is_string($value)) {
                        $cols[] = ['id' => '', 'label' => $key, 'type' => 'string'];
                    } else {
                        $cols[] = ['id' => '', 'label' => $key, 'type' => 'number'];
                    }
                }
            }

            return $cols;
        }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Appends the string to this XmlStringBuilder. XML values are not escaped.

@param string the String to append.
@param encode true to encode the string before output, false to output as is

public void append(final String string, final boolean encode) {
		if (encode) {
			appendOptional(WebUtilities.encode(string));
		} else {
			// unescaped content still has to be XML compliant.
			write(HtmlToXMLUtil.unescapeToXML(string));
		}
	}

void writeConfigPropsXml(List<ConfigPropType> props, Writer out, int indent) throws IOException
   {
      if (props == null || props.size() == 0)
         return;
      for (ConfigPropType prop : props)
      {
         writeIndent(out, indent);
         out.write("<config-property>");
         writeEol(out);

         writeIndent(out, indent + 1);
         out.write("<config-property-name>" + prop.getName() + "</config-property-name>");
         writeEol(out);
         writeIndent(out, indent + 1);
         out.write("<config-property-type>java.lang." + prop.getType() + "</config-property-type>");
         writeEol(out);
         writeIndent(out, indent + 1);
         out.write("<config-property-value>" + prop.getValue() + "</config-property-value>");
         writeEol(out);

         writeIndent(out, indent);
         out.write("</config-property>");
         writeEol(out);
         writeEol(out);
      }
   }

Instruction: Given a code description, retrieve the corresponding code.


Question:
// SendCloudFormationResponse sends the given response
// to the CloudFormation URL that was submitted together
// with this event

func SendCloudFormationResponse(lambdaCtx *awsLambdaCtx.LambdaContext,
	event *CloudFormationLambdaEvent,
	results map[string]interface{},
	responseErr error,
	logger *logrus.Logger) error {

	status := "FAILED"
	if nil == responseErr {
		status = "SUCCESS"
	}
	// Env vars:
	// https://docs.aws.amazon.com/lambda/latest/dg/current-supported-versions.html
	logGroupName := os.Getenv("AWS_LAMBDA_LOG_GROUP_NAME")
	logStreamName := os.Getenv("AWS_LAMBDA_LOG_STREAM_NAME")
	reasonText := ""
	if nil != responseErr {
		reasonText = fmt.Sprintf("%s. Details in CloudWatch Logs: %s : %s",
			responseErr.Error(),
			logGroupName,
			logStreamName)
	} else {
		reasonText = fmt.Sprintf("Details in CloudWatch Logs: %s : %s",
			logGroupName,
			logStreamName)
	}
	// PhysicalResourceId
	// This value should be an identifier unique to the custom resource vendor,
	// and can be up to 1 Kb in size. The value must be a non-empty string and
	// must be identical for all responses for the same resource.
	// Ref: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/crpg-ref-requesttypes-create.html
	physicalResourceID := fmt.Sprintf("LogStreamName: %s", logStreamName)
	responseData := map[string]interface{}{
		"Status":             status,
		"Reason":             reasonText,
		"PhysicalResourceId": physicalResourceID,
		"StackId":            event.StackID,
		"RequestId":          event.RequestID,
		"LogicalResourceId":  event.LogicalResourceID,
	}
	if nil != responseErr {
		responseData["Data"] = map[string]interface{}{
			"Error": responseErr,
		}
	} else if nil != results {
		responseData["Data"] = results
	} else {
		responseData["Data"] = map[string]interface{}{}
	}

	logger.WithFields(logrus.Fields{
		"ResponsePayload": responseData,
	}).Debug("Response Info")

	jsonData, jsonError := json.Marshal(responseData)
	if nil != jsonError {
		return errors.Wrap(jsonError, "Attempting to marshal Cloudformation response")
	}

	responseBuffer := strings.NewReader(string(jsonData))
	req, httpErr := http.NewRequest("PUT",
		event.ResponseURL,
		responseBuffer)

	if nil != httpErr {
		return httpErr
	}
	// Need to use the Opaque field b/c Go will parse inline encoded values
	// which are supposed to be roundtripped to AWS.
	// Ref: https://tools.ietf.org/html/rfc3986#section-2.2
	// Ref: https://golang.org/pkg/net/url/#URL
	// Ref: https://github.com/aws/aws-sdk-go/issues/337
	// parsedURL, parsedURLErr := url.ParseRequestURI(event.ResponseURL)

	// https://en.wikipedia.org/wiki/Percent-encoding
	mapReplace := map[string]string{
		":": "%3A",
		"|": "%7C",
	}
	req.URL.Opaque = req.URL.Path
	for eachKey, eachValue := range mapReplace {
		req.URL.Opaque = strings.Replace(req.URL.Opaque, eachKey, eachValue, -1)
	}
	req.URL.Path = ""
	req.URL.RawPath = ""

	logger.WithFields(logrus.Fields{
		"RawURL": event.ResponseURL,
		"URL":    req.URL,
		"Body":   responseData,
	}).Debug("Created URL response")

	// Although it seems reasonable to set the Content-Type to "application/json" - don't.
	// The Content-Type must be an empty string in order for the
	// AWS Signature checker to pass.
	// Ref: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-code.html
	req.Header.Set("content-type", "")

	client := &http.Client{}
	resp, httpErr := client.Do(req)
	if httpErr != nil {
		return errors.Wrapf(httpErr, "Sending CloudFormation response")
	}
	logger.WithFields(logrus.Fields{
		"LogicalResourceId":  event.LogicalResourceID,
		"Result":             responseData["Status"],
		"ResponseStatusCode": resp.StatusCode,
	}).Debug("Sent CloudFormation response")

	if resp.StatusCode < 200 || resp.StatusCode > 299 {
		body, bodyErr := ioutil.ReadAll(resp.Body)
		if bodyErr != nil {
			logger.Warn("Unable to read body: " + bodyErr.Error())
			body = []byte{}
		}
		return errors.Errorf("Error sending response: %d. Data: %s", resp.StatusCode, string(body))
	}
	defer resp.Body.Close()
	return nil
}

public function defaultMailer($message, string $email): void
    {
        $host = \preg_replace('#[^\w.-]+#', '', $_SERVER['HTTP_HOST'] ?? php_uname('n'));
        $parts = \str_replace(
            ["\r\n", "\n"],
            ["\n", PHP_EOL],
            [
                'headers' => \implode("\n", [
                        'From: ' . ($this->fromEmail ?: "noreply@$host"),
                        'X-Mailer: Tracy',
                        'Content-Type: text/plain; charset=UTF-8',
                        'Content-Transfer-Encoding: 8bit',
                    ]) . "\n",
                'subject' => "PHP: An error occurred on the server $host",
                'body' => Dumper::formatMessage($message) . "\n\nsource: " . Helpers::getSource(),
            ]
        );

        \mail($email, $parts['subject'], $parts['body'], $parts['headers']);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Get info by ajax

        Args:
            url: string
        Returns:
            dict: json decoded into a dict

def ajax(cls, url, param={}, method='get'):

        param = urllib.parse.urlencode(param)
        if method.lower() == 'get':
            req = urllib.request.Request(url + '?' + param)
        elif method.lower() == 'post':
            param = param.encode('utf-8')
            req = urllib.request.Request(url, data=param)
        else:
            raise Exception("invalid method '{}' (GET/POST)".format(method))
        rsp = urllib.request.urlopen(req)
        if rsp:
            rsp_json = rsp.read().decode('utf-8')
            rsp_dict = json.loads(rsp_json)
            return rsp_dict
        return None

def recarray2dict(recarray):
    """"""
    # TODO: subarrays
    result = {}
    for descr, value in zip(recarray.dtype.descr, recarray):
        name, dtype = descr[:2]
        if dtype[1] == 'S':
            value = bytes2str(stripnull(value))
        elif value.ndim < 2:
            value = value.tolist()
        result[name] = value
    return result

Instruction: Given a code description, retrieve the corresponding code.


Question:
Retrieve the minimum value of a given column.

@author Morten Rugaard <moru@nodes.dk>

@param  string $column
@return float|int

public function min($column)
    {
        $result = $this->getBuilder()->min($column);

        // Reset query builder
        $this->resetBuilder();

        return $result;
    }

func interpolationFuncMin() ast.Function {
	return ast.Function{
		ArgTypes:     []ast.Type{ast.TypeFloat},
		ReturnType:   ast.TypeFloat,
		Variadic:     true,
		VariadicType: ast.TypeFloat,
		Callback: func(args []interface{}) (interface{}, error) {
			min := args[0].(float64)

			for i := 1; i < len(args); i++ {
				min = math.Min(min, args[i].(float64))
			}

			return min, nil
		},
	}
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Return a BandStructureSymmLine object interpolating bands along a
        High symmetry path calculated from the structure using HighSymmKpath function

def get_band_structure(self):
        """"""

        kpath = HighSymmKpath(self.data.structure)
        kpt_line = [Kpoint(k, self.data.structure.lattice) for k
                    in
                    kpath.get_kpoints(coords_are_cartesian=False)[
                        0]]
        kpoints = np.array(
            [kp.frac_coords for kp in kpt_line])

        labels_dict = {l: k for k, l in zip(
            *kpath.get_kpoints(coords_are_cartesian=False)) if l}

        lattvec = self.data.get_lattvec()
        egrid, vgrid = fite.getBands(kpoints, self.equivalences, lattvec, self.coeffs)

        bands_dict = {Spin.up: (egrid / units.eV)}

        sbs = BandStructureSymmLine(kpoints, bands_dict,
                                    self.data.structure.lattice.reciprocal_lattice,
                                    self.efermi / units.eV,
                                    labels_dict=labels_dict)
        return sbs

func (c *ScatterChart) AddData(name string, data []EPoint, plotstyle PlotStyle, style Style) {

	// Update styles if non given
	if plotstyle.undefined() {
		plotstyle = PlotStylePoints
	}
	if style.empty() {
		style = AutoStyle(len(c.Data), false)
	}
	// Fix missing values in style
	if (plotstyle & PlotStyleLines) != 0 {
		if style.LineWidth <= 0 {
			style.LineWidth = 1
		}
		if style.LineColor == nil {
			style.LineColor = style.SymbolColor
		}
	}
	if (plotstyle&PlotStylePoints) != 0 && style.Symbol == 0 {
		style.Symbol = '#'
	}

	// Init axis
	if len(c.Data) == 0 {
		c.XRange.init()
		c.YRange.init()
	}

	// Add data
	scd := ScatterChartData{Name: name, PlotStyle: plotstyle, Style: style, Samples: data, Func: nil}
	c.Data = append(c.Data, scd)

	// Autoscale
	for _, d := range data {
		xl, yl, xh, yh := d.BoundingBox()
		c.XRange.autoscale(xl)
		c.XRange.autoscale(xh)
		c.YRange.autoscale(yl)
		c.YRange.autoscale(yh)
	}

	// Add key/legend entry
	if name != "" {
		ke := KeyEntry{Style: style, PlotStyle: plotstyle, Text: name}
		c.Key.Entries = append(c.Key.Entries, ke)
	}
}

Instruction: Given a code description, retrieve the corresponding code.


Question: List options for creating Reserved Capacity

def cli(env):
    """"""
    manager = CapacityManager(env.client)
    items = manager.get_create_options()

    items.sort(key=lambda term: int(term['capacity']))
    table = formatting.Table(["KeyName", "Description", "Term", "Default Hourly Price Per Instance"],
                             title="Reserved Capacity Options")
    table.align["Hourly Price"] = "l"
    table.align["Description"] = "l"
    table.align["KeyName"] = "l"
    for item in items:
        table.add_row([
            item['keyName'], item['description'], item['capacity'], get_price(item)
        ])
    env.fout(table)

    regions = manager.get_available_routers()
    location_table = formatting.Table(['Location', 'POD', 'BackendRouterId'], 'Orderable Locations')
    for region in regions:
        for location in region['locations']:
            for pod in location['location']['pods']:
                location_table.add_row([region['keyname'], pod['backendRouterName'], pod['backendRouterId']])
    env.fout(location_table)

public int getMinSlots(String pool, TaskType taskType) {
    Map<String, Integer> allocationMap = (taskType == TaskType.MAP ?
        mapAllocs : reduceAllocs);
    Integer alloc = allocationMap.get(pool);
    return (alloc == null ? 0 : alloc);
  }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Returns a value indicating whether there is a state of the specified name.

@param string $key state name.
@return boolean whether there is a state of the specified name.

protected function hasState($key) {
		$session = Yii::app()->session;
		$key = $this->getStateKeyPrefix() . $key;
		return isset($session[$key]);
	}

public static function url($identifier, $data = null, $domain = null) {

		if(false === is_string($identifier)) {
			return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($identifier)), E_USER_ERROR);
		}

		if(false === static :: routeExists($identifier)) {
			return trigger_error(sprintf('Route identifier "%s" not found in routes.php', $identifier), E_USER_ERROR);
		}

		if(null !== $data && false === is_string($data) && false === is_array($data)) {
			return trigger_error(sprintf('Argument 2 passed to %s() must be of the type array or string, "%s" given', __METHOD__, gettype($data)), E_USER_ERROR);
		}

		if(null !== $domain && false === is_string($domain)) {
			return trigger_error(sprintf('Argument 3 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($domain)), E_USER_ERROR);
		}

		if(true === is_string($data)) {
			$data = [$data];
		}

		if(null === $data) {
			$data = [];
		}

		$route 		= static :: getRoute($identifier);
		$url 		= $route -> getUrl();
		$parameters = 0;
		$optionals  = 0;

		if(preg_match_all('#\{(.*?)(\?)?\}#i', $url, $matches)) {

			foreach($matches[2] as $optional) {

				if('?' === $optional) {

					$optionals++;
					continue;
				}

				$parameters++;
			}

			if(count($data) < $parameters) {
				return trigger_error(sprintf('Incorrect number of parameters given for Router url with identifier "%s". Expecting %s, got %s with %s optional', $route -> getIdentifier(), count($matches[2]), count($data), $optionals), E_USER_ERROR);
			}

			foreach($matches[0] as $index => $match) {

				$match 		= $matches[0][$index];
				$type 		= $matches[1][$index];
				$optional 	= $matches[2][$index];
				$where 		= $route -> getWhere();
				$replace 	= static :: $types['string'];

				if(true === isset(static :: $types[$type])) {
					$replace = static :: $types[$type];
				}

				if(true === is_array($where)) {

					foreach($where as $key => $regex) {

						if($key === $type) {

							$replace =$regex;
							break;
						}
					}
				}

				if(true === isset($data[$index])) {

					if(false === is_string($data[$index]) && false === is_numeric($data[$index])) {
						return trigger_error(sprintf('Router url width id "%s" expects parameters to be a String', $route -> getIdentifier()));
					}

					if(preg_match('#' . $replace . '#i', $data[$index])) {
						$url = preg_replace('#'. preg_quote($match) .'#i', $data[$index], $url, 1);
					}
					else {
						return trigger_error(sprintf('Parameters given to router url width id "%s" do not match. Trying to match regular expression pattern "%s" with "%s" as subject', $route -> getIdentifier(), $replace, $data[$index]));
					}
				}
				elseif('' !== $optional) {
					$url = preg_replace('#'. '/?' . preg_quote($match) .'#i', '', $url, 1);
				}
			}
		}

		if(null !== $domain && false === static :: domainExists($domain)) {
			return trigger_error(sprintf('Domain "%s" does not exists in routes.php', $domain), E_USER_ERROR);
		}

		//Check if routes has a prefix and add it if it does
		$prefix = $route -> getPrefix();

		if(true === isset($prefix['url'])) {
			$url = $prefix['url'] . $url;
		}

		return (null !== $domain ? rtrim($domain, '/') . '/' : '') . $url;
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Quantile function.

@param val Value
@param shape Shape
@param location TODO
@param scale Scale
@return Quantile

public static double quantile(double val, double shape, double location, double scale) {
    return val < 0 || val > 1 ? Double.NaN : scale * FastMath.pow(val / (1. - val), 1. / shape) + location;
  }

def add_quality_score_vs_no_of_observations_section(self):

        sample_data = []
        data_labels = []
        for rt_type_name, rt_type in recal_table_type._asdict().items():
            sample_tables = self.gatk_base_recalibrator[rt_type]['quality_quantization_map']
            if len(sample_tables) == 0:
                continue

            sample_data.append({
                sample: {int(x): int(y) for x, y in zip(table['QualityScore'], table['Count'])}
                for sample, table in sample_tables.items()
            })

            sample_y_sums = {
                sample: sum(int(y) for y in table['Count'])
                for sample, table
                in sample_tables.items()
            }

            sample_data.append({
                sample: {
                    int(x): float(y) / sample_y_sums[sample]
                    for x, y in zip(table['QualityScore'], table['Count'])
                }
                for sample, table in sample_tables.items()
            })

            flat_proportions = [float(y) / sample_y_sums[sample]
                                for sample, table in sample_tables.items()
                                for y in table['Count']]
            prop_ymax = max(flat_proportions)
            data_labels.append({'name': "{} Count".format(rt_type_name.capitalize().replace('_', '-')),
                                'ylab': 'Count'})
            data_labels.append({'ymax': prop_ymax,
                                'name': "{} Percent".format(rt_type_name.capitalize().replace('_', '-')),
                                'ylab': 'Percent'})

        plot = linegraph.plot(
            sample_data,
            pconfig={
                'title': "Observed Quality Score Counts",
                'id': 'gatk-base-recalibrator-quality-score-vs-number-of-observations',
                'xlab': 'Observed Quality Score',
                'ylab': 'Count',
                'xDecimals': False,
                'data_labels': data_labels,
            })

        # Reported vs empirical quality scores
        self.add_section(
            name='Observed Quality Scores',
            description=(
                'This plot shows the distribution of base quality scores in each sample before and '
                'after base quality score recalibration (BQSR). Applying BQSR should broaden the '
                'distribution of base quality scores.'
            ),
            helptext=(
                'For more information see '
                '[the Broad\'s description of BQSR]'
                '(https://gatkforums.broadinstitute.org/gatk/discussion/44/base-quality-score-recalibration-bqsr)'
                '.'
            ),
            plot=plot,
        )

Instruction: Given a code description, retrieve the corresponding code.


Question: Use preset values for the distance between lines.

def Y_dist(self, new_y_distance):
        """"""
        self.parent.value('y_distance', new_y_distance)
        self.parent.traces.display()

def setMinGapLat(self, typeID, minGapLat):

        self._connection._sendDoubleCmd(
            tc.CMD_SET_VEHICLETYPE_VARIABLE, tc.VAR_MINGAP_LAT, typeID, minGapLat)

Instruction: Given a code description, retrieve the corresponding code.


Question:
@param int $percent

@return mixed

public function lighten($percent)
    {
        $color = $this->toHsl();
        $lightness = $this->clamp(($color->lightness() + $percent) / 100);
        return $color->lightness($lightness * 100)->back($this);
    }

public function getStatusesHuman()
    {
        return [
            self::STATUS_PENDING          => 'Pending',
            self::STATUS_PROCESSING       => 'Processing',
            self::STATUS_COMPLETE         => 'Complete',
            self::STATUS_FAILED           => 'Failed',
            self::STATUS_REFUNDED         => 'Refunded',
            self::STATUS_REFUNDED_PARTIAL => 'Partially Refunded',
        ];
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Return's the category with the passed path.

@param string $path          The path of the category to return
@param string $storeViewCode The store view code of the category to return

@return array The category

protected function getCategoryByPath($path, $storeViewCode = StoreViewCodes::ADMIN)
    {
        return $this->getSubject()->getCategoryByPath($path, $storeViewCode);
    }

public function handleAction(Request $request): Envelope
    {
        $request->attributes->set('pbjx_redact_error_message', false);
        $envelope = EnvelopeV1::create();
        if (!$this->isRequestMethodOk($envelope, $request) || !$this->isContentTypeOk($envelope, $request)) {
            return $envelope;
        }

        if ($request->isMethod('GET')) {
            $json = PbjxToken::urlsafeB64Decode($request->query->get('pbj'));
        } elseif (0 === strpos($request->headers->get('Content-Type'), 'multipart/form-data')) {
            $json = $request->request->get('pbj');
        } else {
            $json = $request->getContent();
        }

        $json = (string)$json;
        $data = json_decode($json, true) ?: [];
        if (!$this->isJsonOk($envelope, $request)) {
            return $envelope;
        }

        $pbjxCategory = $request->attributes->get('pbjx_category');
        if (false !== strpos($pbjxCategory, '_')) {
            $pbjxCategory = str_replace('_', '', $pbjxCategory);
            $request->attributes->set('pbjx_category', $pbjxCategory);
        }

        try {
            $expectedCurie = SchemaCurie::fromString(sprintf(
                '%s:%s:%s:%s',
                $request->attributes->get('pbjx_vendor'),
                $request->attributes->get('pbjx_package'),
                $pbjxCategory,
                $request->attributes->get('pbjx_message')
            ));

            $request->attributes->set('pbjx_curie', $expectedCurie->toString());
            $schemaId = isset($data[Schema::PBJ_FIELD_NAME]) ? SchemaId::fromString($data[Schema::PBJ_FIELD_NAME]) : null;

            /** @var Message $class */
            if (null === $schemaId) {
                $class = MessageResolver::resolveCurie($expectedCurie);
                $schema = $class::schema();
                $schemaId = $schema->getId();
            } else {
                $class = MessageResolver::resolveId($schemaId);
            }

            if ($schemaId->getCurie() !== $expectedCurie) {
                throw new \InvalidArgumentException(
                    sprintf(
                        'The resolved schema [%s] doesn\'t match expected curie [%s].',
                        $schemaId->toString(),
                        $expectedCurie->toString()
                    )
                );
            }
        } catch (\Throwable $e) {
            return $envelope
                ->set('code', Code::INVALID_ARGUMENT)
                ->set('http_code', HttpCode::HTTP_UNPROCESSABLE_ENTITY())
                ->set('error_name', 'UnprocessableEntity')
                ->set('error_message', $e->getMessage());
        }

        $request->attributes->set('pbjx_input', $data);
        $request->attributes->set('pbjx_bind_unrestricted', $request->attributes->getBoolean('pbjx_bind_unrestricted'));

        try {
            /** @var Command|Event|PbjxRequest $message */
            $message = $class::fromArray($data);
            $message->set('ctx_correlator_ref', $envelope->generateMessageRef());
        } catch (\Throwable $e) {
            return $envelope
                ->set('code', Code::INVALID_ARGUMENT)
                ->set('http_code', HttpCode::HTTP_UNPROCESSABLE_ENTITY())
                ->set('error_name', 'UnprocessableEntity')
                ->set('error_message', $e->getMessage());
        }

        $request->attributes->set(
            'pbjx_redact_error_message',
            !$request->attributes->getBoolean('pbjx_console')
        );

        if (!$this->isPbjxTokenOk($envelope, $request, $json)) {
            return $envelope;
        }

        // allows for functional tests/postman tests/etc. to post pbjx but
        // not actually run them.  this is most important for commands/events
        // which can change state but for request, you'd typically not use
        // dry run because you need to get a response in order to make assertions.
        if ($request->headers->has('x-pbjx-dry-run')) {
            return $envelope
                ->set('code', Code::OK)
                ->set('http_code', HttpCode::HTTP_ACCEPTED())
                ->set('message_ref', $message->generateMessageRef());
        }

        if ($message instanceof Command) {
            return $this->handleCommand($envelope, $request, $message);
        }

        if ($message instanceof Event) {
            return $this->handleEvent($envelope, $request, $message);
        }

        if ($message instanceof PbjxRequest) {
            return $this->handleRequest($envelope, $request, $message);
        }

        $request->attributes->set('pbjx_redact_error_message', false);
        return $envelope
            ->set('code', Code::INVALID_ARGUMENT)
            ->set('http_code', HttpCode::HTTP_UNPROCESSABLE_ENTITY())
            ->set('error_name', 'UnprocessableEntity')
            ->set(
                'error_message',
                sprintf('This service does not allow you to submit [%s] messages.', $schemaId->toString())
            );
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
convert Array Object to string list

@param array array to convert
@param delimiter delimiter for the new list
@return list generated from string array
@throws PageException

public static String arrayToList(Array array, String delimiter) throws PageException {
	if (array.size() == 0) return "";
	StringBuilder sb = new StringBuilder(Caster.toString(array.get(1, "")));
	int len = array.size();

	for (int i = 2; i <= len; i++) {
	    sb.append(delimiter);
	    sb.append(Caster.toString(array.get(i, "")));
	}
	return sb.toString();
    }

public void marshall(ListThingsRequest listThingsRequest, ProtocolMarshaller protocolMarshaller) {

        if (listThingsRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(listThingsRequest.getNextToken(), NEXTTOKEN_BINDING);
            protocolMarshaller.marshall(listThingsRequest.getMaxResults(), MAXRESULTS_BINDING);
            protocolMarshaller.marshall(listThingsRequest.getAttributeName(), ATTRIBUTENAME_BINDING);
            protocolMarshaller.marshall(listThingsRequest.getAttributeValue(), ATTRIBUTEVALUE_BINDING);
            protocolMarshaller.marshall(listThingsRequest.getThingTypeName(), THINGTYPENAME_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Parse RELEASES file https://github.com/Squirrel/Squirrel.Windows/blob/0d1250aa6f0c25fe22e92add78af327d1277d97d/src/Squirrel/ReleaseExtensions.cs#L19

function parseRELEASES(content) {
    return _.chain(stripBom(content))
        .replace('\r\n', '\n')
        .split('\n')
        .map(function(line) {
            var parts = releaseRe.exec(line);
            if (!parts) return null;

            var filename = parts[2];
            var isDelta = filename.indexOf('-full.nupkg') == -1;

            var filenameParts = filename
                .replace(".nupkg", "")
                .replace("-delta", "")
                .replace("-full", "")
                .split(/\.|-/)
                .reverse();

            var version = _.chain(filenameParts)
                .filter(function(x) {
                    return /^\d+$/.exec(x);
                })
                .reverse()
                .value()
                .join('.');

            return {
                sha: parts[1],
                filename: filename,
                size: Number(parts[3]),
                isDelta: isDelta,
                version: version,
                semver: toSemver(version)
            };
        })
        .compact()
        .value();
}

func (s *Version) SetSourceCodeArchiveUrl(v string) *Version {
	s.SourceCodeArchiveUrl = &v
	return s
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Sets a new value to map element

        :param value: a new element or map value.

def set_as_object(self, value):

        self.clear()
        map = MapConverter.to_map(value)
        self.append(map)

func AddLabel(labels map[string]string, labelKey, labelValue string) map[string]string {
	if labelKey == "" {
		// Don't need to add a label.
		return labels
	}
	if labels == nil {
		labels = make(map[string]string)
	}
	labels[labelKey] = labelValue
	return labels
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Update frequency of tags and add new tags
@param $tags

public static function addTags($tags)
    {
        self::updateAllCounters(['frequency' => 1], ['name' => $tags]);

        foreach ($tags as $name) {
            if (!self::find()->where(['name' => $name])->exists()) {
                (new self([
                    'name' => $name,
                    'frequency' => 1
                ]))->save();
            }
        }
    }

func getTagKey(currentTag, addTag string) string {
	if currentTag == doNotConsiderTag && addTag == doNotConsiderTag {
		return doNotConsiderTag
	} else if currentTag == doNotConsiderTag && addTag != doNotConsiderTag {
		return addTag
	} else if currentTag != doNotConsiderTag && addTag == doNotConsiderTag {
		return currentTag
	}

	return currentTag + `.` + addTag
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Tests if the {@link HttpMethod method} requires a redirect to another location.

@param method HTTP method

@return boolean <tt>true</tt> if a retry is needed, <tt>false</tt> otherwise.

private boolean isRedirectNeeded(final HttpMethod method) {
		switch (method.getStatusCode()) {
			case HttpStatus.SC_MOVED_TEMPORARILY:
			case HttpStatus.SC_MOVED_PERMANENTLY:
			case HttpStatus.SC_SEE_OTHER:
			case HttpStatus.SC_TEMPORARY_REDIRECT:
				LOG.debug("Redirect required");
                if (method.getFollowRedirects()) {
                    return true;
                } else {
                    return false;
                }
			default:
				return false;
		} //end of switch
	}

async def end_takeout(self, success):

        try:
            async with _TakeoutClient(True, self, None) as takeout:
                takeout.success = success
        except ValueError:
            return False
        return True

Instruction: Given a code description, retrieve the corresponding code.


Question:
将Bean类指定修饰符的属性转换成JSON字符串

@param object Bean对象
@param modifier 属性的权限修饰符

@return 格式化的JSON字符串

@throws IllegalAccessException 异常

public static String toPrettyJson(Object object, FieldModifier modifier) throws IllegalAccessException {
        return Formatter.formatJson(toJsonString(object, modifier));
    }

public void marshall(XMLClassifier xMLClassifier, ProtocolMarshaller protocolMarshaller) {

        if (xMLClassifier == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(xMLClassifier.getName(), NAME_BINDING);
            protocolMarshaller.marshall(xMLClassifier.getClassification(), CLASSIFICATION_BINDING);
            protocolMarshaller.marshall(xMLClassifier.getCreationTime(), CREATIONTIME_BINDING);
            protocolMarshaller.marshall(xMLClassifier.getLastUpdated(), LASTUPDATED_BINDING);
            protocolMarshaller.marshall(xMLClassifier.getVersion(), VERSION_BINDING);
            protocolMarshaller.marshall(xMLClassifier.getRowTag(), ROWTAG_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Update this entity in the database.

public function update()
    {
        $this->callEvent('update');

        if (empty($this->modified)) {
            return;
        }
        $values = array_intersect_key($this->values, $this->modified);
        $where = [static::$primary_key => $this->getPrimaryKey()];
        $this->connection->update(static::$table, $values, $where, static::$types);
        $this->setStored();
    }

public function markJobDone(QueuedJob $job) {
		$fields = [
			'completed' => $this->getDateTime(),
		];
		$job = $this->patchEntity($job, $fields);

		return (bool)$this->save($job);
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Returns list of unloaded aspects in the container

@return Aspect[]

public function getUnloadedAspects(): array
    {
        $unloadedAspects = [];

        foreach ($this->container->getByTag('aspect') as $aspect) {
            if (!isset($this->loadedAspects[get_class($aspect)])) {
                $unloadedAspects[] = $aspect;
            }
        }

        return $unloadedAspects;
    }

protected function mapReflectorPropertiesOntoDescriptor(Function_ $reflector, FunctionDescriptor $descriptor): void
    {
        $packages = new Collection();
        $package = $this->extractPackageFromDocBlock($reflector->getDocBlock());
        //TODO: this looks like a potential bug. Have to investigate this!
        if ($package) {
            $tag = new TagDescriptor('package');
            $tag->setDescription($package);
            $packages->add($tag);
        }

        $descriptor->getTags()->set('package', $packages);

        $descriptor->setFullyQualifiedStructuralElementName($reflector->getFqsen());
        $descriptor->setName($reflector->getName());
        $descriptor->setLine($reflector->getLocation()->getLineNumber());
        $descriptor->setNamespace('\\' . trim(substr(
            (string) $reflector->getFqsen(),
            0,
            -strlen($reflector->getName()) - 2
        ), '\\'));
        $descriptor->setReturnType($reflector->getReturnType());
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Given a list of MOPfiles merge them based on x/y coordinates matching..

def xymatch(outfile, filenames, tol=2):
    """"""
    import math
    import sys
    output={}
    files=[]
    for filename in filenames:
        this_file=read(filename)
        ## match files based on the 'X' and 'Y' column.
        ## if those don't exist then skip this file
        if not this_file['data'].has_key('X') or not this_file['data'].has_key('Y'):
            continue
        if not output.has_key('data'):
            output=this_file
            continue
        delete_list=[]
        for keyword in this_file['header']:
            if not keyword in output['header']:
                output['header'][keyword]=this_file['header'][keyword]
        for col in this_file['data'].keys():
            if not output['data'].has_key(col):
                output['order'].append(col)
                output['data'][col]=[]
                output['order'].append(col)
                if this_file['format'].has_key(col):
                    output['format'][col]=this_file['format'][col]
                else:
                    output['format'][col]='%10s'
                ### pad previously values with empties..
                for i in range(len(output['data']['X'])):
                    output['data'][col].append(None)
        for i in xrange(len(output['data']['X'])):
            x1=float(output['data']['X'][i])
            y1=float(output['data']['Y'][i])
            matched=False
            for j in xrange(len(this_file['data']['X'])):
                x2=float(this_file['data']['X'][j])
                y2=float(this_file['data']['Y'][j])
                if ( ((x1-x2)**2+(y1-y2)**2) < tol**2):
                    for col in this_file['data'].keys():
                        if output['data'][col][i] is None:
                            output['data'][col][i]=this_file['data'][col][j]
                    matched=True
                    break
            if not matched:
                delete_list.append(i)

        delete_list.sort()
        delete_list.reverse()
        for i in delete_list:
            for col in output['data'].keys():
                del output['data'][col][i]

    write(outfile,output)

def _move_files_to_compute(compute, project_id, directory, files_path):

    location = os.path.join(directory, files_path)
    if os.path.exists(location):
        for (dirpath, dirnames, filenames) in os.walk(location):
            for filename in filenames:
                path = os.path.join(dirpath, filename)
                dst = os.path.relpath(path, directory)
                yield from _upload_file(compute, project_id, path, dst)
        shutil.rmtree(os.path.join(directory, files_path))

Instruction: Given a code description, retrieve the corresponding code.


Question:
Define if a scatter serie should be draw with ticks
@param int $ID
@param int $Width

public function setScatterSerieTicks($ID, $Width = 0)
    {
        if (isset($this->Data["ScatterSeries"][$ID])) {
            $this->Data["ScatterSeries"][$ID]["Ticks"] = $Width;
        }
    }

def addTable(D):

    _swap = {
        "1": "measurement",
        "2": "summary",
        "3": "ensemble",
        "4": "distribution"
    }

    print("What type of table would you like to add?\n"
          "1: measurement\n"
          "2: summary\n"
          "3: ensemble (under development)\n"
          "4: distribution (under development)\n"
          "\n Note: if you want to add a whole model, use the addModel() function")
    _ans = input(">")

    if _ans in ["3", "4"]:
        print("I don't know how to do that yet.")
    # if this is a summary or measurement, split the csv into each column
    elif _ans in ["1", "2"]:
        # read in a csv file. have the user point to it
        print("Locate the CSV file with the values for this table: ")
        _path, _files = browse_dialog_file()

        _path = _confirm_file_path(_files)
        _values = read_csv_from_file(_path)
        _table = _build_table(_values)
        _placement = _prompt_placement(D, _swap[_ans])
        D = _put_table(D, _placement, _table)

    else:
        print("That's not a valid option")

    return D

Instruction: Given a code description, retrieve the corresponding code.


Question: Return a long value from a prepared query.

public long queryForLong(DatabaseConnection databaseConnection, PreparedStmt<T> preparedStmt) throws SQLException {
		CompiledStatement compiledStatement = preparedStmt.compile(databaseConnection, StatementType.SELECT_LONG);
		DatabaseResults results = null;
		try {
			results = compiledStatement.runQuery(null);
			if (results.first()) {
				return results.getLong(0);
			} else {
				throw new SQLException("No result found in queryForLong: " + preparedStmt.getStatement());
			}
		} finally {
			IOUtils.closeThrowSqlException(results, "results");
			IOUtils.closeThrowSqlException(compiledStatement, "compiled statement");
		}
	}

func (c *SQLiteContext) ResultInt(i int) {
	if i64 && (i > math.MaxInt32 || i < math.MinInt32) {
		C.sqlite3_result_int64((*C.sqlite3_context)(c), C.sqlite3_int64(i))
	} else {
		C.sqlite3_result_int((*C.sqlite3_context)(c), C.int(i))
	}
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Check whether or not a particular field is has errors.

@param string $field The name of the field to check for validity.
@return bool Returns true if the field has no errors, false otherwise.

public function isValidField(string $field): bool {
        $result = empty($this->errors[$field]);
        return $result;
    }

public function validateValue($value) {

        $model = &$this->_model;

        $attribute = $this->_attributeName;
        if ((!is_array($model->$attribute) || !count($model->$attribute)) && $this->skipOnEmpty) {
            return '';
        }

        $result = count($model->$attribute) > 0;
        $class = $this->baseModel;

        foreach ($model->$attribute as $_key => &$_model) {
            /** @var $_model Model|ActiveRecord */
            if (!is_object($_model)) {
                if (!is_array($_model)) {
                    $_model = [$this->attribute ? : $this->_attributeName => $_model];
                }
                $_model = new $class($_model);
            }

            $result = $_model->validate() && $result;
        }

        return $result || (sizeof($model->$attribute)==1 && $this->skipOnEmpty) ? null : [$this->message, $result];
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Auto Generated Code

def system_monitor_mail_fru_email_list_email(self, **kwargs):

        config = ET.Element("config")
        system_monitor_mail = ET.SubElement(config, "system-monitor-mail", xmlns="urn:brocade.com:mgmt:brocade-system-monitor")
        fru = ET.SubElement(system_monitor_mail, "fru")
        email_list = ET.SubElement(fru, "email-list")
        email = ET.SubElement(email_list, "email")
        email.text = kwargs.pop('email')

        callback = kwargs.pop('callback', self._callback)
        return callback(config)

private function populateAvailableTypes($onlyAutowiringTypes = false)
    {
        $this->types = array();
        if (!$onlyAutowiringTypes) {
            $this->ambiguousServiceTypes = array();
        }

        foreach ($this->container->getDefinitions() as $id => $definition) {
            $this->populateAvailableType($id, $definition, $onlyAutowiringTypes);
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Store in the user home directory an image from a remote location.

def fetch_image(self, path, dest, user='root'):

        self.run('test -f %s || curl -L -s -o %s %s' % (dest, dest, path),
                 user=user, ignore_error=True)

def do_drag_data_received(self, drag_context, x, y, data, info, time):
        '''
        '''
        if not self.app.profile:
            return
        if info == TargetInfo.URI_LIST:
            uris = data.get_uris()
            source_paths = util.uris_to_paths(uris)
            if source_paths:
                self.app.upload_page.upload_files(source_paths, self.path)

Instruction: Given a code description, retrieve the corresponding code.


Question:
Cancel this job.

        Args:
            force (bool, optional): Forcefully cancel this job.

        Returns:
            bool: True if the job was cancelled, otherwise False if an error occurred.

def cancel(self, force=False):

        return self.rest_client._sc._delegator._cancel_job(self, force)

static public DisabledJob fromDeprecatedObject(Object obj) {
    if (obj == null) {
      return null;
    }
    if (obj instanceof String) {
      return new DisabledJob((String)obj);
    } else if (obj instanceof Map) {
      Map<String, Object> map = (Map<String, Object>)obj;
      String name = (String)map.get(SUBFLOW_ID_KEY);
      List<DisabledJob> childJobs = fromDeprecatedObjectList((List<Object>)map.get
          (SUBFLOW_CHILDREN_KEY));
      if (name != null && childJobs != null) {
        return new DisabledJob(name, childJobs);
      }
    }
    return null;
  }

Instruction: Given a code description, retrieve the corresponding code.


Question: Provides padding on sides of frame equal to pad fraction of plot

def _pad_plot_frame(ax, pad=0.01):

    xmin, xmax = ax.get_xlim()
    ymin, ymax = ax.get_ylim()
    xr = xmax - xmin
    yr = ymax - ymin

    ax.set_xlim(xmin - xr*pad, xmax + xr*pad)
    ax.set_ylim(ymin - yr*pad, ymax + yr*pad)

    return ax

def fit(self, X, y=None, **fit_params):

        # Handle the feature names if they're None.
        if self.features_ is None:

            # If X is a data frame, get the columns off it.
            if is_dataframe(X):
                self.features_ = np.array(X.columns)

            # Otherwise create numeric labels for each column.
            else:
                _, ncols = X.shape
                self.features_ = np.arange(0, ncols)

        return self

Instruction: Given a code description, retrieve the corresponding code.


Question:
// GetAWSUniqueID returns the AWSUniqueId from the collected EC2Metadata
// Please note that the dimension/property used in SFX is named "AWSUniqueId"
// and not AWSUniqueID.  This function is named in order to satisfy golint demands

func (e *EC2Metadata) GetAWSUniqueID() (string, error) {
	if e.InstanceID == "" {
		return "", errors.New("unable to build AWSUniqueId (missing InstanceId)")
	}
	if e.AccountID == "" {
		return "", errors.New("unable to build AWSUniqueId (missing AccountId)")
	}
	if e.Region == "" {
		return "", errors.New("unable to build AWSUniqueId (missing Region)")
	}

	return fmt.Sprintf("%s_%s_%s", e.InstanceID, e.Region, e.AccountID), nil
}

function (options) {
    winston.Transport.call(this, options);

    options = options || {};

    var apiKey = options.apiKey;
    var projectId = options.projectId;
    var apiHostName = options.apiHostName;
    var formatter = options.formatter || 'kvp';

    if (!apiKey || !projectId || !apiHostName) {
        throw new Error('apiKey, projectId and apiHostName are neccessary');
    }

    this._storm = new SplunkStorm({
        apiKey: apiKey,
        projectId: projectId,
        apiHostName: apiHostName,
        formatter: formatter
    });
    this._sourceType = options.sourceType || 'syslog';
    this._source = options.source || '';
    this._host = options.host || os.hostname();

    this._options = options;
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Returns link-alternate html tag
- e.g. <link rel="alternate" href="http://sulu.lo/de/test-url" hreflang="de" />.

@param string $url
@param string $webspaceKey
@param string $locale
@param bool $default

@return string

private function getAlternate($url, $webspaceKey, $locale, $default = false)
    {
        $url = $this->contentPath->getContentPath($url, $webspaceKey, $locale);

        return sprintf(
            '<link rel="alternate" href="%s" hreflang="%s" />',
            $url,
            !$default ? str_replace('_', '-', $locale) : 'x-default'
        );
    }

protected function getSlugRouteParameters()
    {
        $slugPath = '/{url}';
        $slugDefaults = array(
            '_controller' => 'KunstmaanNodeBundle:Slug:slug',
            'preview' => false,
            'url' => '',
            '_locale' => $this->getDefaultLocale(),
        );
        $slugRequirements = array(
            'url' => $this->getSlugPattern(),
        );

        $locales = [];

        // If other site provided and multilingual, get the locales from the host config.
        if ($this->otherSite && $this->isMultiLanguage($this->otherSite['host'])) {
            $locales = $this->getHostLocales();
        } elseif ($this->isMultiLanguage() && !$this->otherSite) {
            $locales = $this->getFrontendLocales();
        }

        // Make locale availables for the slug routes.
        if (!empty($locales)) {
            $slugPath = '/{_locale}' . $slugPath;
            unset($slugDefaults['_locale']);
            $slugRequirements['_locale'] = $this->getEscapedLocales($this->getHostLocales());
        }

        return array(
            'path' => $slugPath,
            'defaults' => $slugDefaults,
            'requirements' => $slugRequirements,
        );
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // matchingActions finds actions that match ActionReceiver.

func (st *State) matchingActions(ar ActionReceiver) ([]Action, error) {
	return st.matchingActionsByReceiverId(ar.Tag().Id())
}

public function maybeMatch(string $variable = null, array $labels = []): self
    {
        $query = new self;
        $query->clauses = $this->clauses->add(
            new Clause\OptionalMatchClause(
                Clause\Expression\Path::startWithNode($variable, $labels)
            )
        );

        return $query;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Create a UIContent.

def create_content(self, cli, width, height):

        buffer = self._buffer(cli)

        # Get the document to be shown. If we are currently searching (the
        # search buffer has focus, and the preview_search filter is enabled),
        # then use the search document, which has possibly a different
        # text/cursor position.)
        def preview_now():
            """ True when we should preview a search. """
            return bool(self.preview_search(cli) and
                        cli.buffers[self.search_buffer_name].text)

        if preview_now():
            if self.get_search_state:
                ss = self.get_search_state(cli)
            else:
                ss = cli.search_state

            document = buffer.document_for_search(SearchState(
                text=cli.current_buffer.text,
                direction=ss.direction,
                ignore_case=ss.ignore_case))
        else:
            document = buffer.document

        get_processed_line = self._create_get_processed_line_func(cli, document)
        self._last_get_processed_line = get_processed_line

        def translate_rowcol(row, col):
            " Return the content column for this coordinate. "
            return Point(y=row, x=get_processed_line(row).source_to_display(col))

        def get_line(i):
            " Return the tokens for a given line number. "
            tokens = get_processed_line(i).tokens

            # Add a space at the end, because that is a possible cursor
            # position. (When inserting after the input.) We should do this on
            # all the lines, not just the line containing the cursor. (Because
            # otherwise, line wrapping/scrolling could change when moving the
            # cursor around.)
            tokens = tokens + [(self.default_char.token, ' ')]
            return tokens

        content = UIContent(
            get_line=get_line,
            line_count=document.line_count,
            cursor_position=translate_rowcol(document.cursor_position_row,
                                             document.cursor_position_col),
            default_char=self.default_char)

        # If there is an auto completion going on, use that start point for a
        # pop-up menu position. (But only when this buffer has the focus --
        # there is only one place for a menu, determined by the focussed buffer.)
        if cli.current_buffer_name == self.buffer_name:
            menu_position = self.menu_position(cli) if self.menu_position else None
            if menu_position is not None:
                assert isinstance(menu_position, int)
                menu_row, menu_col = buffer.document.translate_index_to_position(menu_position)
                content.menu_position = translate_rowcol(menu_row, menu_col)
            elif buffer.complete_state:
                # Position for completion menu.
                # Note: We use 'min', because the original cursor position could be
                #       behind the input string when the actual completion is for
                #       some reason shorter than the text we had before. (A completion
                #       can change and shorten the input.)
                menu_row, menu_col = buffer.document.translate_index_to_position(
                    min(buffer.cursor_position,
                        buffer.complete_state.original_document.cursor_position))
                content.menu_position = translate_rowcol(menu_row, menu_col)
            else:
                content.menu_position = None

        return content

def color(self, code):

        def func(content=''):
            return self._apply_color(u'38;5;%d' % code, content)
        return func

Instruction: Given a code description, retrieve the corresponding code.


Question:
Set new cookies

@param CookieJar $cookie

@return bool

public function setCookie(CookieJar $cookie)
    {
        return $this->getCache()->save($this->getCacheKey(), $cookie, Config::get('cache.expire', 100));
    }

public String getCookie(String name, String dfvalue) {
        for (HttpCookie c : getCookies()) {
            if (name.equals(c.getName())) return c.getValue();
        }
        return dfvalue;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
// setupTLS sets up the TLS configuration and installs certificates that
// are specified by the user in the config file. All the automatic HTTPS
// stuff comes later outside of this function.

func setupTLS(c *caddy.Controller) error {
	configGetter, ok := configGetters[c.ServerType()]
	if !ok {
		return fmt.Errorf("no caddytls.ConfigGetter for %s server type; must call RegisterConfigGetter", c.ServerType())
	}
	config := configGetter(c)
	if config == nil {
		return fmt.Errorf("no caddytls.Config to set up for %s", c.Key)
	}

	config.Enabled = true

	for c.Next() {
		var certificateFile, keyFile, loadDir, maxCerts string

		args := c.RemainingArgs()
		switch len(args) {
		case 1:
			// even if the email is one of the special values below,
			// it is still necessary for future analysis that we store
			// that value in the ACMEEmail field.
			config.ACMEEmail = args[0]

			// user can force-disable managed TLS this way
			if args[0] == "off" {
				config.Enabled = false
				return nil
			}

			// user might want a temporary, in-memory, self-signed cert
			if args[0] == "self_signed" {
				config.SelfSigned = true
			}
		case 2:
			certificateFile = args[0]
			keyFile = args[1]
			config.Manual = true
		}

		// Optional block with extra parameters
		var hadBlock bool
		for c.NextBlock() {
			hadBlock = true
			switch c.Val() {
			case "key_type":
				arg := c.RemainingArgs()
				value, ok := supportedKeyTypes[strings.ToUpper(arg[0])]
				if !ok {
					return c.Errf("Wrong key type name or key type not supported: '%s'", c.Val())
				}
				config.KeyType = value
			case "protocols":
				args := c.RemainingArgs()
				if len(args) == 1 {
					value, ok := supportedProtocols[strings.ToLower(args[0])]
					if !ok {
						return c.Errf("Wrong protocol name or protocol not supported: '%s'", args[0])
					}

					config.ProtocolMinVersion, config.ProtocolMaxVersion = value, value
				} else {
					value, ok := supportedProtocols[strings.ToLower(args[0])]
					if !ok {
						return c.Errf("Wrong protocol name or protocol not supported: '%s'", args[0])
					}
					config.ProtocolMinVersion = value
					value, ok = supportedProtocols[strings.ToLower(args[1])]
					if !ok {
						return c.Errf("Wrong protocol name or protocol not supported: '%s'", args[1])
					}
					config.ProtocolMaxVersion = value
					if config.ProtocolMinVersion > config.ProtocolMaxVersion {
						return c.Errf("Minimum protocol version cannot be higher than maximum (reverse the order)")
					}
				}
			case "ciphers":
				for c.NextArg() {
					value, ok := supportedCiphersMap[strings.ToUpper(c.Val())]
					if !ok {
						return c.Errf("Wrong cipher name or cipher not supported: '%s'", c.Val())
					}
					config.Ciphers = append(config.Ciphers, value)
				}
			case "curves":
				for c.NextArg() {
					value, ok := supportedCurvesMap[strings.ToUpper(c.Val())]
					if !ok {
						return c.Errf("Wrong curve name or curve not supported: '%s'", c.Val())
					}
					config.CurvePreferences = append(config.CurvePreferences, value)
				}
			case "clients":
				clientCertList := c.RemainingArgs()
				if len(clientCertList) == 0 {
					return c.ArgErr()
				}

				listStart, mustProvideCA := 1, true
				switch clientCertList[0] {
				case "request":
					config.ClientAuth = tls.RequestClientCert
					mustProvideCA = false
				case "require":
					config.ClientAuth = tls.RequireAnyClientCert
					mustProvideCA = false
				case "verify_if_given":
					config.ClientAuth = tls.VerifyClientCertIfGiven
				default:
					config.ClientAuth = tls.RequireAndVerifyClientCert
					listStart = 0
				}
				if mustProvideCA && len(clientCertList) <= listStart {
					return c.ArgErr()
				}

				config.ClientCerts = clientCertList[listStart:]
			case "load":
				c.Args(&loadDir)
				config.Manual = true
			case "max_certs":
				c.Args(&maxCerts)
				config.OnDemand = true
			case "dns":
				args := c.RemainingArgs()
				if len(args) != 1 {
					return c.ArgErr()
				}
				dnsProvName := args[0]
				if _, ok := dnsProviders[dnsProvName]; !ok {
					return c.Errf("Unsupported DNS provider '%s'", args[0])
				}
				config.DNSProvider = args[0]
			case "storage":
				args := c.RemainingArgs()
				if len(args) != 1 {
					return c.ArgErr()
				}
				storageProvName := args[0]
				if _, ok := storageProviders[storageProvName]; !ok {
					return c.Errf("Unsupported Storage provider '%s'", args[0])
				}
				config.StorageProvider = args[0]
			case "muststaple":
				config.MustStaple = true
			default:
				return c.Errf("Unknown keyword '%s'", c.Val())
			}
		}

		// tls requires at least one argument if a block is not opened
		if len(args) == 0 && !hadBlock {
			return c.ArgErr()
		}

		// set certificate limit if on-demand TLS is enabled
		if maxCerts != "" {
			maxCertsNum, err := strconv.Atoi(maxCerts)
			if err != nil || maxCertsNum < 1 {
				return c.Err("max_certs must be a positive integer")
			}
			config.OnDemandState.MaxObtain = int32(maxCertsNum)
		}

		// don't try to load certificates unless we're supposed to
		if !config.Enabled || !config.Manual {
			continue
		}

		// load a single certificate and key, if specified
		if certificateFile != "" && keyFile != "" {
			err := cacheUnmanagedCertificatePEMFile(certificateFile, keyFile)
			if err != nil {
				return c.Errf("Unable to load certificate and key files for '%s': %v", c.Key, err)
			}
			log.Printf("[INFO] Successfully loaded TLS assets from %s and %s", certificateFile, keyFile)
		}

		// load a directory of certificates, if specified
		if loadDir != "" {
			err := loadCertsInDir(c, loadDir)
			if err != nil {
				return err
			}
		}
	}

	SetDefaultTLSParams(config)

	// generate self-signed cert if needed
	if config.SelfSigned {
		err := makeSelfSignedCert(config)
		if err != nil {
			return fmt.Errorf("self-signed: %v", err)
		}
	}

	return nil
}

def stage_tc_create_security_label(self, label, resource):

        sl_resource = resource.security_labels(label)
        sl_resource.http_method = 'POST'
        sl_response = sl_resource.request()
        if sl_response.get('status') != 'Success':
            self.log.warning(
                '[tcex] Failed adding security label "{}" ({}).'.format(
                    label, sl_response.get('response').text
                )
            )

Instruction: Given a code description, retrieve the corresponding code.


Question:
Executes a command on the server and returns a number.

@param string $command The command to execute
@param string $target  First parameter
@param string $value   Second parameter

@return int The result of the command as a number

public function getNumber($command, $target = null, $value = null)
    {
        $string = $this->getString($command, $target, $value);

        return (int) $string;
    }

public void run() throws Exception {

        Registry registry = LocateRegistry.getRegistry(m_registryPort);
        I_CmsRemoteShellProvider provider = (I_CmsRemoteShellProvider)(registry.lookup(
            CmsRemoteShellConstants.PROVIDER));
        m_remoteShell = provider.createShell(m_additionalCommands);
        m_prompt = m_remoteShell.getPrompt();
        m_out = new PrintStream(System.out);
        try {
            LineNumberReader lnr = new LineNumberReader(new InputStreamReader(m_input, "UTF-8"));
            while (!exitCalled()) {
                if (m_interactive || isEcho()) {
                    // print the prompt in front of the commands to process only when 'interactive'
                    printPrompt();
                }
                String line = lnr.readLine();
                if (line == null) {
                    break;
                }
                if (line.trim().startsWith("#")) {
                    m_out.println(line);
                    continue;
                }
                StringReader lineReader = new StringReader(line);
                StreamTokenizer st = new StreamTokenizer(lineReader);
                st.eolIsSignificant(true);
                st.wordChars('*', '*');
                // put all tokens into a List
                List<String> parameters = new ArrayList<String>();
                while (st.nextToken() != StreamTokenizer.TT_EOF) {
                    if (st.ttype == StreamTokenizer.TT_NUMBER) {
                        parameters.add(Integer.toString(new Double(st.nval).intValue()));
                    } else {
                        parameters.add(st.sval);
                    }
                }
                lineReader.close();

                if (parameters.size() == 0) {
                    // empty line, just need to check if echo is on
                    if (isEcho()) {
                        m_out.println();
                    }
                    continue;
                }

                // extract command and arguments
                String command = parameters.get(0);
                List<String> arguments = new ArrayList<String>(parameters.subList(1, parameters.size()));

                // execute the command with the given arguments
                executeCommand(command, arguments);

            }
            exit(0);
        } catch (Throwable t) {
            t.printStackTrace();
            if (m_errorCode != -1) {
                exit(m_errorCode);
            }
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: see if junction overlaps with tolerance

def overlaps(self,junc,tolerance=0):
    """"""
    if not self.left.overlaps(junc.left,padding=tolerance): return False
    if not self.right.overlaps(junc.right,padding=tolerance): return False
    return True

def check_collision(self, other):
        """"""
        other = Network(other)
        return self.network_long() <= other.network_long() <= self.broadcast_long() or \
            other.network_long() <= self.network_long() <= other.broadcast_long()

Instruction: Given a code description, retrieve the corresponding code.


Question: Executes the query and attempts to create model objects from results.

def execute(self, return_results=True):
        '''

        '''
        if self.results:
            return self.results if return_results else None

        self.execute_raw()

        if self._raw_results_only:
            self.results = self.raw_results
        else:
            self.map_results()

        if return_results:
            return self.results

public function run(string $statement, ...$params)
    {
        return $this->safeQuery($statement, $params, self::DEFAULT_FETCH_STYLE, false, true);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Removes an object from the aggregation.

@see AnObjectSet::extract()

public function extract($entity)
    {
        //if entity is required then delete the entity
        $property = $this->getRepository()
                         ->getDescription()
                         ->getProperty($this->_property);

        if ($property->isRequired()) {
            $entity->delete();
        } else {
            $entity->set($this->_property, null);
        }
    }

protected function internalRemoveItem(&$normalizedKey)
    {
        $filespec = $this->getFileSpec($normalizedKey);
        if (!file_exists($filespec . '.dat')) {
            return false;
        } else {
            $this->unlink($filespec . '.dat');
        }

        return true;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
The |NotesSlide| instance associated with this slide. If the slide
        does not have a notes slide, a new one is created. The same single
        instance is returned on each call.

def notes_slide(self):

        try:
            notes_slide_part = self.part_related_by(RT.NOTES_SLIDE)
        except KeyError:
            notes_slide_part = self._add_notes_slide_part()
        return notes_slide_part.notes_slide

function(class_data) {

		var prototype = {},
			skeleton = class_data.skeleton,
			serialized_value,
			constructor_actions = [],
			name,
			source,
			constructor,
			object_properties,
			uses_references = false,
			is_monomorphic = class_data.is_monomorphic;

		for (name in skeleton) {

			switch (skeleton[name].type) {
				case this.MEMBER_TYPES.STRING:
					if (is_monomorphic) {
						serialized_value = Firestorm.String.quote(skeleton[name].value);
					} else {
						prototype[name] = skeleton[name].value;
					}
					break;
				case this.MEMBER_TYPES.PRIMITIVE: // null, boolean, number
					if (is_monomorphic) {
						serialized_value = skeleton[name].value + '';
					} else {
						prototype[name] = skeleton[name].value;
					}
					break;
				case this.MEMBER_TYPES.EMPTY_ARRAY:
					serialized_value = "[]";
					break;
				case this.MEMBER_TYPES.INLINE_ARRAY:
					serialized_value = this._serializeInlineArray(skeleton[name].value);
					break;
				case this.MEMBER_TYPES.REGEXP:
				case this.MEMBER_TYPES.FUNCTION:
					prototype[name] = class_data.references[skeleton[name].index];
					break;
				case this.MEMBER_TYPES.SLICE_ARRAY:
					serialized_value = 'r[' + skeleton[name].index + '].slice()';
					uses_references = true;
					break;
				case this.MEMBER_TYPES.OBJECT:
					object_properties = [];
					if (this._serializeSkeleton(skeleton[name].skeleton, class_data, "\t", object_properties)) {
						uses_references = true;
					}
					serialized_value = object_properties.length
						? "{\n\t" + object_properties.join(",\n\t") + "\n}"
						: "{}";
					break;
				default:
					Lava.t("[_buildRealConstructor] unknown property descriptor type: " + skeleton[name].type);
			}

			if (serialized_value) {

				if (Lava.VALID_PROPERTY_NAME_REGEX.test(name)) {

					constructor_actions.push('this.' + name + ' = ' + serialized_value);

				} else {

					constructor_actions.push('this[' + Firestorm.String.quote(name) + '] = ' + serialized_value);

				}

				serialized_value = null;

			}

		}

		for (name in class_data.shared) {

			prototype[name] = class_data.shared[name];

		}

		prototype.Class = class_data;

		source = (uses_references ? ("var r=this.Class.references;\n") : '')
			+ constructor_actions.join(";\n")
			+ ";";

		if (class_data.skeleton.init) {

			source += "\nthis.init.apply(this, arguments);";

		}

		constructor = new Function(source);
		// for Chrome we could assign prototype object directly,
		// but in Firefox this will result in performance degradation
		Firestorm.extend(constructor.prototype, prototype);
		return constructor;

	}

Instruction: Given a code description, retrieve the corresponding code.


Question: Checks the return statement is valid.

function (node) {
        if (funcInfo.shouldCheck) {
          funcInfo.hasReturn = true

          if (!node.argument) {
            context.report({
              node: node,
              message: 'Expected a return value'
            })
          }
        }
      }

func (f genHelperDecoder) DecFallback(iv interface{}, chkPtr bool) {
	// println(">>>>>>>>> DecFallback")
	rv := reflect.ValueOf(iv)
	if chkPtr {
		rv = f.d.ensureDecodeable(rv)
	}
	f.d.decodeValue(rv, nil, false)
	// f.d.decodeValueFallback(rv)
}

Instruction: Given a code description, retrieve the corresponding code.


Question: // unfreeze server

func (client *Client) ThawServer(id int, planId int) (server *Server, e error) {
	return client.ChangeState(id, STATUS_THAW, planId)
}

protected String pauseMsg() throws IOException {
        final WorkerStatus status = new WorkerStatus();
        status.setRunAt(new Date());
        status.setPaused(isPaused());
        return ObjectMapperFactory.get().writeValueAsString(status);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Reset the randomizer and remove all rigid bodies, shapes, joints and any object from the world.

function(){
        this.randX=65535;
        while(this.joints!==null){
            this.removeJoint(this.joints);
        }
        while(this.contacts!==null){
            this.removeContact(this.contacts);
        }
        while(this.rigidBodies!==null){
            this.removeRigidBody(this.rigidBodies);
        }
        OIMO.nextID=0;
    }

def from_raw(self, robj: RawObject) -> RootNode:

        cooked = self.schema.from_raw(robj)
        return RootNode(cooked, self.schema, cooked.timestamp)

Instruction: Given a code description, retrieve the corresponding code.


Question:
Get the subviews type or key
@memberOf SubViewManager#
@type {SubViewManager}
@param subview
@return {String|Number}

function (subview) {
            subview = (subview instanceof View === true) ? subview : this.get(subview);
            return subview._subviewtype;
        }

func Validate(m []Validation) error {
	for _, item := range m {
		v := reflect.ValueOf(item.TargetValue)
		for _, constraint := range item.Constraints {
			var err error
			switch v.Kind() {
			case reflect.Ptr:
				err = validatePtr(v, constraint)
			case reflect.String:
				err = validateString(v, constraint)
			case reflect.Struct:
				err = validateStruct(v, constraint)
			case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
				err = validateInt(v, constraint)
			case reflect.Float32, reflect.Float64:
				err = validateFloat(v, constraint)
			case reflect.Array, reflect.Slice, reflect.Map:
				err = validateArrayMap(v, constraint)
			default:
				err = createError(v, constraint, fmt.Sprintf("unknown type %v", v.Kind()))
			}

			if err != nil {
				return err
			}
		}
	}
	return nil
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
get fan information

@return void

private function _fans()
    {
        if (CommonFunctions::executeProgram("snmpwalk", "-Ona -c public -v 1 -t ".PSI_SNMP_TIMEOUT_INT." -r ".PSI_SNMP_RETRY_INT." 127.0.0.1 .1.3.6.1.4.1.24681.1.2.15.1.3", $buffer, PSI_DEBUG)) {
            $lines = preg_split('/\r?\n/', $buffer);
            foreach ($lines as $line) if (preg_match('/^[\.\d]+\.(\d+) = STRING:\s\"?(\d+)\sRPM/', $line, $data)) {
                $dev = new SensorDevice();
                $dev->setName("Fan ".$data[1]);
                $dev->setValue($data[2]);
                $this->mbinfo->setMbFan($dev);
            }
        }
    }

final public function startGetReviews($limit = null, $offset = null, array $uids = array(), $responseType = 'xml')
    {
        switch ($responseType) {
            default:
            case 'xml':
                $this->buffer->setFile($this->config->getReviewsXmlPath());
                break;

            case 'json':
                $this->buffer->setFile($this->config->getReviewsJsonPath());
                break;
        }

        $this->createReviews($limit, $offset, $uids);
        $this->buffer->finish();
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Raise an exception in this element

def throw(self, type, value=None, traceback=None):  # pylint: disable=redefined-builtin
        """"""
        return self.__wrapped__.throw(type, value, traceback)

private function checkDevicesTokens()
    {
        $devices = $this->getDevices();
        $adapter = $this->getAdapter();

        foreach ($devices as $device) {
            if (false === $adapter->supports($device->getToken())) {
                throw new AdapterException(
                    sprintf(
                        'Adapter %s does not support %s token\'s device',
                        (string)$adapter,
                        $device->getToken()
                    )
                );
            }
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Generate directory path to be used for pretty URLs.

@return string

protected function getDirectoryPrettyName()
    {
        $pathName = $this->normalizePath($this->file->getPathname());

        // If the post is inside a child directory of the _blog directory then
        // we deal with it like regular site files and generate a nested
        // directories based post path with exact file name.
        if ($this->isInsideBlogDirectory($pathName)) {
            return str_replace('/_blog/', '/', parent::getDirectoryPrettyName());
        }

        $fileBaseName = $this->getFileName();

        $fileRelativePath = $this->getBlogPostSlug($fileBaseName);

        return KATANA_PUBLIC_DIR."/$fileRelativePath";
    }

protected function routeUrl()
    {
        if (! $this->routeGenerator) {
            $this->routeGenerator = new RouteUrlGenerator($this, $this->request);
        }

        return $this->routeGenerator;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
// This gets an active resource from the resource pool.  Note that the
// resourceLocation argument is ignored (The handles are associated to the
// resource location provided by the first Register call).

func (p *simpleResourcePool) Get(unused string) (ManagedHandle, error) {
	activeCount := atomic.AddInt32(p.numActive, 1)
	if p.options.MaxActiveHandles > 0 &&
		activeCount > p.options.MaxActiveHandles {

		atomic.AddInt32(p.numActive, -1)
		return nil, TooManyHandles{p.location}
	}

	highest := atomic.LoadInt32(p.activeHighWaterMark)
	for activeCount > highest &&
		!atomic.CompareAndSwapInt32(
			p.activeHighWaterMark,
			highest,
			activeCount) {

		highest = atomic.LoadInt32(p.activeHighWaterMark)
	}

	if h := p.getIdleHandle(); h != nil {
		return h, nil
	}

	location, err := p.getLocation()
	if err != nil {
		atomic.AddInt32(p.numActive, -1)
		return nil, err
	}

	if p.openTokens != nil {
		// Current implementation does not wait for tokens to become available.
		// If that causes availability hits, we could increase the wait,
		// similar to simple_pool.go.
		if p.openTokens.TryAcquire(0) {
			defer p.openTokens.Release()
		} else {
			// We could not immediately acquire a token.
			// Instead of waiting
			atomic.AddInt32(p.numActive, -1)
			return nil, OpenHandleError{
				p.location, errors.New("Open Error: reached OpenMaxConcurrency")}
		}
	}

	handle, err := p.options.Open(location)
	if err != nil {
		atomic.AddInt32(p.numActive, -1)
		return nil, OpenHandleError{p.location, err}
	}

	return NewManagedHandle(p.location, handle, p, p.options), nil
}

public function initializeArguments()
    {
        parent::initializeArguments();
        $this->registerArgument('results', '\Solarium\QueryType\Select\Result\Result', 'Query results', true);
        $this->registerArgument('document', '\Solarium\QueryType\Select\Result\Document', 'Result document to work on',
            true);
        $this->registerArgument('field', 'string', 'name of field in document to highlight', true);
        $this->registerArgument('alternateField', 'string',
            'name of alternate field in document to use for highlighting', false, null);
        $this->registerArgument('index', 'int', 'if the field is an array: index of the single element to highlight',
            false);
        $this->registerArgument('idKey', 'string', 'name of the field in document that is its ID', false, 'id');
        $this->registerArgument('highlightTagOpen', 'string', 'opening tag to insert to begin highlighting', false,
            '');
        $this->registerArgument('highlightTagClose', 'string', 'closing tag to insert to end highlighting', false,
            '');
        $this->registerArgument('raw', 'boolean', 'whether to not HTML escape the output', false, false);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Adds a line to the LISP code to execute

        :param string: The line to add
        :return: None

def add_line(self, string):

        self.code_strings.append(string)
        code = ''
        if len(self.code_strings) == 1:
            code = '(setv result ' + self.code_strings[0] + ')'
        if len(self.code_strings) > 1:
            code = '(setv result (and ' + ' '.join(self.code_strings) + '))'
        self._compiled_ast_and_expr = self.__compile_code(code_string=code)

def expect_comment_end(self):

        match = self._expect_match('#}', COMMENT_END_PATTERN)
        self.advance(match.end())

Instruction: Given a code description, retrieve the corresponding code.


Question:
Saving image in jpeg to file with quality 55

@param src      source image
@param fileName destination file name
@throws ImageSaveException if it is unable to save image

public static void saveLq(Bitmap src, String fileName) throws ImageSaveException {
        saveJpeg(src, fileName, JPEG_QUALITY_LOW);
    }

public String getContentType() {
        if (contentType == null)
            contentType = getHeaderField("content-type");
        if (contentType == null) {
            String ct = null;
            try {
                ct = guessContentTypeFromStream(getInputStream());
            } catch(java.io.IOException e) {
            }
            String ce = properties.findValue("content-encoding");
            if (ct == null) {
                ct = properties.findValue("content-type");

                if (ct == null)
                    if (url.getFile().endsWith("/"))
                        ct = "text/html";
                    else
                        ct = guessContentTypeFromName(url.getFile());
            }

            /*
             * If the Mime header had a Content-encoding field and its value
             * was not one of the values that essentially indicate no
             * encoding, we force the content type to be unknown. This will
             * cause a save dialog to be presented to the user.  It is not
             * ideal but is better than what we were previously doing, namely
             * bringing up an image tool for compressed tar files.
             */

            if (ct == null || ce != null &&
                    !(ce.equalsIgnoreCase("7bit")
                      || ce.equalsIgnoreCase("8bit")
                      || ce.equalsIgnoreCase("binary")))
                ct = "content/unknown";
            setContentType(ct);
        }
        return contentType;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Get sites.
@api
@param array|bool $blog_ids
@return array

public static function get_sites( $blog_ids = false ) {
		if ( !is_array($blog_ids) ) {
			global $wpdb;
			$blog_ids = $wpdb->get_col("SELECT blog_id FROM $wpdb->blogs ORDER BY blog_id ASC");
		}
		$return = array();
		foreach ( $blog_ids as $blog_id ) {
			$return[] = new Site($blog_id);
		}
		return $return;
	}

private function unparseUrl($data)
    {
        $scheme = isset($data['scheme']) ? $data['scheme'] . '://' : '';
        $host = isset($data['host']) ? $data['host'] : '';
        $port = isset($data['port']) ? ':' . $data['port'] : '';
        $user = isset($data['user']) ? $data['user'] : '';
        $pass = isset($data['pass']) ? ':' . $data['pass'] : '';
        $pass = ($user || $pass) ? "$pass@" : '';
        $path = isset($data['path']) ? $data['path'] : '';
        $query = isset($data['query']) ? '?' . $data['query'] : '';
        $fragment = isset($data['fragment']) ? '#' . $data['fragment'] : '';

        return "$scheme$user$pass$host$port$path$query$fragment";
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Um quadro é uma tabela com linhas verticais
 Esse método especifica a utilização de linhas verticais
 entre as colunas

 Exemplo de entrada: \begin{longtable}[]{@{}clrc@{}}
 saída: \begin{longtable}[]{|c|l|r|c|}

def quadro_com_linhas_verticais(begin_table)
      alinhamento=begin_table.match(/(?<begin>\\begin{longtable}\[.*\]){@{}(?<alinhamento>.*)@{}}/)[:alinhamento]

      qalign = "|"
      alinhamento.split("").each do |c|
        qalign << c + "|"
      end
      "\\begin{longtable}[]{#{qalign}}"
    end

def _build_interpolation(self):

        interpolation = self._interpolation
        self._data_lookup_fn = self._interpolation_fun[interpolation]
        self.shared_program.frag['get_data'] = self._data_lookup_fn

        # only 'bilinear' uses 'linear' texture interpolation
        if interpolation == 'bilinear':
            texture_interpolation = 'linear'
        else:
            # 'nearest' (and also 'bilinear') doesn't use spatial_filters.frag
            # so u_kernel and shape setting is skipped
            texture_interpolation = 'nearest'
            if interpolation != 'nearest':
                self.shared_program['u_kernel'] = self._kerneltex
                self._data_lookup_fn['shape'] = self._data.shape[:2][::-1]

        if self._texture.interpolation != texture_interpolation:
            self._texture.interpolation = texture_interpolation

        self._data_lookup_fn['texture'] = self._texture

        self._need_interpolation_update = False

Instruction: Given a code description, retrieve the corresponding code.


Question: // ReceiveRaw for a message, returned undecoded as a string.

func (c *Client) ReceiveRaw() (message string, err error) {
	_ = c.SetReadDeadline(time.Now().Add(c.ReadTimeout))
	err = websocket.Message.Receive(c.Conn, &message)
	return
}

def content_encoding
      if content_type = headers["content-type"]
        mime_type, charset = content_type.split(SEMICOLON, 2)
        charset = charset[CHARSET_OFFSET] if charset
        charset ||= EMPTY

        if charset.empty? and mime_type.start_with?("text/")
          Encoding::UTF_8
        elsif charset.empty?
          Encoding::BINARY
        else
          ENCODINGS[charset] or raise StompParser::InvalidEncodingError, "invalid encoding #{charset.inspect}"
        end
      else
        Encoding::BINARY
      end
    end

Instruction: Given a code description, retrieve the corresponding code.


Question:
Set a action to be fired when the notification content gets clicked.

@param listener
@param extra

public void setContentAction(Action.OnActionListener listener, Bundle extra) {
        setContentAction(listener, null, null, null, extra);
    }

public function registerClientScript()
    {
    	$view = $this->getView();
    	PNotifyAsset::register($view);

    	$options = empty($this->pluginOptions) ? '' : Json::encode($this->pluginOptions);
    	$js = "new PNotify(".$options.");";

    	$view->registerJs($js);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
@param array[] $arrays

@return array

@see https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/drupal_array_merge_deep_array/7

public static function deepMergePropertiesArray($arrays)
    {
        $result = array();

        foreach ($arrays as $array) {
            foreach ($array as $key => $value) {
                // Renumber integer keys as array_merge_recursive() does. Note that PHP
                // automatically converts array keys that are integer strings (e.g., '1')
                // to integers.
                if (is_integer($key)) {
                    $result[] = $value;
                } // Recurse when both values are arrays.
                elseif (isset($result [$key]) && is_array($result [$key]) && is_array($value)) {
                    $result[$key] = self::deepMergePropertiesArray(array($result [$key], $value));
                } // Otherwise, use the latter value, overriding any previous value.
                else {
                    $result[$key] = $value;
                }
            }
        }

        return $result;
    }

function flatten(srcArr, isDeep) {
      var tmpArr = [];
      forEach(srcArr, function (val) {
        if (isArr(val)) {
          tmpArr.push.apply(tmpArr, isDeep ? flatten(val, true) : val);
        } else {
          tmpArr.push(val);
        }
      });
      return tmpArr;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Returns a uuid / guid for a given byte array.

@param ba
array of bytes containing the id
@return id

public static String fromByteArray(byte[] ba) {
        if ((ba != null) && (ba.length == 16)) {
            StringBuilder result = new StringBuilder(36);
            for (int i = 0; i < 16; ++i) {
                if ((i == 4) || (i == 6) || (i == 8) || (i == 10)) {
                    result.append('-');
                }
                result.append(hexChars.charAt(((ba[i] & 0xF0) >>> 4)));
                result.append(hexChars.charAt((ba[i] & 0xF)));
            }
            return result.toString();
        }
        return null;
    }

function __deserializeObjectId(buffer, start, options) {
	let step = 1;
	let length = 12;
	let end = start + length;
	let dataView = new DataView(buffer);
	let dataArray = [];
	for (let i = start; i < end; i += step) {
		dataArray.push(dataView.getUint8(i));
	}
	let data = new ObjectId(Uint8Array.from(dataArray).buffer);
	return { anchor: end, value: data };
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Runs all tasks in this runner on the executor.
        Blocks until all tasks have been completed.
        :return:

def run(self):

        for task in self.get_next_tasks(None):
            self.executor.add_task(task, None)
        while not self.executor.is_done():
            done_task_and_result = self.executor.wait_for_tasks()
            for task, task_result in done_task_and_result:
                self._add_sub_tasks_to_executor(task, task_result)

func (p *Pipeline) Teardown() {
	for _, id := range p.containers {
		p.engine.ContainerRemove(id)
	}
	close(p.next)
	close(p.done)

	// TODO we have a race condition here where the program can try to async
	// write to a closed pipe channel. This package, in general, needs to be
	// tested for race conditions.
	// close(p.pipe)
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Converts value into JSON string.

@param value the value to convert.
@return JSON string or null when value is null.
@throws JsonProcessingException when conversion fails for any reason.

public static String toJson(Object value) throws JsonProcessingException {
		if (value == null)
			return null;
		return _mapper.writeValueAsString(value);
	}

public Object getDefaultValue(Parameter parameter) {
    Class<?> type = parameter.getType();

    if (TypeUtils.isaString(type)) {
      return getStringDefaultValue(parameter);
    }

    if (TypeUtils.isaByte(type)) {
      return getByteDefaultValue(parameter);
    }

    if (TypeUtils.isaShort(type)) {
      return getShortDefaultValue(parameter);
    }

    if (TypeUtils.isaInteger(type)) {
      return getIntegerDefaultValue(parameter);
    }

    if (TypeUtils.isaLong(type)) {
      return getLongDefaultValue(parameter);
    }

    if (TypeUtils.isaFloat(type)) {
      return getFloatDefaultValue(parameter);
    }

    if (TypeUtils.isaDouble(type)) {
      return getDoubleDefaultValue(parameter);
    }

    if (TypeUtils.isaCharacter(type)) {
      return getCharacterDefaultValue(parameter);
    }

    if (TypeUtils.isaBoolean(type)) {
      return getBooleanDefaultValue(parameter);
    }

    return null;
  }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Returns the next siblings nodes of the current selection.

@return self

@throws \InvalidArgumentException When current node is empty

public function nextAll()
    {
        if (!$this->nodes) {
            throw new \InvalidArgumentException('The current node list is empty.');
        }

        return $this->createSubCrawler($this->sibling($this->getNode(0)));
    }

protected String getItemPath(boolean disabled) {
        String selector = getBaseItemPath();
        String subPath = applyTemplateValue(disabled ? "disabled" : "enabled");
        if (subPath != null) {
            selector += !Strings.isNullOrEmpty(selector) ? " and " + subPath : subPath;
        }
        Map<String, String[]> templatesValues = getTemplatesValues();
        String[] tagAndPositions = templatesValues.get("tagAndPosition");
        List<String> tagAndPosition = new ArrayList<>();
        if (tagAndPositions != null) {
            tagAndPosition.addAll(Arrays.asList(tagAndPositions));
            tagAndPosition.add(0, getTag());
        }
        String tag;
        if (!tagAndPosition.isEmpty()) {
            tag = applyTemplate("tagAndPosition", tagAndPosition.toArray());
        } else {
            tag = getTag();
        }
        selector = getRoot() + tag + (!Strings.isNullOrEmpty(selector) ? "[" + selector + "]" : "");
        return selector;
    }

Instruction: Given a code description, retrieve the corresponding code.