Question:
Returns whether the given token is the first token covered by the given annotation.

@param token      the token
@param annotation the annotation
@return whether the token is the first covered token

public static boolean isFirstCoveredToken(final Token token, final Annotation annotation)
    {
        final JCas jCas = getJCas(annotation);
        final List<Token> coveredTokens = JCasUtil.selectCovered(jCas, Token.class, annotation);

        if (coveredTokens.isEmpty()) {
            return false;
        }
        else {
            final Token firstCoveredToken = coveredTokens.get(0);
            return haveSameSpan(token, firstCoveredToken);
        }
    }

private static DescriptorProtoPOJO getDescritorProtoPOJO(FileDescriptorProtoPOJO fileDescriptorProto,
            MessageType typeElement, Set<String> messageSet, Set<String> enumSet) {

        DescriptorProtoPOJO ret = new DescriptorProtoPOJO();
        ret.name = typeElement.getName();
        ret.fields = new ArrayList<FieldDescriptorProtoPOJO>();
        ret.nestedTypes = new ArrayList<DescriptorProtoPOJO>();
        ret.enumTypes = new ArrayList<EnumDescriptorProtoPOJO>();
        ret.extensionRanges = new ArrayList<ExtensionRangePOJO>();
        ret.extensions = new ArrayList<FieldDescriptorProtoPOJO>();
        ret.options = new ArrayList<MessageOptionsPOJO>();

        List<com.squareup.protoparser.MessageType.Field> fields = typeElement.getFields();
        if (fields != null) {
            FieldDescriptorProtoPOJO fieldDescriptorProto;
            for (com.squareup.protoparser.MessageType.Field fieldElement : fields) {
                fieldDescriptorProto = new FieldDescriptorProtoPOJO();
                fieldDescriptorProto.name = fieldElement.getName();
                fieldDescriptorProto.extendee = null; // XXX
                fieldDescriptorProto.number = fieldElement.getTag();

                com.squareup.protoparser.MessageType.Label label = fieldElement.getLabel();
                if (label == com.squareup.protoparser.MessageType.Label.OPTIONAL) {
                    fieldDescriptorProto.label = Label.LABEL_OPTIONAL;
                } else if (label == com.squareup.protoparser.MessageType.Label.REQUIRED) {
                    fieldDescriptorProto.label = Label.LABEL_REQUIRED;
                } else if (label == com.squareup.protoparser.MessageType.Label.REPEATED) {
                    fieldDescriptorProto.label = Label.LABEL_REPEATED;
                }

                String type = fieldElement.getType();
                fieldDescriptorProto.defaultValue = fieldElement.getDefault();

                try {
                    fieldDescriptorProto.type = Type.valueOf("TYPE_" + type.toUpperCase());

                } catch (Exception e) {
                    if (messageSet.contains(type)) {
                        fieldDescriptorProto.type = Type.TYPE_MESSAGE;
                    } else {
                        fieldDescriptorProto.type = Type.TYPE_ENUM;
                    }

                    fieldDescriptorProto.typeName = "." + fileDescriptorProto.pkg + "." + type;
                }

                ret.fields.add(fieldDescriptorProto);
            }
        }

        List<com.squareup.protoparser.Type> nestedElements = typeElement.getNestedTypes();
        if (nestedElements != null) {
            for (com.squareup.protoparser.Type nestedTypeElement : nestedElements) {
                if (nestedTypeElement instanceof MessageType) {
                    ret.nestedTypes.add(getDescritorProtoPOJO(fileDescriptorProto, (MessageType) nestedTypeElement,
                            messageSet, enumSet));
                } else {
                    ret.enumTypes.add(getDescritorProtoPOJO(fileDescriptorProto, (EnumType) nestedTypeElement,
                            messageSet, enumSet));
                }
            }
        }

        return ret;
    }

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


Question:
Automatically expires the session if the user has been inactive for too long.

@return boolean TRUE if the session expired, FALSE if not

protected function autoExpire()
    {
        $lastActivitySecondsAgo = time() - $this->getLastActivityTimestamp();
        $expired = false;
        if ($this->getMaximumAge() !== 0 && $lastActivitySecondsAgo > $this->getMaximumAge()) {
            $this->destroy(sprintf('Session %s was inactive for %s seconds, more than the configured timeout of %s seconds.', $this->getId(), $lastActivitySecondsAgo, $this->getMaximumAge()));
            $expired = true;
        }
        return $expired;
    }

public function authenticate(TokenInterface $token = null)
    {
        // If no token is passed in, try and find one from the authenticator
        $token = $token ?: $this->authenticator->present();

        if ( ! $token instanceof TokenInterface) {
            return new Result(Result::FAILURE_NO_TOKEN);
        }

        $result = new Result();

        try {
            $token = $this->authenticator->authenticate($token);
        } catch (AuthenticationException $e) {
            $result->setCode($e->getCode());
            $result->setException($e);
            $result->setToken($e->getToken());

            return $result;
        }

        $result->setCode(Result::SUCCESS);
        $result->setToken($token);

        if ( ! $token instanceof StatelessTokenInterface) {
            $this->storage->write($token);
        }

        $this->setToken($token);

        return $result;
    }

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


Question:
Add a value to this map. If the map previously contained a mapping for the key, then there are two values now.
@param key the key
@param value the value

void add( K key, V value ) {
        List<V> rules = map.get( key );
        if( rules == null ) {
            rules = new ArrayList<>();
            map.put( key, rules );
        }
        rules.add( value );
    }

function onParsingComplete ()
  {
    // Validate defaultParam's value.
    $def = isset($this->props->defaultParam) ? $this->props->defaultParam : null;
    if (!empty($def)) {
      if (!$this->props->defines ($def))
        throw new ComponentException($this,
          "Invalid value for defaultParam on <{$this->getTagName()}>; parameter $def does not exist");

      // Move children to default parameter.
      if ($this->hasChildren ()) {
        $type = $this->props->getTypeOf ($def);
        if ($type != type::content && $type != type::metadata)
          throw new ComponentException($this, sprintf (
            "The macro's default parameter $def can't hold content because its type is %s.",
            type::getNameOf ($type)));

        $param = new Metadata($this->context, ucfirst ($def), $type);
        $this->props->set ($def, $param);
        $param->attachTo ($this);
        $param->setChildren ($this->getChildren ());
      }
    }
    elseif ($this->hasChildren ())
      throw new ComponentException ($this,
        'You may not specify content for this tag because it has no default property');
  }

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


Question:
Iterates over the {@link Resources} and
returns either the resource with specified resourceType or null.

public static Resource getResourceByType(int resourceType) {
    for (Resource resource : Resources.values()) {
      if (resource.resourceType() == resourceType) {
        return resource;
      }
    }
    return null;
  }

protected void addNavDetailLink(List<?> members, Content liNav) {
        addNavDetailLink(members.size() > 0 ? true : false, liNav);
    }

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


Question:
Classify `value` of bold, color, and underline keys.

    Parameters
    ----------
    value : style value

    Returns
    -------
    str, {"simple", "lookup", "re_lookup", "interval"}

def value_type(value):

    try:
        keys = list(value.keys())
    except AttributeError:
        return "simple"
    if keys in [["lookup"], ["re_lookup"], ["interval"]]:
        return keys[0]
    raise ValueError("Type of `value` could not be determined")

public BaseFontParameters getBaseFontParameters(String name) {
        String alias = (String)aliases.get(name);
        if (alias == null)
            return (BaseFontParameters)mapper.get(name);
        BaseFontParameters p = (BaseFontParameters)mapper.get(alias);
        if (p == null)
            return (BaseFontParameters)mapper.get(name);
        else
            return p;
    }

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


Question:
Consults the authenticator and grant for HTTP request parameters and
        headers to send with the access token request, builds the request using
        the stored endpoint and returns it.

def build_url_request(self):

        params = {}
        headers = {}
        self._authenticator(params, headers)
        self._grant(params)
        return Request(self._endpoint, urlencode(params), headers)

func NewAPI(
	backend Backend,
	authorizer facade.Authorizer,
	blockChecker BlockChecker,
) (*API, error) {
	if !authorizer.AuthClient() {
		return nil, common.ErrPerm
	}
	return &API{
		backend:    backend,
		authorizer: authorizer,
		check:      blockChecker,
	}, nil
}

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


Question:
// GetReader returns a reader for the file at index fileIndex,
// once the file has been preloaded successfully.

func (cp *CachePool) GetReader(fileIndex int64) (io.Reader, error) {
	// this will block until the channel is closed,
	// or immediately succeed if it's already closed
	<-cp.fileChans[fileIndex]

	return cp.cache.GetReader(fileIndex)
}

public Metadata readNextMetadata() throws IOException {
        Metadata metadata = null;

        boolean isLast = (bitStream.readRawUInt(Metadata.STREAM_METADATA_IS_LAST_LEN) != 0);
        int type = bitStream.readRawUInt(Metadata.STREAM_METADATA_TYPE_LEN);
        int length = bitStream.readRawUInt(Metadata.STREAM_METADATA_LENGTH_LEN);

        if (type == Metadata.METADATA_TYPE_STREAMINFO) {
        	metadata = streamInfo = new StreamInfo(bitStream, length, isLast);
            pcmProcessors.processStreamInfo((StreamInfo)metadata);
        } else if (type == Metadata.METADATA_TYPE_SEEKTABLE) {
        	metadata = seekTable = new SeekTable(bitStream, length, isLast);
        } else if (type == Metadata.METADATA_TYPE_APPLICATION) {
            metadata = new Application(bitStream, length, isLast);
        } else if (type == Metadata.METADATA_TYPE_PADDING) {
            metadata = new Padding(bitStream, length, isLast);
        } else if (type == Metadata.METADATA_TYPE_VORBIS_COMMENT) {
            metadata = vorbisComment = new VorbisComment(bitStream, length, isLast);
        } else if (type == Metadata.METADATA_TYPE_CUESHEET) {
	    metadata = new CueSheet(bitStream, length, isLast);
	} else if (type == Metadata.METADATA_TYPE_PICTURE) {
	    metadata = new Picture(bitStream, length, isLast);
        } else {
            metadata = new Unknown(bitStream, length, isLast);
        }
        frameListeners.processMetadata(metadata);
        //if (isLast) state = DECODER_SEARCH_FOR_FRAME_SYNC;
        return metadata;
    }

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


Question: Clear internal cache of the current mailbox

protected function clear_mailbox_cache()
    {
        $this->clear_status_cache($this->selected);

        $keys = array('UIDNEXT', 'UIDVALIDITY', 'HIGHESTMODSEQ', 'NOMODSEQ',
            'PERMANENTFLAGS', 'QRESYNC', 'VANISHED', 'READ-WRITE');

        foreach ($keys as $key) {
            unset($this->data[$key]);
        }
    }

func (c *NodbCacher) Flush() (err error) {
	if err = os.RemoveAll(c.filepath); err != nil {
		return err
	}

	c.dbs.Close()
	c.db = nil
	c.dbs = nil

	return c.new()
}

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


Question:
@param FileLocatorInterface     $locator
@param EventDispatcherInterface $eventDispatcher
@param string                   $yamlFile

@return StateMachine

public static function factory(FileLocatorInterface $locator, EventDispatcherInterface $eventDispatcher, $yamlFile)
    {
        $stateMachine = new StateMachine(null, $eventDispatcher);

        $loader = new YamlFileLoader($locator->locate($yamlFile));
        $loader->load($stateMachine);

        return $stateMachine;
    }

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

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

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

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

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

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

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

        methods = {}

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

        service.methods = methods

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

        return service

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


Question: Bodies with offices up for election on election day.

def get_bodies(self, obj):
        """"""
        return reverse(
            'electionnight_api_body-election-list',
            request=self.context['request'],
            kwargs={'date': obj.date}
        )

def update_business_values(self):

        for elt in self.all_my_hosts_and_services():
            if not elt.is_problem:
                was = elt.business_impact
                elt.update_business_impact_value(self.hosts, self.services,
                                                 self.timeperiods, self.businessimpactmodulations)
                new = elt.business_impact
                # Ok, the business_impact change, we can update the broks
                if new != was:
                    self.get_and_register_status_brok(elt)

        # When all impacts and classic elements are updated,
        # we can update problems (their value depend on impacts, so
        # they must be done after)
        for elt in self.all_my_hosts_and_services():
            # We first update impacts and classic elements
            if elt.is_problem:
                was = elt.business_impact
                elt.update_business_impact_value(self.hosts, self.services,
                                                 self.timeperiods, self.businessimpactmodulations)
                new = elt.business_impact
                # Maybe one of the impacts change it's business_impact to a high value
                # and so ask for the problem to raise too
                if new != was:
                    self.get_and_register_status_brok(elt)

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


Question:
Changes attributes of the table given
the field name

@param *string $name       Column name
@param *array  $attributes Column attributes

@return Eden\Mysql\Alter

public function changeField($name, array $attributes)
    {
        //Argument 1 must be a string
        Argument::i()->test(1, 'string');

        $this->changeFields[$name] = $attributes;
        return $this;
    }

def convert_sqlite_to_mysql(
            self):

        from fundamentals.renderer import list_of_dictionaries
        from fundamentals.mysql import directory_script_runner
        self.log.debug('starting the ``convert_sqlite_to_mysql`` method')

        con = lite.connect(self.pathToSqlite)
        con.row_factory = lite.Row
        cur = con.cursor()

        # GET ALL TABLE NAMES
        cur.execute("SELECT name FROM sqlite_master WHERE type='table';")
        tables = cur.fetchall()

        createStatements = []
        inserts = []
        for table in tables:
            table = table['name']
            if table == "sqlite_sequence":
                continue

            # CREATE TABLE collection_books (folder_id, fingerprint, primary key(folder_id, fingerprint));
            # GENEREATE THE MYSQL CREATE STATEMENTS FOR EACH TABLE
            cur.execute(
                "SELECT sql FROM sqlite_master WHERE name = '%(table)s';" % locals())
            createStatement = cur.fetchone()
            createStatement = createStatement[0].replace('"', '`') + ";"
            if "DEFAULT" not in createStatement:
                if "primary key(" in createStatement:
                    tmp = createStatement.split("primary key(")
                    tmp[0] = tmp[0].replace(
                        ",", " varchar(150) DEFAULT NULL,")
                    createStatement = ("primary key(").join(tmp)
                if "primary key," in createStatement:
                    tmp = createStatement.split("primary key,")
                    tmp[1] = tmp[1].replace(
                        ",", " varchar(150) DEFAULT NULL,")
                    tmp[1] = tmp[1].replace(
                        ");", " varchar(150) DEFAULT NULL);")
                    createStatement = ("primary key,").join(tmp)
            createStatement = createStatement.replace(
                "INTEGER PRIMARY KEY", "INTEGER AUTO_INCREMENT PRIMARY KEY")
            createStatement = createStatement.replace(
                "AUTOINCREMENT", "AUTO_INCREMENT")
            createStatement = createStatement.replace(
                "DEFAULT 't'", "DEFAULT '1'")
            createStatement = createStatement.replace(
                "DEFAULT 'f'", "DEFAULT '0'")
            createStatement = createStatement.replace(",'t'", ",'1'")
            createStatement = createStatement.replace(",'f'", ",'0'")
            if "CREATE TABLE `" in createStatement:
                createStatement = createStatement.replace(
                    "CREATE TABLE `", "CREATE TABLE IF NOT EXISTS `" + self.tablePrefix)
            else:
                createStatement = createStatement.replace(
                    "CREATE TABLE ", "CREATE TABLE IF NOT EXISTS " + self.tablePrefix)
            if ", primary key(" in createStatement:
                createStatement = createStatement.replace(", primary key(", """,
`dateCreated` datetime DEFAULT CURRENT_TIMESTAMP,
`dateLastModified` datetime DEFAULT CURRENT_TIMESTAMP,
`updated` tinyint(4) DEFAULT '0',
primary key(""")
            else:
                createStatement = createStatement.replace(");", """,
    `dateCreated` datetime DEFAULT CURRENT_TIMESTAMP,
    `dateLastModified` datetime DEFAULT CURRENT_TIMESTAMP,
    `updated` tinyint(4) DEFAULT '0');
                """)
            createStatement = createStatement.replace(
                " text primary key", " varchar(100) primary key")
            createStatement = createStatement.replace(
                "`EntryText` TEXT NOT NULL,", "`EntryText` TEXT,")
            createStatement = createStatement.replace(
                "`SelectionText` TEXT NOT NULL", "`SelectionText` TEXT")
            createStatement = createStatement.replace(
                "`Filename` INTEGER NOT NULL,", "`Filename` TEXT NOT NULL,")
            createStatement = createStatement.replace(
                "`SessionPartUUID` TEXT NOT NULL UNIQUE,", "`SessionPartUUID` VARCHAR(100) NOT NULL UNIQUE,")
            createStatement = createStatement.replace(
                "`Name` TEXT PRIMARY KEY NOT NULL", "`Name` VARCHAR(100) PRIMARY KEY NOT NULL")
            createStatement = createStatement.replace(
                " VARCHAR ", " VARCHAR(100) ")
            createStatement = createStatement.replace(
                " VARCHAR,", " VARCHAR(100),")

            # GRAB THE DATA TO ADD TO THE MYSQL DATABASE TABLES
            cur.execute(
                "SELECT * from '%(table)s';" % locals())
            rows = cur.fetchall()

            allRows = []
            for row in rows:
                allRows.append(dict(row))

            # RECURSIVELY CREATE MISSING DIRECTORIES
            if not os.path.exists("/tmp/headjack/"):
                os.makedirs("/tmp/headjack/")

            writequery(
                log=self.log,
                sqlQuery=createStatement,
                dbConn=self.dbConn,
            )

            from fundamentals.mysql import insert_list_of_dictionaries_into_database_tables
            # USE dbSettings TO ACTIVATE MULTIPROCESSING
            insert_list_of_dictionaries_into_database_tables(
                dbConn=self.dbConn,
                log=self.log,
                dictList=allRows,
                dbTableName=self.tablePrefix + table,
                uniqueKeyList=[],
                dateModified=True,
                dateCreated=True,
                batchSize=10000,
                replace=True,
                dbSettings=self.settings["database settings"]
            )

            # # DUMP THE DATA INTO A MYSQL DATABASE
            # dataSet = list_of_dictionaries(
            #     log=self.log,
            #     listOfDictionaries=allRows
            # )
            # originalList = dataSet.list
            # now = datetime.now()
            # now = now.strftime("%Y%m%dt%H%M%S%f.sql")
            # mysqlData = dataSet.mysql(
            # tableName=self.tablePrefix + table, filepath="/tmp/headjack/" +
            # now, createStatement=createStatement)

            # directory_script_runner(
            #     log=self.log,
            #     pathToScriptDirectory="/tmp/headjack/",
            #     databaseName=self.settings["database settings"]["db"],
            #     loginPath=self.settings["database settings"]["loginPath"],
            #     successRule="delete",
            #     failureRule="failed"
            # )

        con.close()

        self.log.debug('completed the ``convert_sqlite_to_mysql`` method')
        return None

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


Question:
// IsForNet returns whether or not the AddressWitnessPubKeyHash is associated
// with the passed bitcoin network.
// Part of the Address interface.

func (a *AddressWitnessPubKeyHash) IsForNet(net *chaincfg.Params) bool {
	return a.hrp == net.Bech32HRPSegwit
}

func (bc *BlockChain) reportBlock(block *types.Block, receipts types.Receipts, err error) {
	bc.addBadBlock(block)

	var receiptString string
	for i, receipt := range receipts {
		receiptString += fmt.Sprintf("\t %d: cumulative: %v gas: %v contract: %v status: %v tx: %v logs: %v bloom: %x state: %x\n",
			i, receipt.CumulativeGasUsed, receipt.GasUsed, receipt.ContractAddress.Hex(),
			receipt.Status, receipt.TxHash.Hex(), receipt.Logs, receipt.Bloom, receipt.PostState)
	}
	log.Error(fmt.Sprintf(`
########## BAD BLOCK #########
Chain config: %v

Number: %v
Hash: 0x%x
%v

Error: %v
##############################
`, bc.chainConfig, block.Number(), block.Hash(), receiptString, err))
}

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


Question:
// RemoveXHRBreakpoint - Removes breakpoint from XMLHttpRequest.
// url - Resource URL substring.

func (c *DOMDebugger) RemoveXHRBreakpoint(url string) (*gcdmessage.ChromeResponse, error) {
	var v DOMDebuggerRemoveXHRBreakpointParams
	v.Url = url
	return c.RemoveXHRBreakpointWithParams(&v)
}

function (route) {
  if (!route) {
    return null;
  }
  let ts = route.split('.');
  if (ts.length !== 3) {
    return null;
  }

  return {
    route: route,
    serverType: ts[0],
    handler: ts[1],
    method: ts[2]
  };
}

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


Question:
return setting of element as hidden input fields.

@return string

public function GetActiveSettingAsHiddenInputField()
    {
        $sInput = '';
        if (false !== $this->GetActiveStartValue()) {
            $sInput .= '<input type="hidden" name="'.TGlobal::OutHTML(
                $this->GetURLInputName().'['.self::URL_PARAMETER_FILTER_START_VALUE.']'
            ).'" value="'.TGlobal::OutHTML($this->GetActiveStartValue()).'" />';
        }
        if (false !== $this->GetActiveEndValue()) {
            $sInput .= '<input type="hidden" name="'.TGlobal::OutHTML(
                $this->GetURLInputName().'['.self::URL_PARAMETER_FILTER_END_VALUE.']'
            ).'" value="'.TGlobal::OutHTML($this->GetActiveEndValue()).'" />';
        }

        return $sInput;
    }

function() {
		let search_box = document.getElementById("search-input")
		search_box.onclick = function() {
			document.getElementById("search-image").style.display = "none";
			search_box.style.outline = "none";
			search_box.placeholder = "Search";
			search_box.style.paddingLeft = "2px";
		}
	}

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


Question: Evaluation of Python code with inspect information.

async def jsk_python_inspect(self, ctx: commands.Context, *, argument: CodeblockConverter):

        arg_dict = get_var_dict_from_ctx(ctx, SCOPE_PREFIX)
        arg_dict["_"] = self.last_result

        scope = self.scope

        try:
            async with ReplResponseReactor(ctx.message):
                with self.submit(ctx):
                    async for result in AsyncCodeExecutor(argument.content, scope, arg_dict=arg_dict):
                        self.last_result = result

                        header = repr(result).replace("``", "`\u200b`").replace(self.bot.http.token, "[token omitted]")

                        if len(header) > 485:
                            header = header[0:482] + "..."

                        paginator = WrappedPaginator(prefix=f"```prolog\n=== {header} ===\n", max_size=1985)

                        for name, res in all_inspections(result):
                            paginator.add_line(f"{name:16.16} :: {res}")

                        interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
                        await interface.send_to(ctx)
        finally:
            scope.clear_intersection(arg_dict)

def validate_ip(self):

        if self.request.app.get('_check_ip', False):
            ip_address, accept = self.check_ip()
            if not accept:
                raise web.HTTPUnauthorized()

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


Question:
Создаёт разметку тега <input>

@param string $type   значение для атрибута type
@param string $name   значение для атрибута name
@param string $value  значение для атрибута value
@param string $extra  дополнительные атрибуты

@return string

@since 0.3.0

protected function createInput($type, $name, $value = null, $extra = null)
    {
        $html = '<input type="' . $type . '" name="' . $name . '"';
        if ($value !== null)
        {
            $html .= ' value="' . $value . '"';
        }
        if ($extra !== null)
        {
            $html .= ' ' . $extra;
        }
        $html .= '>';
        return $html;
    }

public function toString(\Closure $linkFormatterCallback = null)
    {

        $format = $this->getFormat();

        $linkFormatter = (null !== $linkFormatterCallback) ? $linkFormatterCallback : self::getDefaultLinkFormatter();
        $placeholderFormatter = self::getPlaceholderFormatter();

        foreach ($this->getArgs() as $arg) {
            switch ($arg->getType()) {
                case ArgTypes::ARG_TYPE_HYPERLINK:
                    $format = $linkFormatter($arg, $format);
                    break;
                case ArgTypes::ARG_TYPE_BYTES:
                case ArgTypes::ARG_TYPE_DISTANCE:
                case ArgTypes::ARG_TYPE_DURATION:
                case ArgTypes::ARG_TYPE_INT_LITERAL:
                case ArgTypes::ARG_TYPE_PERCENTAGE:
                case ArgTypes::ARG_TYPE_SNAPSHOT_RECT:
                case ArgTypes::ARG_TYPE_STRING_LITERAL:
                case ArgTypes::ARG_TYPE_URL:
                case ArgTypes::ARG_TYPE_VERBATIM_STRING:
                    $format = $placeholderFormatter($arg, $format);
                    break;
                default:
                    throw new ArgException(sprintf('Unknown argument type: "%s"!', $arg->getType()));
            }
        }

        return $format;
    }

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


Question:
Strip PaloAlto-specific output.

        PaloAlto will also put a configuration context:
        [edit]

        This method removes those lines.

def strip_context_items(self, a_string):

        strings_to_strip = [r"\[edit.*\]"]

        response_list = a_string.split(self.RESPONSE_RETURN)
        last_line = response_list[-1]

        for pattern in strings_to_strip:
            if re.search(pattern, last_line):
                return self.RESPONSE_RETURN.join(response_list[:-1])

        return a_string

def pairs(args):

    p = OptionParser(pairs.__doc__)
    p.set_firstN()
    p.set_mates()
    p.set_aligner()
    opts, args = p.parse_args(args)

    if len(args) != 2:
        sys.exit(not p.print_help())

    cwd = os.getcwd()
    aligner = opts.aligner
    work = "-".join(("pairs", aligner))
    mkdir(work)

    from jcvi.formats.sam import pairs as ps
    if aligner == "bowtie":
        from jcvi.apps.bowtie import align
    elif aligner == "bwa":
        from jcvi.apps.bwa import align

    folder, ref = args
    ref = get_abs_path(ref)
    messages = []
    for p, prefix in iter_project(folder):
        samplefq = []
        for i in range(2):
            samplefq.append(op.join(work, prefix + "_{0}.first.fastq".format(i+1)))
            first([str(opts.firstN)] + [p[i]] + ["-o", samplefq[i]])

        os.chdir(work)
        align_args = [ref] + [op.basename(fq) for fq in samplefq]
        outfile, logfile = align(align_args)
        bedfile, stats = ps([outfile, "--rclip={0}".format(opts.rclip)])
        os.chdir(cwd)

        median = stats.median
        tag = "MP" if median > 1000 else "PE"
        median = str(median)
        pf, sf = median[:2], median[2:]
        if sf and int(sf) != 0:
            pf = str(int(pf) + 1)  # Get the first two effective digits
        lib = "{0}-{1}".format(tag, pf + '0' * len(sf))
        for i, xp in enumerate(p):
            suffix = "fastq.gz" if xp.endswith(".gz") else "fastq"
            link = "{0}-{1}.{2}.{3}".format(lib, prefix.replace("-", ""),
                                            i + 1, suffix)
            m = "\t".join(str(x) for x in (xp, link))
            messages.append(m)

    messages = "\n".join(messages)
    write_file("f.meta", messages, tee=True)

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


Question:
send the given Particle through the direct @parent

 @param [Particle] p the Particle to be sent
 @param [Boolean] sys if true send to system Particle fifo
 @param [String] a the post action
 @param [Iota] d the post destination

def _send p, sys, a, d
            p.init! self
            p.set_dst! a, d||self if a
            @saved=nil if @saved==p # particle is sent back the data, all is good
            # daddy will know what to do
            sys ? @parent.send_sys_p(p) : @parent.send_p(p)
        end

def create_node(**kwargs):
    '''

    '''
    name = kwargs['name']
    size = kwargs['size']
    image = kwargs['image']
    location = kwargs['location']
    networks = kwargs.get('networks')
    tag = kwargs.get('tag')
    locality = kwargs.get('locality')
    metadata = kwargs.get('metadata')
    firewall_enabled = kwargs.get('firewall_enabled')

    create_data = {
        'name': name,
        'package': size['name'],
        'image': image['name'],
    }
    if networks is not None:
        create_data['networks'] = networks

    if locality is not None:
        create_data['locality'] = locality

    if metadata is not None:
        for key, value in six.iteritems(metadata):
            create_data['metadata.{0}'.format(key)] = value

    if tag is not None:
        for key, value in six.iteritems(tag):
            create_data['tag.{0}'.format(key)] = value

    if firewall_enabled is not None:
        create_data['firewall_enabled'] = firewall_enabled

    data = salt.utils.json.dumps(create_data)

    ret = query(command='my/machines', data=data, method='POST',
                location=location)
    if ret[0] in VALID_RESPONSE_CODES:
        return ret[1]
    else:
        log.error('Failed to create node %s: %s', name, ret[1])

    return {}

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


Question:
Internal mechanism to set the Skill id

@param Lineage $model
@param mixed $relatedId

protected function doSetSkillId(Lineage $model, $relatedId) {
		if ($model->getSkillId() !== $relatedId) {
			$model->setSkillId($relatedId);

			return true;
		}

		return false;
	}

def store_pulse_jobs(pulse_job, exchange, routing_key):

    newrelic.agent.add_custom_parameter("exchange", exchange)
    newrelic.agent.add_custom_parameter("routing_key", routing_key)

    JobLoader().process_job(pulse_job)

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


Question:
Search the plugin's component tree for components (or their controllers) implementing the
IPluginEvent interface. Those that are found are registered as listeners.

@param cmpt BaseComponent to search

private void findListeners(BaseComponent cmpt) {
        for (BaseComponent child : cmpt.getChildren()) {
            tryRegisterListener(child, true);
            tryRegisterListener(FrameworkController.getController(child), true);
            findListeners(child);
        }
    }

def init(self):
        """"""
        # Wrap callback methods in appropriate ctypefunc instances so
        # that the Pulseaudio C API can call them
        self._context_notify_cb = pa_context_notify_cb_t(
            self.context_notify_cb)
        self._sink_info_cb = pa_sink_info_cb_t(self.sink_info_cb)
        self._update_cb = pa_context_subscribe_cb_t(self.update_cb)
        self._success_cb = pa_context_success_cb_t(self.success_cb)
        self._server_info_cb = pa_server_info_cb_t(self.server_info_cb)

        # Create the mainloop thread and set our context_notify_cb
        # method to be called when there's updates relating to the
        # connection to Pulseaudio
        _mainloop = pa_threaded_mainloop_new()
        _mainloop_api = pa_threaded_mainloop_get_api(_mainloop)
        context = pa_context_new(_mainloop_api, "i3pystatus_pulseaudio".encode("ascii"))

        pa_context_set_state_callback(context, self._context_notify_cb, None)
        pa_context_connect(context, None, 0, None)
        pa_threaded_mainloop_start(_mainloop)

        self.colors = self.get_hex_color_range(self.color_muted, self.color_unmuted, 100)
        self.sinks = []

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


Question: Executes all the registered beforeFilters for the current action

public function beforeFilter() {
        if(!isset($this->_beforeFilters[$this->_action])) {
            return false;
        }

        foreach($this->_beforeFilters[$this->_action] as $method) {
            call_user_func($method);
        }
    }

def apply_filters(query, args):

    pre_joins = []
    for querystring_key, filter_value in args.items(multi=True):
        if querystring_key in filter_registry:
            cls_inst = filter_registry[querystring_key]
            query = cls_inst.apply_filter(query, args, pre_joins)
        elif querystring_key in PaginationKeys._value_list:
            pass
        else:
            raise InvalidQueryString(querystring_key, filter_value)
    return query

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


Question:
Generate a basic keyword.

@param keyword the keyword to add.
@param comment a comment for the javadoc.
@param getters filled by this function with the getters' names.
@return the content.

protected StringConcatenationClient generateKeyword(final String keyword, final String comment, Map<String, String> getters) {
		final String fieldName = keyword.toUpperCase().replaceAll("[^a-zA-Z0-9_]+", "_"); //$NON-NLS-1$ //$NON-NLS-2$
		final String methodName = Strings.toFirstUpper(keyword.replaceAll("[^a-zA-Z0-9_]+", "_")) //$NON-NLS-1$ //$NON-NLS-2$
				+ "Keyword"; //$NON-NLS-1$
		if (getters != null) {
			getters.put(methodName, keyword);
		}
		return new StringConcatenationClient() {
			@Override
			protected void appendTo(TargetStringConcatenation it) {
				it.append("\tprivate static final String "); //$NON-NLS-1$
				it.append(fieldName);
				it.append(" = \""); //$NON-NLS-1$
				it.append(Strings.convertToJavaString(keyword));
				it.append("\";"); //$NON-NLS-1$
				it.newLineIfNotEmpty();
				it.newLine();
				it.append("\t/** Keyword: {@code "); //$NON-NLS-1$
				it.append(protectCommentKeyword(keyword));
				it.append("}."); //$NON-NLS-1$
				it.newLine();
				if (!Strings.isEmpty(comment)) {
					it.append("\t * Source: "); //$NON-NLS-1$
					it.append(comment);
					it.newLine();
				}
				it.append("\t */"); //$NON-NLS-1$
				it.newLine();
				it.append("\tpublic String get"); //$NON-NLS-1$
				it.append(methodName);
				it.append("() {"); //$NON-NLS-1$
				it.newLine();
				it.append("\t\treturn "); //$NON-NLS-1$
				it.append(fieldName);
				it.append(";"); //$NON-NLS-1$
				it.newLine();
				it.append("\t}"); //$NON-NLS-1$
				it.newLineIfNotEmpty();
				it.newLine();
			}
		};
	}

@Override
    public void execute() throws BuildException {
        if (path == null)
            throw new BuildException("Path isn't defined");

        if (descriptors == null)
            throw new BuildException("Descriptors isn't defined");

        if (descriptors.getData() == null)
            throw new BuildException("No descriptor defined");

        ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
        try {
            if (classpathRef != null || classpath != null) {
                org.apache.tools.ant.types.Path p = new org.apache.tools.ant.types.Path(getProject());

                if (classpathRef != null) {
                    org.apache.tools.ant.types.Reference reference = new org.apache.tools.ant.types.Reference(
                        getProject(), classpathRef);
                    p.setRefid(reference);
                }

                if (classpath != null) {
                    p.append(classpath);
                }

                ClassLoader cl = getProject().createClassLoader(oldCl, p);
                Thread.currentThread().setContextClassLoader(cl);
            }

            final List<Descriptor> data = descriptors.getData();
            for (Descriptor d : data) {
                d.applyNamespaces();
            }

            List<Javadoc> javadoc = null;
            if (javadocs != null) {
                javadoc = javadocs.getData();
            }

            final MetadataParser metadataParser = new MetadataParser();
            metadataParser.parse(path, data, javadoc, verbose);
        } catch (Throwable t) {
            throw new BuildException(t.getMessage(), t);
        } finally {
            Thread.currentThread().setContextClassLoader(oldCl);
        }
    }

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


Question: Update a format string adding formats if they are not already present.

def update_placeholder_formats(self, format_string, placeholder_formats):

        # Tokenize the format string and process them
        output = []
        for token in self.tokens(format_string):
            if (
                token.group("placeholder")
                and (not token.group("format"))
                and token.group("key") in placeholder_formats
            ):
                output.append(
                    "{%s%s}"
                    % (token.group("key"), placeholder_formats[token.group("key")])
                )
                continue
            value = token.group(0)
            output.append(value)
        return u"".join(output)

public JobUpdateHeaders withLastModified(DateTime lastModified) {
        if (lastModified == null) {
            this.lastModified = null;
        } else {
            this.lastModified = new DateTimeRfc1123(lastModified);
        }
        return this;
    }

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


Question:
// extractToCallback: callback alternative of extractTo
//     would be more effective when walk through the whole JSON is unnecessary
// NOTICE: path [0] & [*] for JSON object other than array is INVALID, which is different from extractTo.

func (bj BinaryJSON) extractToCallback(pathExpr PathExpression, callbackFn extractCallbackFn, fullpath PathExpression) (stop bool, err error) {
	if len(pathExpr.legs) == 0 {
		return callbackFn(fullpath, bj)
	}

	currentLeg, subPathExpr := pathExpr.popOneLeg()
	if currentLeg.typ == pathLegIndex && bj.TypeCode == TypeCodeArray {
		elemCount := bj.GetElemCount()
		if currentLeg.arrayIndex == arrayIndexAsterisk {
			for i := 0; i < elemCount; i++ {
				//buf = bj.arrayGetElem(i).extractTo(buf, subPathExpr)
				path := fullpath.pushBackOneIndexLeg(i)
				stop, err = bj.arrayGetElem(i).extractToCallback(subPathExpr, callbackFn, path)
				if stop || err != nil {
					return
				}
			}
		} else if currentLeg.arrayIndex < elemCount {
			//buf = bj.arrayGetElem(currentLeg.arrayIndex).extractTo(buf, subPathExpr)
			path := fullpath.pushBackOneIndexLeg(currentLeg.arrayIndex)
			stop, err = bj.arrayGetElem(currentLeg.arrayIndex).extractToCallback(subPathExpr, callbackFn, path)
			if stop || err != nil {
				return
			}
		}
	} else if currentLeg.typ == pathLegKey && bj.TypeCode == TypeCodeObject {
		elemCount := bj.GetElemCount()
		if currentLeg.dotKey == "*" {
			for i := 0; i < elemCount; i++ {
				//buf = bj.objectGetVal(i).extractTo(buf, subPathExpr)
				path := fullpath.pushBackOneKeyLeg(string(bj.objectGetKey(i)))
				stop, err = bj.objectGetVal(i).extractToCallback(subPathExpr, callbackFn, path)
				if stop || err != nil {
					return
				}
			}
		} else {
			child, ok := bj.objectSearchKey(hack.Slice(currentLeg.dotKey))
			if ok {
				//buf = child.extractTo(buf, subPathExpr)
				path := fullpath.pushBackOneKeyLeg(currentLeg.dotKey)
				stop, err = child.extractToCallback(subPathExpr, callbackFn, path)
				if stop || err != nil {
					return
				}
			}
		}
	} else if currentLeg.typ == pathLegDoubleAsterisk {
		//buf = bj.extractTo(buf, subPathExpr)
		stop, err = bj.extractToCallback(subPathExpr, callbackFn, fullpath)
		if stop || err != nil {
			return
		}

		if bj.TypeCode == TypeCodeArray {
			elemCount := bj.GetElemCount()
			for i := 0; i < elemCount; i++ {
				//buf = bj.arrayGetElem(i).extractTo(buf, pathExpr)
				path := fullpath.pushBackOneIndexLeg(i)
				stop, err = bj.arrayGetElem(i).extractToCallback(pathExpr, callbackFn, path)
				if stop || err != nil {
					return
				}
			}
		} else if bj.TypeCode == TypeCodeObject {
			elemCount := bj.GetElemCount()
			for i := 0; i < elemCount; i++ {
				//buf = bj.objectGetVal(i).extractTo(buf, pathExpr)
				path := fullpath.pushBackOneKeyLeg(string(bj.objectGetKey(i)))
				stop, err = bj.objectGetVal(i).extractToCallback(pathExpr, callbackFn, path)
				if stop || err != nil {
					return
				}
			}
		}
	}
	return false, nil
}

public function parse(string $path, array $options = []): \stdClass
    {
        $data = $this->getEmptyResult();

        if (!empty($options)) {
            $this->setConfig($options);
        }

        try {
            $result = $this->getDataFromPath($path);
            $data = Convert::dataToJson($result, $this->getConfig('lint'));
            if ($this->getConfig('validate') === true) {
                $this->validate($data);
            }
        } catch (ParsingException $e) {
            $message = sprintf("File: %s\n%s", $path, $e->getMessage());
            $this->errors[] = $message;

            throw new InvalidArgumentException($message, 0, $e);
        } catch (InvalidArgumentException $e) {
            $this->errors[] = $e->getMessage();

            throw $e;
        } catch (JsonValidationException $e) {
            $schemaFile = explode(DIRECTORY_SEPARATOR, $path);

            throw new InvalidArgumentException(sprintf('[%s] : %s', end($schemaFile), $e->getMessage()), 0, $e);
        }

        return $data;
    }

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


Question: DOM contains() method returns true if e1===e2, we define our contains() to return false (a node does not contain itself).

function (e1, e2) {
      var d1 = e1.dom(), d2 = e2.dom();
      return d1 === d2 ? false : d1.contains(d2);
    }

function (a) {

      // inlined from peanut, maybe a micro-optimisation?
      var constant_a = function () { return a; };

      var self = function () {
        // can't Fun.constant this one
        return me;
      };

      var map = function (f) {
        return some(f(a));
      };

      var bind = function (f) {
        return f(a);
      };

      var me = {
        fold: function (n, s) { return s(a); },
        is: function (v) { return a === v; },
        isSome: always,
        isNone: never,
        getOr: constant_a,
        getOrThunk: constant_a,
        getOrDie: constant_a,
        or: self,
        orThunk: self,
        map: map,
        ap: function (optfab) {
          return optfab.fold(none, function(fab) {
            return some(fab(a));
          });
        },
        each: function (f) {
          f(a);
        },
        bind: bind,
        flatten: constant_a,
        exists: bind,
        forall: bind,
        filter: function (f) {
          return f(a) ? me : NONE;
        },
        equals: function (o) {
          return o.is(a);
        },
        equals_: function (o, elementEq) {
          return o.fold(
            never,
            function (b) { return elementEq(a, b); }
          );
        },
        toArray: function () {
          return [a];
        },
        toString: function () {
          return 'some(' + a + ')';
        }
      };
      return me;
    }

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


Question: // SetRequestId sets the RequestId field's value.

func (s *UpdateGroupOutput) SetRequestId(v string) *UpdateGroupOutput {
	s.RequestId = &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: // Start satisfies the telegraf.ServiceInput interface

func (a *AMQPConsumer) Start(acc telegraf.Accumulator) error {
	amqpConf, err := a.createConfig()
	if err != nil {
		return err
	}

	msgs, err := a.connect(amqpConf)
	if err != nil {
		return err
	}

	ctx, cancel := context.WithCancel(context.Background())
	a.cancel = cancel

	a.wg = &sync.WaitGroup{}
	a.wg.Add(1)
	go func() {
		defer a.wg.Done()
		a.process(ctx, msgs, acc)
	}()

	go func() {
		for {
			err := <-a.conn.NotifyClose(make(chan *amqp.Error))
			if err == nil {
				break
			}

			log.Printf("I! [inputs.amqp_consumer] connection closed: %s; trying to reconnect", err)
			for {
				msgs, err := a.connect(amqpConf)
				if err != nil {
					log.Printf("E! AMQP connection failed: %s", err)
					time.Sleep(10 * time.Second)
					continue
				}

				a.wg.Add(1)
				go func() {
					defer a.wg.Done()
					a.process(ctx, msgs, acc)
				}()
				break
			}
		}
	}()

	return nil
}

public final static void main(String[] args) throws Exception {

        if (args == null || args.length <= 0) {
            printUsageMessage();
            return;
        }

        StaticTraceInstrumentation sti = new StaticTraceInstrumentation();

        sti.processArguments(args);
        sti.processPackageInfo();
        sti.executeInstrumentation();
    }

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


Question:
Determine whether this node has an ancestor with any of the supplied types.

@param types the types; may not be null
@return true if there is at least one ancestor that has any of the supplied types, or false otherwise

public boolean hasAncestorOfType( Set<Type> types ) {
        PlanNode node = this.parent;
        while (node != null) {
            if (types.contains(node.getType())) return true;
            node = node.getParent();
        }
        return false;
    }

private Class<?> convertType(Class<?> old)
   {
      if (Boolean.class.equals(old))
      {
         return boolean.class;
      }
      else if (boolean.class.equals(old))
      {
         return Boolean.class;
      }
      else if (Byte.class.equals(old))
      {
         return byte.class;
      }
      else if (byte.class.equals(old))
      {
         return Byte.class;
      }
      else if (Short.class.equals(old))
      {
         return short.class;
      }
      else if (short.class.equals(old))
      {
         return Short.class;
      }
      else if (Integer.class.equals(old))
      {
         return int.class;
      }
      else if (int.class.equals(old))
      {
         return Integer.class;
      }
      else if (Long.class.equals(old))
      {
         return long.class;
      }
      else if (long.class.equals(old))
      {
         return Long.class;
      }
      else if (Float.class.equals(old))
      {
         return float.class;
      }
      else if (float.class.equals(old))
      {
         return Float.class;
      }
      else if (Double.class.equals(old))
      {
         return double.class;
      }
      else if (double.class.equals(old))
      {
         return Double.class;
      }
      else if (Character.class.equals(old))
      {
         return char.class;
      }
      else if (char.class.equals(old))
      {
         return Character.class;
      }

      return null;
   }

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


Question:
Send pay request to server

@return void

@throws AsanpardakhtException

protected function sendPayRequest()
    {
        $this->newTransaction();

        $username = $this->config->get('gateway.asanpardakht.username');
        $password = $this->config->get('gateway.asanpardakht.password');
        $orderId = $this->transactionId();
        $price = $this->amount;
        $localDate = date("Ymd His");
        $additionalData = "";
        $callBackUrl = $this->getCallback();
        $req = "1,{$username},{$password},{$orderId},{$price},{$localDate},{$additionalData},{$callBackUrl},0";

        $encryptedRequest = $this->encrypt($req);
        $params = array(
            'merchantConfigurationID' => $this->config->get('gateway.asanpardakht.merchantConfigId'),
            'encryptedRequest' => $encryptedRequest
        );

        try {
            $soap = new SoapClient($this->serverUrl);
            $response = $soap->RequestOperation($params);

        } catch (\SoapFault $e) {
            $this->transactionFailed();
            $this->newLog('SoapFault', $e->getMessage());
            throw $e;
        }

        $response = $response->RequestOperationResult;
        $responseCode = explode(",", $response)[0];
        if ($responseCode != '0') {
            $this->transactionFailed();
            $this->newLog($response, AsanpardakhtException::getMessageByCode($response));
            throw new AsanpardakhtException($response);
        }
        $this->refId = substr($response, 2);
        $this->transactionSetRefId();
    }

protected function ExecuteExternalPaymentCall()
    {
        $aParameter = $this->GetPaymentParameter();
        $sExternalHandlerURL = $this->GetPaymentURL().'?'.str_replace('&', '&', TTools::GetArrayAsURL($aParameter));
        TTools::WriteLogEntry('OGONE DirectLink: called url: '.$sExternalHandlerURL, 4, __FILE__, __LINE__);
        $sResult = file_get_contents($sExternalHandlerURL);
        TTools::WriteLogEntry('OGONE DirectLink: XML response from DirectLink call: '.$sResult, 1, __FILE__, __LINE__);

        if (false !== $sResult) {
            $this->ParseXMLResponse($sResult);
        }

        return $this->PaymentSuccess();
    }

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


Question:
{@inheritdoc}
@throws Exception

public function getEntry($entryId) {
        $this->gotoEntry($entryId);
        return $this->getFile()->fread(self::B_SZ);
    }

private void exportInternalAPI(ClassLoader cl) {
        String[] packages = {
            "com.sun.tools.doclets",
            "com.sun.tools.doclets.standard",
            "com.sun.tools.doclets.internal.toolkit",
            "com.sun.tools.doclets.internal.toolkit.taglets",
            "com.sun.tools.doclets.internal.toolkit.builders",
            "com.sun.tools.doclets.internal.toolkit.util",
            "com.sun.tools.doclets.internal.toolkit.util.links",
            "com.sun.tools.doclets.formats.html",
            "com.sun.tools.doclets.formats.html.markup"
        };

        try {
            Method getModuleMethod = Class.class.getDeclaredMethod("getModule");
            Object thisModule = getModuleMethod.invoke(getClass());

            Class<?> moduleClass = Class.forName("java.lang.Module");
            Method addExportsMethod = moduleClass.getDeclaredMethod("addExports", String.class, moduleClass);

            Method getUnnamedModuleMethod = ClassLoader.class.getDeclaredMethod("getUnnamedModule");
            Object target = getUnnamedModuleMethod.invoke(cl);

            for (String pack : packages) {
                addExportsMethod.invoke(thisModule, pack, target);
            }
        } catch (Exception e) {
            // do nothing
        }
    }

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


Question: also called by EastAsianME

static String toNumeral(
        NumberSystem numsys,
        char zeroDigit,
        int number
    ) {

        if (numsys.isDecimal()) {
            int delta = zeroDigit - '0';
            String standard = Integer.toString(number);

            if (delta == 0) {
                return standard;
            }

            StringBuilder numeral = new StringBuilder();

            for (int i = 0, n = standard.length(); i < n; i++) {
                int codepoint = standard.charAt(i) + delta;
                numeral.append((char) codepoint);
            }

            return numeral.toString();
        } else {
            return numsys.toNumeral(number);
        }

    }

@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case AfplibPackage.BAG__AEG_NAME:
				setAEGName(AEG_NAME_EDEFAULT);
				return;
			case AfplibPackage.BAG__TRIPLETS:
				getTriplets().clear();
				return;
		}
		super.eUnset(featureID);
	}

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


Question:
// GetRebaseName normalizes and compares path and resolvedPath,
// return completed resolved path and rebased file name

func GetRebaseName(path, resolvedPath string) (string, string) {
	// linkTarget will have been cleaned (no trailing path separators and dot) so
	// we can manually join it with them
	var rebaseName string
	if specifiesCurrentDir(path) && !specifiesCurrentDir(resolvedPath) {
		resolvedPath += string(filepath.Separator) + "."
	}

	if hasTrailingPathSeparator(path) && !hasTrailingPathSeparator(resolvedPath) {
		resolvedPath += string(filepath.Separator)
	}

	if filepath.Base(path) != filepath.Base(resolvedPath) {
		// In the case where the path had a trailing separator and a symlink
		// evaluation has changed the last path component, we will need to
		// rebase the name in the archive that is being copied to match the
		// originally requested name.
		rebaseName = filepath.Base(path)
	}
	return resolvedPath, rebaseName
}

function relativeURI(uri, base) {

    // reduce base and uri strings to just their difference string
    var baseParts = base.split('/');
    baseParts.pop();
    base = baseParts.join('/') + '/';
    i = 0;
    while (base.substr(i, 1) == uri.substr(i, 1))
      i++;
    while (base.substr(i, 1) != '/')
      i--;
    base = base.substr(i + 1);
    uri = uri.substr(i + 1);

    // each base folder difference is thus a backtrack
    baseParts = base.split('/');
    var uriParts = uri.split('/');
    out = '';
    while (baseParts.shift())
      out += '../';

    // finally add uri parts
    while (curPart = uriParts.shift())
      out += curPart + '/';

    return out.substr(0, out.length - 1);
  }

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


Question:
Delete list properties EXCEPT the marker. This is useful for 'set' operations
that need to clear existing properties.

public static void deleteProperties(BeanId id) {
        Query query = getEmOrFail().createNamedQuery(DELETE_ALL_PROPERTIES_FOR_BEANID_NAME);
        query.setParameter(1, id.getInstanceId());
        query.setParameter(2, id.getSchemaName());

        query.setParameter(3, BEAN_MARKER_PROPERTY_NAME);
        query.executeUpdate();

    }

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())

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


Question:
Get a database escaped string

@param    string    The string to be escaped
@param    boolean    Optional parameter to provide extra escaping
@return    string
@access    public
@abstract

final public function getEscaped($text, $extra = false)
    {
        $result = mysqli_real_escape_string($this->resourceId, $text);
        if ($extra) {
            $result = addcslashes($result, '%_');
        }
        return $result;
    }

private void parseTemplate() {
    /*
     * query string and path literals have different reserved characters and different encoding
     * requirements. to ensure compliance with RFC 6570, we'll need to encode query literals
     * differently from path literals. let's look at the template to see if it contains a query
     * string and if so, keep track of where it starts.
     */
    Matcher queryStringMatcher = QUERY_STRING_PATTERN.matcher(this.template);
    if (queryStringMatcher.find()) {
      /*
       * the template contains a query string, split the template into two parts, the path and query
       */
      String path = this.template.substring(0, queryStringMatcher.start());
      String query = this.template.substring(queryStringMatcher.end() - 1);
      this.parseFragment(path, false);
      this.parseFragment(query, true);
    } else {
      /* parse the entire template */
      this.parseFragment(this.template, false);
    }
  }

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


Question: // AutopilotSetConfig is used to set the current Autopilot configuration.

func (s *Store) AutopilotSetConfig(idx uint64, config *autopilot.Config) error {
	tx := s.db.Txn(true)
	defer tx.Abort()

	if err := s.autopilotSetConfigTxn(idx, tx, config); err != nil {
		return err
	}

	tx.Commit()
	return nil
}

func ConfigList(appID string, oneLine bool) error {
	c, appID, err := load(appID)

	if err != nil {
		return err
	}

	config, err := config.List(c, appID)

	if err != nil {
		return err
	}

	var keys []string
	for k := range config.Values {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	if oneLine {
		for _, key := range keys {
			fmt.Printf("%s=%s ", key, config.Values[key])
		}
		fmt.Println()
	} else {
		fmt.Printf("=== %s Config\n", appID)

		configMap := make(map[string]string)

		// config.Values is type interface, so it needs to be converted to a string
		for _, key := range keys {
			configMap[key] = fmt.Sprintf("%v", config.Values[key])
		}

		fmt.Print(prettyprint.PrettyTabs(configMap, 6))
	}

	return nil
}

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


Question: Use this API to renumber nspbr6.

public static base_response renumber(nitro_service client) throws Exception {
		nspbr6 renumberresource = new nspbr6();
		return renumberresource.perform_operation(client,"renumber");
	}

def check_params(features_spec, groups_spec, num_bins, edge_range_spec, trim_outliers, trim_percentile):
    """"""

    if isinstance(features_spec, str) and isinstance(groups_spec, str):
        features, groups = read_features_and_groups(features_spec, groups_spec)
    else:
        features, groups = features_spec, groups_spec

    num_bins, edge_range, features, groups = type_cast_params(num_bins, edge_range_spec, features, groups)
    num_values = len(features)

    # memberships
    group_ids, num_groups = identify_groups(groups)
    num_links = np.int64(num_groups * (num_groups - 1) / 2.0)

    check_param_ranges(num_bins, num_groups, num_values, trim_outliers, trim_percentile)

    return features, groups, num_bins, edge_range, group_ids, num_groups, num_links

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


Question: // checkerNames returns the names of the checks in the same order as passed in.

func checkerNames(checks ...HealthzChecker) []string {
	// accumulate the names of checks for printing them out.
	checkerNames := make([]string, 0, len(checks))
	for _, check := range checks {
		checkerNames = append(checkerNames, check.Name())
	}
	return checkerNames
}

def clean_line_profile_text(text):

    #
    profile_block_list = parse_rawprofile_blocks(text)
    #profile_block_list = fix_rawprofile_blocks(profile_block_list)
    #---
    # FIXME can be written much nicer
    prefix_list, timemap = parse_timemap_from_blocks(profile_block_list)
    # Sort the blocks by time
    sorted_lists = sorted(six.iteritems(timemap), key=operator.itemgetter(0))
    newlist = prefix_list[:]
    for key, val in sorted_lists:
        newlist.extend(val)
    # Rejoin output text
    output_text = '\n'.join(newlist)
    #---
    # Hack in a profile summary
    summary_text = get_summary(profile_block_list)
    output_text = output_text
    return output_text, summary_text

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


Question:
Returns the overwritten view if one set, otherwise the passed one

@param string|array $passedView
@return string|array

protected function finalView($passedView)
    {

        if (!$this->overwrittenView ) {
            return $passedView;
        }

        $overwrittenView = $this->overwrittenView;
        $this->overwrittenView = '';

        if (!is_array($overwrittenView) && !is_array($passedView)) {
            return $overwrittenView;
        }

        if (!is_array($overwrittenView) || !is_array($passedView)) {
            throw new RuntimeException("Overwritten view and passed can not be merged");
        }

        foreach ($overwrittenView as $key=>$value) {
            $passedView[$key] = $value;
        }

        return $passedView;

    }

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

        return;
    }

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


Question: The ``Content-Id`` header.

def content_id(self) -> Optional[UnstructuredHeader]:
        """"""
        try:
            return cast(UnstructuredHeader, self[b'content-id'][0])
        except (KeyError, IndexError):
            return None

public function getHtmlHeadEntrySet($mode = 'min')
    {
        $set = new SwatHtmlHeadEntrySet();
        if (isset($this->html_head_entry_set[$mode])) {
            foreach ($this->dependencies as $component) {
                $set->addEntrySet($component->getHtmlHeadEntrySet($mode));
            }
            $set->addEntrySet($this->html_head_entry_set[$mode]);
        }

        return $set;
    }

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


Question: Clean up PjbProxyClient instance.

public static function unregisterInstance(): void
    {
        if (!self::$unregistering && self::$client !== null) {
            self::$unregistering = true;

            if ((self::$client->preparedToSendBuffer ?: '') !== '') {
                self::$client->sendBuffer .= self::$client->preparedToSendBuffer;
            }

            try {
                self::$client->sendBuffer .= self::$client->protocol->getKeepAlive();
                self::$client->protocol->flush();
            } catch (\Throwable $e) {
            }

            // TODO MUST TEST, IT WAS REMOVED FROM FUNCTION
            // BECAUSE IT SIMPLY LOOKS LIKE THE LINES BEFORE
            // ADDED AN IF TO CHECK THE CHANNEL In CASE OF
            //
            if (isset(self::$client->protocol->handler->channel) &&
                false === strpos(get_class(self::getClient()->protocol->handler->channel), '/EmptyChannel/')) {
                try {
                    self::$client->protocol->keepAlive();
                } catch (\Throwable $e) {
                    // silently discard exceptions when unregistering
                }
            }

            self::$client = null;
            self::$instance = null;
            self::$instanceOptionsKey = null;
            self::$unregistering = false;
        }
    }

def delete(alias_value, platform = nil)
      params = platform.nil? ? nil : { platform: build_platform(platform) }
      url = base_url + alias_value
      Http::Client.delete(@jpush, url, params: params)
    end

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


Question: update the polygons when the model changes

function updatePolys() {
        border.geometry([0,200,
            adsr.a(),50,
            adsr.d(),adsr.s(),
            adsr.r(),adsr.s(),
            300,200]);
        aPoly.geometry([
            0,200,
            adsr.a(),50,
            adsr.a(),200
            ]);
        dPoly.geometry([
            adsr.a(),200,
            adsr.a(),50,
            adsr.d(),adsr.s(),
            adsr.d(),200,
            ]);
        sPoly.geometry([
            adsr.d(),200,
            adsr.d(),adsr.s(),
            adsr.r(),adsr.s(),
            adsr.r(),200,
            ])
        rPoly.geometry([
            adsr.r(),200,
            adsr.r(),adsr.s(),
            300,200
            ]);

    }

func (*SwitchesTable) needsUpdate(row, cfg *Switch) bool {
	return row.Ports != cfg.Ports || row.Description != cfg.Description || row.State != cfg.State || row.RackId != cfg.RackId
}

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


Question:
A list of IpRoutes.

@param ipRoutesInfo
A list of IpRoutes.

public void setIpRoutesInfo(java.util.Collection<IpRouteInfo> ipRoutesInfo) {
        if (ipRoutesInfo == null) {
            this.ipRoutesInfo = null;
            return;
        }

        this.ipRoutesInfo = new com.amazonaws.internal.SdkInternalList<IpRouteInfo>(ipRoutesInfo);
    }

protected function execute(InputInterface $input, OutputInterface $output)
  {
    $method = $input->getOption('method');
    $routes = array();

    foreach (Route::$routes as $key => $route) {
      if ($method == 'all') {
        $middleware = implode('|', $route['middleware']);
        array_push($routes, array(implode(',', $route['method']), $route['pattern'], $route['name'], is_string($route['callback']) ? $route['callback'] : '<comment>Closure</comment>', $middleware));
      } else if (str_contains(implode(' ', $route['method']), $method)) {
        $middleware = implode('|', $route['middleware']);
        array_push($routes, array(implode(',', $route['method']), $route['pattern'], $route['name'], is_string($route['callback']) ? $route['callback'] : '<comment>Closure</comment>', $middleware));
      }
    }

    $table = new Table($output);
    $table->setStyle('box');
    $table
        ->setHeaders(array('Method', 'URI', 'Name', 'Action', 'Middleware'))
        ->setRows(
            $routes
        )
    ;
    $table->render();
  }

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


Question: Use this API to fetch statistics of cachepolicy_stats resource of given name .

public static cachepolicy_stats get(nitro_service service, String policyname) throws Exception{
		cachepolicy_stats obj = new cachepolicy_stats();
		obj.set_policyname(policyname);
		cachepolicy_stats response = (cachepolicy_stats) obj.stat_resource(service);
		return response;
	}

public static function get_contexts_for_userid(int $userid) : \core_privacy\local\request\contextlist {
        $contextlist = new \core_privacy\local\request\contextlist();

        // Always add the user context so we're sure we're not dodging user keys, besides it's not costly to do so.
        $contextlist->add_user_context($userid);

        return $contextlist;
    }

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


Question:
Set a integer value for the given key

@param key the key.
@param key the integer value.
@return this MutableDocument instance

@NonNull
    @Override
    public MutableDocument setInt(@NonNull String key, int value) {
        return setValue(key, value);
    }

protected function addPageParameterNode()
    {
    	$builder = new TreeBuilder();
    	$node = $builder->root('page');

    	$node
	    	->treatTrueLike(array(
	    		'versionable' => false,
	    		'signable' => false,
	    		'form' => array(
	    			'type' => "ASF\DocumentBundle\Form\Type\PageType",
	    			'name' => 'page_type'
	    		)
	    	))
	    	->treatFalseLike(array(
    			'versionable' => false,
    			'signable' => false,
	    		'form' => array(
	    			'type' => "ASF\DocumentBundle\Form\Type\PageType",
	    			'name' => 'page_type'
	    		)
	    	))
	    	->addDefaultsIfNotSet()
	    	->children()
	    		->booleanNode('versionable')
	    			->defaultFalse()
	    		->end()
	    		->booleanNode('signable')
	    			->defaultFalse()
	    		->end()
		    	->arrayNode('form')
			    	->addDefaultsIfNotSet()
			    	->children()
				    	->scalarNode('type')
				    		->defaultValue('ASF\DocumentBundle\Form\Type\PageType')
				    	->end()
				    	->scalarNode('name')
				    		->defaultValue('page_type')
				    	->end()
				    	->arrayNode('validation_groups')
				    		->prototype('scalar')->end()
				    		->defaultValue(array("Default"))
				    	->end()
			    	->end()
		    	->end()
	    	->end()
    	;

    	return $node;
    }

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


Question:
Unlocks the user.<p>

@throws Exception if something goes wrong

public void actionKillUserSessions() throws Exception {

        CmsUUID userId = new CmsUUID(m_paramUserId);
        CmsObject cms = getCms();
        CmsUser user = cms.readUser(userId);
        OpenCms.getSessionManager().killSession(cms, user);
        actionCloseDialog();
    }

public static void sleep (int millis)
    {
        if (RunAnywhere.isLinux() && isLoaded()) {
            nativeSleep(millis);
        } else {
            try {
                Thread.sleep(millis);
            } catch (InterruptedException ie) {
                log.info("Thread.sleep(" + millis + ") interrupted.");
            }
        }
    }

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


Question: // SetDateArrayOptions sets the DateArrayOptions field's value.

func (s *IndexField) SetDateArrayOptions(v *DateArrayOptions) *IndexField {
	s.DateArrayOptions = v
	return s
}

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('day_of_week_numbers', 'choice', array(
                'choices'   => DayOfWeek::getChoices(),
                'multiple'  => true,
                'expanded'  => true,
                'label'     => 'Days of Week',
            ))
            ->add('start_time', 'choice', array(
                'choices'   => WindowMaker::getStartTimeChoices(),
            ))
            ->add('end_time', 'choice', array(
                'choices'   => WindowMaker::getEndTimeChoices(),
            ))
            ->add('delivery_type', 'choice', array(
                'choices' => array(
                  HubWindow::DELIVERY_TYPE_PICKUP   => 'Pickup',
                  HubWindow::DELIVERY_TYPE_DELIVERY => 'Delivery',
                ),
                'multiple'  => false,
                'expanded'  => true,
            ))
        ;
    }

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


Question:
makes a String unique by appending a numerical suffix
@param _xElementContainer the com.sun.star.container.XNameAccess container
that the new Element is going to be inserted to
@param _sElementName the StemName of the Element

public static String createUniqueName(XNameAccess _xElementContainer, String _sElementName) {
        boolean bElementexists = true;
        int i = 1;
        String sIncSuffix = "";
        String BaseName = _sElementName;
        while (bElementexists) {
            bElementexists = _xElementContainer.hasByName(_sElementName);
            if (bElementexists) {
                i += 1;
                _sElementName = BaseName + Integer.toString(i);
            }
        }
        return _sElementName;
    }

public ICalComponentScribe<? extends ICalComponent> getComponentScribe(ICalComponent component) {
		if (component instanceof RawComponent) {
			RawComponent raw = (RawComponent) component;
			return new RawComponentScribe(raw.getName());
		}

		return getComponentScribe(component.getClass());
	}

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


Question:
Download by option.

@return void

private function byOption()
    {
        $option = new OptionForCli($this->interactor);
        $option->setOption($this->option);
        $option->execute();
    }

public function output($image_type = null, $quality = null)
    {
        $image_type = $image_type ?: $this->source_type;

        header('Content-Type: ' . image_type_to_mime_type($image_type));

        $this->save(null, $image_type, $quality);
    }

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


Question:
Decode from URL.
@param txt Text
@return Decoded

private static String decode(final CharSequence txt) {
        try {
            return URLDecoder.decode(
                txt.toString(), Charset.defaultCharset().name()
            );
        } catch (final UnsupportedEncodingException ex) {
            throw new IllegalStateException(ex);
        }
    }

def _wrap_callback_parse_time_info(subscription, on_data, message):

    if message.type == message.REPLY:
        time_response = web_pb2.TimeSubscriptionResponse()
        time_response.ParseFromString(message.reply.data)
        time = parse_isostring(time_response.timeInfo.currentTimeUTC)
        #pylint: disable=protected-access
        subscription._process(time)
        if on_data:
            on_data(time)
    elif message.type == message.DATA:
        if message.data.type == yamcs_pb2.TIME_INFO:
            time_message = getattr(message.data, 'timeInfo')
            time = parse_isostring(time_message.currentTimeUTC)
            #pylint: disable=protected-access
            subscription._process(time)
            if on_data:
                on_data(time)

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


Question: // MarshalJSON implements json.Marshaler interface.

func (sf *ScalarFunction) MarshalJSON() ([]byte, error) {
	return []byte(fmt.Sprintf("\"%s\"", sf)), nil
}

public static <E> Map<String, E> parseMap(InputStream is, Class<E> jsonObjectClass) throws IOException {
        return mapperFor(jsonObjectClass).parseMap(is);
    }

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


Question:
dump Assets

@param string $position
@param boolean $echo
@return string|null

public function dumpAssets($position = 'top', $echo = true)
    {
        $assetHtml = '';

        /** @var array $files css files */
        if ($files = $this->getAttribute('__cssFiles:' . $position)) {
            foreach ($files as $file) {
                $assetHtml .= '<link href="' . $file . '" rel="stylesheet">' . PHP_EOL;
            }
        }

        /** @var array $codes css codes */
        if ($codes = $this->getAttribute('__cssCodes:' . $position)) {
            $assetHtml .= '<style type="text/css">' . PHP_EOL;
            foreach ($codes as $code) {
                $assetHtml .= $code . PHP_EOL;
            }
            $assetHtml .= '</style>' . PHP_EOL;
        }

        /** @var array $files js files */
        if ($files = $this->getAttribute('__jsFiles:' . $position)) {
            foreach ($files as $file) {
                $assetHtml .= '<script src="' . $file . '"></script>' . PHP_EOL;
            }
        }

        /** @var array $codes js codes */
        if ($codes = $this->getAttribute('__jsCodes:' . $position)) {
            $jsCode = '';

            foreach ($codes as $code) {
                $jsCode .= $code . PHP_EOL;
            }

            if ($jsCode) {
                $assetHtml .= "<script type=\"text/javascript\">\n{$jsCode}</script>\n";
            }
        }

        if (!$echo) {
            return $assetHtml;
        }

        // echo it.
        if ($assetHtml) {
            echo '<!-- dumped assets -->' . PHP_EOL . $assetHtml;
        }

        return null;
    }

def from_array(array):

        if array is None or not array:
            return None
        # end if
        assert_type_or_raise(array, dict, parameter_name="array")

        data = {}
        data['longitude'] = float(array.get('longitude'))
        data['latitude'] = float(array.get('latitude'))
        data['_raw'] = array
        return Location(**data)

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


Question:
@param ServerRequestInterface $request
@param Tree                   $tree

@return ResponseInterface

public function postAdminDeleteAction(ServerRequestInterface $request, Tree $tree): ResponseInterface
    {
        $block_id = (int) $request->get('block_id');

        DB::table('block_setting')->where('block_id', '=', $block_id)->delete();

        DB::table('block')->where('block_id', '=', $block_id)->delete();

        $url = route('module', [
            'module' => $this->name(),
            'action' => 'Admin',
            'ged'    => $tree->name(),
        ]);

        return redirect($url);
    }

def get_interface_detail_output_interface_ifHCInErrors(self, **kwargs):

        config = ET.Element("config")
        get_interface_detail = ET.Element("get_interface_detail")
        config = get_interface_detail
        output = ET.SubElement(get_interface_detail, "output")
        interface = ET.SubElement(output, "interface")
        interface_type_key = ET.SubElement(interface, "interface-type")
        interface_type_key.text = kwargs.pop('interface_type')
        interface_name_key = ET.SubElement(interface, "interface-name")
        interface_name_key.text = kwargs.pop('interface_name')
        ifHCInErrors = ET.SubElement(interface, "ifHCInErrors")
        ifHCInErrors.text = kwargs.pop('ifHCInErrors')

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

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


Question: // HTML renders this Link as HTML.

func (l *Link) HTML() template.HTML {
	if l == nil {
		return ""
	}
	buf := bytes.Buffer{}
	if err := linkifyTemplate.Execute(&buf, l); err != nil {
		panic(err)
	}
	return template.HTML(buf.Bytes())
}

public static String unescapeLink(String source) {

        if (source == null) {
            return null;
        }
        return CmsStringUtil.substitute(source, "&", "&");

    }

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


Question:
Gets the Neighbour based on the UUID supplied

@param neighbourUUID  The UUID for the Neighbour

@return the Neighbour object

Neighbour getNeighbour(SIBUuid8 neighbourUuid)
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "getNeighbour", neighbourUuid);

    Neighbour neighbour = null;
    synchronized(_neighbours)
    {
      neighbour = (Neighbour) _neighbours.get(neighbourUuid);
    }

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "getNeighbour", neighbour);

    return neighbour;
  }

def _check_dimension(typeattr, unit_id=None):

    if unit_id is None:
        unit_id = typeattr.unit_id

    dimension_id = _get_attr(typeattr.attr_id).dimension_id

    if unit_id is not None and dimension_id is None:
        # First error case
        unit_dimension_id = units.get_dimension_by_unit_id(unit_id).id
        raise HydraError("Unit %s (abbreviation=%s) has dimension_id %s(name=%s), but attribute has no dimension"%
                        (unit_id, units.get_unit(unit_id).abbreviation,
                        unit_dimension_id, units.get_dimension(unit_dimension_id, do_accept_dimension_id_none=True).name))
    elif unit_id is not None and dimension_id is not None:
        unit_dimension_id = units.get_dimension_by_unit_id(unit_id).id
        if unit_dimension_id != dimension_id:
            # Only error case
            raise HydraError("Unit %s (abbreviation=%s) has dimension_id %s(name=%s), but attribute has dimension_id %s(name=%s)"%
                            (unit_id, units.get_unit(unit_id).abbreviation,
                            unit_dimension_id, units.get_dimension(unit_dimension_id, do_accept_dimension_id_none=True).name,
                            dimension_id, units.get_dimension(dimension_id, do_accept_dimension_id_none=True).name))

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


Question:
Reads and returns a number.

@return the parsed number as Token

protected Token fetchNumber() {
        Token result = Token.create(Token.TokenType.INTEGER, input.current());
        result.addToContent(input.consume());
        while (input.current().isDigit() || input.current().is(decimalSeparator) || (input.current()
                                                                                .is(groupingSeparator)
                                                                                && input.next().isDigit())) {
            if (input.current().is(groupingSeparator)) {
                result.addToSource(input.consume());
            } else if (input.current().is(decimalSeparator)) {
                if (result.is(Token.TokenType.DECIMAL)) {
                    problemCollector.add(ParseError.error(input.current(), "Unexpected decimal separators"));
                } else {
                    Token decimalToken = Token.create(Token.TokenType.DECIMAL, result);
                    decimalToken.setContent(result.getContents() + effectiveDecimalSeparator);
                    decimalToken.setSource(result.getSource());
                    result = decimalToken;
                }
                result.addToSource(input.consume());
            } else {
                result.addToContent(input.consume());
            }
        }

        return result;
    }

public void marshall(GetCrawlerMetricsRequest getCrawlerMetricsRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(getCrawlerMetricsRequest.getCrawlerNameList(), CRAWLERNAMELIST_BINDING);
            protocolMarshaller.marshall(getCrawlerMetricsRequest.getMaxResults(), MAXRESULTS_BINDING);
            protocolMarshaller.marshall(getCrawlerMetricsRequest.getNextToken(), NEXTTOKEN_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
Re-implementation of the core Sass import mechanism, which looks for
        files using the staticfiles storage and staticfiles finders.

def handle_import(self, name, compilation, rule):

        original_path = PurePath(name)

        search_exts = list(compilation.compiler.dynamic_extensions)
        if original_path.suffix and original_path.suffix in search_exts:
            basename = original_path.stem
        else:
            basename = original_path.name

        if original_path.is_absolute():
            # Remove the beginning slash
            search_path = original_path.relative_to('/').parent
        elif rule.source_file.origin:
            search_path = rule.source_file.origin
            if original_path.parent:
                search_path = os.path.normpath(str(search_path / original_path.parent))
        else:
            search_path = original_path.parent

        for prefix, suffix in product(('_', ''), search_exts):
            filename = PurePath(prefix + basename + suffix)

            full_filename, storage = get_file_and_storage(str(search_path / filename))

            if full_filename:
                with storage.open(full_filename) as f:
                    return SourceFile.from_file(f, origin=search_path, relpath=filename)

def _get_fashion_mnist(directory):
  """"""
  # Fashion mnist files have the same names as MNIST.
  # We must choose a separate name (by adding 'fashion-' prefix) in the tmp_dir.
  for filename in [
      _MNIST_TRAIN_DATA_FILENAME, _MNIST_TRAIN_LABELS_FILENAME,
      _MNIST_TEST_DATA_FILENAME, _MNIST_TEST_LABELS_FILENAME
  ]:
    generator_utils.maybe_download(directory,
                                   _FASHION_MNIST_LOCAL_FILE_PREFIX + filename,
                                   _FASHION_MNIST_URL + filename)

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


Question:
Generate a random token.

@param string $intention contextual string

@return string

public function generate($intention = 'm@J0raOaUth')
    {
        $bytes = false;
        if (function_exists('openssl_random_pseudo_bytes') && 0 !== stripos(PHP_OS, 'win')) {
            $bytes = openssl_random_pseudo_bytes(32, $strong);

            if (true !== $strong) {
                $bytes = false;
            }
        }

        // let's just hope we got a good seed
        if (false === $bytes) {
            $bytes = hash('sha512',
                sprintf('-[%s}\%s/{%s]-',
                    $intention,
                    uniqid(mt_rand(), true),
                    $this->secret
                ),
                true
            );
        }

        return str_pad(
            base_convert(bin2hex($bytes), 16, 36),
            50,
            rand(0, 9)
        );
    }

public void logMessageForTask(String taskId, String logMessage) {
        Preconditions.checkArgument(StringUtils.isNotBlank(taskId), "Task id cannot be blank");
        postForEntityWithRequestOnly("tasks/" + taskId + "/log", logMessage);
    }

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


Question:
The method used to handle an explicitly defined image directory by the
    user as a parsed argument.

def explicit_images(images, image_destination, rootname, config):

    log.info('Explicit image directory specified: {0}'.format(images))
    if '*' in images:
        images = images.replace('*', rootname)
        log.debug('Wildcard expansion for image directory: {0}'.format(images))
    try:
        shutil.copytree(images, image_destination)
    except:
        #The following is basically a recipe for log.exception() but with a
        #CRITICAL level if the execution should be killed immediately
        #log.critical('Unable to copy from indicated directory', exc_info=True)
        log.exception('Unable to copy from indicated directory')
        return False
    else:
        return True

def extract_paths_dead(self, paths, *args, **kwargs):

        return self.provider.extract_paths_dead(paths, *args, **kwargs)

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


Question: // Create takes the representation of a podPreset and creates it.  Returns the server's representation of the podPreset, and an error, if there is any.

func (c *podPresets) Create(podPreset *v1alpha1.PodPreset) (result *v1alpha1.PodPreset, err error) {
	result = &v1alpha1.PodPreset{}
	err = c.client.Post().
		Namespace(c.ns).
		Resource("podpresets").
		Body(podPreset).
		Do().
		Into(result)
	return
}

public function parse(array $data, ParsingDispatcher $parsingDispatcher)
    {
        $contentType = null;
        if (array_key_exists('ContentType', $data) && is_array($data['ContentType'])) {
            if (!array_key_exists('_href', $data['ContentType'])) {
                throw new Exceptions\Parser("Missing '_href' attribute for ContentType element in UserCreate.");
            }

            $contentType = $this->contentTypeService->loadContentType(
                $this->requestParser->parseHref($data['ContentType']['_href'], 'contentTypeId')
            );
        }

        if (!array_key_exists('mainLanguageCode', $data)) {
            throw new Exceptions\Parser("Missing 'mainLanguageCode' element for UserCreate.");
        }

        if (!array_key_exists('login', $data)) {
            throw new Exceptions\Parser("Missing 'login' element for UserCreate.");
        }

        if (!array_key_exists('email', $data)) {
            throw new Exceptions\Parser("Missing 'email' element for UserCreate.");
        }

        if (!array_key_exists('password', $data)) {
            throw new Exceptions\Parser("Missing 'password' element for UserCreate.");
        }

        $userCreateStruct = $this->userService->newUserCreateStruct(
            $data['login'],
            $data['email'],
            $data['password'],
            $data['mainLanguageCode'],
            $contentType
        );

        if (array_key_exists('Section', $data) && is_array($data['Section'])) {
            if (!array_key_exists('_href', $data['Section'])) {
                throw new Exceptions\Parser("Missing '_href' attribute for Section element in UserCreate.");
            }

            $userCreateStruct->sectionId = $this->requestParser->parseHref($data['Section']['_href'], 'sectionId');
        }

        if (array_key_exists('remoteId', $data)) {
            $userCreateStruct->remoteId = $data['remoteId'];
        }

        if (array_key_exists('enabled', $data)) {
            $userCreateStruct->enabled = $this->parserTools->parseBooleanValue($data['enabled']);
        }

        if (!array_key_exists('fields', $data) || !is_array($data['fields']) || !is_array($data['fields']['field'])) {
            throw new Exceptions\Parser("Missing or invalid 'fields' element for UserCreate.");
        }

        foreach ($data['fields']['field'] as $fieldData) {
            if (!array_key_exists('fieldDefinitionIdentifier', $fieldData)) {
                throw new Exceptions\Parser("Missing 'fieldDefinitionIdentifier' element in field data for UserCreate.");
            }

            $fieldDefinition = $userCreateStruct->contentType->getFieldDefinition($fieldData['fieldDefinitionIdentifier']);
            if (!$fieldDefinition) {
                throw new Exceptions\Parser(
                    "'{$fieldData['fieldDefinitionIdentifier']}' is invalid field definition identifier for '{$userCreateStruct->contentType->identifier}' content type in UserCreate."
                );
            }

            if (!array_key_exists('fieldValue', $fieldData)) {
                throw new Exceptions\Parser("Missing 'fieldValue' element for '{$fieldData['fieldDefinitionIdentifier']}' identifier in UserCreate.");
            }

            $fieldValue = $this->fieldTypeParser->parseValue($fieldDefinition->fieldTypeIdentifier, $fieldData['fieldValue']);

            $languageCode = null;
            if (array_key_exists('languageCode', $fieldData)) {
                $languageCode = $fieldData['languageCode'];
            }

            $userCreateStruct->setField($fieldData['fieldDefinitionIdentifier'], $fieldValue, $languageCode);
        }

        return $userCreateStruct;
    }

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


Question:
Register an event listener with the dispatcher.

@param  \Closure|string  $listener
@param  bool  $wildcard
@return \Closure

public function makeListener($listener, $wildcard = false)
    {
        if (is_string($listener)) {
            return $this->createClassListener($listener, $wildcard);
        }

        return function ($event, $payload) use ($listener, $wildcard) {
            if ($wildcard) {
                return $listener($event, $payload);
            } else {
                return $listener(...array_values($payload));
            }
        };
    }

function(container_config, x) {

		var i,
			count,
			name;

		if ('event' in x) {

			if (typeof(x.event) != 'object') Lava.t("Malformed x:event attribute");

			container_config.events = {};

			for (name in x.event) {

				container_config.events[name] = Lava.parsers.Common.parseTargets(x.event[name]);

			}

		}

		// Attribute binding. Example: x:bind:src="<any_valid_expression>"
		if ('bind' in x) {

			if (typeof(x.bind) != 'object') Lava.t("Malformed x:bind attribute");

			container_config.property_bindings = this._parseBindingsHash(x.bind);

		}

		if ('style' in x) {

			if (typeof(x.style) != 'object') Lava.t("Malformed x:style attribute");

			container_config.style_bindings = this._parseBindingsHash(x.style);

		}

		if ('classes' in x) {

			var arguments = Lava.ExpressionParser.parse(x.classes, Lava.ExpressionParser.SEPARATORS.SEMICOLON),
				class_bindings = {};

			for (i = 0, count = arguments.length; i < count; i++) {

				class_bindings[i] = arguments[i];

			}

			container_config.class_bindings = class_bindings;

		}

		if ('container_class' in x) {

			container_config['class'] = x.container_class;

		}

	}

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


Question:
Set whether or not responses to this request should be cached.

@return This Request object to allow for chaining.

public final <R extends Request<T>> R setShouldCache(boolean shouldCache) {
        checkIfActive();
        this.shouldCache = shouldCache;
        return (R) this;
    }

func (c *Client) WatchRetryStrategy(agentTag names.Tag) (watcher.NotifyWatcher, error) {
	var results params.NotifyWatchResults
	args := params.Entities{
		Entities: []params.Entity{{Tag: agentTag.String()}},
	}
	err := c.facade.FacadeCall("WatchRetryStrategy", args, &results)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if len(results.Results) != 1 {
		return nil, fmt.Errorf("expected 1 result, got %d", len(results.Results))
	}
	result := results.Results[0]
	if result.Error != nil {
		return nil, errors.Trace(result.Error)
	}
	w := apiwatcher.NewNotifyWatcher(c.facade.RawAPICaller(), result)
	return w, nil
}

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