Question:
Outputs HTTP status to the client, optionally with a message (as HTTP
response message).

@param int $code of HTTP response
@param string $message of HTTP response

public static function status(
    /*int*/ $code,
    /*string*/ $message = null
  ) {
    // General header as response.
    $header =
      @intval($code) .
      (!$message ? '' : ' ' . $message);

    // Send status for both CGI and non-CGI web servers.
    header(self::getProtocol() . ' ' . $header);
    header('Status: ' . $header);
  }

public function check()
    {
        $this->pingBinFactory();

        $ipAddress = ip_address_from_hostname($this->target->hostname);

        $latency = $this->ping($ipAddress);

        $latencyFormatted = $latency ? "{$latency}ms" : 'error!';

        $this->target->setDisplay(
            "{$this->target->name} ({$latencyFormatted})"
        );

        if ($latency === false || $latency > $this->target->acceptedLatency) {
            $result = $this->makeResult(
                false,
                sprintf(
                    $this->target->getErrorMessage(),
                    $this->hosnameAndIp($this->target->hostname, $ipAddress),
                    $latency === false ? '[ping error]' : $latency,
                    $this->target->acceptedLatency
                )
            );
        } else {
            $result = $this->makeHealthyResult();
        }

        return $result->setValue($latency)->setValueHuman("{$latency}ms");
    }

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


Question:
...
@static		public
@access		public
@return		...

static public function getWidth( $force = FALSE ){
		if( !self::$width || $force )
			self::$width	= intval( `tput cols` );
//			self::$width	= exec( 'tput cols' );
		return self::$width;
	}

function yy_r130()
    {
        $this->_retvalue = '[' . $this->compiler->compileTag('private_special_variable', array(), '[\'section\'][\'' .
                                                                                $this->yystack[ $this->yyidx +
                                                                                - 1 ]->minor .
                                                                                '\'][\'index\']') . ']';
    }

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


Question: returns {attr1: href, attr2: href2}

def links(self):

        dlinks = {}
        for key, value in self.__dict__.items():
            if isinstance(value, dict) and value['link']:
                dlinks[key] = value['link']
        return dlinks

public function toUrl($url, $parameters)
	{
		foreach ($parameters as $key => $value)
		{
			if (\is_array($value))
			{
				foreach ($value as $k => $v)
				{
					if (strpos($url, '?') === false)
					{
						$url .= '?' . $key . '=' . $v;
					}
					else
					{
						$url .= '&' . $key . '=' . $v;
					}
				}
			}
			else
			{
				if (strpos($value, ' ') !== false)
				{
					$value = $this->safeEncode($value);
				}

				if (strpos($url, '?') === false)
				{
					$url .= '?' . $key . '=' . $value;
				}
				else
				{
					$url .= '&' . $key . '=' . $value;
				}
			}
		}

		return $url;
	}

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


Question: // Config validates and print the compose file.

func (p *Project) Config() (string, error) {
	cfg := ExportedConfig{
		Version:  "2.0",
		Services: p.ServiceConfigs.All(),
		Volumes:  p.VolumeConfigs,
		Networks: p.NetworkConfigs,
	}

	bytes, err := yaml.Marshal(cfg)
	return string(bytes), err
}

public function build() {
    $options_data = $this->buildOptionsData();

    $out_text =
      $this->buildUsageLine($this->arguments_spec->getUsage(), $options_data);

    $options_text = '';
    if ($options_data['lines']) {
      foreach($options_data['lines'] as $option_line_data) {
        $options_text .= $this->buildOptionLine($option_line_data, $options_data)."\n";
      }

      $out_text .=
        "\n".
        ConsoleFormat::applyformatToText('bold','cyan','Options:')."\n".
        $options_text;
    }

    return $out_text;
  }

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


Question:
Обработка расширенных тегов

@param DOMNode $node  Элемент

@return DOMNode  $node или его замена

protected function processExtendedNode(DOMNode $node)
	{
		$handler = 'extendedNode' . $node->localName;

		if (method_exists($this, $handler))
		{
			return $this->$handler($node);
		}
		else
		{
            Eresus_Kernel::log(__METHOD__, LOG_WARNING, 'Unsupported EresusForm tag "%s"', $node->localName);
			return $node;
		}
	}

public function parse()
    {

        if (!count($this->xPaths)) {
            return [[]];
        }

        //create copy of xPaths
        $xPaths = $this->xPaths;
        return $this->parseXPath($xPaths, $this->xml);
    }

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


Question: Convert the YAML object into an RDF Graph object.

def rdf_graph_from_yaml(yaml_root):
    """"""
    G = Graph()
    for top_entry in yaml_root:
        assert len(top_entry) == 1
        node = list(top_entry.keys())[0]
        build_relations(G, node, top_entry[node], None)
    return G

def get_rml(self, rml_name):

        try:
            return getattr(self, rml_name)
        except AttributeError:
            return self.load_rml(rml_name)

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


Question:
Declarative Services method for setting the context service reference

@param ref reference to the service

@Reference(policy = ReferencePolicy.DYNAMIC, target = "(id=unbound)")
    protected void setContextService(ServiceReference<WSContextService> ref) {
        contextSvcRef.setReference(ref);
    }

private void createImplicitVariableType(XtextResource resource, IAcceptor<? super ICodeMining> acceptor) {
		createImplicitVarValType(resource, acceptor, XtendVariableDeclaration.class,
			it -> it.getType(),
			it -> {
				LightweightTypeReference type = getLightweightType(it.getRight());
				if (type.isAny()) {
					type = getTypeForVariableDeclaration(it.getRight());
				}
				return type.getSimpleName();
			},
			it -> it.getRight(),
			() -> this.grammar.getXVariableDeclarationAccess().getRightAssignment_3_1());
	}

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


Question:
instance
@param  mixed $arg1
@param  mixed $arg2
@return static

static public function instance($args=null)
    {
        $args = func_get_args();

        $id = get_called_class() . '.' . md5(serialize($args));
        if (isset(static::$instances[$id])) {
            return static::$instances[$id];
        }

        if ($args) {
            switch (count($args)) {
                case 1:
                    $obj = new static($args[0]);
                    break;
                case 2:
                    $obj = new static($args[0], $args[1]);
                    break;
                case 3:
                    $obj = new static($args[0], $args[1], $args[2]);
                    break;
                case 4:
                    $obj = new static($args[0], $args[1], $args[2], $args[3]);
                    break;
                case 5:
                    $obj = new static($args[0], $args[1], $args[2], $args[3], $args[4]);
                    break;
                case 6:
                    $obj = new static($args[0], $args[1], $args[2], $args[3], $args[4], $args[5]);
                    break;
                default:
                    $obj = new static($args);
                    break;
            }
        } else {
            $obj = new static();
        }

        static::$instances[$id] = $obj;
        return static::$instances[$id];
    }

function (parameters) {

        /**
         * Job identifier.
         * @type {string}
         */
        this.hash = parameters.hash;

        /**
         * Array of hashes to {@link Artifact}s containing each requested result.
         * @type {string[]}
         */
        this.resultHashes = parameters.resultHashes || [];

        /**
         * Hash to an {@link Artifact} containing the union of all requests results.
         * @type {string}
         */
        this.resultSuperSet = parameters.resultSuperSet || null;

        this.userId = parameters.userId || [];

        /**
         * Current status of the job.
         * @type {string}
         */
        this.status = parameters.status || null;

        /**
         * Timestamp of when the job was created.
         * @type {string}
         */
        this.createTime = parameters.createTime || null;

        /**
         * Timestamp of when the job execution started by a worker.
         * @type {string}
         */
        this.startTime = parameters.startTime || null;

        /**
         * Timestamp of when the job execution finished on the worker.
         * @type {string}
         */
        this.finishTime = parameters.finishTime || null;

        /**
         * Id/label of the worker processing the job.
         * @type {string}
         */
        this.worker = parameters.worker || null;

        /**
         * Array of labels for the job.
         * @type {string[]}
         */
        this.labels = parameters.labels || [];

        /**
         * The (id) outputNumber (0, 1, 2, ...) of the latest {@link OutputInfo} (for this job) available on the server.
         * When no output is available the number is <b>null</b>.
         * @type {number}
         */
        this.outputNumber = typeof parameters.outputNumber === 'number' ? parameters.outputNumber : null;
    }

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


Question: returns the file based on dataType and subjectArea

def get_full_filename(self, dataType, subjectArea):

        return dataPath + os.sep + 'core' + os.sep + dataType + '_' + subjectArea + '.CSV'

protected void saveFile(SebEvent event, String content, String name, String extension) {
		event.saveFile(content, getListenerFileName(name), extension);
	}

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


Question: Convert to a nested dict.

def to_dict(self):

        return {k: v.to_dict() if isinstance(v, AttrDict) else v
                for k, v in self.__dict__.items() if not k.startswith('_')}

def flatten_all(list_of_list):

    for i in list_of_list:
        if hasattr(i, "__iter__"):
            for j in flatten_all(i):
                yield j
        else:
            yield i

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


Question:
Get column type
@param $result_object A result set
@param $index Integer index
@param $which_connection see method close()
@return The column type

public function fieldType($result_object,$index,$which_connection='')
    {
        if ($which_connection == '') {
            $which_connection = $this->default_db;
        }
        $fld = $result_object->FetchField($index);
        // mysqli puts a integer constant in the type property
        // ADOdb provides MetaType to convert to relative type
        $dbtype = $this->connectionType($which_connection);
        if (strtolower($dbtype) === 'mysqli') {
            $meta = $this->connections[$which_connection]->MetaType($fld->type);
            switch ($meta) {
                case 'C':
                case 'X':
                    $fld->type = 'varchar';
                    break;
                case 'B':
                case 'X':
                    $fld->type= 'blob';
                    break;
                case 'D':
                case 'T':
                    $fld->type= 'datetime';
                    break;
                case 'R':
                case 'I':
                    $fld->type= 'int';
                    break;
                case 'N':
                    $fld->type= 'numeric';
                    break;
            }
        }

        return $fld->type;
    }

def set_row(row, val)
      # Setter
      if !row.is_a?(String) || (!val.is_a?(Hash) && !val.is_a?(Array))
        raise ArgumentError, 'Illegal argument type'
      elsif val.is_a?(Array) && val.size != col_keys.size
        raise ArgumentError, 'Column size not match'
      end

      case val
      when Array
        if @row_keys[row]
          row = @row_keys[row]
          @content[row] = val
        else
          @row_keys[row] = @row_keys.size
          @content << val
        end
      when Hash
        unless @row_keys[row]
          @row_keys[row] = @row_keys.size
          @content << ([''] * @col_keys.size)
        end

        row = @row_keys[row]
        val.each do |k, v|
          col = @col_keys[k]
          @content[row][col] = v if col
        end
      end

      self
    end

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


Question: Add a single build XML output file to our data.

def add_input(self, input):
        '''

        '''
        events = xml.dom.pulldom.parse(input)
        context = []
        for (event,node) in events:
            if event == xml.dom.pulldom.START_ELEMENT:
                context.append(node)
                if node.nodeType == xml.dom.Node.ELEMENT_NODE:
                    x_f = self.x_name_(*context)
                    if x_f:
                        events.expandNode(node)
                        # expanding eats the end element, hence walking us out one level
                        context.pop()
                        # call handler
                        (x_f[1])(node)
            elif event == xml.dom.pulldom.END_ELEMENT:
                context.pop()

func (s *SSHRunner) CombinedOutputTo(cmd string, w io.Writer) error {
	out, err := s.CombinedOutput(cmd)
	if err != nil {
		return err
	}
	_, err = w.Write([]byte(out))
	return err
}

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


Question: Marshall the given parameter object.

public void marshall(ListTagOptionsRequest listTagOptionsRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(listTagOptionsRequest.getFilters(), FILTERS_BINDING);
            protocolMarshaller.marshall(listTagOptionsRequest.getPageSize(), PAGESIZE_BINDING);
            protocolMarshaller.marshall(listTagOptionsRequest.getPageToken(), PAGETOKEN_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

public function beforeMarshal(Event $event, \ArrayObject $data, \ArrayObject $options)
    {
        $this->_prepareParamsData($data);
    }

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


Question:
This is a method required by Lev::Routine.  It enforces the steps common
 to all handlers.

def exec(options)
      self.params = options[:params]
      self.request = options[:request]
      self.caller = options[:caller]
      self.options = options.except(:params, :request, :caller)

      setup
      raise Lev.configuration.security_transgression_error, auth_error_details unless authorized?
      validate_paramified_params
      handle unless errors?
    end

def request_setup req_or_uri # :nodoc:
    req = if URI === req_or_uri then
            Net::HTTP::Get.new req_or_uri.request_uri
          else
            req_or_uri
          end

    @headers.each do |pair|
      req.add_field(*pair)
    end

    @override_headers.each do |name, value|
      req[name] = value
    end

    unless req['Connection'] then
      req.add_field 'Connection', 'keep-alive'
      req.add_field 'Keep-Alive', @keep_alive
    end

    req
  end

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


Question:
Set the translatable text.

@param string $context The string context
@param string $text The string text (singular form)
@param string $plural The string text (plural form)

public function setString($context, $text, $plural = '')
    {
        $this->context = (string) $context;
        $this->text = (string) $text;
        $this->plural = (string) $plural;
        $this->hash = md5($this->plural ? $this->context . "\004" . $this->text . "\005" . $this->plural : $this->context . "\004" . $this->text);
    }

def get_cached_translated_field(instance, field_name, language_code=None, use_fallback=False):

    if language_code is None:
        language_code = instance.get_current_language()

    # In django-parler 1.1 the order of the arguments was fixed, It used to be language_code, field_name
    # This serves as detection against backwards incompatibility issues.
    if len(field_name) <= 5 and len(language_code) > 5:
        raise RuntimeError("Unexpected language code, did you swap field_name, language_code?")

    translated_model = instance._parler_meta.get_model_by_field(field_name)
    values = _get_cached_values(instance, translated_model, language_code, use_fallback)
    if not values:
        return None

    # Allow older cached versions where the field didn't exist yet.
    return values.get(field_name, None)

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


Question:
Dump data into php file.

@param  string $file
@param  mixed  $content
@throws \Exception

public function dump($file, $content)
    {
        $fileWrited = file_put_contents($file, '<?php return ' . var_export($content, true) . ';');

        if ($fileWrited === false) {
            throw new \Exception('Unable to dump data into php file !');
        }
    }

public function catchError(array $error_files)
    {
        $this->app->set(Web::ERROR_VIEWS, $error_files);
        $whoops = new Run;
        if ($this->debug) {
            error_reporting(E_ALL);
            $whoops->pushHandler(new PrettyPageHandler);
        } else {
            error_reporting(E_ERROR);
            $whoops->pushHandler($this->getErrorView());
        }
        $whoops->register();
        return $this;
    }

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


Question:
@param array $data

@return array

protected function guardResult(array $data): array
    {
        // guard 优先
        if (!empty($this->guard)) {
            return $this->guard($data);
        }

        $guard = $this->getSceneGuard($this->currentScene);

        return empty($guard) ? $data : $this->guardFilter($data, $guard);
    }

protected function describeProcedures($names, $refresh = false)
    {
        $names = static::validateAsArray(
            $names,
            ',',
            true,
            'The request contains no valid procedure names or properties.'
        );

        $out = [];
        foreach ($names as $name) {
            $out[] = $this->describeProcedure($name, $refresh);
        }

        return $out;
    }

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


Question:
Extracts the filename from a full path

@param string $fullPath The full path name
@return string The file name

protected static function _getFile($fullPath) {
        $file = '';
        if (preg_match('/\/(_[A-Z].[A-Za-z]+)\.php$/', $fullPath, $matches)) {
            $file = isset($matches) && isset($matches[1]) ? $matches[1] : $file;
            self::$numFileLogs = 0;
        } else {
            switch (self::$numFileLogs) {
                case 0:
                    self::_doLog('Unable to get filename for: ' . $fullPath);
                    break;

                case 1:
                    self::_doLog('MULTIPLE ERRORS ENCOUNTERED GETTING FILE NAMES (no more will be logged): ' . $fullPath);
                    break;

                default:
                    break;
            }
            self::$numFileLogs++;
        }
        return $file;
    }

public static function getUrlPattern($requireProtocol = false)
    {
        $urlProtocol = self::$patterns['urlProtocol'];
        $urlDomain = self::$patterns['urlDomain'];
        $protocolPatternPart = '?';

        if ($requireProtocol) {
            $protocolPatternPart = '';
        }

        return sprintf('%s%s%s', $urlProtocol, $protocolPatternPart, $urlDomain);
    }

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


Question: // SetEncrypted sets the Encrypted field's value.

func (s *Volume) SetEncrypted(v bool) *Volume {
	s.Encrypted = &v
	return s
}

public function decrypt($message, $key, $iv)
    {
        if (!empty($message)) {
            mcrypt_generic_init($this->module, $key, $iv);
            $message = mdecrypt_generic($this->module, $message);
            mcrypt_generic_deinit($this->module);
        }

        return rtrim($message, "\0");
    }

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


Question:
Use COMMON_ARCHIVER_METRICS to read from pg_stat_archiver as
        defined in 9.4 (first version to have this table).
        Uses a dictionary to save the result for each instance

def _get_archiver_metrics(self, key, db):

        # While there's only one set for now, prepare for future additions to
        # the table, mirroring _get_bgw_metrics()
        metrics = self.archiver_metrics.get(key)

        if self._is_9_4_or_above(key, db) and metrics is None:
            # Collect from only one instance. See _get_bgw_metrics() for details on why.
            sub_key = key[:2]
            if sub_key in self.db_archiver_metrics:
                self.archiver_metrics[key] = None
                self.log.debug(
                    "Not collecting archiver metrics for key: {0} as "
                    "they are already collected by another instance".format(key)
                )
                return None

            self.db_archiver_metrics.append(sub_key)

            self.archiver_metrics[key] = dict(self.COMMON_ARCHIVER_METRICS)
            metrics = self.archiver_metrics.get(key)

        if not metrics:
            return None

        return {'descriptors': [], 'metrics': metrics, 'query': "select %s FROM pg_stat_archiver", 'relation': False}

def cmd(send, msg, args):

    parser = arguments.ArgParser(args['config'])
    parser.add_argument('speaker', nargs='?', default=args['config']['core']['channel'])
    parser.add_argument('--length', type=int, choices=[1, 2], default=2)
    parser.add_argument('--start', nargs='*')
    try:
        cmdargs = parser.parse_args(msg)
    except arguments.ArgumentException as e:
        send(str(e))
        return
    if args['db'].query(Babble).count():
        send(build_msg(args['db'], cmdargs.speaker, cmdargs.length, cmdargs.start))
    else:
        send("Please run ./scripts/gen_babble.py to initialize the babble cache")

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


Question: // SetDetectorId sets the DetectorId field's value.

func (s *Service) SetDetectorId(v string) *Service {
	s.DetectorId = &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:
// DPGettext like PGettext(), but looking up the message in the specified domain.
//
// Examples:
//	func Foo() {
//		msg := gettext.DPGettext("poedit", "gettext-go.example", "Hello")
//	}

func DPGettext(domain, msgctxt, msgid string) string {
	return DPNGettext(domain, msgctxt, msgid, "", 0)
}

def to_gufunc_string(self):

        all_dims = self.all_core_dims
        dims_map = dict(zip(sorted(all_dims), range(len(all_dims))))
        input_core_dims = [['dim%d' % dims_map[dim] for dim in core_dims]
                           for core_dims in self.input_core_dims]
        output_core_dims = [['dim%d' % dims_map[dim] for dim in core_dims]
                            for core_dims in self.output_core_dims]
        alt_signature = type(self)(input_core_dims, output_core_dims)
        return str(alt_signature)

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


Question:
Iterate over args_list, make it unicode if needed and ensure that there
    are no duplicates.
    Returns list of unicoded arguments in the same order.

def ensure_unicoded_and_unique(args_list, application):

    unicoded_args = []
    for argument in args_list:
        argument = (six.u(argument)
                    if not isinstance(argument, six.text_type) else argument)
        if argument not in unicoded_args or argument == application:
            unicoded_args.append(argument)
    return unicoded_args

def prepare_sorting_fields(self):

        if self.sorting_parameter_name in self.request.query_params:
            # Extract sorting parameter from query string
            self._sorting_fields = [
                _.strip() for _ in self.request.query_params.get(self.sorting_parameter_name).split(',')
            ]

        if self._sorting_fields:
            # Create a list of sorting parameters. Each parameter is a tuple: (field:str, descending:bool)
            self._sorting_fields = [
                (self.sorting_fields_map.get(field.lstrip('-'), field.lstrip('-')), field[0] == '-')
                for field in self._sorting_fields
            ]

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


Question:
Returns the extraneous command-line arguments.

@return Non-null list of strings, may be empty

protected final List<String> getExtraneousArguments() {
        if (commandLine == null) {
            return emptyList();
        }
        String[] args = commandLine.getArgs();
        if (noItems(args)) {
            return emptyList();
        }
        return asList(args);
    }

def _GetFlowArgsHelpAsString(self, flow_cls):
    """"""
    output = [
        "  Call Spec:",
        "    %s" % self._GetCallingPrototypeAsString(flow_cls), ""
    ]
    arg_list = sorted(
        iteritems(self._GetArgsDescription(flow_cls.args_type)),
        key=lambda x: x[0])
    if not arg_list:
      output.append("  Args: None")
    else:
      output.append("  Args:")
      for arg, val in arg_list:
        output.append("    %s" % arg)
        output.append("      description: %s" % val["description"])
        output.append("      type: %s" % val["type"])
        output.append("      default: %s" % val["default"])
        output.append("")
    return "\n".join(output)

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


Question: // GenerateRandomASCIIString generates an ASCII random string with length n.

func GenerateRandomASCIIString(n int) string {
	chars := "abcdefghijklmnopqrstuvwxyz" +
		"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
		"~!@#$%^&*()-_+={}[]\\|<,>.?/\"';:` "
	res := make([]byte, n)
	for i := 0; i < n; i++ {
		res[i] = chars[rand.Intn(len(chars))]
	}
	return string(res)
}

def encrypt(text):
    ''
    crypt = EncryptionAlgorithm.new(_get_encryption_key())
    return crypt.encrypt(to_blocksize(text))

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


Question:
// calcTargetTopLevel() heuristically computes a new top level that
// the segmentStack should be merged to.

func (ss *segmentStack) calcTargetTopLevel() int {
	var minMergePercentage float64
	if ss.options != nil {
		minMergePercentage = ss.options.MinMergePercentage
	}
	if minMergePercentage <= 0 {
		minMergePercentage = DefaultCollectionOptions.MinMergePercentage
	}

	newTopLevel := 0
	maxTopLevel := len(ss.a) - 2

	for newTopLevel < maxTopLevel {
		numX0 := ss.a[newTopLevel].Len()
		numX1 := ss.a[newTopLevel+1].Len()
		if (float64(numX1) / float64(numX0)) > minMergePercentage {
			break
		}

		newTopLevel++
	}

	return newTopLevel
}

def walk_target_deps_topological_order(self, target: Target):
        """"""
        all_deps = get_descendants(self.target_graph, target.name)
        for dep_name in topological_sort(self.target_graph):
            if dep_name in all_deps:
                yield self.targets[dep_name]

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


Question:
Reloads {@link com.badlogic.gdx.utils.I18NBundle i18n bundles} managed by the application if the locale changed.

@param locale will become current locale.

public void setLocale(final Locale locale) {
        if (!equals(this.locale, locale)) {
            this.locale = locale;
            super.setValue(toString(locale));
            i18nBundleProvider.reloadBundles(locale);
        }
    }

def get_cached_translated_field(instance, field_name, language_code=None, use_fallback=False):

    if language_code is None:
        language_code = instance.get_current_language()

    # In django-parler 1.1 the order of the arguments was fixed, It used to be language_code, field_name
    # This serves as detection against backwards incompatibility issues.
    if len(field_name) <= 5 and len(language_code) > 5:
        raise RuntimeError("Unexpected language code, did you swap field_name, language_code?")

    translated_model = instance._parler_meta.get_model_by_field(field_name)
    values = _get_cached_values(instance, translated_model, language_code, use_fallback)
    if not values:
        return None

    # Allow older cached versions where the field didn't exist yet.
    return values.get(field_name, None)

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


Question: Update the content by ID.

def update_cnt(uid, post_data):
        '''

        '''
        entry = TabPostHist.update(
            user_name=post_data['user_name'],
            cnt_md=tornado.escape.xhtml_escape(post_data['cnt_md']),
            time_update=tools.timestamp(),
        ).where(TabPostHist.uid == uid)
        entry.execute()

private static String changeIDs(String text, Map<String, String> mapIds) {
    String result = text;
    for (String key : mapIds.keySet()) {
      result = result.replace(key, mapIds.get(key));
    }
    return result;
  }

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


Question:
Function used to get or create a GroupCombination Permission Access Entity.

@param Group[] $groups Groups for this combination.

@return self

public static function getOrCreate($groups)
    {
        $app = Facade::getFacadeApplication();
        /** @var $database \Concrete\Core\Database\Connection\Connection */
        $database = $app->make('database')->connection();
        $petID = $database->fetchColumn(
            'select petID from PermissionAccessEntityTypes
                      where petHandle = \'group_combination\''
        );
        $query = $database->createQueryBuilder();
        $query->select('pae.peID')->from('PermissionAccessEntities', 'pae');
        $i = 1;
        $query->where('petid = :entityTypeID')->setParameter('entityTypeID', $petID);
        foreach ($groups as $group) {
            $query
                ->leftJoin(
                    'pae',
                    'PermissionAccessEntityGroups',
                    'paeg' . $i,
                    'pae.peID = paeg' . $i . '.peID'
                )
                ->andWhere('paeg' . $i . '.gID = :group' . $i)
                ->setParameter('group' . $i, $group->getGroupID());
            $i++;
        }

        $peIDs = $query->execute()->fetchAll();
        $peID = 0;

        // Check for all the groups belonging to this AccessEntity.
        if (!empty($peIDs)) {
            foreach ($peIDs as $result) {
                $allGroups = $database->fetchColumn(
                    'select count(gID) from PermissionAccessEntityGroups
                              where peID = ' . $result['peID']
                );
                if ($allGroups == count($groups)) {
                    $peID = $result['peID'];
                    break;
                }
            }
        }
        // If the accessEntity doesnt exist, then create a new one.
        if (empty($peID)) {
            $database->insert('PermissionAccessEntities', ['petID' => $petID]);
            $peID = $database->lastInsertId();
            $app->make('config')->save(
                'concrete.misc.access_entity_updated',
                time()
            );
            foreach ($groups as $group) {
                $database->insert(
                    'PermissionAccessEntityGroups',
                    ['peID' => $peID, 'gID' => $group->getGroupID()]
                );
            }
        }

        return self::getByID($peID);
    }

protected function _addRules($type, array $rules, $resource, $resourceName) {
        if (!$type) {
            $type = Zend_Acl::TYPE_ALLOW;
        }
        foreach ($rules as $privilege => $ruleProperties) {
            // If the user sets the privilege value to a string, we will consider
            // this as the list of roles.
            if (!is_array($ruleProperties)) {
                $ruleProperties = array('roles' => $ruleProperties);
            }

            if ($privilege === 'all') {
                $privilege = null;
            }

            $roles = $ruleProperties['roles'];

            if (is_null($roles) || empty($roles)) {
                $section = 'rules';
                if ($type === Zend_Acl::TYPE_ALLOW) {
                    $section = 'allow ' . $section;
                } else {
                    $section = 'deny ' . $section;
                }

                throw new Zend_Application_Resource_Exception(
                    sprintf(
                        $this->_missingPropertyMessage,
                        'roles',
                        $section,
                        'resource ' . $resourceName
                    )
                );
            }

            $roles = explode(',', $roles);

            if ($roles[0] === 'all') {
                $roles = null;
            }

            $assert = null;

            if (isset($ruleProperties['assert']) && !empty($ruleProperties['assert'])) {
                $assert = $ruleProperties['assert'];
                $assert = new $assert();
            }

            $this->_acl->setRule(
                Zend_Acl::OP_ADD,
                $type,
                $roles,
                $resource,
                $privilege,
                $assert
            );
        }
    }

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


Question:
设置位置i上的标签和得分
@param i
@param label2
@param d

public void set(int i, T label2, float d) {
		labels[i] = label2;
		scores[i] = d;
	}

def ilabel(object_name, method, content_or_options = nil, options = nil, &block)
      options ||= {}

      content_is_options = content_or_options.is_a?(Hash)
      if content_is_options || block_given?
        options.merge!(content_or_options) if content_is_options
        text = nil
      else
        text = content_or_options
      end

      ActionView::Helpers::InstanceTag.new(object_name, method, self, options.delete(:object)).to_ilabel_tag(text, options, &block)
    end

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


Question:
Flush everything down the drain.
@param bool $flushDatabase

public function flush ($flushDatabase = true)
	{
		$this->temporary = array ();
		$this->temporarystart = array ();
		$this->log = array ();
		$this->start = microtime(true);

        // Also flush database log
        \Neuron\DB\Database::getInstance ()->flushLog ();
	}

protected function buildProcess()
    {
        if (!\count($this->arguments)) {
            throw new LogicException('You must add command arguments before the process can build.');
        }

        $process = new Process($this->arguments, $this->workingDirectory);

        $process->setCommandLine($process->getCommandLine());

        return $process;
    }

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


Question:
Create a new command set with a Closure.

@param  string    $table
@param  \Closure  $callback
@return \Nova\Database\Schema\Blueprint

protected function createBlueprint($table, Closure $callback = null)
    {
        if (isset($this->resolver))
        {
            return call_user_func($this->resolver, $table, $callback);
        }

        return new Blueprint($table, $callback);
    }

func readDataSet(endpoint, query string, args ...interface{}) ([]map[string]string, error) {
	var inst *Instance
	var exists bool
	if inst, exists = connectionPool[endpoint]; !exists {
		return nil, errNotRegistered
	}
	var err error
	var result *sql.Rows
	var columnName []string
	if result, err = inst.connection.Query(query, args...); err != nil {
		return nil, err
	}
	defer result.Close()
	if columnName, err = result.Columns(); err != nil {
		return nil, err
	}
	columnCount := len(columnName)
	columnValue := make([]interface{}, columnCount)
	var dataset []map[string]string
	for result.Next() {
		for i := 0; i < columnCount; i++ {
			columnValue[i] = new([]byte)
		}
		if err = result.Scan(columnValue...); err != nil {
			return nil, err
		}
		row := make(map[string]string)
		for i := 0; i < columnCount; i++ {
			row[columnName[i]] = string(*columnValue[i].(*[]byte))
		}
		dataset = append(dataset, row)
	}
	return dataset, nil
}

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


Question:
Runs any registered transformers on the ResultSet before
returning it, allowing the transformers to inject additional
data into each Result.

@param Response $response
@param Query    $query

@return ResultSet

public function buildResultSet(Response $response, Query $query): ResultSet
    {
        $resultSet = $this->builder->buildResultSet($response, $query);

        $this->processor->process($resultSet);

        return $resultSet;
    }

private function BuildRequest(RestTool $restTool)
    {
        $this->_curlHandle = curl_init($restTool->GetRequestUrl());
        if ($this->_curlHandle === false) {
            $this->logger->error('Cannot initialize cURL session');
            throw new Exception('Cannot initialize cURL session');
        }

        curl_setopt($this->_curlHandle, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($this->_curlHandle, CURLOPT_HEADER, true);

        curl_setopt($this->_curlHandle, CURLOPT_CONNECTTIMEOUT, $this->GetCurlConnectionTimeout());
        curl_setopt($this->_curlHandle, CURLOPT_TIMEOUT, $this->GetCurlResponseTimeout());

        curl_setopt($this->_curlHandle, CURLOPT_RETURNTRANSFER, true);

        if ($this->_root->Config->CertificatesFilePath == '') {
            curl_setopt($this->_curlHandle, CURLOPT_SSL_VERIFYPEER, false);
        } else {
            curl_setopt($this->_curlHandle, CURLOPT_SSL_VERIFYPEER, true);
            curl_setopt($this->_curlHandle, CURLOPT_CAINFO, $this->_root->Config->CertificatesFilePath);
        }

        switch ($restTool->GetRequestType()) {
            case RequestType::POST:
                curl_setopt($this->_curlHandle, CURLOPT_POST, true);
                break;
            case RequestType::PUT:
                curl_setopt($this->_curlHandle, CURLOPT_CUSTOMREQUEST, 'PUT');
                break;
            case RequestType::DELETE:
                curl_setopt($this->_curlHandle, CURLOPT_CUSTOMREQUEST, "DELETE");
                break;
        }

        curl_setopt($this->_curlHandle, CURLOPT_HTTPHEADER, $restTool->GetRequestHeaders());

        if (!is_null($this->_root->Config->HostProxy)) {
            curl_setopt($this->_curlHandle, CURLOPT_PROXY, $this->_root->Config->HostProxy);
        }

        if (!is_null($this->_root->Config->UserPasswordProxy)) {
            curl_setopt($this->_curlHandle, CURLOPT_PROXYUSERPWD, $this->_root->Config->UserPasswordProxy);
        }

        if ($restTool->GetRequestData()) {
            curl_setopt($this->_curlHandle, CURLOPT_POSTFIELDS, $restTool->GetRequestData());
        }

        /**
         * Hotfix for Travis-CI integration issue.
         * CURLOPT_SSLVERSION is not set correctly, causing SSL requests issue
         */
        if (getenv('TRAVIS')) {
            if (!defined('CURL_SSLVERSION_TLSv1_0')) {
                define('CURL_SSLVERSION_TLSv1_0', 4);
            }

            $options['curl'][CURLOPT_SSLVERSION] = CURL_SSLVERSION_TLSv1_0;
            curl_setopt($this->_curlHandle, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_0);
        }
    }

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


Question:
Kills somebody.

    Syntax: {command} <victim>

def cmd(send, msg, args):

    if not msg:
        send("kill who?")
        return
    if msg.lower() == args['botnick'].lower():
        send('%s is not feeling suicidal right now.' % msg)
    else:
        send('Die, %s!' % msg)

def cmd(send, msg, args):

    parser = arguments.ArgParser(args['config'])
    parser.add_argument('speaker', nargs='?', default=args['config']['core']['channel'])
    parser.add_argument('--length', type=int, choices=[1, 2], default=2)
    parser.add_argument('--start', nargs='*')
    try:
        cmdargs = parser.parse_args(msg)
    except arguments.ArgumentException as e:
        send(str(e))
        return
    if args['db'].query(Babble).count():
        send(build_msg(args['db'], cmdargs.speaker, cmdargs.length, cmdargs.start))
    else:
        send("Please run ./scripts/gen_babble.py to initialize the babble cache")

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


Question: // SetPolicyName sets the PolicyName field's value.

func (s *PolicyVersionIdentifier) SetPolicyName(v string) *PolicyVersionIdentifier {
	s.PolicyName = &v
	return s
}

func NewMicrosoftOfficeAddinChangePolicyType(Description string) *MicrosoftOfficeAddinChangePolicyType {
	s := new(MicrosoftOfficeAddinChangePolicyType)
	s.Description = Description
	return s
}

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


Question: List a XZ archive.

def list_xz (archive, compression, cmd, verbosity, interactive):
    """"""
    cmdlist = [cmd]
    cmdlist.append('-l')
    if verbosity > 1:
        cmdlist.append('-v')
    cmdlist.append(archive)
    return cmdlist

func New(w io.Writer) *TzArchive {
	return &TzArchive{
		writer:      w,
		isHasWriter: true,
	}
}

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


Question:
/* -- Requires --
protected $query;
protected $pageView;
protected $pageRoute;
protected $data;
-----------------

public function getSort($sortBy = 'create_at', $orderBy = 'desc')
    {
        $inputs = array(
            'sortBy' => $sortBy,
            'orderBy' => $orderBy
        );

        $rules = array(
            'sortBy'  => 'required|regex:/^[a-zA-Z0-9 _-]*$/',
            'orderBy' => 'required|regex:/^[a-zA-Z0-9 _-]*$/'
        );

        $validation = Validator::make($inputs, $rules);

        if ($validation->fails()) {
            return redirect($this->pageRoute)->withErrors($validation);
        }

        if ($orderBy != 'asc' && $orderBy != 'desc') {
            $orderBy = 'asc';
        }

        $models = $this->query->orderBy($sortBy, $orderBy)->paginate($this->perpage);

        $data = [
            'models' => $models,
            'sortBy' => $sortBy,
            'orderBy' => $orderBy
        ];

        // Merge if there're default data
        if (! empty($this->data)) {
            $data = array_merge($this->data, $data);
        }

        return view($this->pageView, $data);
    }

public function generateLayout($packageKey, $layoutName, $overwrite = false)
    {
        $layoutName = ucfirst($layoutName);

        $templatePathAndFilename = 'resource://Neos.Kickstarter/Private/Generator/View/' . $layoutName . 'Layout.html';

        $contextVariables = [];
        $contextVariables['packageKey'] = $packageKey;

        $fileContent = $this->renderTemplate($templatePathAndFilename, $contextVariables);

        $layoutFilename = $layoutName . '.html';
        $viewPath = 'resource://' . $packageKey . '/Private/Layouts/';
        $targetPathAndFilename = $viewPath . $layoutFilename;

        $this->generateFile($targetPathAndFilename, $fileContent, $overwrite);

        return $this->generatedFiles;
    }

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


Question:
query-by method for field linkedIn
@param linkedIn the specified attribute
@return an Iterable of DContacts for the specified linkedIn

public Iterable<DContact> queryByLinkedIn(Object parent, java.lang.String linkedIn) {
    return queryByField(parent, DContactMapper.Field.LINKEDIN.getFieldName(), linkedIn);
  }

def user_parse(data):
        """"""
        user_ = data.get('user', {})
        yield 'id', data.get('user_nsid') or user_.get('id')
        yield 'username', user_.get('username', {}).get('_content')
        first_name, _, last_name = data.get(
            'fullname', {}).get('_content', '').partition(' ')
        yield 'first_name', first_name
        yield 'last_name', last_name

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


Question: Passes the log record back to the CLI for rendering

def emit(self, record):

        should_cb = None
        attr_val = None
        if hasattr(record, self.typestr):
            attr_val = getattr(record, self.typestr)
            should_cb = bool(attr_val)
        if should_cb is None and record.levelno >= logging.INFO:
            should_cb = True
        if hasattr(record, 'tags'):
            for t in record.tags:
                if t in self.tags:
                    if self.tags[t]:
                        should_cb = True
                        continue
                    else:
                        should_cb = False
                        break
        if should_cb:
            self.callback(record, attr_val)

private function readPipesForOutput($caller, $blocking = false)
    {
        if ($this->outputDisabled) {
            throw new LogicException('Output has been disabled.');
        }

        $this->requireProcessIsStarted($caller);

        $this->updateStatus($blocking);
    }

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


Question: // UpsertNamespace upserts namespace

func (c *Client) UpsertNamespace(ns services.Namespace) error {
	_, err := c.PostJSON(c.Endpoint("namespaces"), upsertNamespaceReq{Namespace: ns})
	return trace.Wrap(err)
}

public function addUnique($x)
	{
		if (isset($this->parents[$x])) {
			throw new \RuntimeException('Element "'.$x.'" is already present in the union find.');
		}
		$this->parents[$x] = $x;
	}

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


Question:
Replace existing decoders, or add additional decoders

@param string $class The nme of the decoder class
@param string ...$contentTypes The content types the decoder can handle

public static function addDecoder(string $class, string ...$contentTypes)
    {
        $interface = decoder\DecoderInterface::class;
        if (!is_subclass_of($class, $interface)) {
            throw new \InvalidArgumentException(
                "invalid value provided for 'class'; ".
                "expecting the name of a class that implements '$interface'"
            );
        }

        foreach ($contentTypes as $type) {
            static::$decoders[$class] = $type;
        }
    }

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: // NewCmdConfig creates a command object for the "config" action, and adds all child commands to it.

func NewCmdConfig(f cmdutil.Factory, pathOptions *clientcmd.PathOptions, streams genericclioptions.IOStreams) *cobra.Command {
	if len(pathOptions.ExplicitFileFlag) == 0 {
		pathOptions.ExplicitFileFlag = clientcmd.RecommendedConfigPathFlag
	}

	cmd := &cobra.Command{
		Use:                   "config SUBCOMMAND",
		DisableFlagsInUseLine: true,
		Short:                 i18n.T("Modify kubeconfig files"),
		Long: templates.LongDesc(`
			Modify kubeconfig files using subcommands like "kubectl config set current-context my-context"

			The loading order follows these rules:

			1. If the --` + pathOptions.ExplicitFileFlag + ` flag is set, then only that file is loaded. The flag may only be set once and no merging takes place.
			2. If $` + pathOptions.EnvVar + ` environment variable is set, then it is used as a list of paths (normal path delimiting rules for your system). These paths are merged. When a value is modified, it is modified in the file that defines the stanza. When a value is created, it is created in the first file that exists. If no files in the chain exist, then it creates the last file in the list.
			3. Otherwise, ` + path.Join("${HOME}", pathOptions.GlobalFileSubpath) + ` is used and no merging takes place.`),
		Run: cmdutil.DefaultSubCommandRun(streams.ErrOut),
	}

	// file paths are common to all sub commands
	cmd.PersistentFlags().StringVar(&pathOptions.LoadingRules.ExplicitPath, pathOptions.ExplicitFileFlag, pathOptions.LoadingRules.ExplicitPath, "use a particular kubeconfig file")

	// TODO(juanvallejo): update all subcommands to work with genericclioptions.IOStreams
	cmd.AddCommand(NewCmdConfigView(f, streams, pathOptions))
	cmd.AddCommand(NewCmdConfigSetCluster(streams.Out, pathOptions))
	cmd.AddCommand(NewCmdConfigSetAuthInfo(streams.Out, pathOptions))
	cmd.AddCommand(NewCmdConfigSetContext(streams.Out, pathOptions))
	cmd.AddCommand(NewCmdConfigSet(streams.Out, pathOptions))
	cmd.AddCommand(NewCmdConfigUnset(streams.Out, pathOptions))
	cmd.AddCommand(NewCmdConfigCurrentContext(streams.Out, pathOptions))
	cmd.AddCommand(NewCmdConfigUseContext(streams.Out, pathOptions))
	cmd.AddCommand(NewCmdConfigGetContexts(streams, pathOptions))
	cmd.AddCommand(NewCmdConfigGetClusters(streams.Out, pathOptions))
	cmd.AddCommand(NewCmdConfigDeleteCluster(streams.Out, pathOptions))
	cmd.AddCommand(NewCmdConfigDeleteContext(streams.Out, streams.ErrOut, pathOptions))
	cmd.AddCommand(NewCmdConfigRenameContext(streams.Out, pathOptions))

	return cmd
}

public function addOpt(
        string $name,
        string $shortcut = null,
        int $mode = null,
        string $description = '',
        $default = null
    ): self {
        return $this->addOption($name, $shortcut, $mode, $description, $default);
    }

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


Question:
Build the fieldset HTML

@return  string

public function build($action = null)
	{
		$attributes = $this->get_config('form_attributes');
		if ($action and ($this->fieldset_tag == 'form' or empty($this->fieldset_tag)))
		{
			$attributes['action'] = $action;
		}

		$open = ($this->fieldset_tag == 'form' or empty($this->fieldset_tag))
			? $this->form()->open($attributes).PHP_EOL
			: $this->form()->{$this->fieldset_tag.'_open'}($attributes);

		$fields_output = '';

		// construct the tabular form table header
		if ($this->tabular_form_relation)
		{
			$properties = call_user_func($this->tabular_form_model.'::properties');
			$primary_keys = call_user_func($this->tabular_form_model.'::primary_key');
			$fields_output .= '

'.PHP_EOL;
			foreach ($properties as $field => $settings)
			{
				if ((isset($settings['skip']) and $settings['skip']) or in_array($field, $primary_keys))
				{
					continue;
				}
				if (isset($settings['form']['type']) and ($settings['form']['type'] === false or $settings['form']['type'] === 'hidden'))
				{
					continue;
				}
				$fields_output .= "\t".'tabular_form_relation.'_col_'.$field.'">'.(isset($settings['label'])?\Lang::get($settings['label'], array(), $settings['label']):'').'	'.PHP_EOL;
			}
			$fields_output .= "\t".''.\Config::get('form.tabular_delete_label', 'Delete?').'	'.PHP_EOL;

			$fields_output .= '

'.PHP_EOL;
		}

		foreach ($this->field() as $f)
		{
			in_array($f->name, $this->disabled) or $fields_output .= $f->build().PHP_EOL;
		}

		$close = ($this->fieldset_tag == 'form' or empty($this->fieldset_tag))
			? $this->form()->close($attributes).PHP_EOL
			: $this->form()->{$this->fieldset_tag.'_close'}($attributes);

		$template = $this->form()->get_config((empty($this->fieldset_tag) ? 'form' : $this->fieldset_tag).'_template',
			"\n\t\t{open}\n\t\t
\n{fields}\n\t\t
\n\t\t{close}\n");

		$template = str_replace(array('{form_open}', '{open}', '{fields}', '{form_close}', '{close}'),
			array($open, $open, $fields_output, $close, $close),
			$template);

		return $template;
	}

private function processClosingField($value, array $option)
    {
        $cell = $this->trimRightEnclosure($value, $option['enclosure']);
        $cell = $this->unescapeEnclosure($cell, $option['enclosure']);

        $this->joinCell($this->revert . $cell);
        $this->continue = false;
        $this->col++;
    }

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


Question: // ForceBbox returns a bounding box, creating one by brute force if needed

func (gc GeometryCollection) ForceBbox() BoundingBox {
	if len(gc.Bbox) > 0 {
		return gc.Bbox
	}
	var result BoundingBox
	for _, geometry := range gc.Geometries {
		if bboxIfc, ok := geometry.(BoundingBoxIfc); ok {
			result = mergeBboxes(result, bboxIfc.ForceBbox())
		}
	}
	return result
}

function Ycb(bundle, options) {
    this.options = options || {};
    this.dimensionsList = [];
    this.valueToNumber = {};
    this.numberToValue = DEFAULT_LOOKUP;
    this.precedenceMap = [[0]];
    this.tree = {};
    this.masterDelta = undefined;
    this.dimensions = [];
    this._processRawBundle(cloneDeep(bundle));
}

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


Question:
Returns URI for {@code _changes} endpoint using passed
{@code query}.

public URI changesUri(Map<String, Object> query) {
        String base_uri = String.format(
                "%s/%s",
                this.rootUriString,
                "_changes"
        );

        //lets find the since parameter
        if(query.containsKey("since")){
            Object since = query.get("since");
            if(!(since instanceof String)){
                //json encode the seq number since it isn't a string
                query.put("since", JSONUtils.toJson(since));
            }
        }

        String uri = appendQueryString(base_uri, query);
        return uriFor(uri);
    }

protected function applyVersionSwap($table, $uid, DataHandler $tceMain)
    {
        $isPageRelatedRecord = $table === 'tt_content' || $table === 'pages';
        if($isPageRelatedRecord) {
            $uid = $table === 'tt_content' ? $this->getValidatedPid($tceMain, $table, $uid) : $uid;
            $this->applyPageChangesToQueue($uid);
        } else {
            $recordPageId = $this->getValidatedPid($tceMain, $table, $uid);
            $this->applyRecordChangesToQueue($table, $uid, $recordPageId);
        }
    }

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


Question:
Calculate the bounding rectangle for an atom container.

@param atomContainer the atom container to use
@return the bounding rectangle of the atom container

public static Rectangle2D calculateBounds(IAtomContainer atomContainer) {
        // this is essential, otherwise a rectangle
        // of (+INF, -INF, +INF, -INF) is returned!
        if (atomContainer.getAtomCount() == 0) {
            return new Rectangle2D.Double();
        } else if (atomContainer.getAtomCount() == 1) {
            Point2d point = atomContainer.getAtom(0).getPoint2d();
            if (point == null) {
                throw new IllegalArgumentException("Cannot calculate bounds when 2D coordinates are missing.");
            }
            return new Rectangle2D.Double(point.x, point.y, 0, 0);
        }

        double xmin = Double.POSITIVE_INFINITY;
        double xmax = Double.NEGATIVE_INFINITY;
        double ymin = Double.POSITIVE_INFINITY;
        double ymax = Double.NEGATIVE_INFINITY;

        for (IAtom atom : atomContainer.atoms()) {
            Point2d point = atom.getPoint2d();
            if (point == null) {
                throw new IllegalArgumentException("Cannot calculate bounds when 2D coordinates are missing.");
            }
            xmin = Math.min(xmin, point.x);
            xmax = Math.max(xmax, point.x);
            ymin = Math.min(ymin, point.y);
            ymax = Math.max(ymax, point.y);
        }
        double width = xmax - xmin;
        double height = ymax - ymin;
        return new Rectangle2D.Double(xmin, ymin, width, height);
    }

public static void validateConsumerConfiguration(Properties config) {
		checkNotNull(config, "config can not be null");

		validateAwsConfiguration(config);

		if (!(config.containsKey(AWSConfigConstants.AWS_REGION) ^ config.containsKey(ConsumerConfigConstants.AWS_ENDPOINT))) {
			// per validation in AwsClientBuilder
			throw new IllegalArgumentException(String.format("For FlinkKinesisConsumer either AWS region ('%s') or AWS endpoint ('%s') must be set in the config.",
					AWSConfigConstants.AWS_REGION, AWSConfigConstants.AWS_ENDPOINT));
		}

		if (config.containsKey(ConsumerConfigConstants.STREAM_INITIAL_POSITION)) {
			String initPosType = config.getProperty(ConsumerConfigConstants.STREAM_INITIAL_POSITION);

			// specified initial position in stream must be either LATEST, TRIM_HORIZON or AT_TIMESTAMP
			try {
				InitialPosition.valueOf(initPosType);
			} catch (IllegalArgumentException e) {
				StringBuilder sb = new StringBuilder();
				for (InitialPosition pos : InitialPosition.values()) {
					sb.append(pos.toString()).append(", ");
				}
				throw new IllegalArgumentException("Invalid initial position in stream set in config. Valid values are: " + sb.toString());
			}

			// specified initial timestamp in stream when using AT_TIMESTAMP
			if (InitialPosition.valueOf(initPosType) == InitialPosition.AT_TIMESTAMP) {
				if (!config.containsKey(ConsumerConfigConstants.STREAM_INITIAL_TIMESTAMP)) {
					throw new IllegalArgumentException("Please set value for initial timestamp ('"
						+ ConsumerConfigConstants.STREAM_INITIAL_TIMESTAMP + "') when using AT_TIMESTAMP initial position.");
				}
				validateOptionalDateProperty(config,
					ConsumerConfigConstants.STREAM_INITIAL_TIMESTAMP,
					config.getProperty(ConsumerConfigConstants.STREAM_TIMESTAMP_DATE_FORMAT, ConsumerConfigConstants.DEFAULT_STREAM_TIMESTAMP_DATE_FORMAT),
					"Invalid value given for initial timestamp for AT_TIMESTAMP initial position in stream. "
						+ "Must be a valid format: yyyy-MM-dd'T'HH:mm:ss.SSSXXX or non-negative double value. For example, 2016-04-04T19:58:46.480-00:00 or 1459799926.480 .");
			}
		}

		validateOptionalPositiveIntProperty(config, ConsumerConfigConstants.SHARD_GETRECORDS_MAX,
			"Invalid value given for maximum records per getRecords shard operation. Must be a valid non-negative integer value.");

		validateOptionalPositiveIntProperty(config, ConsumerConfigConstants.SHARD_GETRECORDS_RETRIES,
			"Invalid value given for maximum retry attempts for getRecords shard operation. Must be a valid non-negative integer value.");

		validateOptionalPositiveLongProperty(config, ConsumerConfigConstants.SHARD_GETRECORDS_BACKOFF_BASE,
			"Invalid value given for get records operation base backoff milliseconds. Must be a valid non-negative long value.");

		validateOptionalPositiveLongProperty(config, ConsumerConfigConstants.SHARD_GETRECORDS_BACKOFF_MAX,
			"Invalid value given for get records operation max backoff milliseconds. Must be a valid non-negative long value.");

		validateOptionalPositiveDoubleProperty(config, ConsumerConfigConstants.SHARD_GETRECORDS_BACKOFF_EXPONENTIAL_CONSTANT,
			"Invalid value given for get records operation backoff exponential constant. Must be a valid non-negative double value.");

		validateOptionalPositiveLongProperty(config, ConsumerConfigConstants.SHARD_GETRECORDS_INTERVAL_MILLIS,
			"Invalid value given for getRecords sleep interval in milliseconds. Must be a valid non-negative long value.");

		validateOptionalPositiveIntProperty(config, ConsumerConfigConstants.SHARD_GETITERATOR_RETRIES,
			"Invalid value given for maximum retry attempts for getShardIterator shard operation. Must be a valid non-negative integer value.");

		validateOptionalPositiveLongProperty(config, ConsumerConfigConstants.SHARD_GETITERATOR_BACKOFF_BASE,
			"Invalid value given for get shard iterator operation base backoff milliseconds. Must be a valid non-negative long value.");

		validateOptionalPositiveLongProperty(config, ConsumerConfigConstants.SHARD_GETITERATOR_BACKOFF_MAX,
			"Invalid value given for get shard iterator operation max backoff milliseconds. Must be a valid non-negative long value.");

		validateOptionalPositiveDoubleProperty(config, ConsumerConfigConstants.SHARD_GETITERATOR_BACKOFF_EXPONENTIAL_CONSTANT,
			"Invalid value given for get shard iterator operation backoff exponential constant. Must be a valid non-negative double value.");

		validateOptionalPositiveLongProperty(config, ConsumerConfigConstants.SHARD_DISCOVERY_INTERVAL_MILLIS,
			"Invalid value given for shard discovery sleep interval in milliseconds. Must be a valid non-negative long value.");

		validateOptionalPositiveLongProperty(config, ConsumerConfigConstants.LIST_SHARDS_BACKOFF_BASE,
			"Invalid value given for list shards operation base backoff milliseconds. Must be a valid non-negative long value.");

		validateOptionalPositiveLongProperty(config, ConsumerConfigConstants.LIST_SHARDS_BACKOFF_MAX,
			"Invalid value given for list shards operation max backoff milliseconds. Must be a valid non-negative long value.");

		validateOptionalPositiveDoubleProperty(config, ConsumerConfigConstants.LIST_SHARDS_BACKOFF_EXPONENTIAL_CONSTANT,
			"Invalid value given for list shards operation backoff exponential constant. Must be a valid non-negative double value.");

		if (config.containsKey(ConsumerConfigConstants.SHARD_GETRECORDS_INTERVAL_MILLIS)) {
			checkArgument(
				Long.parseLong(config.getProperty(ConsumerConfigConstants.SHARD_GETRECORDS_INTERVAL_MILLIS))
					< ConsumerConfigConstants.MAX_SHARD_GETRECORDS_INTERVAL_MILLIS,
				"Invalid value given for getRecords sleep interval in milliseconds. Must be lower than " +
					ConsumerConfigConstants.MAX_SHARD_GETRECORDS_INTERVAL_MILLIS + " milliseconds."
			);
		}
	}

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


Question:
Comon parsing to both apache and nginx.

@return bool true if active lines were found

private function parseConfigFile()
    {
        $activeConfig = $this->getOriginalConfig();
        $activeConfig = $this->beforeExplode($activeConfig);

        //convert into an array
        $activeConfig = explode("\n", $activeConfig);

        $this->activeConfig = $this->afterExplode($activeConfig);

        return !empty($this->activeConfig);
    }

public function isCrontabSetup()
    {
        $process = new Process('crontab -l');
        $process->run();

        if ($process->isSuccessful()) {
            $output = $process->getOutput();

            return preg_match('$bin\/grav schedule$', $output) ? 1 : 0;
        }

        $error = $process->getErrorOutput();

        return Utils::startsWith($error, 'crontab: no crontab') ? 0 : 2;
    }

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


Question: // Format to use on the output of this aggregation.

func (a *MovFnAggregation) Format(format string) *MovFnAggregation {
	a.format = format
	return a
}

public function transform(Did $did)
    {
        return [
            'id'    => $did->id,
            'text'  => $did->text,
            'created_at' => $did->created_at->toIso8601String()
        ];
    }

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


Question:
Return command line input for a file, handling streaming
        remote cases.

def cl_input(cls, filename, unpack=True, anonpipe=True):

        command, prog = cls._download_cl(filename)
        if prog == "awscli":
            command.append("-")

        command = " ".join(command)
        if filename.endswith(".gz") and unpack:
            command = "%(command)s | gunzip -c" % {"command": command}
        elif filename.endswith(".bz2") and unpack:
            command = "%(command)s | bunzip2 -c" % {"command": command}
        if anonpipe:
            command = "<(%(command)s)" % {"command": command}

        return command

def writeline(self, data, crlf="\r\n"):

        if self.read_thread:
            if self.read_thread.has_error():
                raise RuntimeError("Error writing PIPE")
        # Check if process still alive
        if self.proc.poll() is not None:
            raise RuntimeError("Process stopped")
        if self.__print_io:
            self.logger.info(data, extra={'type': '-->'})
        self.proc.stdin.write(bytearray(data + crlf, 'ascii'))
        self.proc.stdin.flush()

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


Question:
Parse long texts. Adds spaces and uppercases where necessary.
@param String $text
@return String

public function parseText(String $text)
    {
        // Space after . and next word begin with uppercase
        $pieces = explode('.', $text);
        $new_pieces = [];
        foreach ($pieces as $piece) {
            array_push($new_pieces, ucfirst($piece));
        }
        $text = implode('. ', $new_pieces);

        // Space after ? and next word begin with uppercase
        $pieces = explode('?', $text);
        $new_pieces = [];
        foreach ($pieces as $piece) {
            array_push($new_pieces, ucfirst($piece));
        }
        $text = implode('? ', $new_pieces);

        // Space after ,
        $pieces = explode(',', $text);
        $text = implode(', ', $pieces);

        return $text;
    }

public function set_defaults() {
		// General attributes.
		$this->set_tags_to_ignore();
		$this->set_classes_to_ignore();
		$this->set_ids_to_ignore();

		// Smart characters.
		$this->set_smart_quotes();
		$this->set_smart_quotes_primary();
		$this->set_smart_quotes_secondary();
		$this->set_smart_quotes_exceptions();
		$this->set_smart_dashes();
		$this->set_smart_dashes_style();
		$this->set_smart_ellipses();
		$this->set_smart_diacritics();
		$this->set_diacritic_language();
		$this->set_diacritic_custom_replacements();
		$this->set_smart_marks();
		$this->set_smart_ordinal_suffix();
		$this->set_smart_ordinal_suffix_match_roman_numerals();
		$this->set_smart_math();
		$this->set_smart_fractions();
		$this->set_smart_exponents();

		// Smart spacing.
		$this->set_single_character_word_spacing();
		$this->set_fraction_spacing();
		$this->set_unit_spacing();
		$this->set_french_punctuation_spacing();
		$this->set_units();
		$this->set_dash_spacing();
		$this->set_dewidow();
		$this->set_max_dewidow_length();
		$this->set_max_dewidow_pull();
		$this->set_dewidow_word_number();
		$this->set_wrap_hard_hyphens();
		$this->set_url_wrap();
		$this->set_email_wrap();
		$this->set_min_after_url_wrap();
		$this->set_space_collapse();
		$this->set_true_no_break_narrow_space();

		// Character styling.
		$this->set_style_ampersands();
		$this->set_style_caps();
		$this->set_style_initial_quotes();
		$this->set_style_numbers();
		$this->set_style_hanging_punctuation();
		$this->set_initial_quote_tags();

		// Hyphenation.
		$this->set_hyphenation();
		$this->set_hyphenation_language();
		$this->set_min_length_hyphenation();
		$this->set_min_before_hyphenation();
		$this->set_min_after_hyphenation();
		$this->set_hyphenate_headings();
		$this->set_hyphenate_all_caps();
		$this->set_hyphenate_title_case();
		$this->set_hyphenate_compounds();
		$this->set_hyphenation_exceptions();

		// Parser error handling.
		$this->set_ignore_parser_errors();
	}

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


Question:
Returns whether the object named by `key` exists.
       LoggingDatastore logs the access.

def contains(self, key):
    '''
    '''
    self.logger.info('%s: contains %s' % (self, key))
    return super(LoggingDatastore, self).contains(key)

def _check_initialized(self):

    baddies = self._find_uninitialized()
    if baddies:
      raise datastore_errors.BadValueError(
          'Entity has uninitialized properties: %s' % ', '.join(baddies))

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


Question:
// Combine updates s's statistics as if all samples added to o were
// added to s.

func (s *StreamStats) Combine(o *StreamStats) {
	count := s.Count + o.Count

	// Compute combined online variance statistics
	delta := o.mean - s.mean
	mean := s.mean + delta*float64(o.Count)/float64(count)
	vM2 := s.vM2 + o.vM2 + delta*delta*float64(s.Count)*float64(o.Count)/float64(count)

	s.Count = count
	s.Total += o.Total
	if o.Min < s.Min {
		s.Min = o.Min
	}
	if o.Max > s.Max {
		s.Max = o.Max
	}
	s.mean = mean
	s.meanOfSquares += (o.meanOfSquares - s.meanOfSquares) * float64(o.Count) / float64(count)
	s.vM2 = vM2
}

def _line(self, element):
        """"""
        for v in _get_xml_version(element):
            if "id" in element.attrib:
                tline = TemplateLine(element, None, self.versions[v].comment)
                self.versions[v].entries[tline.identifier] = tline
                self.versions[v].order.append(tline.identifier)
            else:
                msg.warn("no id element in {}. Ignored. (_line)".format(element))

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


Question: wake the reader up before using the pipe again.

@Override
    public boolean flush()
    {
        //  If there are no un-flushed items, do nothing.
        if (w == f) {
            return true;
        }

        //  Try to set 'c' to 'f'.
        if (!c.compareAndSet(w, f)) {
            //  Compare-and-swap was unsuccessful because 'c' is NULL.
            //  This means that the reader is asleep. Therefore we don't
            //  care about thread-safeness and update c in non-atomic
            //  manner. We'll return false to let the caller know
            //  that reader is sleeping.
            c.set(f);
            w = f;
            return false;
        }

        //  Reader is alive. Nothing special to do now. Just move
        //  the 'first un-flushed item' pointer to 'f'.
        w = f;
        return true;
    }

def _get_future_devices(self, context):
        """"""
        monitor = Monitor.from_netlink(context)
        monitor.filter_by("hidraw")
        monitor.start()

        self._scanning_log_message()
        for device in iter(monitor.poll, None):
            if device.action == "add":
                # Sometimes udev rules has not been applied at this point,
                # causing permission denied error if we are running in user
                # mode. With this sleep this will hopefully not happen.
                sleep(1)

                yield device
                self._scanning_log_message()

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


Question:
Set the prefix for the node (see Leaf class).

        DEPRECATED; use the prefix property directly.

def set_prefix(self, prefix):

        warnings.warn("set_prefix() is deprecated; use the prefix property",
                      DeprecationWarning, stacklevel=2)
        self.prefix = prefix

public function getPath() {
    $path = '';
    /** @var TokenNode $child */
    $child = $this->head;
    while ($child) {
      $type = $child->getType();
      if ($type === T_NAMESPACE || $type === T_NS_SEPARATOR || $type === T_STRING) {
        $path .= $child->getText();
      }
      $child = $child->next;
    }
    return $path;
  }

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


Question:
Resolve a relative URL pathname against a base URL pathname.

@param {String} relative Pathname of the relative URL.
@param {String} base Pathname of the base URL.
@return {String} Resolved pathname.
@private

function resolve(relative, base) {
  var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/'))
    , i = path.length
    , last = path[i - 1]
    , unshift = false
    , up = 0;

  while (i--) {
    if (path[i] === '.') {
      path.splice(i, 1);
    } else if (path[i] === '..') {
      path.splice(i, 1);
      up++;
    } else if (up) {
      if (i === 0) unshift = true;
      path.splice(i, 1);
      up--;
    }
  }

  if (unshift) path.unshift('');
  if (last === '.' || last === '..') path.push('');

  return path.join('/');
}

private function renderPaths()
    {
        if (!$this->pathsTable) {
            $this->pathsTable = new Table($this->io);
            $style = clone Table::getStyleDefinition('symfony-style-guide');
            $this->pathsTable->setStyle($style);

            $this->pathsTable->setHeaders(['#', 'Name', 'Path']);

            $style = clone $style;
            $style->setCellHeaderFormat('<info>%s</info>');
            $this->pathsTable->setColumnStyle(0, $style);
        }

        $i = 0;
        $rows = [];
        $root = $this->resolver->resolve('root');
        foreach ($this->resolver->names() as $name) {
            $raw = $this->resolver->raw($name);
            $resolved = $this->resolver->resolve($name);
            $resolved = Path::makeRelative($resolved, $root);
            if ($resolved === '') {
                $resolved = '.';
            }
            $path = "<comment>$raw</comment>";
            if ($raw !== $resolved) {
                $path .= " ($resolved)";
            }
            $rows[] = ['<info>' . ++$i . '</info>', "<info>$name</info>", $path];
        }
        $this->pathsTable->setRows($rows);

        $this->pathsTable->overwrite();
    }

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


Question: // UnpackLog unpacks a retrieved log into the provided output structure.

func (c *BoundContract) UnpackLog(out interface{}, event string, log types.Log) error {
	if len(log.Data) > 0 {
		if err := c.abi.Unpack(out, event, log.Data); err != nil {
			return err
		}
	}
	var indexed abi.Arguments
	for _, arg := range c.abi.Events[event].Inputs {
		if arg.Indexed {
			indexed = append(indexed, arg)
		}
	}
	return parseTopics(out, indexed, log.Topics[1:])
}

func (v *Bools) MarshalLogObject(enc zapcore.ObjectEncoder) (err error) {
	if v == nil {
		return nil
	}
	if v.ImTrue != nil {
		enc.AddBool("im_true", *v.ImTrue)
	}
	if v.ImFalse != nil {
		enc.AddBool("im_false", *v.ImFalse)
	}
	return err
}

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


Question: Shows the questions in a survey

public function questionsAction()
    {
        if (!$this->getTokenId()) {
            $params = $this->_processParameters($this->questionsParameters);
        } else {
            $params = $this->_processParameters($this->questionsParameters + $this->defaultTokenParameters);
        }
        if ($this->questionsSnippets) {
            $params = $this->_processParameters($this->questionsParameters + $this->defaultTokenParameters);

            $this->addSnippets($this->questionsSnippets, $params);
        }
    }

public function AnimeStats(int $id): Model\Anime\AnimeStats
    {
        return $this->myanimelist->getAnimeStats(
            new Request\Anime\AnimeStatsRequest($id)
        );
    }

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


Question:
//
// "any" patterns
//
// any returns a Pattern designed to match paths that include at least one
// any pattern '**', specifying recursive matching.

func (p *pattern) any(tokens []*Token) Pattern {
	// consider only the non-SEPARATOR tokens, as these will be matched
	// against the path components
	_tokens := make([]*Token, 0)
	for _, _token := range tokens {
		if _token.Type != SEPARATOR {
			_tokens = append(_tokens, _token)
		}
	}

	return &any{*p, _tokens}
}

public static int parseBlockComment(final char[] query, int offset) {
    if (offset + 1 < query.length && query[offset + 1] == '*') {
      // /* /* */ */ nest, according to SQL spec
      int level = 1;
      for (offset += 2; offset < query.length; ++offset) {
        switch (query[offset - 1]) {
          case '*':
            if (query[offset] == '/') {
              --level;
              ++offset; // don't parse / in */* twice
            }
            break;
          case '/':
            if (query[offset] == '*') {
              ++level;
              ++offset; // don't parse * in /*/ twice
            }
            break;
          default:
            break;
        }

        if (level == 0) {
          --offset; // reset position to last '/' char
          break;
        }
      }
    }
    return offset;
  }

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


Question:
Get Rating Value.

@return integer

public function getRatingValue()
    {
        if ($this->_ratingValue === null) {
            return null;
        }

        $range = new RangeValue($this->_ratingValue);
        $range->ensureRange($this->_worstRating ?: 0, $this->_bestRating ?: 5);

        return $this->_ratingValue = $range->getValue();
    }

public void setMatchReturnValue(String filterReturnValue) {
    if (filterReturnValue.equalsIgnoreCase("accept")) {
      matchReturnValue = ACCEPT;
    } else if (filterReturnValue.equalsIgnoreCase("deny")) {
      matchReturnValue = DENY;
    } else if (filterReturnValue.equalsIgnoreCase("neutral")) {
      matchReturnValue = NEUTRAL;
    } else {
      LogLog.error("invalid matchReturnValue: " + filterReturnValue);
    }
  }

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


Question:
Returns the last error message when building a JSON file. Mimics json_last_error_msg() from PHP 5.5
@param  {String}       the file that generated the error

public static function hasError() {
		$error        = json_last_error();
		$errorMessage = array_key_exists($error, self::$errors) ? self::$errors[$error] : "Unknown error ({$error})";
		return $errorMessage;
	}

protected function _dumpRenderLite($data, $varname = '...', $params = array())
    {
        if (is_bool($data)) {
            $data = $data ? 'TRUE' : 'FALSE';
        } elseif (is_null($data)) {
            $data = 'NULL';
        }

        if (is_string($data) && strlen($data) == 0) {
            $printrOut = '""';
        } else {
            $printrOut = print_r($data, true);
        }

        if (!self::isCli()) {
            $printrOut = $this->_htmlChars($printrOut);
        }

        if (self::isAjax()) {
            $printrOut = str_replace('] =>', '] =>', $printrOut);
        }

        $output   = array();
        if (!self::isCli()) {
            $output[] = '
------------------------------' . PHP_EOL;
        }

        $output[] = $varname . ' = ';
        $output[] = rtrim($printrOut, PHP_EOL);

        if (!self::isCli()) {
            $output[] = PHP_EOL . '------------------------------
' . PHP_EOL;
        } else {
            $output[] = PHP_EOL;
        }

        if (!self::isAjax()) {
            echo '
' . implode('', $output) . '
' . PHP_EOL;
        } else {
            echo implode('', $output);
        }
    }

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


Question:
Loads localized names for day periods in the requested format.
@param resourceMap Contains the dayPeriod resource to load

private String[] loadDayPeriodStrings(Map<String, String> resourceMap) {
        String strings[] = new String[DAY_PERIOD_KEYS.length];
        if (resourceMap != null) {
            for (int i = 0; i < DAY_PERIOD_KEYS.length; ++i) {
                strings[i] = resourceMap.get(DAY_PERIOD_KEYS[i]);  // Null if string doesn't exist.
            }
        }
        return strings;
    }

private void registerChildInternal(IgnoreDomainResourceTypeResource child) {
        child.setParent(this);
        children.put(child.getName(), child);
    }

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


Question:
Erases all breakpoints in all processes.

        @see:
            erase_code_breakpoint,
            erase_page_breakpoint,
            erase_hardware_breakpoint

def erase_all_breakpoints(self):

        # This should be faster but let's not trust the GC so much :P
        # self.disable_all_breakpoints()
        # self.__codeBP       = dict()
        # self.__pageBP       = dict()
        # self.__hardwareBP   = dict()
        # self.__runningBP    = dict()
        # self.__hook_objects = dict()

##        # erase hooks
##        for (pid, address, hook) in self.get_all_hooks():
##            self.dont_hook_function(pid, address)

        # erase code breakpoints
        for (pid, bp) in self.get_all_code_breakpoints():
            self.erase_code_breakpoint(pid, bp.get_address())

        # erase page breakpoints
        for (pid, bp) in self.get_all_page_breakpoints():
            self.erase_page_breakpoint(pid, bp.get_address())

        # erase hardware breakpoints
        for (tid, bp) in self.get_all_hardware_breakpoints():
            self.erase_hardware_breakpoint(tid, bp.get_address())

public function updateCache(Smarty_Template_Cached $cached, Smarty_Internal_Template $_template, $no_output_filter)
    {
        if ($_template->source->handler->uncompiled) {
            ob_start();
            $_template->source->render($_template);
        } else {
            ob_start();
            if (!isset($_template->compiled)) {
                $_template->loadCompiled();
            }
            $_template->compiled->render($_template);
        }
        if ($_template->smarty->debugging) {
            $_template->smarty->_debug->start_cache($_template);
        }
        $this->removeNoCacheHash($cached, $_template, $no_output_filter);
        $compile_check = $_template->smarty->compile_check;
        $_template->smarty->compile_check = false;
        if (isset($_template->parent) && $_template->parent->_objType == 2) {
            $_template->compiled->unifunc = $_template->parent->compiled->unifunc;
        }
        if (!$_template->cached->processed) {
            $_template->cached->process($_template, true);
        }
        $_template->smarty->compile_check = $compile_check;
        $cached->getRenderedTemplateCode($_template);
        if ($_template->smarty->debugging) {
            $_template->smarty->_debug->end_cache($_template);
        }
    }

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


Question: // SetSubDomain sets the SubDomain field's value.

func (s *Workteam) SetSubDomain(v string) *Workteam {
	s.SubDomain = &v
	return s
}

def _request_modify_dns_record(self, record):
        """"""
        return self._request_internal("Modify_DNS_Record",
                                      domain=self.domain,
                                      record=record)

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


Question:
Displays this frame disclosure container

Creates appropriate divs and outputs closed or opened based on the
initial state.

The disclosure is always displayed as opened in case the user has
JavaScript turned off.

public function display()
    {
        if (!$this->visible) {
            return;
        }

        SwatWidget::display();

        // default header level is h2
        $level = 2;
        $ancestor = $this->parent;

        // get appropriate header level, limit to h6
        while ($ancestor !== null && $level < 6) {
            if ($ancestor instanceof SwatFrame) {
                $level++;
            }

            $ancestor = $ancestor->parent;
        }

        $header_tag = new SwatHtmlTag('h' . $level);
        $header_tag->class = 'swat-frame-title';

        $control_div = $this->getControlDivTag();
        $span_tag = $this->getSpanTag();
        $input_tag = $this->getInputTag();
        $container_div = $this->getContainerDivTag();
        $container_div->class .= ' swat-frame-contents';
        $animate_div = $this->getAnimateDivTag();

        $control_div->open();

        $header_tag->open();
        $span_tag->display();
        $header_tag->close();

        $input_tag->display();

        $animate_div->open();
        echo '<div>';
        $container_div->open();
        $this->displayChildren();
        $container_div->close();
        echo '</div>';
        $animate_div->close();

        Swat::displayInlineJavaScript($this->getInlineJavascript());

        $control_div->close();
    }

function getOptions () {
  return {
    compress: ('compress' in program) ? program.compress : false,
    debug: ('debug' in program) ? program.debug : false,
    deploy: false,
    grep: ('grep' in program) ? program.grep : false,
    invert: ('invert' in program) ? program.invert : false,
    maps: ('maps' in program) ? program.maps : false,
    reload: ('reload' in program) ? program.reload : false,
    script: ('script' in program) ? program.script : false,
    serve: ('serve' in program) ? program.serve : false,
    watch: false
  };
}

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


Question:
Determine if the given user can view the job.

@param UserPolicy $user
@param Job $job

@return bool

public function view(UserPolicy $user, Job $job)
    {
        if ($user->canDo('career.job.view') && $user->isAdmin()) {
            return true;
        }

        return $job->user_id == user_id() && $job->user_type == user_type();
    }

public function isTrustedTag($tag_name, $compiler)
    {
        // check for internal always required tags
        if (in_array($tag_name, array('assign', 'call', 'private_filter', 'private_block_plugin', 'private_function_plugin', 'private_object_block_function',
                    'private_object_function', 'private_registered_function', 'private_registered_block', 'private_special_variable', 'private_print_expression', 'private_modifier'))) {
            return true;
        }
        // check security settings
        if (empty($this->allowed_tags)) {
            if (empty($this->disabled_tags) || !in_array($tag_name, $this->disabled_tags)) {
                return true;
            } else {
                $compiler->trigger_template_error("tag '{$tag_name}' disabled by security setting", $compiler->lex->taglineno);
            }
        } elseif (in_array($tag_name, $this->allowed_tags) && !in_array($tag_name, $this->disabled_tags)) {
            return true;
        } else {
            $compiler->trigger_template_error("tag '{$tag_name}' not allowed by security setting", $compiler->lex->taglineno);
        }

        return false; // should not, but who knows what happens to the compiler in the future?
    }

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


Question:
@param string $documentClass

@return AbstractGenerator

private function getGenerator(string $documentClass): AbstractGenerator
    {
        if (!array_key_exists($documentClass, $this->generatorsCache)) {
            $metadata = $this->metadataFactory->getClassMetadata($documentClass);
            $this->generatorsCache[$documentClass] = $metadata->isNested()
                ? new NestedProxyGenerator($metadata, $this, $this->proxiesNamespace)
                : new RootProxyGenerator($metadata, $this, $this->proxiesNamespace);
        }

        return $this->generatorsCache[$documentClass];
    }

public function api()
    {
        if (config('swagger-lume.generate_always')) {
            Generator::generateDocs();
        }

        //need the / at the end to avoid CORS errors on Homestead systems.
        $response = new Response(
            view('swagger-lume::index', [
                'secure' => Request::secure(),
                'urlToDocs' => route('swagger-lume.docs'),
                'operationsSorter' => config('swagger-lume.operations_sort'),
                'configUrl' => config('swagger-lume.additional_config_url'),
                'validatorUrl' => config('swagger-lume.validator_url'),
            ]),
            200,
            ['Content-Type' => 'text/html']
        );

        return $response;
    }

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


Question:
finds the zeros of a function, given two starting points (which must
have opposite signs

function bisect(f, a, b, parameters) {
        parameters = parameters || {};
        var maxIterations = parameters.maxIterations || 100,
            tolerance = parameters.tolerance || 1e-10,
            fA = f(a),
            fB = f(b),
            delta = b - a;

        if (fA * fB > 0) {
            throw "Initial bisect points must have opposite signs";
        }

        if (fA === 0) return a;
        if (fB === 0) return b;

        for (var i = 0; i < maxIterations; ++i) {
            delta /= 2;
            var mid = a + delta,
                fMid = f(mid);

            if (fMid * fA >= 0) {
                a = mid;
            }

            if ((Math.abs(delta) < tolerance) || (fMid === 0)) {
                return mid;
            }
        }
        return a + delta;
    }

def gt(self, value):

        self.op = '>'
        self.negate_op = '<='
        self.value = self._value(value)
        return self

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


Question:
local-part      = dot-atom / quoted-string / obs-local-part
obs-local-part  = word *("." word)

@return string  The local part.

@throws Horde_Mail_Exception

protected function _parseLocalPart()
    {
        if (($curr = $this->_curr()) === false) {
            throw new Horde_Mail_Exception('Error when parsing local part.');
        }

        if ($curr == '"') {
            $this->_rfc822ParseQuotedString($str);
        } else {
            $this->_rfc822ParseDotAtom($str, ',;@');
        }

        return $str;
    }

def implode(self, env):

        juicer.utils.Log.log_debug("imploding %s" % self.cart_name)

        # rm -r self.remotes_storage()
        if os.path.exists(self.remotes_storage):
            for item in os.listdir(self.remotes_storage):
                ipath = os.path.expanduser(self.remotes_storage + '/' + item)
                if os.path.exists(ipath):
                    juicer.utils.Log.log_debug("removing %s" % ipath)
                    os.remove(ipath)
                juicer.utils.Log.log_debug("removing %s's remote item storage dir" % self.cart_name)
                os.rmdir(self.remotes_storage)

        # rm cart_file()
        if os.path.exists(self.cart_file()):
            juicer.utils.Log.log_debug("removing %s's cart file" % self.cart_name)
            os.remove(self.cart_file())

        # db.carts.delete(self.name)
        juicer.utils.Log.log_debug("removing %s from the database" % self.cart_name)
        juicer.utils.cart_db()[env].remove({'_id': self.cart_name})

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


Question:
Return title (copying) content.
 NOTE: this method is not used yet.
       see lib/review/epubmaker.rb#build_titlepage

def titlepage
      @title = CGI.escapeHTML(@producer.config.name_of('title'))

      @body = <<EOT

#{@title}

EOT

      if @producer.config['subtitle']
        @body << <<EOT

#{CGI.escapeHTML(@producer.config.name_of('subtitle'))}

EOT
      end

      if @producer.config['aut']
        @body << <<EOT

#{CGI.escapeHTML(join_with_separator(@producer.config.names_of('aut'), ReVIEW::I18n.t('names_splitter')))}

EOT
      end

      publisher = @producer.config.names_of('pbl')
      if publisher
        @body << <<EOT

#{CGI.escapeHTML(join_with_separator(publisher, ReVIEW::I18n.t('names_splitter')))}

EOT
      end

      @language = @producer.config['language']
      @stylesheets = @producer.config['stylesheet']
      tmplfile = if @producer.config['htmlversion'].to_i == 5
                   File.expand_path('./html/layout-html5.html.erb', ReVIEW::Template::TEMPLATE_DIR)
                 else
                   File.expand_path('./html/layout-xhtml1.html.erb', ReVIEW::Template::TEMPLATE_DIR)
                 end
      tmpl = ReVIEW::Template.load(tmplfile)
      tmpl.result(binding)
    end

def set_itunes(self):
        """"""
        self.set_itunes_author_name()
        self.set_itunes_block()
        self.set_itunes_complete()
        self.set_itunes_explicit()
        self.set_itune_image()
        self.set_itunes_keywords()
        self.set_itunes_new_feed_url()
        self.set_itunes_categories()
        self.set_items()

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


Question:
Writes $text and reads the user's input

@param string $text
@param string $default
@param bool $displayDefault
@return string

public function ask($text, $default = '', $displayDefault = true)
    {
        if ($displayDefault && !empty($default)) {
            $defaultText = $default;
            if (strlen($defaultText) > 30) {
                $defaultText = substr($default, 0, 30) . '...';
            }
            $text .= " [$defaultText]";
        }
        $this->textWriter->write("$text ");
        return trim(fgets(STDIN)) ?: $default;
    }

def process(self, txt, mode):

        result = ''
        if mode == 'ADD':  # already in add mode, so add data
            if txt in self.all_commands['cmd'][0]:
                self.show_output('Returning to Command mode')
                mode = 'COMMAND'
                self.prompt = '> '
            else:
                self.show_output('Adding Text : ', txt)
                result = self.cmd_add(txt)
        elif mode == 'QUERY':
            if txt in self.all_commands['cmd'][0]:
                self.show_output('Returning to Command mode')
                mode = 'COMMAND'
                self.prompt = '> '
            else:
                self.show_output('Query : ', txt)
                result = self.cmd_query(txt)
        else:
            if txt in self.all_commands['exit'][0]:
                self.cmd_exit()

            elif txt in self.all_commands['help'][0]:
                self.cmd_help()

            elif txt in self.all_commands['cmd'][0]:
                result = 'Returning to Command mode'
                mode = 'COMMAND'
                self.prompt = '> '

            elif txt in self.all_commands['add'][0]:
                result = 'Entering Add mode'
                mode = 'ADD'
                self.prompt = 'ADD > '

            elif txt in self.all_commands['query'][0]:
                result = 'Entering Query mode'
                mode = 'QUERY'
                self.prompt = '?? > '
            else:
                result = 'Unknown command - type help for list of commands'

        return result, mode

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


Question: // CardinalPluralRule returns the cardinal PluralRule given 'num' and digits/precision of 'v' for 'fil'

func (fil *fil) CardinalPluralRule(num float64, v uint64) locales.PluralRule {

	n := math.Abs(num)
	i := int64(n)
	f := locales.F(n, v)
	iMod10 := i % 10
	fMod10 := f % 10

	if (v == 0 && (i == 1 || i == 2 || i == 3)) || (v == 0 && (iMod10 != 4 && iMod10 != 6 && iMod10 != 9)) || (v != 0 && (fMod10 != 4 && fMod10 != 6 && fMod10 != 9)) {
		return locales.PluralRuleOne
	}

	return locales.PluralRuleOther
}

def load_training_data
      File.open(@training_file) {|file|
        @training_set = Nimbus::TrainingSet.new({}, {})
        file.each do |line|
          next if line.strip == ''
          data_feno, data_id, *snp_list = line.strip.split
          raise Nimbus::InputFileError, "Individual ##{data_id} from training set has no value for all #{@tree_SNP_total_count} SNPs" unless snp_list.size == @tree_SNP_total_count
          raise Nimbus::InputFileError, "There are individuals with no ID, please check data in training file." unless (!data_id.nil? && data_id.strip != '')
          raise Nimbus::InputFileError, "Individual ##{data_id} has no fenotype value, please check data in training file." unless (!data_feno.nil? && data_feno.strip != '')
          raise Nimbus::InputFileError, "Individual ##{data_id} has invalid class (not in [#{classes*', '}]), please check data in training file." unless (@classes.nil? || @classes.include?(data_feno))

          data_feno = (@classes ? data_feno.to_s : data_feno.to_f)
          @training_set.individuals[data_id.to_i] = Nimbus::Individual.new(data_id.to_i, data_feno, snp_list.map{|snp| snp.to_i})
          @training_set.ids_fenotypes[data_id.to_i] = data_feno
        end
      }
    end

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


Question: // SetVersionId sets the VersionId field's value.

func (s *DeliveryStreamDescription) SetVersionId(v string) *DeliveryStreamDescription {
	s.VersionId = &v
	return s
}

func (s *Finding) SetUpdatedAt(v string) *Finding {
	s.UpdatedAt = &v
	return s
}

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