Question: // Checksum returns the 32bits Hash value.

def receive_newblockhashes(proto, newblockhashes)
      logger.debug 'received newblockhashes', num: newblockhashes.size, proto: proto

      newblockhashes = newblockhashes.select {|h| !@chainservice.knows_block(h) }

      known = @protocols.include?(proto)
      if !known || newblockhashes.empty? || @synctask
        logger.debug 'discarding', known: known, synctask: syncing?, num: newblockhashes.size
        return
      end

      if newblockhashes.size != 1
        logger.warn 'supporting only one newblockhash', num: newblockhashes.size
      end
      blockhash = newblockhashes[0]

      logger.debug 'starting synctask for newblockhashes', blockhash: Utils.encode_hex(blockhash)
      @synctask = SyncTask.new self, proto, blockhash, 0, true
    end

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


Question: This function check if a Page has static vars

def check_static_vars(self, node):

        if self.static_vars == "" and hasattr(self, "template"):
            self.static_vars = {
                'upy_context': {
                    'template_name': u"{}/{}".format(self.template.app_name, self.template.file_name)
                }
            }
        elif hasattr(self, "template"):
            self.static_vars = literal_eval(self.static_vars)
            self.static_vars['upy_context']['template_name'] = u"{}/{}".format(
                self.template.app_name, self.template.file_name
            )
        self.static_vars['upy_context']['NODE'] = node
        self.static_vars['upy_context']['PAGE'] = self

public function getServerParam($name)
    {
        $name = strtoupper($name);

        return isset($this->server[$name]) ? $this->server[$name] : false;
    }

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


Question:
@param VideoItemValidator $validator
@param                    $loc
@param                    $playerEmbedded
@param                    $playerAutoPlay

@return string

public static function setPlayerLoc($validator, $loc, $playerEmbedded, $playerAutoPlay)
    {
        self::validateInput(
            $loc,
            $validator,
            'validatePlayerLoc',
            self::$exception,
            'Provided player URL is not a valid value.'
        );

        self::$tag = '<video:player_loc';
        self::setPlayerEmbedded($validator, $playerEmbedded);
        self::setPlayerAutoPlay($validator, $playerAutoPlay);

        self::$tag .= '>'.$loc.'</video:player_loc>';

        return self::$tag;
    }

function namedParameterList()
    {
        $def = array( $this->Name => array( 'context' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => false ),
                                            'comment' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => '' ),
                                            'arguments' => array( 'type' => 'hash',
                                                                  'required' => false,
                                                                  'default' => false ) ),
                      $this->ExtensionName => array( 'extension' => array( 'type' => 'string',
                                                                           'required' => true,
                                                                           'default' => false ),
                                                     'context' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => false ),
                                                     'comment' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => '' ),
                                                     'arguments' => array( 'type' => 'hash',
                                                                           'required' => false,
                                                                           'default' => false ) ) );
        $def[ $this->DynamicName ] = $def[ $this->Name ];
        return $def;
    }

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


Question:
Merging Relative URI path with Base URI path

@param string $path

@return string

protected function mergePath(string $path): string
    {
        $base_path = $this->base_uri->getPath();
        if ('' !== $this->base_uri->getAuthority() && '' === $base_path) {
            return (string) $this->filterPath($path)->withLeadingSlash();
        }

        if ('' !== $base_path) {
            $segments = explode('/', $base_path);
            array_pop($segments);
            $path = implode('/', $segments).'/'.$path;
        }

        return $path;
    }

private static void mergeApiPathParamDoc(ApiPathParam apiPathParam, ApiParamDoc apiParamDoc) {
		if (apiPathParam != null) {
			if (apiParamDoc.getName().trim().isEmpty()) {
				apiParamDoc.setName(apiPathParam.name());
			}
			apiParamDoc.setDescription(apiPathParam.description());
			apiParamDoc.setAllowedvalues(apiPathParam.allowedvalues());
			apiParamDoc.setFormat(apiPathParam.format());
		}
	}

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


Question: Returns a role object

def get_role(self, role):

        role = AuthGroup.objects(role=role, creator=self.client).first()
        return role

func (c *FakeClusterRoles) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *authorization.ClusterRole, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootPatchSubresourceAction(clusterrolesResource, name, pt, data, subresources...), &authorization.ClusterRole{})
	if obj == nil {
		return nil, err
	}
	return obj.(*authorization.ClusterRole), err
}

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


Question: // Limit setup to query.

func (bldr *UserQueryBuilder) Limit(limit int) *UserQueryBuilder {
	bldr.q = bldr.q.Limit(limit)
	if bldr.plugin != nil {
		bldr.plugin.Limit(limit)
	}
	return bldr
}

def _CheckPacketSize(cursor):
  """"""
  cur_packet_size = int(_ReadVariable("max_allowed_packet", cursor))
  if cur_packet_size < MAX_PACKET_SIZE:
    raise Error(
        "MySQL max_allowed_packet of {0} is required, got {1}. "
        "Please set max_allowed_packet={0} in your MySQL config.".format(
            MAX_PACKET_SIZE, cur_packet_size))

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


Question: Main function when running from CLI.

def cli_main():  # pragma: no cover

    if '--debug' in sys.argv:
        LOG.setLevel(logging.DEBUG)
    elif '--verbose' in sys.argv:
        LOG.setLevel(logging.INFO)

    args = _get_arguments()
    try:
        plugin, folder = get_plugin_and_folder(
            inputzip=args.inputzip,
            inputdir=args.inputdir,
            inputfile=args.inputfile)
        LOG.debug('Plugin: %s -- Folder: %s' % (plugin.name, folder))
        run_mq2(
            plugin, folder, lod_threshold=args.lod, session=args.session)
    except MQ2Exception as err:
        print(err)
        return 1
    return 0

func (c *bundleDiffCommand) Info() *cmd.Info {
	return jujucmd.Info(&cmd.Info{
		Name:    "diff-bundle",
		Args:    "<bundle file or name>",
		Purpose: "Compare a bundle with a model and report any differences.",
		Doc:     bundleDiffDoc,
	})
}

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


Question:
Ensures the build directory is in place

@param string $path
@param OutputInterface $output
@return string The directory

protected function ensureBuildDir($path, OutputInterface $output)
    {
        $parts = explode(DIRECTORY_SEPARATOR, $this->getPath());

        foreach ($parts as $part) {
            if (!$part) continue;

            $path .= DIRECTORY_SEPARATOR . $part;

            if (!file_exists($path)) {
                $output->writeln(sprintf('<info>Creating namespace build directory: <comment>%s</comment></info>', $path));
                mkdir($path);
            }
        }

        return $path;
    }

func (c *sioClient) getSioDiskPaths() ([]os.FileInfo, error) {
	files, err := ioutil.ReadDir(sioDiskIDPath)
	if err != nil {
		if os.IsNotExist(err) {
			// sioDiskIDPath may not exist yet which is fine
			return []os.FileInfo{}, nil
		}
		klog.Error(log("failed to ReadDir %s: %v", sioDiskIDPath, err))
		return nil, err

	}
	result := []os.FileInfo{}
	for _, file := range files {
		if c.diskRegex.MatchString(file.Name()) {
			result = append(result, file)
		}
	}

	return result, nil

}

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


Question:
Implements 'select' that does not require changes to any
existing plugin in configuration file(s).

private void executeThis() throws MojoExecutionException {
        // Try to attach agent that will modify Surefire.
        if (AgentLoader.loadEkstaziAgent()) {
            // Prepare initial list of options and set property.
            System.setProperty(AbstractMojoInterceptor.ARGLINE_INTERNAL_PROP, prepareEkstaziOptions());
            // Find non affected classes and set property.
            List<String> nonAffectedClasses = computeNonAffectedClasses();
            System.setProperty(AbstractMojoInterceptor.EXCLUDES_INTERNAL_PROP, Arrays.toString(nonAffectedClasses.toArray(new String[0])));
        } else {
            throw new MojoExecutionException("Ekstazi cannot attach to the JVM, please specify Ekstazi 'restore' explicitly.");
        }
    }

public function addColor(Color $color)
    {
        if (!$this->colors->contains($color)) {
            $this->colors->add($color);
            $color->setInteractionSelection($this);
        }
    }

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


Question:
Set the mode script and restart.
Only available to Admin.
@param string $script
@param bool $multicall
@return bool
@throws InvalidArgumentException

function setModeScriptText($script, $multicall = false)
    {
        if (!is_string($script)) {
            throw new InvalidArgumentException('script = ' . print_r($script, true));
        }

        return $this->execute(ucfirst(__FUNCTION__), array($script), $multicall);
    }

protected function runGenerator($name, array $config, array $args)
    {
        echo $this->renderVersion();

        if (!isset($args[0])) {
            $this->usageError("You must specify a subject for what you are generating.");
        }

        list ($config['context'], $config['subject']) = strpos($args[0], ':') !== false
            ? explode(':', $args[0])
            : array('app', $args[0]);

        echo Line::begin('Running generator', Line::YELLOW)->nl();
        echo Line::begin()
            ->indent(2)
            ->text("Generating $name '{$args[0]}'.")
            ->nl(2);

        $generator = Generator::create($name, $config);

        if (!$generator->validate()) {
            $generator->renderErrors();
        }

        $files = $generator->generate();

        $this->save($files);
    }

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


Question:
Send a ping request to a lambda function.

    :param awsclient:
    :param function_name:
    :param alias_name:
    :param version:
    :return: ping response payload

def ping(awsclient, function_name, alias_name=ALIAS_NAME, version=None):

    log.debug('sending ping to lambda function: %s', function_name)
    payload = '{"ramuda_action": "ping"}'  # default to ping event
    # reuse invoke
    return invoke(awsclient, function_name, payload, invocation_type=None,
                  alias_name=alias_name, version=version)

def update(self, lb, name=None, algorithm=None, protocol=None,
            halfClosed=None, port=None, timeout=None, httpsRedirect=None):

        body = {}
        if name is not None:
            body["name"] = name
        if algorithm is not None:
            body["algorithm"] = algorithm
        if protocol is not None:
            body["protocol"] = protocol
        if halfClosed is not None:
            body["halfClosed"] = halfClosed
        if port is not None:
            body["port"] = port
        if timeout is not None:
            body["timeout"] = timeout
        if httpsRedirect is not None:
            body["httpsRedirect"] = httpsRedirect
        if not body:
            # Nothing passed
            return
        body = {"loadBalancer": body}
        uri = "/loadbalancers/%s" % utils.get_id(lb)
        try:
            resp, resp_body = self.api.method_put(uri, body=body)
        except exc.ClientException as e:
            message = e.message
            details = e.details
            if message and details:
                errmsg = "%s - %s" % (message, details)
            else:
                errmsg = message
            raise exc.InvalidLoadBalancerParameters(errmsg)
        return resp, resp_body

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


Question:
Convert an array to an object
@param array  $array The array to convert
@reeturn object

public static function to_object($array, $recursive = false) {
        if (!is_object($array) && !is_array($array)) return $array;

        if (!$recursive) return (object)$array;

        if (is_array($array)) return (object)array_map([
            __CLASS__,
            'to_object'
        ], $array);
        else return $array;
    }

private function parseOptionsArray($options, \stdClass $result)
    {
        foreach ($options as $option => $value) {
            if (! property_exists($this, $option)) {
                $result->invalidOptions[] = $option;
                continue;
            }

            //Define Option
            $this->$option = $value;
            unset($result->missingOptions[$option]);
        }
    }

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


Question: Clears any caches

@VisibleForTesting
  void clear() {
    insertServiceName.clear();
    if (insertRemoteServiceName != null) insertRemoteServiceName.clear();
    insertSpanName.clear();
    indexer.clear();
    if (insertAutocompleteValue != null) insertAutocompleteValue.clear();
  }

private function reset() : void
    {
        $this->content = [];

        $this->scheme = null;
        $this->brand_label = null;
        $this->brand_uri = null;
    }

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


Question:
Strip the config from the post and return the config and content
in an array.
@param  string $postContent
@param  string $wrap
@return array

public function strip($postContent, $wrap)
    {
        $pattern = '/'.$wrap.'(.*?)'.$wrap.'/s';
        $match = preg_match($pattern, $postContent, $matches);

        if ($match) {
            $post['config'] = $matches[1];
            $post['content'] = str_replace($matches[0], '', $postContent);
            return $post;
        }

        return array('config' => '', 'content' => $postContent);
    }

public function formatOutput(Route $route, Output $output, $type = self::STYLE_DETAIL)
    {
        switch ($type) {
            case self::STYLE_DETAIL:
                $output->write('Route [');
                $output->write('<success>"' . $route->getName() . '"</success>');
                $output->writeln(']');
                $output->writeln("Path:\t\t" . str_replace('//', '/', $route->getPath()));
                $output->writeln("Method:\t\t" . $route->getMethod());
                $output->writeln("Format:\t\t" . implode(', ', $route->getFormats()));
                $output->writeln("Callback:\t" . (is_callable($route->getCallback()) ? 'Closure' : $route->getCallback()));
                $output->writeln("Defaults:\t" . implode(', ', $route->getDefaults()));
                $output->writeln("Requirements:\t" . implode(', ', $route->getRequirements()));
                $output->writeln("Path-Regex:\t" . $route->getPathRegex());
                $output->writeln('');
                break;
            case self::STYLE_LIST:
            default:
                $name = $route->getName();
                $method = $route->getMethod();
                $schema = $route->getScheme() ?? 'http';
                $path = $route->getPath();
                $output->write($name . str_repeat(' ', 25 - strlen($name)));
                $output->write($method . str_repeat(' ', 15 - strlen($method)));
                $output->write($schema . str_repeat(' ', 15 - strlen($schema)));
                $output->writeln($path);
        }

        return;
    }

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


Question: // SetParameterGroupNames sets the ParameterGroupNames field's value.

func (s *DescribeParameterGroupsInput) SetParameterGroupNames(v []*string) *DescribeParameterGroupsInput {
	s.ParameterGroupNames = v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

    if (isLog(4)) {
      log("change getfield " + owner + " name:" + name);
    }
    typeQueryUser = true;
  }

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


Question:
// SetComments sets the comments for the given section or key.
// Use an empty key to set the section comments.

func (ini *INI) SetComments(section, key string, comments ...string) {
	sec := ini.getSection(section)

	if key == "" {
		if sec == nil {
			sec = ini.addSection(section)
		}
		sec.Comments = comments
		return
	}

	if item := sec.getItem(key, ini.isCaseSensitive); item != nil {
		item.Comments = comments
	}
}

public void dataToField(ComponentCache componentCache, int iRowIndex, int iColumnIndex)
    {
        if (componentCache.m_rgcompoments[iColumnIndex] != null)
        {
            String string = null;
            if (componentCache.m_rgcompoments[iColumnIndex] instanceof JTextComponent)
                string = ((JTextComponent)componentCache.m_rgcompoments[iColumnIndex]).getText();
            if (componentCache.m_rgcompoments[iColumnIndex] instanceof JCheckBox)
                if (((JCheckBox)componentCache.m_rgcompoments[iColumnIndex]).isSelected())
                    string = "1";
            //xif (string != null) if (string.length() > 0)
            this.getModel().setValueAt(string, iRowIndex, iColumnIndex);
        }
    }

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


Question: Move file to a new destination and update ``uri``.

def move(self, dst, **kwargs):
        """"""
        _fs, filename = opener.parse(self.uri)
        _fs_dst, filename_dst = opener.parse(dst)
        movefile(_fs, filename, _fs_dst, filename_dst, **kwargs)
        self.uri = dst

func (up UnitPayloads) SetStatus(name, status string) error {
	if err := payload.ValidateState(status); err != nil {
		return errors.Trace(err)
	}

	change := payloadSetStatusChange{
		Unit:   up.unit,
		Name:   name,
		Status: status,
	}
	if err := Apply(up.db, change); err != nil {
		return errors.Trace(err)
	}
	return nil
}

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


Question: Calculate paths etc

function () {

		var series = this,
			yAxis = series.yAxis,
			options = series.options,
			center = yAxis.center;

		series.generatePoints();

		each(series.points, function (point) {

			var dialOptions = merge(options.dial, point.dial),
				radius = (pInt(pick(dialOptions.radius, 80)) * center[2]) / 200,
				baseLength = (pInt(pick(dialOptions.baseLength, 70)) * radius) / 100,
				rearLength = (pInt(pick(dialOptions.rearLength, 10)) * radius) / 100,
				baseWidth = dialOptions.baseWidth || 3,
				topWidth = dialOptions.topWidth || 1,
				overshoot = options.overshoot,
				rotation = yAxis.startAngleRad + yAxis.translate(point.y, null, null, null, true);

			// Handle the wrap and overshoot options
			if (overshoot && typeof overshoot === 'number') {
				overshoot = overshoot / 180 * Math.PI;
				rotation = Math.max(yAxis.startAngleRad - overshoot, Math.min(yAxis.endAngleRad + overshoot, rotation));

			} else if (options.wrap === false) {
				rotation = Math.max(yAxis.startAngleRad, Math.min(yAxis.endAngleRad, rotation));
			}

			rotation = rotation * 180 / Math.PI;

			point.shapeType = 'path';
			point.shapeArgs = {
				d: dialOptions.path || [
					'M',
					-rearLength, -baseWidth / 2,
					'L',
					baseLength, -baseWidth / 2,
					radius, -topWidth / 2,
					radius, topWidth / 2,
					baseLength, baseWidth / 2,
					-rearLength, baseWidth / 2,
					'z'
				],
				translateX: center[0],
				translateY: center[1],
				rotation: rotation
			};

			// Positions for data label
			point.plotX = center[0];
			point.plotY = center[1];
		});
	}

public function process(array $items)
    {
        foreach ($items as $key => $item) {
            $items[$key] = $this->fixPaths($item);
        }

        return $items;
    }

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


Question:
Get Entity Value

@param mixed $key Entity Key
@param null $default Default If Not Value/Key Exists

@return mixed|null
@throws exIOError

function get($key, $default = null)
    {
        \Poirot\Storage\assertKey($key);

        return ( isset($this->data[$key]) ) ? $this->data[$key] : $default;
    }

def _parse_caps_cpu(node):
    '''

    '''
    result = {}
    for mode in node.findall('mode'):
        if not mode.get('supported') == 'yes':
            continue

        name = mode.get('name')
        if name == 'host-passthrough':
            result[name] = True

        elif name == 'host-model':
            host_model = {}
            model_node = mode.find('model')
            if model_node is not None:
                model = {
                    'name': model_node.text
                }

                vendor_id = model_node.get('vendor_id')
                if vendor_id:
                    model['vendor_id'] = vendor_id

                fallback = model_node.get('fallback')
                if fallback:
                    model['fallback'] = fallback
                host_model['model'] = model

            vendor = mode.find('vendor').text if mode.find('vendor') is not None else None
            if vendor:
                host_model['vendor'] = vendor

            features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')}
            if features:
                host_model['features'] = features

            result[name] = host_model

        elif name == 'custom':
            custom_model = {}
            models = {model.text: model.get('usable') for model in mode.findall('model')}
            if models:
                custom_model['models'] = models
            result[name] = custom_model

    return result

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


Question:
Returns the version of the Aimeos package

@return string Version string

public function getVersion()
	{
		if( ( $content = @file_get_contents( base_path( 'composer.lock' ) ) ) !== false
			&& ( $content = json_decode( $content, true ) ) !== null && isset( $content['packages'] )
		) {
			foreach( (array) $content['packages'] as $item )
			{
				if( $item['name'] === 'aimeos/aimeos-laravel' ) {
					return $item['version'];
				}
			}
		}

		return '';
	}

public function generateTo($directory){
        $translations = array();

        foreach($this->extensions as $extension){
            $jsFilePath = $this->basePath . '/' . $extension . '/locales/' . $this->langCode . '/messages_po.js';
            if(file_exists($jsFilePath)){
                $translate = json_decode(file_get_contents($jsFilePath),false);
                if($translate != null){
                    $translations = array_merge($translations, (array)$translate);
                }
            }
        }
        //the bundle contains as well some translations
        $content = array(
            'serial' =>  $this->getSerial(),
            'date'   => time(),
            'translations' =>   $translations
        );

        if (!empty($this->taoVersion)) {
            $content['version'] = $this->taoVersion;
        }

        if(is_dir($directory)){
            if(!is_dir($directory. '/' . $this->langCode)){
                mkdir($directory. '/' . $this->langCode);
            }
            $file = $directory. '/' . $this->langCode . '/messages.json';
            if(@file_put_contents($file, json_encode($content))){
                return $file;
            }
        }
        return false;
    }

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


Question:
Returns the mailer to send emails

@return Swift_Mailer

public function getMailer() {
		if ($this->mailer === null) {
			$prefs = $this->getPreferenceLoader()->getSystemPreferences();
			switch ($prefs->getMailTransport()) {
				case SystemPreferences::MAIL_TRANSPORT_SMTP:
					$transport = new Swift_SmtpTransport($prefs->getSmtpServer(), $prefs->getSmtpPort());
					$transport->setUsername($prefs->getSmtpUsername());
					$transport->setPassword($prefs->getSmtpPassword());
					$encryption = $prefs->getSmtpEncryption();
					if ($encryption != SystemPreferences::SMTP_ENCRYPTION_NONE) {
						$transport->setEncryption($encryption);
					}
					break;

				case SystemPreferences::MAIL_TRANSPORT_SENDMAIL:
					$transport = new Swift_SendmailTransport($prefs->getSendmail());
					break;

				case SystemPreferences::MAIL_TRANSPORT_MAIL:
				default:
					$transport = new Swift_MailTransport();
					break;
			}

			$this->mailer = new Swift_Mailer($transport);
		}

		return $this->mailer;
	}

def read(self):
    ""
    log.msg('APNSService read (connecting)')
    try:
      server, port = ((FEEDBACK_SERVER_SANDBOX_HOSTNAME
                      if self.environment == 'sandbox'
                      else FEEDBACK_SERVER_HOSTNAME), FEEDBACK_SERVER_PORT)
      factory = self.feedbackProtocolFactory()
      context = self.getContextFactory()
      reactor.connectSSL(server, port, factory, context)
      factory.deferred.addErrback(log_errback('apns-feedback-read'))

      timeout = reactor.callLater(self.timeout,
        lambda: factory.deferred.called or factory.deferred.errback(
          Exception('Feedbcak fetch timed out after %i seconds' % self.timeout)))
      def cancel_timeout(r):
        try: timeout.cancel()
        except: pass
        return r

      factory.deferred.addBoth(cancel_timeout)
    except Exception, e:
      log.err('APNService feedback error initializing: %s' % str(e))
      raise
    return factory.deferred

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


Question:
Checks/fixes so the VAT input is valid.

@param float &$vat VAT.

@throws KlarnaException
@return void

private function _checkVAT(&$vat)
    {
        if (!isset($vat)) {
            throw new Klarna_ArgumentNotSetException("VAT");
        }
        if (is_numeric($vat) && (!is_int($vat) || !is_float($vat))) {
            $vat = floatval($vat);
        }
        if (!is_numeric($vat) || (!is_int($vat) && !is_float($vat))) {
            throw new Klarna_InvalidTypeException("VAT", "integer or float");
        }
    }

public static function findParamValue(&$value, &$operator): bool
    {
        if (is_array($value) || is_object($value)) {
            $value = static::assembleParamValue($value, $operator);
        } else {
            self::normalizeEmptyValue($value);

            $operator = self::parseParamOperator($value);

            if (is_numeric($value)) {
                $value = self::prependOperator($value, $operator);
            } else {
                $value = StringHelper::toLowerCase($value);

                if ($value !== ':empty:' || $value !== 'not :empty:') {
                    // Trim any whitespace from the value
                    $value = StringHelper::trim($value);

                    return false;
                }
            }
        }

        return true;
    }

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


Question:
Publishes the given node to the specified targetWorkspace

@param NodeInterface $node
@param string $targetWorkspaceName
@return void

public function publishNodeAction(NodeInterface $node, $targetWorkspaceName = null)
    {
        $targetWorkspace = ($targetWorkspaceName !== null) ? $this->workspaceRepository->findOneByName($targetWorkspaceName) : null;
        $this->publishingService->publishNode($node, $targetWorkspace);

        $this->throwStatus(204, 'Node published', '');
    }

def set_args(self, args, unknown_args=None):

        if unknown_args is None:
            unknown_args = []
        self.logger.setLevel(getattr(logging, args.log_level))

        parent = hdfs.path.dirname(hdfs.path.abspath(args.output.rstrip("/")))
        self.remote_wd = hdfs.path.join(
            parent, utils.make_random_str(prefix="pydoop_submit_")
        )
        self.remote_exe = hdfs.path.join(self.remote_wd, str(uuid.uuid4()))
        self.properties[JOB_NAME] = args.job_name or 'pydoop'
        self.properties[IS_JAVA_RR] = (
            'false' if args.do_not_use_java_record_reader else 'true'
        )
        self.properties[IS_JAVA_RW] = (
            'false' if args.do_not_use_java_record_writer else 'true'
        )
        self.properties[JOB_REDUCES] = args.num_reducers
        if args.job_name:
            self.properties[JOB_NAME] = args.job_name
        self.properties.update(args.job_conf or {})
        self.__set_files_to_cache(args)
        self.__set_archives_to_cache(args)
        self.requested_env = self._env_arg_to_dict(args.set_env or [])
        self.args = args
        self.unknown_args = unknown_args

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


Question:
Retrieves the requested column's data from the given row.

    @cat_time_ns: If the column_name has "_time" in it, will concatenate
    the column with any column having the same name but "_time_ns".

def get_row_data(row, column_name, cat_time_ns = True):

    column_name_ns = re.sub(r'_time', r'_time_ns', column_name)
    try:
        rowattrs = [attr for attr in row.__slots__]
    except AttributeError:
        rowattrs = [attr for attr in row.__dict__.iterkeys()]

    if cat_time_ns and "_time" in column_name and column_name_ns in rowattrs:
        return int(getattr(row, column_name)) + 10**(-9.)*int(getattr(row, column_name_ns))
    else:
        return getattr(row, column_name)

static public HsqlName getAutoColumnName(int i) {

        if (i < autoColumnNames.length) {
            return autoColumnNames[i];
        }

        return new HsqlName(staticManager, makeAutoColumnName("C_", i), 0, false);
    }

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


Question:
// PerformUpgrade runs the business logic needed to upgrade the current "from" version to this
// version of Juju on the "target" type of machine.

func PerformUpgrade(from version.Number, targets []Target, context Context) error {
	if hasStateTarget(targets) {
		ops := newStateUpgradeOpsIterator(from)
		if err := runUpgradeSteps(ops, targets, context.StateContext()); err != nil {
			return err
		}
	}
	ops := newUpgradeOpsIterator(from)
	if err := runUpgradeSteps(ops, targets, context.APIContext()); err != nil {
		return err
	}
	logger.Infof("All upgrade steps completed successfully")
	return nil
}

def invoke(tasks)
      remote_shell do |shell|
        # setup the deployment repository
        invoke_task(:setup,shell) if tasks.include?(:setup)

        # cd into the deployment repository
        shell.cd(shell.uri.path)

        # update the deployment repository
        invoke_task(:update,shell) if tasks.include?(:update)

        # framework tasks
        invoke_task(:install,shell) if tasks.include?(:install)
        invoke_task(:migrate,shell) if tasks.include?(:migrate)

        # server tasks
        if tasks.include?(:config)
          invoke_task(:config,shell)
        elsif tasks.include?(:start)
          invoke_task(:start,shell)
        elsif tasks.include?(:stop)
          invoke_task(:stop,shell)
        elsif tasks.include?(:restart)
          invoke_task(:restart,shell)
        end
      end

      return true
    end

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


Question:
Reverses bytes.

@param bytes bytes.
@return reversed byte array.

public static byte[] reverse(byte... bytes) {
        byte[] res = new byte[bytes.length];
        int j = 0;
        for (int i = bytes.length - 1; i >= 0; i--) {
            res[j] = bytes[i];
            j++;
        }
        return res;
    }

protected void setByteArrayValue(byte[] input, int offset, int length) {
        if ((offset + length) > input.length) {
            throw new IllegalArgumentException(
                            "Invalid length: " + offset + "+" + length + " > " + input.length);
        }
        this.sValue = null;
        this.bValue = input;
        this.offset = offset;
        this.valueLength = length;
        if (ELEM_ADDED != this.status) {
            this.status = ELEM_CHANGED;
        }
    }

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


Question: /* OBJECT CLASSES /* REGION

function attachExtensions(root, parent, maps)
  {
    this.root = root;
    this.pointers = [];
    this.parent = parent;
    this.maps = maps;
    Object.defineProperties(this, {
      localmaps: setDescriptorLocalMaps(parent),
      subnodes: setDescriptorSubNodes(parent)
    })
  }

public function setProvincia(\Matudelatower\UbicacionBundle\Entity\Provincia $provincia = null) {
        $this->provincia = $provincia;

        return $this;
    }

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


Question:
Trims string values of given array and returns the new array

@param array $array The array which values should be trimmed
@return array

public static function trimRecursive(array $array)
    {
        /*
         * No elements?
         * Nothing to do
         */
        if (empty($array)) {
            return [];
        }

        $result = [];

        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $result[$key] = self::trimRecursive($value);

                continue;
            }

            if (is_string($value)) {
                $value = trim($value);
            }

            $result[$key] = $value;
        }

        return $result;
    }

protected function filter()
	{
		foreach ($this->filters as $attribute => $filters) {
			// Check if the attribute is present in the input data
			if (!array_key_exists($attribute, $this->data)) {
				continue;
			}

			$data = $this->data[$attribute];

			foreach ($filters as $filter) {
				// The format for specifying filter and parameters follows an
				// easy {filter}:{parameters} formatting convention.
				if (strpos($filter, ':') !== false) {
					list($filter, $parameterList) = explode(':', $filter, 2);
					$parameters = explode(',', $parameterList);
				} else {
					$parameters = [];
				}

				if (method_exists($this, $this->camelCase($filter))) {
					$data = $this->filterWalker($filter, $data, $parameters);
				} elseif (isset($this->extensions[$filter])) {
					$data = $this->filterExtensionWalker($filter, $data, $parameters);
				} else {
					throw new \Exception("'$filter' is not a valid filter.");
				}
			}

			$this->filteredData[$attribute] = $data;
		}

		return $this->filteredData;
	}

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


Question:
Converts TMS tile coordinates to QuadTree

@param pMapTileIndex
The tile coordinates to convert
@return The QuadTree as String.

protected String quadTree(final long pMapTileIndex) {
		final StringBuilder quadKey = new StringBuilder();
		for (int i = MapTileIndex.getZoom(pMapTileIndex); i > 0; i--) {
			int digit = 0;
			final int mask = 1 << (i - 1);
			if ((MapTileIndex.getX(pMapTileIndex) & mask) != 0)
				digit += 1;
			if ((MapTileIndex.getY(pMapTileIndex) & mask) != 0)
				digit += 2;
			quadKey.append("" + digit);
		}

		return quadKey.toString();
	}

def to_array(self):

        array = super(InlineQueryResultLocation, self).to_array()
        # 'type' and 'id' given by superclass
        array['latitude'] = float(self.latitude)  # type float
        array['longitude'] = float(self.longitude)  # type float
        array['title'] = u(self.title)  # py2: type unicode, py3: type str
        if self.live_period is not None:
            array['live_period'] = int(self.live_period)  # type int
        if self.reply_markup is not None:
            array['reply_markup'] = self.reply_markup.to_array()  # type InlineKeyboardMarkup
        if self.input_message_content is not None:
            array['input_message_content'] = self.input_message_content.to_array()  # type InputMessageContent
        if self.thumb_url is not None:
            array['thumb_url'] = u(self.thumb_url)  # py2: type unicode, py3: type str
        if self.thumb_width is not None:
            array['thumb_width'] = int(self.thumb_width)  # type int
        if self.thumb_height is not None:
            array['thumb_height'] = int(self.thumb_height)  # type int
        return array

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


Question:
Shallow tuple copy.
@return A new Tuple with the same fields as this.

@Override
	@SuppressWarnings("unchecked")
	public Tuple3<T0, T1, T2> copy() {
		return new Tuple3<>(this.f0,
			this.f1,
			this.f2);
	}

def set_sampled_topics(self, sampled_topics):

        assert sampled_topics.dtype == np.int and \
            len(sampled_topics.shape) <= 2

        if len(sampled_topics.shape) == 1:
            self.sampled_topics = \
                sampled_topics.reshape(1, sampled_topics.shape[0])
        else:
            self.sampled_topics = sampled_topics

        self.samples = self.sampled_topics.shape[0]

        self.tt = self.tt_comp(self.sampled_topics)
        self.dt = self.dt_comp(self.sampled_topics)

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


Question: Returns a RelaxNG definition for this element (as an XML element (lxml.etree) rather than a string)

def relaxng(cls, includechildren=True,extraattribs = None, extraelements=None, origclass = None):
        """"""

        E = ElementMaker(namespace="http://relaxng.org/ns/structure/1.0",nsmap={None:'http://relaxng.org/ns/structure/1.0' , 'folia': "http://ilk.uvt.nl/folia", 'xml' : "http://www.w3.org/XML/1998/namespace",'a':"http://relaxng.org/ns/annotation/0.9" })

        if origclass: cls = origclass

        preamble = []
        try:
            if cls.__doc__:
                E2 = ElementMaker(namespace="http://relaxng.org/ns/annotation/0.9", nsmap={'a':'http://relaxng.org/ns/annotation/0.9'} )
                preamble.append(E2.documentation(cls.__doc__))
        except AttributeError:
            pass

        if cls.REQUIRED_ATTRIBS is None: cls.REQUIRED_ATTRIBS = () #bit hacky
        if cls.OPTIONAL_ATTRIBS is None: cls.OPTIONAL_ATTRIBS = () #bit hacky

        attribs = [ ]
        if cls.REQUIRED_ATTRIBS and Attrib.ID in cls.REQUIRED_ATTRIBS:
            attribs.append( E.attribute(E.data(type='ID',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),name='id', ns="http://www.w3.org/XML/1998/namespace") )
        elif Attrib.ID in cls.OPTIONAL_ATTRIBS:
            attribs.append( E.optional( E.attribute(E.data(type='ID',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'), name='id', ns="http://www.w3.org/XML/1998/namespace") ) )
        if Attrib.CLASS in cls.REQUIRED_ATTRIBS:
            #Set is a tough one, we can't require it as it may be defined in the declaration: we make it optional and need schematron to resolve this later
            attribs.append( E.attribute(E.data(type='string',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),name='class') )
            attribs.append( E.optional( E.attribute( E.data(type='string',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),name='set' ) ) )
        elif Attrib.CLASS in cls.OPTIONAL_ATTRIBS:
            attribs.append( E.optional( E.attribute(E.data(type='string',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),name='class') ) )
            attribs.append( E.optional( E.attribute(E.data(type='string',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'), name='set' ) ) )
        if Attrib.ANNOTATOR in cls.REQUIRED_ATTRIBS or Attrib.ANNOTATOR in cls.OPTIONAL_ATTRIBS:
            #Similarly tough
            attribs.append( E.optional( E.attribute(E.data(type='string',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'), name='annotator') ) )
            attribs.append( E.optional( E.attribute(name='annotatortype') ) )
        if Attrib.CONFIDENCE in cls.REQUIRED_ATTRIBS:
            attribs.append(  E.attribute(E.data(type='double',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'), name='confidence') )
        elif Attrib.CONFIDENCE in cls.OPTIONAL_ATTRIBS:
            attribs.append(  E.optional( E.attribute(E.data(type='double',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'), name='confidence') ) )
        if Attrib.N in cls.REQUIRED_ATTRIBS:
            attribs.append( E.attribute( E.data(type='string',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),name='n') )
        elif Attrib.N in cls.OPTIONAL_ATTRIBS:
            attribs.append( E.optional( E.attribute( E.data(type='string',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),name='n') ) )
        if Attrib.DATETIME in cls.REQUIRED_ATTRIBS:
            attribs.append( E.attribute(E.data(type='dateTime',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'), name='datetime') )
        elif Attrib.DATETIME in cls.OPTIONAL_ATTRIBS:
            attribs.append( E.optional( E.attribute( E.data(type='dateTime',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),  name='datetime') ) )
        if Attrib.BEGINTIME in cls.REQUIRED_ATTRIBS:
            attribs.append(E.attribute(name='begintime') )
        elif Attrib.BEGINTIME in cls.OPTIONAL_ATTRIBS:
            attribs.append( E.optional( E.attribute(name='begintime') ) )
        if Attrib.ENDTIME in cls.REQUIRED_ATTRIBS:
            attribs.append(E.attribute(name='endtime') )
        elif Attrib.ENDTIME in cls.OPTIONAL_ATTRIBS:
            attribs.append( E.optional( E.attribute(name='endtime') ) )
        if Attrib.SRC in cls.REQUIRED_ATTRIBS:
            attribs.append(E.attribute(E.data(type='anyURI',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),name='src') )
        elif Attrib.SRC in cls.OPTIONAL_ATTRIBS:
            attribs.append( E.optional( E.attribute(E.data(type='anyURI',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),name='src') ) )
        if Attrib.SPEAKER in cls.REQUIRED_ATTRIBS:
            attribs.append(E.attribute(E.data(type='string',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'), name='speaker') )
        elif Attrib.SPEAKER in cls.OPTIONAL_ATTRIBS:
            attribs.append( E.optional( E.attribute(E.data(type='string',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),name='speaker') ) )
        if Attrib.TEXTCLASS in cls.REQUIRED_ATTRIBS:
            attribs.append(E.attribute(name='textclass') )
        elif Attrib.TEXTCLASS in cls.OPTIONAL_ATTRIBS:
            attribs.append( E.optional( E.attribute(name='textclass') ) )
        if Attrib.METADATA in cls.REQUIRED_ATTRIBS:
            attribs.append(E.attribute(name='metadata') )
        elif Attrib.METADATA in cls.OPTIONAL_ATTRIBS:
            attribs.append( E.optional( E.attribute(name='metadata') ) )
        if cls.XLINK:
            attribs += [ #loose interpretation of specs, not checking whether xlink combinations are valid
                    E.optional(E.attribute(name='href',ns="http://www.w3.org/1999/xlink"),E.attribute(name='type',ns="http://www.w3.org/1999/xlink") ),
                    E.optional(E.attribute(name='role',ns="http://www.w3.org/1999/xlink")),
                    E.optional(E.attribute(name='title',ns="http://www.w3.org/1999/xlink")),
                    E.optional(E.attribute(name='label',ns="http://www.w3.org/1999/xlink")),
                    E.optional(E.attribute(name='show',ns="http://www.w3.org/1999/xlink")),
            ]

        attribs.append( E.optional( E.attribute( name='auth' ) ) )

        if extraattribs:
            for e in extraattribs:
                attribs.append(e) #s

        attribs.append( E.ref(name="allow_foreign_attributes") )

        elements = [] #(including attributes)
        if cls.TEXTCONTAINER or cls.PHONCONTAINER:
            elements.append( E.text())
            #We actually want to require non-empty text (E.text() is not sufficient)
            #but this is not solved yet, see https://github.com/proycon/folia/issues/19
            #elements.append( E.data(E.param(r".+",name="pattern"),type='string'))
            #elements.append( E.data(E.param(r"(.|\n|\r)*\S+(.|\n|\r)*",name="pattern"),type='string'))
        done = {}
        if includechildren and cls.ACCEPTED_DATA: #pylint: disable=too-many-nested-blocks
            for c in cls.ACCEPTED_DATA:
                if c.__name__[:8] == 'Abstract' and inspect.isclass(c):
                    for c2 in globals().values():
                        try:
                            if inspect.isclass(c2) and issubclass(c2, c):
                                try:
                                    if c2.XMLTAG and c2.XMLTAG not in done:
                                        if c2.OCCURRENCES == 1:
                                            elements.append( E.optional( E.ref(name=c2.XMLTAG) ) )
                                        else:
                                            elements.append( E.zeroOrMore( E.ref(name=c2.XMLTAG) ) )
                                            if c2.XMLTAG == 'item': #nasty hack for backward compatibility with deprecated listitem element
                                                elements.append( E.zeroOrMore( E.ref(name='listitem') ) )
                                        done[c2.XMLTAG] = True
                                except AttributeError:
                                    continue
                        except TypeError:
                            pass
                elif issubclass(c, Feature) and c.SUBSET:
                    attribs.append( E.optional( E.attribute(name=c.SUBSET)))  #features as attributes
                else:
                    try:
                        if c.XMLTAG and c.XMLTAG not in done:
                            if cls.REQUIRED_DATA and c in cls.REQUIRED_DATA:
                                if c.OCCURRENCES == 1:
                                    elements.append( E.ref(name=c.XMLTAG) )
                                else:
                                    elements.append( E.oneOrMore( E.ref(name=c.XMLTAG) ) )
                            elif c.OCCURRENCES == 1:
                                elements.append( E.optional( E.ref(name=c.XMLTAG) ) )
                            else:
                                elements.append( E.zeroOrMore( E.ref(name=c.XMLTAG) ) )
                                if c.XMLTAG == 'item':
                                    #nasty hack for backward compatibility with deprecated listitem element
                                    elements.append( E.zeroOrMore( E.ref(name='listitem') )  )
                            done[c.XMLTAG] = True
                    except AttributeError:
                        continue

        if extraelements:
            for e in extraelements:
                elements.append( e )

        if elements:
            if len(elements) > 1:
                attribs.append( E.interleave(*elements) )
            else:
                attribs.append( *elements )

        if not attribs:
            attribs.append( E.empty() )

        if cls.XMLTAG in ('desc','comment'):
            return E.define( E.element(E.text(), *(preamble + attribs), **{'name': cls.XMLTAG}), name=cls.XMLTAG, ns=NSFOLIA)
        else:
            return E.define( E.element(*(preamble + attribs), **{'name': cls.XMLTAG}), name=cls.XMLTAG, ns=NSFOLIA)

def _clean(self):
        """"""
        found_ids = {}
        nodes = [self._nodes[_node.Root.ID]]
        while nodes:
            node = nodes.pop()
            found_ids[node.id] = None
            nodes = nodes + node.children

        for node_id in self._nodes:
            if node_id in found_ids:
                continue
            logger.error('Dangling node: %s', node_id)

        for node_id in found_ids:
            if node_id in self._nodes:
                continue
            logger.error('Unregistered node: %s', node_id)

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


Question: ikkatsu : ikkatsuline+

def parse_ikkatsu
      s0 = @current_pos
      s2 = parse_ikkatsu_line
      if s2 != :failed
        s1 = []
        while s2 != :failed
          s1 << s2
          s2 = parse_ikkatsu_line
        end
      else
        s1 = :failed
      end
      if s1 != :failed
        @reported_pos = s0
        s1 = -> (lines) do
          board = []
          9.times do |i|
            line = []
            9.times do |j|
              line << lines[j][8 - i]
            end
            board << line
          end
          { "preset" => "OTHER", "data" => { "board" => board } }
        end.call(s1)
      end
      s0 = s1
      s0
    end

public function votePlus($post_id)
    {
        $this->checkId($post_id);

        return $this->vote($post_id, self::VOTE_PLUS);
    }

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


Question: Connect the provided channels

def connect_channels(self, channels):
        """"""
        self.log.info(f"Connecting to channels...")
        for chan in channels:
            chan.connect(self.sock)
            self.log.info(f"\t{chan.channel}")

func (b block) invoke(ch chan<- block) error {
	for {
		select {
		case <-b.stop:
			return errStopped
		case <-b.cancel:
			return lease.ErrWaitCancelled
		case ch <- b:
			ch = nil
		case <-b.unblock:
			return nil
		}
	}
}

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


Question:
Show a single post.
@param string $postName The name of the post to retrieve.
@return \View

public function showPost($category, $postName)
    {
        if (!$this->post->exists($category, $postName)) {
            return \Response::view($this->theme.'.404', array('global' => $this->global), 404);
        }

        $post = $this->post->getPost($category, $postName);
        $category = $this->category->getCategory($category);

        $viewParamaters = array(
            'post' => $post,
            'global' => $this->global,
            'category' => $category
        );

        return \View::make($this->theme.'.post', $viewParamaters);
    }

public static function findParamValue(&$value, &$operator): bool
    {
        if (is_array($value) || is_object($value)) {
            $value = static::assembleParamValue($value, $operator);
        } else {
            self::normalizeEmptyValue($value);

            $operator = self::parseParamOperator($value);

            if (is_numeric($value)) {
                $value = self::prependOperator($value, $operator);
            } else {
                $value = StringHelper::toLowerCase($value);

                if ($value !== ':empty:' || $value !== 'not :empty:') {
                    // Trim any whitespace from the value
                    $value = StringHelper::trim($value);

                    return false;
                }
            }
        }

        return true;
    }

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


Question:
Make server sockets

@throws SocketException|\Exception
@return void

protected function makeSocket(): void
    {
        if ($this->useSSL) {
            if (!file_exists($this->cert)) {
                throw new \Exception('Cert file not found');
            }

            $context = stream_context_create([
                'ssl' => [
                    'local_cert'        => $this->cert,
                    'passphrase'        => $this->passPhrase,
                    'verify_peer'       => false,
                    'verify_peer_name'  => false,
                    'allow_self_signed' => true,
                    'verify_depth'      => 0
                ]
            ]);

            $protocol = 'ssl';
        } else {
            $context = stream_context_create();
            $protocol = 'tcp';
        }

        $this->socket = stream_socket_server("$protocol://{$this->host}:{$this->port}", $errorNumber, $errorString, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $context);

        if ($this->useConnector) {
            if (file_exists(static::$connector)) {
                unlink(static::$connector);
            }

            $this->unixConnector = stream_socket_server('unix://' . static::$connector, $errorNumber, $errorString, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN);
            chmod(static::$connector, 0777);
        }

        if (!$this->socket) {
            throw new SocketException($errorString, $errorNumber);
        }
    }

func (c *Client) SetServerHost(host string, port int) {
	c.serverAddr = net.JoinHostPort(host, strconv.Itoa(port))
}

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


Question:
Calling this method only makes sense if the whole LC/MS structure has been parsed.

@param scans the scan collection, it will be modified in-place

public static void finalizePrecursorWindows(IScanCollection scans) {
    TreeMap<Integer, IntervalST<Double, TreeMap<Integer, IScan>>> mapMsLevel2rangeGroups = scans
        .getMapMsLevel2rangeGroups();

    List<Integer> msLevelsToRemove = new ArrayList<>();

    msLevelLoop:
    for (Map.Entry<Integer, IntervalST<Double, TreeMap<Integer, IScan>>> entry : mapMsLevel2rangeGroups
        .entrySet()) {

      int msLevel = entry.getKey();
      IntervalST<Double, TreeMap<Integer, IScan>> rangeMapMS2 = entry.getValue();

      if (rangeMapMS2.size() == 1) {
        msLevelsToRemove.add(msLevel);
      } else {
        // if we have a precursor range map, we want to see if it actually contains
        // ranges that have lots of MS2 spectra in them.
        // ALL ranges are required to have more than 1 MS2 spectra

        for (IntervalST.Node<Double, TreeMap<Integer, IScan>> node : rangeMapMS2) {
          if (node.getValue().size() <= 1) {
            // if we didn't have at least 1 scans in even one range, then discard the whole sub-tree
            msLevelsToRemove.add(msLevel);
            continue msLevelLoop;
          }
        }

        // we also check that all ranges contain approximately equal amount of scans
        // THIS WILL NOT WORK FOR MSX DATA, UNLESS "maxScanCountDiff" is set to some large value, which
        // should be at least [ms1_mz_range / (msx_isolation_width * msx_multiplex_number)]
        if (!isAllRangesHaveApproxSameScanCounts(rangeMapMS2)) {
          msLevelsToRemove.add(msLevel);
          continue msLevelLoop;
        }

        // otherwise we just keep it there, but the tree needs to be recreated, because the ranges are incorrect
      }
    }
      for (Integer msLevel : msLevelsToRemove) {
          mapMsLevel2rangeGroups.remove(msLevel);
      }
  }

public ReadOnlyStyledDocumentBuilder<PS, SEG, S> addParagraph(SEG segment, S style, PS paragraphStyle) {
        return addPar(new Paragraph<>(argumentOrDefault(paragraphStyle), segmentOps, segment, style));
    }

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


Question:
@param Validator $validator
@param mixed $object

@param $forScenario

@return bool

public function validate(Validator $validator, $object, $forScenario)
    {
        if (!is_array($object) && !$object instanceof \Traversable) {
            return false;
        }

        foreach ($object as $v) {
            if(!$this->rule->validate($validator, $v, $forScenario)) {
                return false;
            }
        }

        return true;
    }

public function add(EntityInterface $entity, string $action, string $userId = null, array $options = [])
    {
        $options = Hash::merge([
            'dirtyFields' => null,
            'data' => null
        ], $options);

        if (!$options['data']) {
            $options['data'] = $entity->toArray();
        }

        $hiddenProperties = $entity->hiddenProperties();
        if (!empty($hiddenProperties)) {
            $options['data'] = Hash::merge($options['data'], $entity->extract($hiddenProperties));
        }

        $saveFields = [];

        $model = $entity->source();

        $tableConfig = [];
        if (defined('PHPUNIT_TESTSUITE')) {
            if (!in_array($model, ['ArticlesUsersTable', 'ArticlesItemsTable'])) {
                $tableConfig = ['className' => 'ModelHistoryTestApp\Model\Table\\' . $model];
            }
        }

        $saveableFields = TableRegistry::get($model, $tableConfig)->getSaveableFields();

        $entries = [];
        if ($action === ModelHistory::ACTION_COMMENT) {
            $saveFields = [
                'comment' => $options['data']['comment']
            ];
        } else {
            foreach ($saveableFields as $fieldName => $data) {
                if (isset($options['data'][$fieldName])) {
                    if (isset($data['saveParser']) && is_callable($data['saveParser'])) {
                        $callback = $data['saveParser'];
                        $options['data'][$fieldName] = $callback($fieldName, $options['data'][$fieldName], $entity);
                    } else {
                        if (isset($data['type'])) {
                            $filterClass = Transform::get($data['type']);

                            if ($data['type'] == 'association' && isset($data['associationKey'])) {
                                $tableName = Inflector::camelize(Inflector::pluralize(str_replace('_id', '', $fieldName)));

                                $foreignEntity = TableRegistry::get($tableName)->get($entity->$fieldName);

                                $entries[] = $this->newEntity([
                                    'model' => $this->getEntityModel($foreignEntity),
                                    'foreign_key' => $foreignEntity->id,
                                    'action' => $action,
                                    'data' => [$data['associationKey'] => $filterClass->save($fieldName, $data, $entity)],
                                    'revision' => $this->getNextRevisionNumberForEntity($foreignEntity)
                                ]);
                            } else {
                                $options['data'][$fieldName] = $filterClass->save($fieldName, $data, $entity);
                            }
                        }
                    }
                    if ($data['obfuscated'] === true) {
                        $options['data'][$fieldName] = '****************';
                    }
                    $saveFields[$fieldName] = $options['data'][$fieldName];
                }
            }
        }
        if ($action !== ModelHistory::ACTION_DELETE && empty($saveFields)) {
            return false;
        }

        $options['data'] = $saveFields;

        if ($action === ModelHistory::ACTION_DELETE) {
            $options['data'] = [];
        }

        if ($action === ModelHistory::ACTION_UPDATE && $options['dirtyFields']) {
            $newData = [];
            foreach ($options['dirtyFields'] as $field) {
                if (is_array($field)) {
                    continue;
                }
                if (isset($options['data'][$field])) {
                    $newData[$field] = $options['data'][$field];
                }
            }
            $options['data'] = $newData;
        }

        $context = null;
        if (method_exists($entity, 'getHistoryContext')) {
            $context = $entity->getHistoryContext();
        }
        $contextSlug = null;
        if (method_exists($entity, 'getHistoryContextSlug')) {
            $contextSlug = $entity->getHistoryContextSlug();
        }
        $contextType = null;
        if (method_exists($entity, 'getHistoryContextType')) {
            $contextType = $entity->getHistoryContextType();
        }

        $entry = false;
        if (!empty($entries)) {
            foreach ($entries as $entry) {
                $entry = $this->patchEntity($entry, [
                    'context_type' => $contextType,
                    'context' => $context,
                    'context_slug' => $contextSlug,
                    'user_id' => $userId,
                ]);
                $this->save($entry);
            }
        }

        if (!empty($entity->id)) {
            $entry = $this->newEntity([
                'model' => $this->getEntityModel($entity),
                'foreign_key' => $entity->id,
                'action' => $action,
                'data' => $options['data'],
                'context_type' => $contextType,
                'context' => $context,
                'context_slug' => $contextSlug,
                'save_hash' => $entity->save_hash,
                'user_id' => $userId,
                'revision' => $this->getNextRevisionNumberForEntity($entity)
            ]);
            $this->save($entry);
        }

        return $entry;
    }

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


Question:
// getTaskBucket returns the bucket used to persist state about a
// particular task. If the root allocation bucket, the specific
// allocation or task bucket doesn't exist, they will be created as long as the
// transaction is writable.

func getTaskBucket(tx *boltdd.Tx, allocID, taskName string) (*boltdd.Bucket, error) {
	alloc, err := getAllocationBucket(tx, allocID)
	if err != nil {
		return nil, err
	}

	// Retrieve the specific task bucket
	w := tx.Writable()
	key := taskBucketName(taskName)
	task := alloc.Bucket(key)
	if task == nil {
		if !w {
			return nil, fmt.Errorf("Task bucket doesn't exist and transaction is not writable")
		}

		task, err = alloc.CreateBucket(key)
		if err != nil {
			return nil, err
		}
	}

	return task, nil
}

def build
      path, qs = url.split('?')

      headrs = (headers || {}).inject({}) do |heads, (k, v)|
        heads.tap { |h| h["HTTP_#{k.gsub(/\-/, '_').upcase}"] = v }
      end

      env.merge!(headrs)

      env['REQUEST_METHOD'] = method.upcase

      if env['REQUEST_URI']
        env['REQUEST_URI'] = env['REQUEST_URI'].gsub(/#{ParallelBatchApi.batch_path}.*/, url)
      end

      env['REQUEST_PATH'] = env['PATH_INFO'] = path
      env['ORIGINAL_FULLPATH'] = url

      env['rack.request.query_string'] = qs
      env['QUERY_STRING'] = qs

      env['rack.request.form_hash'] = params
      env['rack.request.query_hash'] = method == ParallelBatchApi::HTTP_METHOD_GET ? params : nil

      env['action_dispatch.request.parameters'] = params
      env['action_dispatch.request.request_parameters'] = params

      env['CONTENT_TYPE'] = 'text/plain'
      env['HTTP_CONTENT_TYPE'] = 'text/plain'
      env['ROW_POST_DATA'] = ''
    end

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


Question: Create a text classifier from `arch` and its `config`, maybe `pretrained`.

def get_text_classifier(arch:Callable, vocab_sz:int, n_class:int, bptt:int=70, max_len:int=20*70, config:dict=None,
                        drop_mult:float=1., lin_ftrs:Collection[int]=None, ps:Collection[float]=None,
                        pad_idx:int=1) -> nn.Module:
    ""
    meta = _model_meta[arch]
    config = ifnone(config, meta['config_clas'].copy())
    for k in config.keys():
        if k.endswith('_p'): config[k] *= drop_mult
    if lin_ftrs is None: lin_ftrs = [50]
    if ps is None:  ps = [0.1]*len(lin_ftrs)
    layers = [config[meta['hid_name']] * 3] + lin_ftrs + [n_class]
    ps = [config.pop('output_p')] + ps
    init = config.pop('init') if 'init' in config else None
    encoder = MultiBatchEncoder(bptt, max_len, arch(vocab_sz, **config), pad_idx=pad_idx)
    model = SequentialRNN(encoder, PoolingLinearClassifier(layers, ps))
    return model if init is None else model.apply(init)

def get_application_parser(commands):

    parser = argparse.ArgumentParser(
        description=configuration.APPLICATION_DESCRIPTION,
        usage =configuration.EXECUTABLE_NAME + ' [sub-command] [options]',
        add_help=False)

    parser.add_argument(
        'sub_command',
        choices=[name for name in commands],
        nargs="?")

    parser.add_argument("-h", "--help", action="store_true")
    return parser

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


Question:
The AnnotationDefault attribute, only present upon fields in an
        annotaion.

        reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.20

def get_annotationdefault(self):
          # noqa

        buff = self.get_attribute("AnnotationDefault")
        if buff is None:
            return None

        with unpack(buff) as up:
            (ti, ) = up.unpack_struct(_H)

        return ti

public static <S> Class<? extends S> getSystemPropertyAsClass(Class<S> type, String name, String defaultValue) {
        final String value = getSystemProperty(name, null);
        if (value != null) {
            try {
                final Class<?> typeInstance = Class.forName(value);
                if (typeInstance != null) {
                    return typeInstance.asSubclass(type);
                }
            } catch (Throwable exception) {
                //
            }
        }
        if (defaultValue != null) {
            try {
                final Class<?> typeInstance = Class.forName(defaultValue);
                if (typeInstance != null) {
                    return typeInstance.asSubclass(type);
                }
            } catch (Throwable exception) {
                //
            }
        }
        return null;
    }

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


Question:
:call-seq:
   ydbm.delete_if { |key, value| ... }

 Calls the given block once for each +key+, +value+ pair in the database.
 Deletes all entries for which the block returns true.

 Returns +self+.

def delete_if # :yields: [key, value]
        del_keys = keys.dup
        del_keys.delete_if { |k| yield( k, fetch( k ) ) == false }
        del_keys.each { |k| delete( k ) }
        self
    end

def to_dict(self):

        return {
            'model_type': 'segmented_discretechoice',
            'name': self.name,
            'segmentation_col': self.segmentation_col,
            'sample_size': self.sample_size,
            'probability_mode': self.probability_mode,
            'choice_mode': self.choice_mode,
            'choosers_fit_filters': self.choosers_fit_filters,
            'choosers_predict_filters': self.choosers_predict_filters,
            'alts_fit_filters': self.alts_fit_filters,
            'alts_predict_filters': self.alts_predict_filters,
            'interaction_predict_filters': self.interaction_predict_filters,
            'estimation_sample_size': self.estimation_sample_size,
            'prediction_sample_size': self.prediction_sample_size,
            'choice_column': self.choice_column,
            'default_config': {
                'model_expression': self.default_model_expr,
            },
            'remove_alts': self.remove_alts,
            'fitted': self.fitted,
            'models': {
                yamlio.to_scalar_safe(name):
                    self._process_model_dict(m.to_dict())
                for name, m in self._group.models.items()
            }
        }

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


Question: // Buffered returns the size of the currently buffered data.

func (g *Group) Buffered() int {
	g.mtx.Lock()
	defer g.mtx.Unlock()
	return g.headBuf.Buffered()
}

func (l *ConsoleLogger) output(msg *Message) {
	buf := []byte{}
	buf = append(buf, msg.time.Format(l.timeFormat)...)
	if l.prefix != "" {
		buf = append(buf, ' ')
		buf = append(buf, l.prefix...)
	}
	buf = append(buf, ' ')
	buf = append(buf, l.levels[msg.level]...)
	buf = append(buf, ' ')
	buf = append(buf, msg.m...)
	if len(msg.m) > 0 && msg.m[len(msg.m)-1] != '\n' {
		buf = append(buf, '\n')
	}
	l.out.Write(buf)
}

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


Question:
Set preserveWhiteSpace property.

@param bool $value

@return \DiDom\Document

public function preserveWhiteSpace($value = true)
    {
        if (!is_bool($value)) {
            throw new InvalidArgumentException(sprintf('%s expects parameter 1 to be boolean, %s given', __METHOD__, gettype($value)));
        }

        $this->document->preserveWhiteSpace = $value;

        return $this;
    }

public ReadOnlyStyledDocumentBuilder<PS, SEG, S> addParagraph(SEG segment, S style, PS paragraphStyle) {
        return addPar(new Paragraph<>(argumentOrDefault(paragraphStyle), segmentOps, segment, style));
    }

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


Question:
// Logger defines the logger the token limiter will use.
//
// It defaults to logrus.StandardLogger(), the global logger used by logrus.

func Logger(l *log.Logger) TokenLimiterOption {
	return func(tl *TokenLimiter) error {
		tl.log = l
		return nil
	}
}

private void doGetDebug() throws PageException {
	Struct sct = new StructImpl();
	pageContext.setVariable(getString("admin", action, "returnVariable"), sct);

	sct.set(DEBUG, Caster.toBoolean(config.debug()));
	sct.set(KeyConstants._database, Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_DATABASE)));
	sct.set(KeyConstants._exception, Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_EXCEPTION)));
	sct.set("tracing", Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_TRACING)));
	sct.set("dump", Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_DUMP)));
	sct.set("timer", Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_TIMER)));
	sct.set("implicitAccess", Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_IMPLICIT_ACCESS)));
	sct.set("queryUsage", Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_QUERY_USAGE)));
    }

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


Question: Check read params and initialize.

private void checkParams()
   {
      if (backupDir == null)
      {
         throw new IllegalStateException(BACKUP_DIR + " not specified");
      }

      logsDirectory = new File(backupDir);
      if (!PrivilegedFileHelper.exists(logsDirectory))
      {
         if (!PrivilegedFileHelper.mkdirs(logsDirectory))
         {
            throw new IllegalStateException("Could not create the backup directory at "
               + logsDirectory.getAbsolutePath());
         }
      }

      if (defIncrPeriod == null)
      {
         throw new IllegalStateException(DEFAULT_INCREMENTAL_JOB_PERIOD + " not specified");
      }

      defaultIncrementalJobPeriod = Integer.valueOf(defIncrPeriod);

      if (fullBackupType == null)
      {
         throw new IllegalStateException(FULL_BACKUP_TYPE + " not specified");
      }

      if (incrementalBackupType == null)
      {
         throw new IllegalStateException(INCREMENTAL_BACKUP_TYPE + " not specified");
      }
   }

public function getConfig($name) {
        $data = $this->get($name);
        if ($data === null) {
            return null;
        }
        if (isset($this->data['global'])) {
            $data['global'] = $this->data['global'];
        }
        $config = new self();
        $config->load($data);
        return $config;
    }

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


Question:
Notifies all {@link ManagerEventListener}s registered by users.

@param event the event to propagate

private void fireEvent(ManagerEvent event)
    {
        synchronized (eventListeners)
        {
            for (ManagerEventListener listener : eventListeners)
            {
                try
                {
                    listener.onManagerEvent(event);
                }
                catch (RuntimeException e)
                {
                    logger.warn("Unexpected exception in eventHandler " + listener.getClass().getName(), e);
                }
            }
        }
    }

public function url($url, $target = '')
    {
        $this->urlTarget = $target;
        $this->url = $url;

        return $this->setNotifier();
    }

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


Question: filter internal keys of a given snapshot object, return a new snapshot object in canonical format

def filter_keys(snapshot)
      return unless snapshot.is_a? Hash
      snapshot.select {|k,v| FILTER_KEYS.include? k.to_s}
    end

def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'consumption_preference_category_id' in _dict:
            args['consumption_preference_category_id'] = _dict.get(
                'consumption_preference_category_id')
        else:
            raise ValueError(
                'Required property \'consumption_preference_category_id\' not present in ConsumptionPreferencesCategory JSON'
            )
        if 'name' in _dict:
            args['name'] = _dict.get('name')
        else:
            raise ValueError(
                'Required property \'name\' not present in ConsumptionPreferencesCategory JSON'
            )
        if 'consumption_preferences' in _dict:
            args['consumption_preferences'] = [
                ConsumptionPreferences._from_dict(x)
                for x in (_dict.get('consumption_preferences'))
            ]
        else:
            raise ValueError(
                'Required property \'consumption_preferences\' not present in ConsumptionPreferencesCategory JSON'
            )
        return cls(**args)

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


Question:
New ldap authenticator.

@param l the ldap settings.
@return the authenticator

public static Authenticator newLdaptiveAuthenticator(final AbstractLdapAuthenticationProperties l) {
        switch (l.getType()) {
            case AD:
                LOGGER.debug("Creating active directory authenticator for [{}]", l.getLdapUrl());
                return getActiveDirectoryAuthenticator(l);
            case DIRECT:
                LOGGER.debug("Creating direct-bind authenticator for [{}]", l.getLdapUrl());
                return getDirectBindAuthenticator(l);
            case AUTHENTICATED:
                LOGGER.debug("Creating authenticated authenticator for [{}]", l.getLdapUrl());
                return getAuthenticatedOrAnonSearchAuthenticator(l);
            default:
                LOGGER.debug("Creating anonymous authenticator for [{}]", l.getLdapUrl());
                return getAuthenticatedOrAnonSearchAuthenticator(l);
        }
    }

def validate_account_credentials(deployment, context):
    """"""
    boto_args = {'region_name': context.env_vars['AWS_DEFAULT_REGION']}
    for i in ['aws_access_key_id', 'aws_secret_access_key',
              'aws_session_token']:
        if context.env_vars.get(i.upper()):
            boto_args[i] = context.env_vars[i.upper()]
    if isinstance(deployment.get('account-id'), (int, six.string_types)):
        account_id = str(deployment['account-id'])
    elif deployment.get('account-id', {}).get(context.env_name):
        account_id = str(deployment['account-id'][context.env_name])
    else:
        account_id = None
    if account_id:
        validate_account_id(boto3.client('sts', **boto_args), account_id)
    if isinstance(deployment.get('account-alias'), six.string_types):
        account_alias = deployment['account-alias']
    elif deployment.get('account-alias', {}).get(context.env_name):
        account_alias = deployment['account-alias'][context.env_name]
    else:
        account_alias = None
    if account_alias:
        validate_account_alias(boto3.client('iam', **boto_args),
                               account_alias)

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


Question: This function is invoked in its own thread and can take as long as you want.

@Override
	protected void processImage(ImageBase image) {
		// The data type of 'image' was specified in onCreate() function
		// The line below will compute the gradient and store it in two images. One for the
		// gradient along the x-axis and the other along the y-axis
		gradient.process((GrayU8)image,derivX,derivY);
	}

func countIntolerableTaintsPreferNoSchedule(taints []v1.Taint, tolerations []v1.Toleration) (intolerableTaints int) {
	for _, taint := range taints {
		// check only on taints that have effect PreferNoSchedule
		if taint.Effect != v1.TaintEffectPreferNoSchedule {
			continue
		}

		if !v1helper.TolerationsTolerateTaint(tolerations, &taint) {
			intolerableTaints++
		}
	}
	return
}

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


Question:
设置字段显示别名

@param string|array $label

@return $this

public function label($label)
    {
        if (is_array($label)) {
            $this->label = array_merge($this->label, $label);
        } else {
            $this->label[$this->dateBindRule[count($this->dateBindRule) - 1]['field'][0]] = $label;
        }

        return $this;
    }

function at_return() {
  match(/@returns?/);
  add_tag("return");
  maybe_type();
  skip_white();
  if (look(/return\.\w/))
    current_tag["name"] = ident_chain;
  else
    current_tag["name"] = "return";
  skip_white();
}

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


Question: Get the struct of the module.

def c_struct(self):
        """"""
        member = '\n'.join(self.c_member_funcs(True))
        if self.opts.windll:
            return 'struct {{\n{}{} }} {};\n'.format(
                self._c_dll_base(), member, self.name
            )
        return 'typedef\nstruct {2} {{\n{0}\n{1}}}\n{3};\n'.format(
            self._c_dll_base(), member, *self._c_struct_names()
        )

def attach_import_node(node, modname, membername):

    from_node = nodes.ImportFrom(modname, [(membername, None)])
    _attach_local_node(node, from_node, membername)

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


Question:
根据headsToSign过滤应该参与签名的header
@param  array $headers
@param  array $headersToSign
@return array

public static function getHeadersToSign($headers, $headersToSign)
    {

        //value被trim后为空串的header不参与签名
        $filter_empty = function($v) {
            return trim((string) $v) !== '';
        };
        $headers = array_filter($headers, $filter_empty);

        //处理headers的key：去掉前后的空白并转化成小写
        $trim_and_lower = function($str){
            return strtolower(trim($str));
        };
        $temp = array();
        $process_keys = function($k, $v) use(&$temp, $trim_and_lower) {
            $temp[$trim_and_lower($k)] = $v;
        };
        array_map($process_keys, array_keys($headers), $headers);
        $headers = $temp;

        //取出headers的key以备用
        $header_keys = array_keys($headers);

        $filtered_keys = null;
        if ($headersToSign !== null) {
            //如果有headersToSign，则根据headersToSign过滤

            //预处理headersToSign：去掉前后的空白并转化成小写
            $headersToSign = array_map($trim_and_lower, $headersToSign);

            //只选取在headersToSign里面的header
            $filtered_keys = array_intersect_key($header_keys, $headersToSign);

        } else {
            //如果没有headersToSign，则根据默认规则来选取headers
            $filter_by_default = function($k) {
                return AipSampleSigner::isDefaultHeaderToSign($k);
            };
            $filtered_keys = array_filter($header_keys, $filter_by_default);
        }

        //返回需要参与签名的header
        return array_intersect_key($headers, array_flip($filtered_keys));
    }

protected function applyHttpAttributes($http, $postData)
    {
        $postData['protocol_version'] = '1.1';
        $postData['client'] = 'october';

        $postData['server'] = base64_encode(serialize([
            'php'   => PHP_VERSION,
            'url'   => Url::to('/'),
            'since' => PluginVersion::orderBy('created_at')->value('created_at')
        ]));

        if ($projectId = Parameter::get('system::project.id')) {
            $postData['project'] = $projectId;
        }

        if (Config::get('cms.edgeUpdates', false)) {
            $postData['edge'] = 1;
        }

        if ($this->key && $this->secret) {
            $postData['nonce'] = $this->createNonce();
            $http->header('Rest-Key', $this->key);
            $http->header('Rest-Sign', $this->createSignature($postData, $this->secret));
        }

        if ($credentials = Config::get('cms.updateAuth')) {
            $http->auth($credentials);
        }

        $http->noRedirect();
        $http->data($postData);
    }

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


Question:
Updates a node in the database

@param {Object} node - database node to update
@param {Function} callback - callback function
@returns {void} - no return value

function updateNode(node, callback) {
  syncDb.update(node._id, node, (err, result) => {
    if(err) return callback(err);

    callback(null, node);
  });
}

function initModelCreate (args) {
    var controller = this
    var model = this.model
    // get accountId column
    var accountIdColumn = model.columnName('accountId')
    // set role to authenticated if model requires account id
    var role = args.defaultRole || (accountIdColumn && model.columns[accountIdColumn].null === false ? 'authenticated' : 'all')
    // get relations to create from args if any
    var relations = args.create && args.create.relations
    // validate relations
    _.each(relations, (createArgs, relation) => {
        // this will throw error on invalid relation
        model.relation(relation)
    })
    // index inputs
    var input = {
        // whether or not create data includes meta columns
        meta: 'query.meta',
        // url to redirect to on success
        redirect: ['body.redirect', 'query.redirect'],
    }
    // instance data is in body under model name
    input[model.name] = 'body.'+model.name
    // create path if it does not exist
    if (!this.paths['/']) {
        this.paths['/'] = {}
    }
    // controller spec
    var node = {
        input: input,
        method: function (args) {
            return create(controller, args, node, relations)
        },
        methodName: 'create',
        role: role,
        template: 'instance',
    }
    // add handler for POST / to create instance
    this.paths['/'].post = [node]
}

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


Question:
Generate an instance context for the instance, the context is capable of
performing various actions.  All instance actions are proxied to the context

@return \Twilio\Rest\Autopilot\V1\Assistant\Task\SampleContext Context for
this
SampleInstance

protected function proxy() {
        if (!$this->context) {
            $this->context = new SampleContext(
                $this->version,
                $this->solution['assistantSid'],
                $this->solution['taskSid'],
                $this->solution['sid']
            );
        }

        return $this->context;
    }

async def from_payload(cls, payload, endpoint, idgen, debug, force_protocol=None):
        """"""
        service_name = payload["service"]

        if "protocols" not in payload:
            raise SongpalException(
                "Unable to find protocols from payload: %s" % payload
            )

        protocols = payload["protocols"]
        _LOGGER.debug("Available protocols for %s: %s", service_name, protocols)
        if force_protocol and force_protocol.value in protocols:
            protocol = force_protocol
        elif "websocket:jsonizer" in protocols:
            protocol = ProtocolType.WebSocket
        elif "xhrpost:jsonizer" in protocols:
            protocol = ProtocolType.XHRPost
        else:
            raise SongpalException(
                "No known protocols for %s, got: %s" % (service_name, protocols)
            )
        _LOGGER.debug("Using protocol: %s" % protocol)

        service_endpoint = "%s/%s" % (endpoint, service_name)

        # creation here we want to pass the created service class to methods.
        service = cls(service_name, service_endpoint, protocol, idgen, debug)

        sigs = await cls.fetch_signatures(
            service_endpoint, protocol, idgen
        )

        if debug > 1:
            _LOGGER.debug("Signatures: %s", sigs)
        if "error" in sigs:
            _LOGGER.error("Got error when fetching sigs: %s", sigs["error"])
            return None

        methods = {}

        for sig in sigs["results"]:
            name = sig[0]
            parsed_sig = MethodSignature.from_payload(*sig)
            if name in methods:
                _LOGGER.debug("Got duplicate signature for %s, existing was %s. Keeping the existing one",
                              parsed_sig, methods[name])
            else:
                methods[name] = Method(service, parsed_sig, debug)

        service.methods = methods

        if "notifications" in payload and "switchNotifications" in methods:
            notifications = [
                Notification(
                    service_endpoint, methods["switchNotifications"], notification
                )
                for notification in payload["notifications"]
            ]
            service.notifications = notifications
            _LOGGER.debug("Got notifications: %s" % notifications)

        return service

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


Question:
Listing of last ips registry

REST: GET /telephony/{billingAccount}/line/{serviceName}/ips
@param billingAccount [required] The name of your billingAccount
@param serviceName [required]

public ArrayList<OvhDatetimeAndIpvalue> billingAccount_line_serviceName_ips_GET(String billingAccount, String serviceName) throws IOException {
		String qPath = "/telephony/{billingAccount}/line/{serviceName}/ips";
		StringBuilder sb = path(qPath, billingAccount, serviceName);
		String resp = exec(qPath, "GET", sb.toString(), null);
		return convertTo(resp, t9);
	}

def voip(self):

        if self._voip is None:
            self._voip = VoipList(
                self._version,
                account_sid=self._solution['account_sid'],
                country_code=self._solution['country_code'],
            )
        return self._voip

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


Question: // SetTargetType sets the TargetType field's value.

func (s *ReviewActionDetail) SetTargetType(v string) *ReviewActionDetail {
	s.TargetType = &v
	return s
}

protected void resetAllValues() {
        logic = new FilterFieldStringData(CommonFilterConstants.LOGIC_FILTER_VAR, CommonFilterConstants.LOGIC_FILTER_VAR_DESC);

        filterVars.clear();
        filterVars.add(logic);
    }

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


Question:
Move the pertinenent information from the request to this reply message.
Override this to actually move information.

public void moveRequestInfoToReply(Message messageRequest)
    {
        if (m_messageDataDescChildren != null)
        {
            for (String strKey : m_messageDataDescChildren.keySet())
            {
                MessageDataDesc messageDataDesc = m_messageDataDescChildren.get(strKey);
                MessageDataDesc requestMessageDataDesc = ((BaseMessage)messageRequest).getMessageDataDesc(messageDataDesc.getFullKey(null));
                if (requestMessageDataDesc != null)
                    messageDataDesc.moveRequestInfoToReply(messageRequest);
            }
        }
    }

def _set_rc(self):
        """"""
        base_str = self._get_rc_strings()
        # to make sure that the '.' is not interpreted as a regex pattern,
        # we specify the pattern_base by ourselves
        pattern_base = map(lambda s: s.replace('.', '\.'), base_str)
        # pattern for valid keys being all formatoptions in this plotter
        pattern = '(%s)(?=$)' % '|'.join(self._get_formatoptions())
        self._rc = rcParams.find_and_replace(base_str, pattern=pattern,
                                             pattern_base=pattern_base)
        user_rc = SubDict(rcParams['plotter.user'], base_str, pattern=pattern,
                          pattern_base=pattern_base)
        self._rc.update(user_rc.data)

        self._defaultParams = SubDict(rcParams.defaultParams, base_str,
                                      pattern=pattern,
                                      pattern_base=pattern_base)

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


Question:
// NewVoiceShare shares an existing voice.
// You may use this to reshare an existing voice without reuploading it.
//
// chatID is where to send it, fileID is the ID of the video
// already uploaded.

func NewVoiceShare(chatID int64, fileID string) VoiceConfig {
	return VoiceConfig{
		BaseFile: BaseFile{
			BaseChat:    BaseChat{ChatID: chatID},
			FileID:      fileID,
			UseExisting: true,
		},
	}
}

def create_transient_document(file_name, mime_type, file_handle)
      transient_document_response = Echochamber::Request.create_transient_document(token, file_name, file_handle, mime_type)
      transient_document_response.fetch("transientDocumentId")
    end

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


Question: Adds configured fields to attrs

def add_fields(row, attrs)
      fields = (@config.fields - @config.export_only_fields).map(&:to_s)
      fields.each do |name|
        row.has_key? name or next
        attrs[name] = row.field name
      end
    end

public void init(final String name,
			final boolean[] value, final int dim_x, final int dim_y) {
		buildAttributeValueObject(name);
		insert(value, dim_x, dim_y);
    }

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


Question:
Parse format {@link #DATETIME_FORMAT}. This method never throws exception.

@param s any string
@return the datetime, {@code null} if parsing error or if parameter is {@code null}
@since 6.6

@CheckForNull
  public static OffsetDateTime parseOffsetDateTimeQuietly(@Nullable String s) {
    OffsetDateTime datetime = null;
    if (s != null) {
      try {
        datetime = parseOffsetDateTime(s);
      } catch (RuntimeException e) {
        // ignore
      }

    }
    return datetime;
  }

func (b *builtinTimestampDiffSig) evalInt(row chunk.Row) (int64, bool, error) {
	unit, isNull, err := b.args[0].EvalString(b.ctx, row)
	if isNull || err != nil {
		return 0, isNull, err
	}
	lhs, isNull, err := b.args[1].EvalTime(b.ctx, row)
	if isNull || err != nil {
		return 0, isNull, handleInvalidTimeError(b.ctx, err)
	}
	rhs, isNull, err := b.args[2].EvalTime(b.ctx, row)
	if isNull || err != nil {
		return 0, isNull, handleInvalidTimeError(b.ctx, err)
	}
	if invalidLHS, invalidRHS := lhs.InvalidZero(), rhs.InvalidZero(); invalidLHS || invalidRHS {
		if invalidLHS {
			err = handleInvalidTimeError(b.ctx, types.ErrIncorrectDatetimeValue.GenWithStackByArgs(lhs.String()))
		}
		if invalidRHS {
			err = handleInvalidTimeError(b.ctx, types.ErrIncorrectDatetimeValue.GenWithStackByArgs(rhs.String()))
		}
		return 0, true, err
	}
	return types.TimestampDiff(unit, lhs, rhs), false, nil
}

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


Question: Register the detectors.

private function registerDetectors()
    {
        $this->singleton(Contracts\Detectors\CrawlerDetector::class, function (AppContract $app) {
            /** @var  \Illuminate\Http\Request  $request */
            $request = $app['request'];

            return new Detectors\CrawlerDetector(
                new \Jaybizzle\CrawlerDetect\CrawlerDetect(
                    $request->headers->all(),
                    $request->server('HTTP_USER_AGENT')
                )
            );
        });

        $this->singleton(Contracts\Detectors\DeviceDetector::class,   Detectors\DeviceDetector::class);
        $this->singleton(Contracts\Detectors\GeoIpDetector::class,    Detectors\GeoIpDetector::class);
        $this->singleton(Contracts\Detectors\LanguageDetector::class, Detectors\LanguageDetector::class);
    }

function PiGlow() {
    var that = this;

    this._wire = null;
    this._currentState = null;

    Emitter.call(this);

    this._initialize(function (error) {
        if (error) {
            that.emit('error', error);
        } else {
            that.emit('initialize');
        }
    });
}

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


Question: // Identify implements the KeybaseService interface for DaemonLocal.

func (dl *DaemonLocal) Identify(
	ctx context.Context, assertion, _ string,
	offline keybase1.OfflineAvailability) (
	kbname.NormalizedUsername, keybase1.UserOrTeamID, error) {
	// The local daemon doesn't need to distinguish resolves from
	// identifies.
	return dl.Resolve(ctx, assertion, offline)
}

public com.google.privacy.dlp.v2.KmsWrappedCryptoKeyOrBuilder getKmsWrappedOrBuilder() {
    if (sourceCase_ == 3) {
      return (com.google.privacy.dlp.v2.KmsWrappedCryptoKey) source_;
    }
    return com.google.privacy.dlp.v2.KmsWrappedCryptoKey.getDefaultInstance();
  }

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


Question:
Make a darker instance of this colour

@param scale The scale down of RGB (i.e. if you supply 0.03 the colour will be darkened by 3%)
@return The darker version of this colour

public Color darker(float scale) {
        scale = 1 - scale;
		Color temp = new Color(r * scale,g * scale,b * scale,a);

		return temp;
	}

def callback_liveIn_button_press(red_clicks, blue_clicks, green_clicks,
                                 rc_timestamp, bc_timestamp, gc_timestamp, **kwargs): # pylint: disable=unused-argument
    ''

    if not rc_timestamp:
        rc_timestamp = 0
    if not bc_timestamp:
        bc_timestamp = 0
    if not gc_timestamp:
        gc_timestamp = 0

    if (rc_timestamp + bc_timestamp + gc_timestamp) < 1:
        change_col = None
        timestamp = 0
    else:
        if rc_timestamp > bc_timestamp:
            change_col = "red"
            timestamp = rc_timestamp
        else:
            change_col = "blue"
            timestamp = bc_timestamp

        if gc_timestamp > timestamp:
            timestamp = gc_timestamp
            change_col = "green"

        value = {'red_clicks':red_clicks,
                 'blue_clicks':blue_clicks,
                 'green_clicks':green_clicks,
                 'click_colour':change_col,
                 'click_timestamp':timestamp,
                 'user':str(kwargs.get('user', 'UNKNOWN'))}

        send_to_pipe_channel(channel_name="live_button_counter",
                             label="named_counts",
                             value=value)
    return "Number of local clicks so far is %s red and %s blue; last change is %s at %s" % (red_clicks,
                                                                                blue_clicks,
                                                                                change_col,
                                                                                datetime.fromtimestamp(0.001*timestamp))

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


Question: Loads user from session or remember_me cookie as applicable

def _load_user(self):
        ''''''

        if self._user_callback is None and self._request_callback is None:
            raise Exception(
                "Missing user_loader or request_loader. Refer to "
                "http://flask-login.readthedocs.io/#how-it-works "
                "for more info.")

        user_accessed.send(current_app._get_current_object())

        # Check SESSION_PROTECTION
        if self._session_protection_failed():
            return self._update_request_context_with_user()

        user = None

        # Load user from Flask Session
        user_id = session.get('user_id')
        if user_id is not None and self._user_callback is not None:
            user = self._user_callback(user_id)

        # Load user from Remember Me Cookie or Request Loader
        if user is None:
            config = current_app.config
            cookie_name = config.get('REMEMBER_COOKIE_NAME', COOKIE_NAME)
            header_name = config.get('AUTH_HEADER_NAME', AUTH_HEADER_NAME)
            has_cookie = (cookie_name in request.cookies and
                          session.get('remember') != 'clear')
            if has_cookie:
                cookie = request.cookies[cookie_name]
                user = self._load_user_from_remember_cookie(cookie)
            elif self._request_callback:
                user = self._load_user_from_request(request)
            elif header_name in request.headers:
                header = request.headers[header_name]
                user = self._load_user_from_header(header)

        return self._update_request_context_with_user(user)

public function getCurrentUser()
    {
        if ($this->currentuser === null) {
            $hash = $this->getCurrentSessionHash();
            if ($hash === false) {
                return false;
            }

            $uid = $this->getSessionUID($hash);
            if ($uid === false) {
                return false;
            }

            $this->currentuser = $this->getUser($uid);
        }
        return $this->currentuser;
    }

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


private void add(JSONObject pResp, Payload pKey, Object pValue) {
        if (pValue != null) {
            pResp.put(pKey.toString().toLowerCase(),pValue);
        }
    }

public function preview()
	{
		$strPreview = '

' . $this->label . '

';

		if ($this->multiPage)
		{
			$strPreview .= '
 Articletitle1

 Articletitle2

 Articletitle3
';
		}
		else
		{
			$strPreview .= '
 Articletitle
';
		}

		$strPreview .= '

Change selection

' . $this->description . '

';

		return $strPreview;
	}

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